@amityco/ts-sdk-react-native 7.27.0 → 7.27.1-65962e20.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/channelRepository/observers/getChannels/ChannelLiveCollectionController.d.ts.map +1 -1
- package/dist/channelRepository/observers/searchChannels/SearchChannelLiveCollectionController.d.ts.map +1 -1
- package/dist/index.cjs.js +17 -1
- package/dist/index.esm.js +17 -1
- package/dist/index.umd.js +1 -1
- package/package.json +1 -1
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),A=m(c),T=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"}),j=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),k=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}}),N="ONLY_ADMIN_CAN_POST";var K;e.AmityCommunityType=void 0,(K=e.AmityCommunityType||(e.AmityCommunityType={})).Default="default",K.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",EVENT:"event"}),L=Object.freeze({TEXT:"text",IMAGE:"image",VIDEO:"video",FILE:"file",AUDIO:"audio",MIXED:"mixed",EVENT:"event"});var Q,V,J,H,G,z,Y,W,X,Z,ee,te,ne,ae,se,oe,ie,re,ce,de,le,ue,he;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,(G=e.JoinRequestStatusEnum||(e.JoinRequestStatusEnum={})).Pending="pending",G.Approved="approved",G.Rejected="rejected",G.Cancelled="cancelled",e.JoinResultStatusEnum=void 0,(z=e.JoinResultStatusEnum||(e.JoinResultStatusEnum={})).Success="success",z.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",e.AmityLiveViewerCountMode=void 0,(he=e.AmityLiveViewerCountMode||(e.AmityLiveViewerCountMode={})).ALWAYS_SHOW="always",he.HIDE_ENTIRELY="hidden",he.SHOW_ABOVE_MINIMUM="above-minimum";const me=function(){try{return"v7.27.0-umd"}catch(e){return"__dev__"}}(),ge=5,pe=20,ye="cache_then_server",ve="For using Live Collection feature you need to enable Cache!",fe="Observing unsynced object is not supported by Live Object.",be=-5,Ie=1e3,Ce=6e5,we="/api/v1/feeds/for-you",Se="dead",Oe=6e4,Ae=e=>JSON.stringify(e,((e,t)=>{return null!==t&&"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),Re=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>Re(e[n],t[n])))),Pe=e=>[400400,400300].includes(e),De=e=>["skip"].some((t=>t in e)),Ue=e=>["after","before","first","last","limit"].some((t=>t in e)),je=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")),Ee=(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&&Ue(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},Me=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(De(n))return{after:n.skip,limit:n.limit};if(Ue(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},qe=e=>"locally"in e,xe=e=>"optimistically"in e,Ne=e=>qe(e)||xe(e),Ke=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),Fe=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},_e=(e,...t)=>({func:e,args:t}),Be=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<Oe?Oe:t},$e=({func:e,args:t},n,a=Be("cache_then_server"))=>{let s;const{lifeSpan:o}=Be("cache_then_server",a.lifeSpan);if(Ne(e)){try{s=xe(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(Le(void 0,{origin:"local",loading:!1,error:e}))}const a=Ke(s)&&Fe(s,o);if(null==n||n(Le(s,{origin:"local",loading:!(qe(e)&&a)})),a)return}else null==n||n(Le(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(Le(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(Le(void 0,{origin:"server",loading:!1,error:e}))}))};function Le(e,t){return ke(e)||Ke(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}class Qe 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,Qe)}}class Ve extends Qe{constructor(e,t,n){super(e,t,n)}}class Je extends Qe{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class He extends Qe{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class Ge extends Qe{constructor(e){super(e,800110,"error")}}let ze=null;const Ye=()=>{if(!ze)throw new Qe("There is no active client",8e5,"fatal");return ze},We=e=>{ze=e},Xe={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},Ze=e=>Xe[e],et={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 tt(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}const nt=e=>{const{log:t,cache:n}=Ye();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=Te(t);return Re(e,n)})).map((e=>n.data[e]))},at=e=>{const{log:t,cache:n}=Ye();if(!n)return;t("cache/api/pullFromCache",e);const a=Ae(e);return n.data[a]?n.data[a]:void 0},st=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:s}=Ye();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=Ae(e);return s.data[o]=Object.assign({key:e,data:t},n),!0},ot=(e,t,n)=>{const{log:a,cache:s}=Ye();if(!s)return!1;a("cache/api/mergeInCache",{key:e,mutation:t});const o=at(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))&&(st(e,i,n),!0);var r,c},it=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:s}=Ye();if(!s)return!1;a("cache/api/upsertInCache",{key:e,data:t,options:n});return at(e)?ot(e,t,n):st(e,t,n)},rt=(e,t=!1)=>{const{log:n,cache:a}=Ye();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=>Re(e,t))).map((e=>rt(e,!0))).every((e=>e));const s=Ae(e);return s in a.data&&(delete a.data[s],!0)},ct=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,dt=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,lt=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,ut=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;if("community"===e.type)return!0;const s=Ze("channelUsers")({channelId:e.channelPublicId,userId:n}),o=null===(a=at(["channelUsers","get",s]))||void 0===a?void 0:a.data;return"member"===t?o&&"none"!==o.membership:!o||"none"===o.membership})),ht=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var a;const s=null===(a=at(["feed","get",Ze("feed")({targetId:e,feedId:n})]))||void 0===a?void 0:a.data;return s&&s.feedType===t})),mt=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;const s=Ze("communityUsers")({communityId:e.communityId,userId:n}),o=null===(a=at(["communityUsers","get",s]))||void 0===a?void 0:a.data;return"member"===t?o&&"member"===o.communityMembership:!o||"none"!==o.communityMembership})),gt=(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=at(["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}),[]),pt=(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))}))},yt=()=>{var e;const{userId:t}=Ye(),n=new Set;return(null!==(e=nt(["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},vt=e=>{const t=yt();return 0===t.size?e:e.filter((e=>{var n,a;if(t.has(e.postedUserId))return!1;return!(null!==(a=null===(n=e.mentionees)||void 0===n?void 0:n.flatMap((e=>"user"===e.type?e.userIds:[])))&&void 0!==a?a:[]).some((e=>t.has(e)))}))},ft=e=>{const t=yt();return 0===t.size?e:e.filter((e=>!t.has(e.userId)))},bt=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,It=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,Ct=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),wt=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),St=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),Ot=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),At=({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(),Rt=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")},Pt=(e,t,n)=>{const a=new Date(e).valueOf(),s=new Date(t).valueOf();return"firstCreated"===n?a>=s:a<=s};let Dt=null;const Ut=()=>{if(!Dt)throw new Qe("Connect client first",8e5,"fatal");return Dt},jt=e=>{Dt={_id:e._id,userId:e.userId,path:e.path}};let kt,Et=[];const Mt=e=>{clearTimeout(kt),Et.push(e),kt=setTimeout((()=>{Et.forEach((e=>e())),Et=[]}),0)},qt=["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"],xt=(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)}},Nt=(e,t)=>{const{emitter:n}=Ye();Mt((()=>{n.emit(e,t)}))};let Kt,Ft;async function _t(){var e;const{mqtt:t,emitter:n,token:a}=Ye();if(!t)return;const s=null!==(e=null==a?void 0:a.accessToken)&&void 0!==e?e:"",o=Ut();Kt===s&&Ft===o._id||(Kt=s,Ft=o._id,await t.connect({accessToken:Kt,userId:Ft}),((e,t)=>{qt.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 Bt=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=at(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),$t=()=>{var e;const t=Ye();if(!t)throw new Qe("Connect client first",8e5,"fatal");const n=null===(e=at(["user","get",t.userId]))||void 0===e?void 0:e.data;return n?Bt(n):null};var Lt;e.SubscriptionLevels=void 0,(Lt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",Lt.POST="post",Lt.COMMENT="comment",Lt.POST_AND_COMMENT="post_and_comment",Lt.USER="user";const Qt=(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}},Vt=e=>e.path.split("/user/")[0],Jt=()=>{const e=Ut();return`${Vt(e)}/membership/${e._id}/+/+`},Ht=()=>{const e=Ut();return`${Vt(e)}/membership/+/${e._id}/+`},Gt=({channelId:e,subChannelId:t})=>{const n=Ut();return`${Vt(n)}/marker/channel/${e}/message/${t}`},zt=()=>Vt(Ut()),Yt=()=>{const e=Ut();return`${Vt(e)}/smartfeed/${e._id}/channels`},Wt=()=>{const e=Ut();return`${Vt(e)}/smartfeed/${e._id}/messagefeeds`},Xt=()=>{const e=Ut();return`${Vt(e)}/smartfeed/${e._id}/messages`},Zt=()=>{const e=Ut();return`${Vt(e)}/videostreaming`};function en(e,t){const{mqtt:n}=Ye();return n?(_t(),n.subscribe(e,t)):()=>null}var tn;const nn="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:an={}}=nn,sn="production"===(null===(tn=an.env)||void 0===tn?void 0:tn.NODE_ENV),on={EU:"eu",SG:"sg",US:"us"},rn={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function cn(e,t){return rn[e].replace("{region}",t)}class dn{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 ln;var un,hn=()=>(ln||(ln=new dn),ln);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(un||(un={}));let mn=new AbortController;const gn=e=>{switch(e){case un.UserGlobalBanned:throw new Qe(e,400312,"fatal");case un.UserDeleted:throw new Qe(e,400100,"fatal");case un.TokenExpired:throw Nt("tokenExpired","tokenExpired"),new Qe(e,800403,"fatal");default:throw new Qe("Request Aborted",8e5,"error")}};let pn=0;const yn=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:mn.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&&(mn.abort(),gn(un.UserGlobalBanned)),a&&(mn.abort(),gn(un.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),hn().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)&&Nt("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-pn<2e3||(pn=e,Nt("visitorUsageLimitReached",void 0))}(),new Qe("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 Ve(e.message,e.code,"error")})(null==s?void 0:s.data),mn.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 vn{constructor(){this._sessionState="notLoggedIn",this._listener=new Map}onSessionStateChange(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setSessionState(e,t){this._sessionState!==e&&(this._sessionState=e,this._listener.forEach((n=>n(e,t))))}destroy(){this._listener.clear()}}let fn;var bn=()=>(fn||(fn=new vn),fn);const In=e=>bn().onSessionStateChange(e),Cn={[e.AmityAutoSubscription.NETWORK]:[zt],[e.AmityAutoSubscription.CHAT]:[Yt,Wt,Xt],[e.AmityAutoSubscription.LIVESTREAM]:[Zt],[e.AmityAutoSubscription.BLOCK]:[Jt,Ht]},wn=[e.AmityAutoSubscription.CHAT,e.AmityAutoSubscription.NETWORK,e.AmityAutoSubscription.LIVESTREAM,e.AmityAutoSubscription.BLOCK],Sn=Object.values(e.AmityAutoSubscription);class On{constructor(){this.refCountByFeature=new Map,this.disposers=new Map,this.seed()}seed(){this.refCountByFeature.clear(),wn.forEach((e=>this.refCountByFeature.set(e,1)))}isActive(e){var t;return(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)>0}subscribeTopics(e){this.unsubscribeTopics(e),this.disposers.set(e,Cn[e].map((e=>en(e()))))}unsubscribeTopics(e){var t;(null!==(t=this.disposers.get(e))&&void 0!==t?t:[]).forEach((e=>e())),this.disposers.delete(e)}initialize(){Sn.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 Sn.map((e=>({feature:e,isActive:this.isActive(e),isSystem:!0,topicCount:Cn[e].length})))}reset(){Sn.forEach((e=>this.unsubscribeTopics(e))),this.disposers.clear(),this.seed()}}let An=null;const Tn=()=>(An||(An=new On),An);class Rn{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 Pn=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new Rn},Dn=async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await O.default.setItem(e,t),!0):new Promise((n=>{Pn().localStorage.setItem(e,t),n(!0)})),Un=async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){return await O.default.getItem(e)}return new Promise((t=>{t(Pn().localStorage.getItem(e))}))},jn=()=>A.default.v4().toString();let kn=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=jn(),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 En=async()=>{var e;const t=`${null!==(e=Ye().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await Un(t);if(n)return n;const a=`ascWebSdk#${jn()}`;return await Dn(t,a),a},Mn=()=>{const e=(()=>{var e,t;return(null===(e=an.versions)||void 0===e?void 0:e.node)?an.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:me}},qn=1e3;var xn;!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"}(xn||(xn={}));const Nn=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 Qe(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 En()}_${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:qn,resubscribe:!0,keepalive:30,properties:{sessionExpiryInterval:1800}},e)}({username:n.userId,password:n.accessToken,clientId:a})),t.on("connect",(()=>{t.options.reconnectPeriod=qn,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||qn),8e3)})),t.on("close",(()=>{o.forEach((({timer:e})=>clearTimeout(e))),o.clear()})),new Promise((e=>t.once("connect",(()=>e()))))},async disconnect(e){if(this.connected)return(null==e?void 0:e.endSession)?new Promise((e=>null==t?void 0:t.end(!1,{reasonCode:0,properties:{sessionExpiryInterval:0}},(()=>e())))):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 Qe("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=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t},Fn=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,a])=>{const s=et[e];if(!s)return;const o=Ze(s);o&&a&&a.forEach((e=>{(n?st:it)([s,"get",o(e)],e,t)}))}))},_n=(e,t)=>{const{log:n,cache:a}=Ye(),s=[e,Se,t],o={cachedAt:Date.now()};a&&(n("cache/api/pushToTombstone",{cacheKey:s,data:o}),rt([e,"get",t],!0),st(s,o))};function Bn(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 $n=(e,t="userId",n="user")=>{var a;return null!==(a=null==e?void 0:e.map((e=>((e,t="userId",n="user")=>e[n]?e:Object.assign({get[n](){var n;if(!Ye().cache)return;return(null===(n=at(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==a?a:e},Ln=(e,t,n="userId",a="user")=>{const s=e,o=t,i=s[o],r=Bn(s,["symbol"==typeof o?o:o+""]),c=$n(i,n,a);return Object.assign(Object.assign({},r),{[t]:c})};function Qn(e){return e.map((e=>{var{isMentioned:t}=e,n=Bn(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function Vn(e){return Qn(e)}function Jn(e){return Qn(e)}const Hn=e=>{var t,n;return null!==(n=null===(t=at(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Gn=e=>new Date(e).getTime(),zn=e=>{var t,n;return null!==(n=null===(t=at(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Yn=e=>{var t;const n=e.messagePreviewId?zn(e.subChannelId):null,a=n?Object.assign(Object.assign({},n),{user:null===(t=at(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:a})},Wn=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:[]};Fn(a)};function Xn(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function Zn(e,t,n){st(["subChannel","get",e],Xn(t,n))}const ea=(e,t)=>{const{log:n,cache:a}=Ye(),s=[e,Se,t];if(!a)return;n("cache/api/isInTombstone",s);const o=at(s),{lifeSpan:i}=Be("cache_then_server",18e4);if(o&&Fe(o.data,i))throw new Ve("Item not found!",400400,"error")},ta=e=>{var t;const n=["channelUnreadInfo","get",e],a=null===(t=at(n))||void 0===t?void 0:t.data,s=nt(["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 st(n,r),r},na=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};Fn({subChannelUnreadInfo:[s]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{ta(e)}))}},aa=async()=>{const e=Ye();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&&Fn({userMarkers:n},{cachedAt:a}),Nt("local.userMarker.fetched",{userMarkers:n});return{data:n.reduce(((e,t)=>null==e||new Date(e.lastSyncAt).getTime()<new Date(t.lastSyncAt).getTime()?t:e),void 0),cachedAt:a}},sa=e=>{var t,n;const a=null===(t=at(["message","get",e]))||void 0===t?void 0:t.data;if(a)return a;const s=nt(["message","get"]);return null===(n=null==s?void 0:s.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data},oa=e=>!0===e&&void 0;function ia(e,t,n){var a,s;if(n)return n.hasMentioned;const o=Ye();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(a=at(["subChannelUnreadInfo","get",t]))||void 0===a?void 0:a.data;return!!e&&e.isMentioned}const i={entityId:e,feedId:t,userId:Ut()._id},r=null===(s=at(["subChannelMarker","get",Ze("subChannelMarker")(i)]))||void 0===s?void 0:s.data;return!!r&&r.hasMentioned}const ra=["broadcast","conversation","community"],ca=({channelType:e})=>ra.includes(e);function da(e){var{channelId:t,channelPublicId:n,channelType:a,childCount:s,creatorId:o,creatorPublicId:i,lastMessageId:r,lastMessageTimestamp:c,messageFeedId:d,name:l}=e,u=Bn(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=Ye();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(a=at(["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:Ut()._id},r=null===(s=at(["subChannelMarker","get",Ze("subChannelMarker")(i)]))||void 0===s?void 0:s.data;return r?r.unreadCount:0}(t,d)},get hasMentioned(){return ia(t,d)},get isMentioned(){return ia(t,d)}},u),{channelId:n,creatorId:i,displayName:l,lastActivity:c,latestMessageId:r,messageCount:s,subChannelId:d,isUnreadCountSupport:ca({channelType:a})})}function la(e,t,n){var a;const s=(e=>{var t,n,a;const s=null===(n=null===(t=nt(["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=Bn(s,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let f;m&&(f=at(["message","get",m])),f||(f=at(["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=Ye(),s=sa(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 ua={},ha=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Fn({messages:(a=e).messages.map((e=>la(e,a.reactions)))});const t=n.join("");ua[t]&&clearTimeout(ua[t]),ua[t]=setTimeout((()=>{try{(async e=>{const t=Ye();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&&Fn({contentMarkers:a,feedMarkers:s,userMarkers:o},{cachedAt:i}),Nt("local.feedMarker.fetched",{feedMarkers:s}),Nt("local.messageMarker.fetched",{contentMarkers:a}),Nt("local.userMarker.fetched",{userMarkers:o})})(n)}catch(e){}}),2e3)}var a;const{messageFeeds:s}=e,o=Bn(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,n;const a=null!==(n=null===(t=at(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},s=Bn(da(e),["unreadCount","isMentioned"]);Zn(e.messageFeedId,a,s)}))),Object.assign(Object.assign({},o),{messages:e.messages.map((n=>la(n,e.reactions,t)))})};function ma(e){var{subChannelId:t,mentionees:n,dataType:a,data:s}=e,o=Bn(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 ga(e){var{sortBy:t,subChannelId:n,includingTags:a,excludingTags:s,includeDeleted:o,aroundMessageId:i,limit:r,type:c}=e,d=Bn(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const l=Object.assign(Object.assign({},d),{messageFeedId:n,isDeleted:oa(o),options:{sortBy:t,limit:r||ge,around:i}});return a&&(l.includeTags=a),c&&(l.dataType=c),s&&(l.excludeTags=s),l}function pa(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const ya=["broadcast","conversation","community"],va=({channelType:e})=>ya.includes(e),fa=async e=>{const t=e.messageFeeds.filter(va).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Fn({messageFeeds:e.messageFeeds.map((e=>da(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=Ye();n.log("channel/getSubChannelMarkers",e,t);const{data:a}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:Ee(t,"skiplimit")}}}),{paging:s}=a,o=Bn(a,["paging"]),{userEntityMarkers:i,userFeedMarkers:r,userMarkers:c,feedMarkers:d}=o;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&na({feedMarkers:d,userFeedMarkers:r});const l=Vn(i),u=Jn(r),h=n.cache&&Date.now();n.cache&&Fn({userEntityMarkers:l,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),Nt("local.channelMarker.fetched",{userEntityMarkers:l}),Nt("local.subChannelMarker.fetched",{userFeedMarkers:u}),Nt("local.userMarker.fetched",{userMarkers:c});const m=Me(s.next);return{data:u,cachedAt:h,prevPage:Me(s.previous),nextPage:m}})(t)}catch(e){}}Wn(e);const n=e.messageFeeds.map(da),a=e.messages.map((e=>la(e))),s=e.users.map(pa);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:a,users:s})};const ba=async e=>{const t=Ye();t.log("channel/getSubChannel",e),ea("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),a=await fa(n.data),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),Nt("local.message-feed.fetched",a),{data:a.messageFeeds[0],cachedAt:s}}catch(t){throw Pe(null==t?void 0:t.code)&&_n("subChannel",e),t}};ba.locally=e=>{const t=Ye();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=at(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ia=async e=>{var t;let n=null===(t=at(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await ba(e)).data),n},Ca=async e=>{const t=await(async()=>Ye().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 Ia(d);"no-message-preview"!==t?(e=>{var t;const n=null===(t=at(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Gn(n.createdAt)<=Gn(e.createdAt)})(e)&&(st(["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}),Zn(e.subChannelId,h,{lastActivity:o,messagePreviewId:a})):Gn(h.lastActivity)<Gn(o)&&Zn(e.subChannelId,h,{lastActivity:o})},wa=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=at(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Ia(d);st(["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})}},Sa=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=at(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Gn(n.createdAt)<=Gn(e.createdAt)})(e)){const u=await Ia(c);st(["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})}},Oa=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=at(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Ia(d);st(["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})}},Aa=async e=>{var t,n,a,s;const{channelId:o,subChannelId:i}=e,r=null===(t=at(["messagePreviewChannel","get",o]))||void 0===t?void 0:t.data;if((null==r?void 0:r.subChannelId)===i){const e=null===(n=at(["subChannel","get",i]))||void 0===n?void 0:n.data;st(["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=at(["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=at(["subChannel","get",i]))||void 0===s?void 0:s.data;st(["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"],Ra=({type:e})=>Ta.includes(e);function Pa(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:a}=e;const s=null===(n=at(["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:Ra(e),messagePreviewId:a})}const Da=(e,t={isMessagePreviewUpdated:!0})=>{Fn({channels:e.channels.map((e=>Pa(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Ua=async(e,t={isMessagePreviewUpdated:!0})=>{const n=Ye(),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=at(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Gn(n.createdAt)<=Gn(e.createdAt)}));0!==n.length&&Fn({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(Ra(t[i])){const r=["channelUnread","get",t[i].channelId],c=n.find((n=>n.channelId===t[i].channelId&&n.userId===e)),d=null===(a=at(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};st(r,p),o.push(p)}o.length>0&&Nt("local.channelUnread.updated",o)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(Ra).map((({channelInternalId:e})=>e));if(n.length>0){Da(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=Ye();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=Vn(a),i=t.cache&&Date.now();return t.cache&&Fn({userEntityMarkers:o,userMarkers:s},{cachedAt:i}),Nt("local.channelMarker.fetched",{userEntityMarkers:o}),Nt("local.userMarker.fetched",{userMarkers:s}),{data:o,cachedAt:i}})(n)}catch(e){}}}const s=e.channels.map((e=>Pa(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),o=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(Ye().cache)return(null===(e=at(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),i=e.users.map(pa),r=Bn(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},r),{users:i,channels:s,channelUsers:o})},ja=async e=>{const t=Ye();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return Nt("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},ka=async e=>{const t=Ye(),n=await ja(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:a,userFeedMarkers:s}=n;na({feedMarkers:a,userFeedMarkers:s}),t.log("channel/prepareUnreadCountInfo",e.channels)},Ea=(e,t)=>{var n,a,s,o;const i=Ye();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=at(["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:Ut()._id};return null===(t=at(["channelMarker","get",Ze("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===s?void 0:s.hasMentioned)&&void 0!==o&&o},Ma=(e,t)=>{var n,a,s,o,i;const r=Ye();return r.isUnreadCountEnabled&&r.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=at(["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:Ut()._id};return null===(t=at(["channelMarker","get",Ze("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===o?void 0:o.unreadCount)&&void 0!==i?i:0},qa=e=>{var t;return null===(t=at(["channelUnread","get",e]))||void 0===t?void 0:t.data},xa=e=>{const t=Ye(),n=Bn(e,["messageCount"]);return Xn(n,{get unreadCount(){var e,t;return null!==(t=null===(e=qa(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Ma(n)},get isMentioned(){var e,a;return t.useLegacyUnreadCount?null!==(a=null===(e=qa(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==a&&a:Ea(n)}})},Na=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],a=null===(t=at(n))||void 0===t?void 0:t.data;return a?Bt(a):void 0})()}}),Ka=e=>{const t=Ye();t.log("channel/getMyMembership.locally");const n=at(["channelUsers","get",`${e}#${t.userId}`]);if(!n)throw new Ve("Item not found!",400400,"error");return{data:n.data,cachedAt:n.cachedAt}};function Fa(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(!Fa(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=>Fa(e[n],t[n])))}const _a=[];let Ba=null;const $a=e=>{if(0===_a.length){const e=Ye();Ba=xt(e,"onChannelCreated","channel.created",(async e=>{const t=await Ua(e);Fn(t),_a.forEach((e=>e(t.channels[0])))}))}return _a.push(e),()=>(e=>{const t=_a.indexOf(e);t>-1&&_a.splice(t,1),0===_a.length&&(null==Ba||Ba())})(e)},La=[],Qa=[],Va=e=>{const t=Ye();if(0===La.length){const e=async e=>{const t=await Ua(e);Fn(t),La.forEach((e=>e(t.channels[0])))};Qa.push(xt(t,"onChannelUpdated","channel.updated",e)),Qa.push(xt(t,"onChannelUpdated","local.channel.updated",(e=>La.forEach((t=>t(e.channels[0]))))))}return La.push(e),()=>(e=>{const t=La.indexOf(e);t>-1&&La.splice(t,1),0===La.length&&Qa.forEach((e=>e()))})(e)},Ja=e=>{const t=nt(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{st(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Ha=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=at(n))||void 0===t?void 0:t.data)&&rt(n)},Ga=[];let za=null;const Ya=e=>{if(0===Ga.length){const e=Ye(),t=async t=>{const n=await Ua(t),a=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,s=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(a)Ja(e.channelId),Ha(e.channelId);else if(s){const t=["channelUnread","get",e.channelId],n=at(t);n&&st(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Fn(n),Ga.forEach((e=>e(n.channels[0])))};za=xt(e,"onChannelDeleted","channel.deleted",t)}return Ga.push(e),()=>(e=>{const t=Ga.indexOf(e);t>-1&&Ga.splice(t,1),0===Ga.length&&(null==za||za())})(e)},Wa=[];let Xa=null;const Za=e=>{if(0===Wa.length){const e=Ye();Xa=xt(e,"onChannelJoined","channel.joined",(async e=>{const t=await Ua(e),{channels:n,channelUsers:a}=t;Fn(t),Wa.forEach((e=>e(n[0],a[0])))}))}return Wa.push(e),()=>(e=>{const t=Wa.indexOf(e);t>-1&&Wa.splice(t,1),0===Wa.length&&(null==Xa||Xa())})(e)},es=[];let ts=null;const ns=e=>{if(0===es.length){const e=Ye(),t=async t=>{const{userId:n}=Ye(),{channelUsers:a}=t,s=a.some((e=>e.userId===n)),o=await Ua(t,{isMessagePreviewUpdated:s}),i=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,r=e.useLegacyUnreadCount;s&&o.channels.forEach((e=>{i?(Ja(e.channelId),Ha(e.channelId)):r&&rt(["channelUnread","get",e.channelId])}));const{channels:c,channelUsers:d}=o;Fn(o),es.forEach((e=>e(c[0],d[0])))};ts=xt(e,"onChannelLeft","channel.left",t)}return es.push(e),()=>(e=>{const t=es.indexOf(e);t>-1&&es.splice(t,1),0===es.length&&(null==ts||ts())})(e)},as=[];let ss=null;const os=e=>{if(0===as.length){const e=Ye(),t=async e=>{var t;it(["channel","get",e.channelId],{isMuted:Date.parse(e.muteTimeout)>Date.now()});const n=null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data;n&&as.forEach((e=>e(n)))};ss=xt(e,"onChannelMute","channel.setMuted",t)}return as.push(e),()=>(e=>{const t=as.indexOf(e);t>-1&&as.splice(t,1),0===as.length&&(null==ss||ss())})(e)},is=[];let rs=null;const cs=e=>{if(0===is.length){const e=Ye();rs=xt(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await Ua(e),{channels:n,channelUsers:a}=t;Fn(t),is.forEach((e=>e(n[0],a.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==rs||rs())})(e)},ds=[];let ls=null;const us=e=>{if(0===ds.length){const e=Ye();ls=xt(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await Ua(e),{channels:n,channelUsers:a}=t;Fn(t),ds.forEach((e=>e(n[0],a[0])))}))}return ds.push(e),()=>(e=>{const t=ds.indexOf(e);t>-1&&ds.splice(t,1),0===ds.length&&(null==ls||ls())})(e)},hs=[];let ms=null;const gs=e=>{const t=Ye();return ms=xt(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await Ua(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),Ha(e.channelId)})),Fn(n),hs.forEach((e=>e(a[0],s.find((e=>"banned"===e.membership)))))})),hs.push(e),()=>(e=>{const t=hs.indexOf(e);t>-1&&hs.splice(t,1),0===hs.length&&(null==ms||ms())})(e)},ps=[];let ys=null;const vs=e=>{if(0===ps.length){const e=Ye();ys=xt(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await Ua(e),{channels:n,channelUsers:a}=t;Fn(t),ps.forEach((e=>e(n[0],a.find((e=>"none"===e.membership)))))}))}return ps.push(e),()=>(e=>{const t=ps.indexOf(e);t>-1&&ps.splice(t,1),0===ps.length&&(null==ys||ys())})(e)},fs=[];let bs=null;const Is=e=>{if(0===fs.length){const e=Ye();bs=xt(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;fs.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return fs.push(e),()=>(e=>{const t=fs.indexOf(e);t>-1&&fs.splice(t,1),0===fs.length&&(null==bs||bs())})(e)},Cs=[];let ws=null;const Ss=e=>{if(0===Cs.length){const e=Ye();ws=xt(e,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async e=>{const{channels:t,channelUsers:n}=e;Cs.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return Cs.push(e),()=>(e=>{const t=Cs.indexOf(e);t>-1&&Cs.splice(t,1),0===Cs.length&&(null==ws||ws())})(e)},Os=e=>{const t=Ye();return xt(t,"onChannelArchived","local.channel.archived",(async t=>{e(t)}))},As=e=>{const t=Ye();return xt(t,"onChannelUnarchived","local.channel.unarchived",(async t=>{e(t)}))},Ts=[];let Rs=null;const Ps=e=>{if(0===Ts.length){const e=Ye(),t=async e=>{var t,n,a;e.userIds.forEach((t=>it(["channelUsers","get",`${e.channelId}#${t}`],{isMuted:Date.parse(e.muteTimeout)>Date.now()})));const s=null===(n=null===(t=nt(["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=at(["channelUsers","get",`${e.channelId}#${e.userIds[0]}`]))||void 0===a?void 0:a.data;s&&o&&Ts.forEach((e=>e(s,o)))};Rs=xt(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==Rs||Rs())})(e)},Ds=e=>{var t;let n=[];if(["conversation","community"].includes(e.type)){const a=nt(["channelUsers","get"]);a&&(null==a?void 0:a.length)>0&&(n=(null!==(t=null==a?void 0:a.filter((({data:t})=>t.channelId===e.channelId&&"none"!==t.membership)))&&void 0!==t?t:[]).sort(((e,t)=>e.data.userInternalId.localeCompare(t.data.userInternalId))).slice(0,4).map((({data:e})=>Na(e))))}return Xn(e,{markAsRead:()=>(async e=>{const t=Ye();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=Bn(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),r=t.cache&&Date.now(),c=Vn(s),d=Jn(o);return t.cache&&Fn(Object.assign({userMarkers:a,userEntityMarkers:c,userFeedMarkers:d},i),{cachedAt:r}),Nt("local.channelMarker.updated",{userEntityMarkers:c}),Nt("local.subChannelMarker.updated",{userFeedMarkers:d}),!0})(e.channelInternalId),previewMembers:n,myMembership:t=>((e,t)=>{const{_id:n}=Ut();if(!n)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:a,cache:s}=Ye();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?Na(e.data):e.data}))},c=(t,n)=>{const{data:a}=Ka(e);Fa(void 0,a)||r({loading:!1,data:a})};return o.push(gs(c)),o.push(vs(c)),o.push(Ps(c)),(()=>{const t=_e((async()=>Ka(e)));$e(t,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{s===be?(r({data:t,origin:a,loading:!1,error:new Ve(fe,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=at(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}})},Us=e=>Ds(xa((e=>{var t;const n=e.messagePreviewId?Hn(e.channelId):null,a=null===(t=at(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,s=n?Object.assign(Object.assign({},n),{user:a?Bt(a):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})})(e))),js=async e=>{const t=Ye();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=>{Pe(null==t?void 0:t.code)&&_n("channel",e)})),t}const s=await Ua(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ka(a);const o=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:o}),Nt("local.channel.fetched",s.channels),{data:s.channels.map((e=>Us(e))),cachedAt:o}};js.locally=e=>{var t,n;const a=Ye();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const s=null===(t=nt(["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=>Us(e))),cachedAt:i.cachedAt}};const ks=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let Es=!1;const Ms={},qs=async()=>{const e=Object.entries(Ms).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=Ye();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=Vn(a),c=Jn(s),d=t.cache&&Date.now();return t.cache&&Fn({userEntityMarkers:r,userFeedMarkers:c,feedMarkers:o,userMarkers:i},{cachedAt:d}),Nt("local.feedMarker.fetched",{feedMarkers:o}),Nt("local.channelMarker.fetched",{userEntityMarkers:r}),Nt("local.subChannelMarker.fetched",{userFeedMarkers:c}),Nt("local.userMarker.fetched",{userMarkers:i}),!0})(e)},xs=()=>{Es=!1},Ns=()=>(Es=!0,In((e=>{"notLoggedIn"===e&&xs()})),()=>{xs()});ks((async()=>{Es&&await qs()}),3e4);const Ks=async e=>{const t=Ye();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),a=await fa(n.data),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),Nt("local.message-feed.fetched",a),{data:a.messageFeeds,cachedAt:s}};Ks.locally=e=>{var t;const n=Ye();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const a=e.map((e=>at(["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 Fs=async(e=!0)=>{var t;const n=null===(t=at(["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"},_s=async()=>{var e;const t=await Fs();if(t===(null===(e=at(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;st(["MessagePreviewSetting"],t);const n=[],a=[];if("no-message-preview"===t){const e=nt(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{rt(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=nt(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(rt(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&a.push(t.subChannelId))})),0!==n.length&&await js(n),0!==a.length&&await Ks(a)}},Bs=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},$s=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/users");return t},Ls={mode:e.AmityLiveViewerCountMode.ALWAYS_SHOW,threshold:50},Qs=async()=>{var t,n;const a=Ye(),{data:s}=await a.http.get("/api/v3/network-settings/video-streaming"),o=null===(t=null==s?void 0:s.videoStreaming)||void 0===t?void 0:t.viewerCountDisplayMode,i=null===(n=null==s?void 0:s.videoStreaming)||void 0===n?void 0:n.viewerCountDisplayMinimum;return(r=o)!==e.AmityLiveViewerCountMode.ALWAYS_SHOW&&r!==e.AmityLiveViewerCountMode.HIDE_ENTIRELY&&r!==e.AmityLiveViewerCountMode.SHOW_ABOVE_MINIMUM||!(e=>"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=1e3)(i)?(a.log("client/getLiveViewerCountConfig","malformed videoStreaming settings, falling back to default",{mode:o,threshold:i}),Ls):{mode:o,threshold:i};var r},Vs=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/product");return t},Js=async()=>{var e,t;const n=Ye(),{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}}},Hs=(e,t)=>{var n;const a=null===(n=at(["user","get",e]))||void 0===n?void 0:n.data;return!!a&&a.permissions.some((e=>e===t))},Gs=e=>{const{userId:t}=Ye();return{currentUser:()=>Hs(t,e),community:n=>((e,t,n)=>{var a;if(!e)return!1;const s=null===(a=at(["communityUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!s&&(!!s.permissions.some((e=>e===t))||Hs(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var a;if(!e)return!1;const s=null===(a=at(["channelUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!s&&(!!s.permissions.some((e=>e===t))||Hs(e,t))})(t,e,n)}},zs=async e=>{const t=Ye();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},Ys=async e=>{const t=Ye();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},Ws=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Xs={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Zs=(e,t)=>{const n=Ye();n.log("client/api/setSessionState",e,t);const{sessionState:a}=n;if(a===e)return!1;if(!((e,t)=>Xs[e].includes(t))(a,e))throw new Qe(`Session state cannot change from ${a} to ${e}`,8e5,"error");return n.sessionState=e,bn().setSessionState(e,t),!0};function eo(e){return{users:e.users.map(pa),files:e.files}}const to=async e=>{const t=Ye();Zs("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getToken",e);const a=Mn(),{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},Zs("established"),Fn(eo({users:a,files:r})),{accessToken:n,users:a,userType:i}},no=async e=>{const t=Ye();Zs("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getVisitorToken",e);const a=Mn(),{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},Zs("established"),Fn(eo({users:a,files:r})),{accessToken:n,users:a,userType:i}},ao=async()=>{var e;const t=Ye();return t.log("client/api/disconnectClient"),t.mqtt&&t.mqtt.connected&&await t.mqtt.disconnect({endSession:!0}),"established"===t.sessionState&&Zs("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.isGloballyBanned=!1,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},so=e=>{const t=Ye();Zs("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,ao()};let oo=null;const io=e=>{oo=e},ro=({user:e,userType:t})=>{jt(e),io(t)},co=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=eo(e);n.cache&&Fn(a),t(a.users[0])}))},lo=e=>co("user.deleted",e),uo=["analytic","normal-priority"],ho=["analytic","high-priority"],mo=async e=>{const t=Ye(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class go{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=at(uo);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await mo(t),rt(uo)}catch(e){this.stop(),rt(uo)}}async syncHighPriorityCapturedEvent(){try{const e=at(ho);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await mo(t),rt(ho)}catch(e){this.stop(),rt(ho)}}}class po{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=at(uo);(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),it(uo,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=at(["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=at(ho);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()}),it(ho,s),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;st(["story-seen","get",e.storyId],(new Date).toISOString());const i=at(["story-last-seen",e.targetId]);(null==i?void 0:i.data)?new Date(i.data).getTime()<new Date(e.expiresAt).getTime()&&st(["story-last-seen",e.targetId],e.expiresAt):st(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),Nt("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},rt(uo),rt(ho)}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 yo{constructor(){this._client=Ye(),this._eventCapturer=new po,this._eventSyncer=new go}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 vo;var fo=()=>(vo||(vo=new yo),vo),bo=()=>{const e=fo();return e.established(),In((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}};class Io{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ye(),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=nt(["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=at(["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=Ye();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=at(a))||void 0===t?void 0:t.data;st(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=at(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),st(a,s),Nt("local.channelUnread.updated",[s])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=at(["readReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)st(["readReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{st(["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 Co=null;var wo=()=>(Co||(Co=new Io),Co),So=()=>{const e=wo();return e.startSyncReadReceipt(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Oo{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ye(),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=nt(["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=at(["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=Ye();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=at(["legacyReadReceipt",a]))||void 0===t?void 0:t.data;st(["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=at(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=ta(s.channelId);Nt("local.channelUnreadInfo.updated",e),st(a,s),Nt("local.subChannelUnread.updated",s)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=at(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)st(["legacyReadReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{st(["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 Ao=null;var To=()=>(Ao||(Ao=new Oo),Ao),Ro=()=>{const e=To();return e.startSyncReadReceipt(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const Po=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")},Do=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")},Uo=async e=>{const t=Ye();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=>{Pe(null==t?void 0:t.code)&&_n("channel",e)})),t}const s=await Ua(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ka(a);const o=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:o}),Nt("local.channel.fetched",s.channels),{data:s.channels,cachedAt:o}};Uo.locally=e=>{var t,n;const a=Ye();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const s=null===(t=nt(["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 jo{constructor(){this.TIMER_INTERVAL_MS=Ie,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(Po((()=>{this.isConnected=!0}))),this.connectionListener.push(Do((()=>{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 Uo(e);const s=null!==(a=null===(n=null===(t=nt(["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:[];Nt("local.channel.resolved",s)})(e),t.length>0&&(async e=>{const t=await ja(e),{feedMarkers:n,userFeedMarkers:a}=t;na({feedMarkers:n,userFeedMarkers:a}),Nt("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 ko=null;var Eo=()=>(ko||(ko=new jo),ko),Mo=()=>{const e=Eo();return e.startResolver(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class qo{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(Po((()=>{this.isConnected=!0}))),this.connectionListener.push(Do((()=>{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=Bn(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=Ye();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 xo;var No=()=>(xo||(xo=new qo),xo);function Ko(e){const{users:t,follows:n}=e,a=Bn(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:pa(n)})})),users:t.map(pa)})}class Fo{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=Ye(),{data:t}=await e.http.get("/api/v4/me/user-blocks",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=Ko(t);e.cache&&Fn(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ye();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=nt(["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=at(["user","get",e.to]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(Bt)}}let _o=null;var Bo=()=>(_o||(_o=new Fo),_o);function $o(e){const{users:t,follows:n}=e,a=Bn(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:pa(n)})})),users:t.map(pa)})}class Lo{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=Ye(),{data:t}=await e.http.get("/api/v4/me/blockers",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=$o(t);e.cache&&Fn(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ye();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=nt(["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=at(["user","get",e.from]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(Bt)}}let Qo=null;var Vo=()=>(Qo||(Qo=new Lo),Qo);function Jo(e){const{users:t,follows:n}=e,a=Bn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(pa)})}function Ho(e){const{users:t,follows:n}=e,a=Bn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(pa)})}function Go(e){const{follows:t}=e,n=Bn(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const zo=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Jo(e);n.cache&&Fn(a),t(a.follows[0])}))},Yo=e=>zo("user.didBlock",e),Wo=e=>zo("user.didUnblock",e);class Xo{constructor(e,t){this.networkId=e,this.userId=t}static current(){try{const e=$t();if(!e)return null;const t=Vt(e),{userId:n}=e;return t&&n?new Xo(t,n):null}catch(e){return null}}static isExpired(e){return Date.now()>=e}static clearOnLogout(){return In((e=>{var t;"terminated"===e&&(null===(t=Xo.current())||void 0===t||t.clear())}))}get key(){return`amity:forYouFeed:cursor:${this.networkId}:${this.userId}`}async get(){const e=await Un(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 Dn(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 Dn(this.key,"")}}const Zo=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],ei=e=>{const t=Ye(),n=Zo.map((n=>xt(t,`client/onConnectionError(${n})`,n,(t=>{const a=(null==t?void 0:t.code)?new Qe(t.message,t.code,"fatal"):new He(n);e(a)}))));return()=>{n.forEach((e=>e()))}},ti=e=>{const t=Ye();return xt(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},ni=e=>{const t=Ye();return xt(t,"client/onTokenExpired","tokenExpired",e)},ai=e=>{const t=Ye();return xt(t,"client/onTokenTerminated","tokenTerminated",e)},si=e=>{const t=Ze("channelMarker")({userId:Ut()._id,entityId:e.channelId});rt(["channelMarker","get",t],!0)},oi=e=>{const t=Ye(),n=[];return n.push(ti((t=>{so("globalBan"),n.forEach((e=>e())),e()})),ai((t=>{so(),n.forEach((e=>e())),e()})),lo((a=>{a.userId===t.userId&&(so("userDeleted"),n.forEach((e=>e())),e())})),ni((e=>{bn().setSessionState(e),ao(),n.forEach((e=>e()))})),Ya(si),gs(si),Ns(),bo(),Mo(),(()=>{const e=No();return e.startReactionsSync(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=Bo();return In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=Vo();return In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=[Yo((()=>{})),Wo((()=>{}))];return()=>e.forEach((e=>e()))})(),In((e=>{"established"!==e&&Tn().reset()})),Xo.clearOnLogout()),t.useLegacyUnreadCount?n.push(So()):n.push(Ro()),n};let ii=[];const ri=async(e,t,n)=>{const a=Ye();let s;a.log("client/api/connectClient",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&a.userId!==e.userId&&(await ao(),ii.forEach((e=>e())),ii=[]);const o=await En();try{const{users:n,userType:i}=await to({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 Qe(`${e.userId} has not been founded`,8e5,"error");if(r.isDeleted)return so("userDeleted"),!1;if(r.isGlobalBan)return so("globalBan"),!1;a.userId=r.userId,a.sessionHandler=t,a.loginType="userId",s=a.accessTokenExpiryWatcher(),ro({user:r,userType:i})}catch(e){throw bn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await _t()}(),await _s(),0===ii.length&&(ii=oi(s)),!0},ci=[],di=async e=>{const t=Ye();let n;t.log("client/api/connectClient",Object.assign({apiKey:t.apiKey,sessionState:t.sessionState},e));const a=await En();let s;try{const{users:o,userType:i}=await no({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(),ro({user:s,userType:i})}catch(e){throw bn().setSessionState("notLoggedIn"),e}return await _s(),0===ci.length&&ci.push(ai((e=>{so(),ci.forEach((e=>e())),n()})),ni((e=>{bn().setSessionState(e),ao(),ci.forEach((e=>e()))}))),!0},li=()=>{let e,t=!1;const n=Ye();n.log("initiating access token renewal");const a=async a=>{const{userId:s,displayName:o}=Ut(),i={userId:s,displayName:o,authToken:a,deviceId:await En()};"tokenExpired"===n.sessionState&&n.sessionHandler?await ri(i,n.sessionHandler):await to({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(li())}),Ce)},renewWithAuthSignature:a=>{t?console.log("'renew' method can be called only once per renewal instance"):(async({authSignature:a,authSignatureExpiresAt:s})=>{const o=await En();"tokenExpired"===n.sessionState&&n.sessionHandler?await di({sessionHandler:n.sessionHandler}):await no({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(li())}),Ce)}}},ui=async({token:e,userId:t})=>{const n=Ye(),{data:a}=await n.http.get("/api/v4/sessions",{headers:{Authorization:`Bearer ${e.accessToken}`}}),{users:s,files:o,userType:i}=a,[r]=s;return t&&(null==r?void 0:r.userId)&&t!==r.userId&&n.log("client/api/validateAccessToken",{message:"session userId does not match the token userId; using the server value",tokenUserId:t,sessionUserId:r.userId}),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,Fn(eo({users:s,files:o})),io(i),r},hi=e=>{var t;const n=Ye(),a=T.default(e);return(null===(t=null==a?void 0:a.user)||void 0===t?void 0:t.publicUserId)===n.userId};let mi=[];const gi=async e=>{var t,n;const a=Ye();let s,o;if(a.log("client/api/loginWithAccessToken",{apiKey:a.apiKey,sessionState:a.sessionState}),!e||"string"!=typeof e||""===e.trim())throw new Qe("Access token must be a non-empty string",8e5,"error");try{o=T.default(e)}catch(e){throw new Qe("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 Qe("Access token does not contain userId",400100,"error");if(a.userId){hi(e)||await ao()}try{Zs("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 ui({token:t,userId:i});if(null==n)throw Zs("notLoggedIn"),new Qe(`User ${i} has not been found`,8e5,"error");a.userId=n.userId,a.loginType="accessToken",jt(n),s=a.accessTokenExpiryWatcher(),Zs("established")}catch(e){if(Zs("notLoggedIn"),e instanceof Qe)throw 400312===e.code&&(a.isGloballyBanned=!0),e;throw new Qe((e instanceof Error?e.message:void 0)||"Login with access token failed",400100,"error")}return async function(){await _t()}(),await _s(),0===mi.length&&(mi=oi(s)),!0},pi=async e=>{var t,n;const a=Ye();if(a.log("initiating access token renewal"),!e||"string"!=typeof e||""===e.trim())throw new Qe("Access token must be a non-empty string",8e5,"error");let s;try{s=T.default(e)}catch(e){throw new Qe("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 Qe("Access token does not contain userId",400100,"error");if(a.userId){hi(e)||await ao()}const i={accessToken:e,issuedAt:s.iat?new Date(1e3*s.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*s.exp).toISOString()};if("tokenExpired"===a.sessionState&&a.sessionHandler)await gi(e);else try{await ui({token:i,userId:o})}catch(e){throw e instanceof Qe&&400312===e.code&&(a.isGloballyBanned=!0),e}},yi=async({useScheduledTask:e=!1})=>{const t=Ye();if(t.userId&&t.accessTokenHandler&&!t.isGloballyBanned)try{const n=await t.accessTokenHandler.onTokenRenew(t.userId);e?Mt((()=>pi(n))):pi(n)}catch(e){t.log("Proactive token renewal failed, will retry when token expires",e)}},vi=3e5,fi=()=>{const e=setInterval((async()=>{const e=Ye(),{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)-vi)(o))return Nt("tokenExpired","tokenExpired"),void("accessToken"===a&&n?await yi({useScheduledTask:!1}):"userId"===a&&t&&Mt((()=>t.sessionWillRenewAccessToken(li()))));(e=>{const{expiresAt:t,issuedAt:n}=e,a=Date.parse(t),s=Date.parse(n),o=Date.now();return o>s+.8*(a-s-vi)&&o<a})({expiresAt:o,issuedAt:s})&&("accessToken"===a&&n?await yi({useScheduledTask:!1}):"userId"===a&&t&&t.sessionWillRenewAccessToken(li()))}),Ce);return()=>clearInterval(e)},bi=e=>{if(Ye().useLegacyUnreadCount){wo().markRead(e.channelId,e.channelSegment)}else{To().markRead(e.subChannelId,e.channelSegment)}},Ii=e=>{const t=Ye(),n=Ut(),a=[xt(t,"message/onMessageCreated","message.created",(async a=>{const s=await ha(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messages.forEach((e=>{(e=>{var t;const n=Ye(),a=["subChannelUnreadInfo","get",e.messageFeedId],s=null===(t=at(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)});st(a,c)})(e),ta(e.channelId)})),t.useLegacyUnreadCount&&a.messages.forEach((e=>{var n,a,s;const o=null===(n=at(["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});st(["channelUnread","get",e.channelId],d),Nt("local.channelUnread.updated",[d])})),Fn(s),s.messages.forEach((t=>{t.creatorPrivateId===n._id&&bi(t),e(t)}))}))];return()=>{a.forEach((e=>e()))}},Ci=e=>{const t=Ye(),n=[xt(t,"message/onMessageCreated","local.message.created",(async t=>(Fn(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},wi=e=>{const t=Ye();return xt(t,"onSubChannelCreated","message-feed.created",(async n=>{const a=await fa(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};st(["subChannelUnreadInfo","get",o.subChannelId],o)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Fn(a),e(a.messageFeeds[0])}))},Si=e=>{const t=Ye(),n=[xt(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const a=await fa(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],a=null===(t=at(n))||void 0===t?void 0:t.data;a&&st(n,Object.assign(Object.assign({},a),{isDeleted:!0}))})(e.subChannelId),ta(e.channelId)})),Fn(a),e(a.messageFeeds[0])})),xt(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Oi=async e=>{const t=Ye();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=Vn(a),c=Jn(s),d=t.cache&&Date.now();return t.cache&&Fn({userEntityMarkers:r,userFeedMarkers:c,feedMarkers:o,userMarkers:i},{cachedAt:d}),Nt("local.feedMarker.fetched",{feedMarkers:o}),Nt("local.channelMarker.fetched",{userEntityMarkers:r}),Nt("local.subChannelMarker.fetched",{userFeedMarkers:c}),Nt("local.userMarker.fetched",{userMarkers:i}),{data:n,hasMore:n.feedMarkers.length>0}};let Ai=!1,Ti=[],Ri=!1;let Pi=null;let Di=[];const Ui=e=>{Di=e},ji=async()=>{var e;if(!Ri&&0!==Di.length)try{Ri=!0,Di=[];const t=await Oi((null==Pi?new Date:Pi).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)&&(!Pi||e.getTime()>Pi.getTime())&&(Pi=e),t.hasMore&&Di.push("has_more")}catch(e){}finally{Ri&&(Ri=!1)}};ks((async()=>{Ai&&await ji()}),2e3);const ki=()=>true,Ei=e=>{var t;const n=Ye();if(n.mqtt)return null===(t=n.mqtt)||void 0===t?void 0:t.listen(e)},Mi=async()=>{const e=Ye(),t=await En(),{data:{status:n,error:a}}=await e.http.delete("/v1/notification",{params:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(a)throw new Ve(a,5e5,"error");return"success"===n};let qi=[];var xi;class Ni{constructor(){xi.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,xi,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,xi,"f")}}let Ki;xi=new WeakMap;var Fi=()=>(Ki||(Ki=new Ni),Ki);const _i={[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"}},Bi=async e=>{const t=Ye();Zs("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getBotToken");const a=Mn(),{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},Zs("established"),Fn(eo({users:a,files:r})),{accessToken:n,users:a,userType:i}},$i=[];function Li(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 Qi(t){return(null==t?void 0:t.type)===e.NotificationRolesFilterTypeEnum.ONLY?{listenFromRoleIds:t.roleIds}:{listenFromRoleIds:[]}}class Vi{constructor(e){this.channelId=e}async enable(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!0};await t.http.post("/api/v3/notification/setting",n)}async disable(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!1};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){const t=Ye(),{data:n}=await t.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.CHANNEL}&channelId=${encodeURIComponent(this.channelId)}`);return{isEnabled:n.isPushNotifiable}}}class Ji{async enable(t){var n;const a=Ye(),s=null!==(n=null==t?void 0:t.map((e=>Object.assign({moduleName:e.moduleName,isPushNotifiable:e.isEnabled},Qi(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=Ye(),n={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=Ye(),{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:Li(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,modules:o}}}class Hi{constructor(e){this.communityId=e}async enable(t){var n;const a=Ye(),s=null!==(n=null==t?void 0:t.map((t=>Object.assign({moduleName:e.UserNotificationModuleNameEnum.SOCIAL,name:t.eventName,isPushNotifiable:t.isEnabled},Qi(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=Ye(),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=Ye(),{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:Li(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,events:o}}}class Gi{user(){return new Ji}community(e){return new Hi(e)}channel(e){return new Vi(e)}}const zi=e=>{const t=Ye();return xt(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},Yi=e=>{const t=Ye();return xt(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},Wi=e=>{const t=Ye();return xt(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},Xi=e=>{const t=Ye();return xt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},Zi=e=>{const t=Ye();return xt(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},er=e=>{const t=Ye();return xt(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,a,s;Fn(t);const o=nt(["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=>at(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==s?s:[]).forEach((e=>{var t,n;const a=["messageMarker","get",Ze("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],s=null===(t=at(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});st(a,e)}}))}}e(t.contentMarkers[0])}))};function tr(e){return"object"==typeof e&&null!==e}const nr=e=>{if(!tr(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)},ar=e=>{if(!tr(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var sr=Object.freeze({__proto__:null,getActiveClient:Ye,getActiveUser:Ut,setActiveUser:jt,createClient:(e,t=on.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&&!sn,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:cn("http",t),u=null!==(r=null==a?void 0:a.upload)&&void 0!==r?r:cn("upload",t),h=null!==(c=null==a?void 0:a.mqtt)&&void 0!==c?c:cn("mqtt",t),m=yn(l),g=yn(u);let p;o&&(p=Nn(h));const y=b.default(),v={version:`${me}`,apiKey:e,log:d,cache:{data:{}},http:m,ws:undefined,mqtt:p,upload:g,emitter:y,sessionState:"notLoggedIn",accessTokenExpiryWatcher:fi,sessionHandler:undefined,hasPermission:Gs,validateUrls:zs,validateTexts:Ys,getFeedSettings:Ws,getCoreUserSettings:$s,getSocialSettings:Bs,getChatSettings:Kn,getLiveViewerCountConfig:Qs,getVisitorDeviceId:En,getMessagePreviewSetting:Fs,onRTEConnectionStateChange:Ei,use:()=>We(v),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:ki,getProductCatalogueSetting:Vs,getForYouFeedSetting:Js,prefixDeviceIdKey:s};try{const t=Ye();if(t.apiKey===e)return t;We(v)}catch(e){We(v)}return v},login:ri,loginWithAccessToken:gi,logout:ao,secureLogout:async()=>{const e=Ye();try{await Mi()}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 ao()},resumeSession:async(e,t,n)=>{const a=Ye();let s;a.log("client/api/resumeSession",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&(a.userId===e.userId&&hi(e.token.accessToken)?(a.mqtt&&a.mqtt.connected&&a.mqtt.disconnect(),qi.forEach((e=>e())),qi=[]):(await ao(),qi.forEach((e=>e())),qi=[]));try{Zs("establishing");const n=await ui(e);if(null==n)throw new Qe(`${e.userId} has not been found`,8e5,"error");a.userId=n.userId,a.sessionHandler=t,s=a.accessTokenExpiryWatcher(),jt(n)}catch(e){throw bn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await _t()}(),await _s(),0===qi.length&&(qi.push(ti((e=>{so("globalBan"),qi.forEach((e=>e())),s()})),ai((e=>{so(),qi.forEach((e=>e())),s()})),lo((e=>{e.userId===a.userId&&(so("userDeleted"),qi.forEach((e=>e())),s())})),ni((e=>{bn().setSessionState(e),ao(),qi.forEach((e=>e()))})),Ya(si),gs(si),Ns(),bo(),Mo()),a.useLegacyUnreadCount?qi.push(So()):qi.push(Ro())),!0},isConnected:()=>{var e,t;const n=Ye();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:Ws,renewal:li,markerSync:Oi,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){Fi().setFileAccessType(e)},registerPushNotification:async e=>{const t=Ye();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new Ge("Unsupported platform");n=l.Platform.OS;const a=await En(),{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 Ve(o,5e5,"error");return"success"===s},unregisterPushNotification:Mi,onRTEConnectionStateChange:Ei,fetchLinkPreview:async e=>{const t=Ye();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=Ye(),{data:n}=await t.http.get(`/api/v1/link-preview?url=${e}`);return n},getSocialSettings:Bs,getShareableLinkConfiguration:async()=>{var e,t;const n=Ye(),{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}=_i[e];return!!s&&!!o[t]},getPattern(e){const{key:t}=_i[e];return o[t]||null},generateLink(e,t){const{key:n,placeholder:a}=_i[e];return s&&o[n]?s+o[n].replace(`{${a}}`,t):null}}},getProductCatalogueSetting:Vs,getForYouFeedSetting:Js,loginAsVisitor:di,loginAsBot:async e=>{const t=Ye();let n;t.log("client/api/connectClient",{apiKey:t.apiKey,sessionState:t.sessionState});const a=await En();let s;try{const{users:o,userType:i}=await Bi({params:{deviceId:a},options:{setAccessTokenCookie:!0}});[s]=o,t.userId=s.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),ro({user:s,userType:i})}catch(e){throw bn().setSessionState("notLoggedIn"),e}return await _s(),0===$i.length&&$i.push(ai((e=>{so(),$i.forEach((e=>e())),n()})),ni((e=>{bn().setSessionState(e),ao(),$i.forEach((e=>e()))}))),!0},getCurrentUser:$t,getCurrentUserType:()=>{if(!oo)throw new Qe("Connect client first",8e5,"fatal");return oo},setCurrentUserType:io,setAccessTokenHandler:e=>{const t=Ye();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,getLiveViewerCountConfig:Qs,getCoreUserSettings:$s,notifications:()=>new Gi,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:ei,onClientDisconnected:e=>ei((({code:t})=>{800211===t&&e()})),onClientBanned:ti,onSessionStateChange:In,onNetworkActivities:e=>hn().onNetworkActivities(e),onVisitorUsageLimitReached:e=>{const t=Ye();return xt(t,"client/onVisitorUsageLimitReached","visitorUsageLimitReached",e)},getUserUnread:e=>{const{_id:t}=Ut();if(!t)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=Ye();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?nr(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return s.push(Xi((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))};Fa(o,i)||r({loading:!1,data:i})})(e)))),(()=>{const e=_e(aa);$e(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===be?(r({data:t,origin:a,loading:!1,error:new Ve(fe,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:()=>Di,setMarkerSyncEvents:Ui,pushMarkerSyncEvent:e=>Di.push(e),markerSyncTrigger:ji,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{Ai=!1,Ui([]),Ti.forEach((e=>e())),Ti=[]},getMarkerSyncConsistentMode:ki});const or=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Jo(e);n.cache?(Fn(a),t(a.follows[0])):t(a.follows[0])}))},ir=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Go(e);n.cache?(Fn(a),t(a.follows[0])):t(a.follows[0])}))},rr=e=>or("follow.created",e),cr=e=>or("follow.unfollowed",e),dr=e=>or("follow.followerDeleted",e),lr=e=>or("follow.requested",e),ur=e=>or("follow.requestCanceled",e),hr=e=>or("follow.accepted",e),mr=e=>or("follow.requestDeclined",e),gr=async e=>{var t,n;const a=Ye();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&&st(["followInfo","get",e],i,{cachedAt:o}),{data:i,cachedAt:o}};gr.locally=e=>{const t=Ye();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=at(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const pr=e=>{const t=async t=>{const[{data:n},{data:a}]=await Promise.all([gr(t.from),gr(t.to)]);e(n),e(a)},n=[or("follow.created",t),or("follow.requested",t),or("follow.accepted",t),or("follow.unfollowed",t),or("follow.requestCanceled",t),or("follow.requestDeclined",t),or("follow.followerDeleted",t),ir("local.follow.created",t),ir("local.follow.requested",t),ir("local.follow.accepted",t),ir("local.follow.unfollowed",t),ir("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},yr=e=>ir("local.follow.created",e),vr=e=>ir("local.follow.unfollowed",e),fr=e=>ir("local.follow.requested",e),br=e=>ir("local.follow.accepted",e),Ir=e=>ir("local.follow.requestDeclined",e);class Cr{constructor(e){const{http:t}=Ye();this.queryParams=e,this.http=t}loadFirstPage(){return this.onFetch("first")}loadNextPage(){return this.onFetch("next")}loadPreviousPage(){return this.onFetch("prev")}async onFetch(e="first"){var t,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 wr extends Cr{async getRequest(e,t){const{limit:n=ge,userId:a}=e,s=Bn(e,["limit","userId"]),o=t?{token:t}:{limit:n},i=Ye().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 Sr{constructor(e,t){this.query=e,this.cacheKey=t}}var Or;!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"}(Or||(Or={}));class Ar extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.follows.map(Ze("follow"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Ze("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&a){switch(e){case Or.OnDeclined:case Or.OnCanceled:case Or.OnUnfollowed:case Or.OnDeleted:a.data=a.data.filter((e=>e!==Ze("follow")(t)));break;case Or.OnRequested:case Or.OnAccepted:case Or.OnFollowed:a.data=[...new Set([Ze("follow")(t),...a.data])]}st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Tr{constructor(e){const{http:t}=Ye();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class Rr{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 Tr?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 Tr)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 Tr)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(nr).map(ar);return!Fa(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function Pr(e){return null!=e}const Dr=({userId:e})=>t=>{const n=Ye();return xt(n,"user.deleted","user.deleted",(n=>{const a=eo(n);Fn(a);const s=at(["follow","get",Ze("follow")({from:a.users[0].userId,to:e})]);s&&t(null==s?void 0:s.data)}))};class Ur extends Rr{constructor(e,t){const n=R.default(Object.assign(Object.assign({},e),{type:"follower"})),a=["follow","collection",n];super(new wr(e),n,a,t),this.query=e,this.queryStreamController=new Ar(this.query,this.cacheKey,this.notifyChange.bind(this),Jo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Or.OnFollowed},{fn:cr,action:Or.OnUnfollowed},{fn:hr,action:Or.OnAccepted},{fn:mr,action:Or.OnDeclined},{fn:ur,action:Or.OnCanceled},{fn:dr,action:Or.OnDeleted},{fn:br,action:Or.OnAccepted},{fn:Ir,action:Or.OnDeclined},{fn:yr,action:Or.OnFollowed},{fn:vr,action:Or.OnUnfollowed},{fn:Dr({userId:this.query.userId}),action:Or.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["follow","get",e]))).filter(Pr).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=at(["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 jr extends Cr{async getRequest(e,t){const{limit:n=ge,userId:a}=e,s=Bn(e,["limit","userId"]),o=t?{token:t}:{limit:n},i=Ye().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 kr extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.follows.map(Ze("follow"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Ze("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&a){switch(e){case Or.OnDeclined:case Or.OnCanceled:case Or.OnUnfollowed:case Or.OnDeleted:a.data=a.data.filter((e=>e!==Ze("follow")(t)));break;case Or.OnRequested:case Or.OnAccepted:case Or.OnFollowed:a.data=[...new Set([Ze("follow")(t),...a.data])]}st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Er=({userId:e})=>t=>{const n=Ye();return xt(n,"user.deleted","user.deleted",(n=>{const a=eo(n);Fn(a);const s=at(["follow","get",Ze("follow")({from:e,to:a.users[0].userId})]);s&&t(null==s?void 0:s.data)}))};class Mr extends Rr{constructor(e,t){const n=R.default(Object.assign(Object.assign({},e),{type:"following"})),a=["follow","collection",n];super(new jr(e),n,a,t),this.query=e,this.queryStreamController=new kr(this.query,this.cacheKey,this.notifyChange.bind(this),Ho),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:lr,action:Or.OnRequested},{fn:hr,action:Or.OnAccepted},{fn:mr,action:Or.OnDeclined},{fn:ur,action:Or.OnCanceled},{fn:rr,action:Or.OnFollowed},{fn:cr,action:Or.OnUnfollowed},{fn:dr,action:Or.OnDeleted},{fn:fr,action:Or.OnRequested},{fn:br,action:Or.OnAccepted},{fn:Ir,action:Or.OnDeclined},{fn:yr,action:Or.OnFollowed},{fn:vr,action:Or.OnUnfollowed},{fn:Er({userId:this.query.userId}),action:Or.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["follow","get",e]))).filter(Pr).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=at(["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 qr=(e,t,n,a,s,o)=>{const{forceDispatch:i,callbackDataSelector:r,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},o),{cache:d}=Ye();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=Bn(e,["data"]);c&&!c(n,l)||t(Object.assign({data:r(n)},a)),l=nr(n)};return h.push(...s.map((t=>t((t=>((t,a=!1)=>{e===t[n]&&(l&&!a&&Fa(l,t)||m({loading:!1,data:t,origin:"event"}))})(t,i)))))),(()=>{const t=_e(a,e,!0);$e(t,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{s===be?(m({data:t,origin:a,loading:!1,error:new Ve(fe,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 xr=Object.freeze({__proto__:null,blockUser:async e=>{const t=Ye();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&&(Fn(i,{cachedAt:a}),it(["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=Go(r);return Nt("local.follow.unfollowed",c),n},unBlockUser:async e=>{const t=Ye();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&&(Fn(i,{cachedAt:a}),it(["followInfo","get",e],o[0],{cachedAt:a}));const r=Go(i);return Nt("local.follow.created",r),n},onUserDidBlock:Yo,onUserDidUnblock:Wo,follow:async e=>{const t=Ye();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const s=Go(n);return"accepted"===n.follows[0].status?Nt("local.follow.created",s):Nt("local.follow.requested",s),{data:n.follows[0],cachedAt:a}},unfollow:async e=>{const t=Ye();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Fn(n);const a=Go(n);return Nt("local.follow.unfollowed",a),!0},acceptMyFollower:async e=>{const t=Ye();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Fn(n);const a=Go(n);return Nt("local.follow.accepted",a),!0},declineMyFollower:async e=>{const t=Ye();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Fn(n);const a=Go(n);return Nt("local.follow.requestDeclined",a),!0},onUserFollowed:rr,onUserUnfollowed:cr,onFollowerDeleted:dr,onFollowerRequested:lr,onFollowRequestCanceled:ur,onFollowRequestAccepted:hr,onFollowRequestDeclined:mr,onFollowInfoUpdated:pr,onLocalUserFollowed:yr,onLocalUserUnfollowed:vr,onLocalFollowerRequested:fr,onLocalFollowRequestAccepted:br,onLocalFollowRequestDeclined:Ir,getFollowers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getFollowers(tmpid: ${o}) > listen`);const i=new Ur(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getFollowers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:a,cache:s}=Ye();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 Mr(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getFollowings(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getFollowInfo:(e,t)=>qr(e,t,"userId",gr,[pr],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=Ut();return qr(t,e,"userId",gr,[pr],{forceDispatch:!0})}});function Nr(e,t){return e.map((e=>{const n=at(["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}=Ut();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:a})}))}const Kr=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:N};function Fr({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,a=Bn(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:Kr({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},a)}))}const _r=e=>{const t=Fr({communities:e.communities}),n=e.users.map(pa),a=e.communityUsers.map((e=>{const t=n.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),s=Nr(t,a);return Object.assign(Object.assign({},e),{users:e.users.map(pa),communities:s,communityUsers:a})},Br=e=>{const t=e.joinRequests.map((e=>Object.assign(Object.assign({},e),{joinRequestId:e._id}))),n=e.users.map(pa);return Object.assign(Object.assign({},e),{joinRequests:t,users:n})},$r=e=>{const t=Fr({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=Nr(t,n);return Object.assign(Object.assign({},e),{communities:a,communityUsers:n})},Lr=e=>{const{postSetting:t,storySetting:n}=e,a=Bn(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})},Qr=e=>{var t=Bn(e,["searchResult"]);const n=_r(t);return Object.assign({},n)},Vr=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=at(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return Bt(n)},cancel:async()=>{await(async e=>{var t;const n=Ye();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:a}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),s=null===(t=at(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(it(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),Nt("local.joinRequest.deleted",[s])),a.success})(e)},approve:async()=>{await(async e=>{var t;const n=Ye();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=at(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(it(["joinRequest","get",e.joinRequestId],{status:"approved"}),Nt("local.joinRequest.updated",[s])),a.success})(e)},reject:async()=>{await(async e=>{var t;const n=Ye();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=at(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(it(["joinRequest","get",e.joinRequestId],{status:"rejected"}),Nt("local.joinRequest.updated",[s])),a.success})(e)}});class Jr extends Cr{async getRequest(e,t){const{limit:n=20,communityId:a}=e,s=Bn(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 Hr;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Hr||(Hr={}));class Gr extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.joinRequests.map((e=>Ze("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Ze("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Hr.OnLocalJoinRequestUpdated){if(!a.data.find((e=>e===t[0].joinRequestId)))return}e===Hr.OnLocalJoinRequestCreated&&(a.data=[...new Set([...t.map((e=>e.joinRequestId)),...a.data])]),e===Hr.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>e!==t[0].joinRequestId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const zr=e=>{const t=Ye(),n=[xt(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Yr=e=>{const t=Ye(),n=[xt(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Wr=e=>{const t=Ye(),n=[xt(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Xr extends Rr{constructor(e,t){const n=R.default(e),a=["joinRequest","collection",n];super(new Jr(e),n,a,t),this.query=e,this.queryStreamController=new Gr(this.query,this.cacheKey,this.notifyChange.bind(this),Br),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:zr,action:Hr.OnLocalJoinRequestCreated},{fn:Yr,action:Hr.OnLocalJoinRequestUpdated},{fn:Wr,action:Hr.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(s.data.map((e=>at(["joinRequest","get",e]))).filter(Pr).map((({data:e})=>e)).map(Vr));(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?Ct:St)();return t=t.sort(n),t}}const Zr=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),ec=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map(Zr),users:e.users.map(pa)}),tc=async e=>{const t=Ye();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),a=ec(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),Nt("local.invitation.created",a.invitations),{data:a.invitations,cachedAt:s}},nc=e=>Object.assign(Object.assign({},e),{users:e.users.map(pa),invitations:e.invitations.map(Zr)}),ac=e=>Object.assign(Object.assign({},e),{get user(){const t=at(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return Bt(t.data)},get createdBy(){const t=at(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return Bt(t.data)},get target(){if("community"===e.targetType){const t=at(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=Ye();n.log("invitation/acceptInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/accept`),s=null===(t=at(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(it(["invitation","get",e],{status:"approved"}),Nt("local.invitation.updated",[s])),a.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=Ye();n.log("invitation/rejectInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/reject`),s=null===(t=at(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(it(["invitation","get",e],{status:"rejected"}),Nt("local.invitation.updated",[s])),a.success})(e._id)}}),sc=async e=>{const t=Ye();t.log("invitation/getInvitation",e.targetType,e.targetId,e.type);const{data:n}=await t.http.get("/api/v1/invitations/me",{params:e}),a=nc(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.invitations[0]?ac(a.invitations[0]):void 0,cachedAt:s}};var oc;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationCanceled="onLocalInvitationCanceled"}(oc||(oc={}));class ic extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 rc extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.invitations.map(Ze("invitation"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Ze("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===oc.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}e===oc.OnLocalInvitationCreated&&(a.data=[...new Set([...t.map((e=>e.invitationId)),...a.data])]),e===oc.OnLocalInvitationDeleted&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const cc=e=>{const t=Ye(),n=[xt(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},dc=e=>{const t=Ye(),n=[xt(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},lc=e=>{const t=Ye(),n=[xt(t,"onLocalInvitationCanceled","local.invitation.canceled",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class uc extends Rr{constructor(e,t){const n=R.default(e),a=["invitation","collection",n];super(new ic(e),n,a,t),this.query=e,this.queryStreamController=new rc(this.query,this.cacheKey,this.notifyChange.bind(this),ec),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:cc,action:oc.OnLocalInvitationCreated},{fn:dc,action:oc.OnLocalInvitationUpdated},{fn:lc,action:oc.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["invitation","get",e]))).filter(Pr).map((({data:e})=>ac(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?Ct:St)();return t=t.sort(n),t}}const hc=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=at(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),mc=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=at(["category","get",e]);if(null==t?void 0:t.data)return hc(t.data)})).filter((e=>!!e))},get avatar(){var t;if(!e.avatarFileId)return;return null===(t=at(["file","get",e.avatarFileId]))||void 0===t?void 0:t.data},createInvitations:async t=>{await tc({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getInvitations: (tmpid: ${o}) > listen`);const i=new uc(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(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 sc({targetType:"community",targetId:e.communityId});return t},join:async()=>(async e=>{var t;const n=Ye();n.log("community/joinRequest",e);const{data:a}=await n.http.post(`/api/v4/communities/${e}/join`),s=Br(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const i="approved"===s.joinRequests[0].status?"success":"pending";if("success"===i&&n.cache){const n=null===(t=at(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});it(["community","get",e],t)}}return Nt("v4.local.community.joined",s.joinRequests),"success"===i?{status:i}:{status:i,request:Vr(s.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getJoinRequests: (tmpid: ${o}) > listen`);const i=new Xr(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(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=Ye();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),a=Br(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.joinRequests[0]?Vr(a.joinRequests[0]):void 0,cachedAt:s}})(e.communityId);return t}});class gc{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=at(["story-expire",this._targetId]),this.cacheStoreSeenTime=at(["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=at(["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 at(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=nt(["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 pc=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:a,lastStorySeenExpiresAt:s,targetUpdatedAt:o,localFilter:i}=e,r=new gc(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()}},yc=async e=>{const t=Ye();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=Bn(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 Ua(n.data),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{channels:o}=a;return{data:Us(o[0]),cachedAt:s}},vc=async e=>{const t=Ye();let n;t.log("channel/getChannel",e),ea("channel",e);try{const{data:a}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await Ua(a),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&ka(a)}catch(t){throw Pe(null==t?void 0:t.code)&&_n("channel",e),t}const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{channels:s}=n;return{data:s.find((t=>t.channelId===e)),cachedAt:a}};vc.locally=e=>{var t;const n=Ye();if(n.log("channel/getChannel.locally",e),!n.cache)return;const a=null===(t=nt(["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 fc=Symbol("getWatcherUrls"),bc=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=at(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=at(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=at(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=at(["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=at(["stream","get",e]))||void 0===t?void 0:t.data;if(n)return bc(n)})).filter(Pr):[]},getLiveChat:()=>(async e=>{var t;const n=Ye();if(n.log("stream/getLiveChat",e.streamId),e.channelId){const n=null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data;if(n)return Ds(Us(n));const{data:a}=await vc(e.channelId);return Ds(Us(a))}if(e.userId===n.userId){const{data:t}=await yc({type:"live",postId:e.postId,videoStreamId:e.streamId});return ot(["stream","get",e.streamId],{channelId:t.channelId}),t}})(e),isBanned:!e.watcherUrl,watcherUrl:null,get[fc](){return e.watcherUrl}}),Ic=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=at(["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=at(["user","get",e.userId]);if(null==t?void 0:t.data)return Bt(t.data)},get childrenComment(){return e.children.map((e=>{const t=at(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(Pr).map((e=>Ic(e)))}});function Cc(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}function wc(e){return!(!e.data||"string"==typeof e.data||!("streamId"in e.data)||"liveStream"!==e.dataType)}class Sc{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 Oc=null;const Ac=()=>(Oc||(Oc=new Sc),Oc),Tc={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},Rc="-----BEGIN PRIVATE KEY-----";function Pc(e){const n=new Uint8Array(e);let a="";return n.forEach((e=>{a+=String.fromCharCode(e)})),t.btoa(a)}function Dc(e){return e<128?new Uint8Array([e]):e<256?new Uint8Array([129,e]):new Uint8Array([130,e>>8&255,255&e])}async function Uc(e){let n=e;n=e.includes(Rc)?e.substring(Rc.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=Dc(e.length),s=n.length+t.length+1+a.length+e.length,o=Dc(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,Tc,!1,["sign"])}async function jc({timestamp:e,rooms:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),a=A.default.v4(),s=`nonceStr=${a}×tamp=${e}&data=${n}==`,o=(new TextEncoder).encode(s),i=await Uc("-----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:Pc(await crypto.subtle.sign(Tc,i,o)),nonceStr:a}}async function kc(){const e=Ac(),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 jc({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=Ye();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 Ec=["live","recorded"];class Mc{constructor(e){this.storage=Ac(),this.client=Ye(),this.room=e}async createWatchSession(e){if(!Ec.includes(this.room.status))throw new Ve("room is not in watchable state",5e5,"error");const t=("live"===this.room.status?"room_":"room_playback_")+A.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 kc(),this.client.log("room/RoomAnalytics: syncWatchSessions completed")}catch(e){console.error("Failed to sync watch sessions:",e)}}),e)}}const qc=e=>Object.assign(Object.assign({},e),{get post(){var t;if("post"===e.referenceType)return null===(t=at(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=at(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;const n=null===(t=at(["user","get",e.createdBy]))||void 0===t?void 0:t.data;return n?Bt(n):n},get childRooms(){return e.childRoomIds&&0!==e.childRoomIds.length?e.childRoomIds.map((e=>{var t;const n=null===(t=at(["room","get",e]))||void 0===t?void 0:t.data;if(n)return qc(n)})).filter(Pr):[]},participants:e.participants.map((e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=at(["user","get",e.userId]))||void 0===t?void 0:t.data;return n?Bt(n):n}}))),getLiveChat:()=>(async e=>{var t;const n=Ye();if(n.log("room/getLiveChat",e.roomId),e.liveChannelId){const n=null===(t=at(["channel","get",e.liveChannelId]))||void 0===t?void 0:t.data;if(n)return Ds(Us(n));const{data:a}=await vc(e.liveChannelId);return Ds(Us(a))}if(e.createdBy===n.userId){const{data:t}=await yc({type:"live",postId:e.referenceId,roomId:e.roomId});return ot(["room","get",e.roomId],{liveChannelId:t.channelId}),t}})(e),createInvitation:t=>tc({type:"livestreamCohostInvite",targetType:"room",targetId:e.roomId,userIds:[t]}),getInvitations:async()=>{const{data:t}=await sc({targetId:e.roomId,targetType:"room",type:"livestreamCohostInvite"});return t},analytics(){return new Mc(this)}}),xc=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=at(["file","get",e.fileId]))||void 0===t?void 0:t.data}})))}),Nc=e=>{const t=fo();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)}}})},Kc=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},Fc=e=>Xn(e,{childrenPosts:e.children.map((e=>{var t;return null===(t=at(["post","get",e]))||void 0===t?void 0:t.data})).filter(Pr).map(Fc),analytics:{markAsViewed:()=>{fo().markPostAsViewed(e.postId)},markAsMeaningfullyViewed:t=>{fo().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=at(["product","get",e.productId]))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{product:n?Nc(n):void 0})})(e))))&&void 0!==n?n:[]},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=at(["comment","get",e]))||void 0===t?void 0:t.data;return n?Ic(n):null})).filter(Boolean)||[]},get creator(){if(!e.postedUserId)return;const t=at(["user","get",e.postedUserId]);return(null==t?void 0:t.data)?Bt(t.data):void 0},get targetCommunity(){var t;if(!e.targetId)return;const n=null===(t=at(["community","get",e.targetId]))||void 0===t?void 0:t.data;return n?mc(n):void 0},getImageInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return Kc(null===(n=at(["file","get",e.data.fileId]))||void 0===n?void 0:n.data)},getVideoInfo(){var t,n,a;const s=Cc(e)?null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original:void 0;if(s)return Kc(null===(a=at(["file","get",s]))||void 0===a?void 0:a.data)},getVideoThumbnailInfo(){var t,n;const a=Cc(e)?null===(t=e.data)||void 0===t?void 0:t.thumbnailFileId:void 0;if(a)return Kc(null===(n=at(["file","get",a]))||void 0===n?void 0:n.data)},getFileInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"file"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=at(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getLivestreamInfo(){var t,n;if(!wc(e)||!(null===(t=e.data)||void 0===t?void 0:t.streamId))return;const a=null===(n=at(["stream","get",e.data.streamId]))||void 0===n?void 0:n.data;return a?bc(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)||!(null===(t=e.data)||void 0===t?void 0:t.pollId))return;const a=null===(n=at(["poll","get",e.data.pollId]))||void 0===n?void 0:n.data;return a?xc(a):void 0},getClipInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"clip"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=at(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getAudioInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"audio"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=at(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getRoomInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("roomId"in e.data)||"room"!==e.dataType)}(e)||!(null===(t=e.data)||void 0===t?void 0:t.roomId))return;const a=null===(n=at(["room","get",e.data.roomId]))||void 0===n?void 0:n.data;return a?qc(a):void 0},getEventInfo(){var t,n;if(!function(e){return"event"===e.dataType||"event"===e.structureType}(e))return;const a=e=>{if(e&&"object"==typeof e&&"eventId"in e){const t=e.eventId;return"string"==typeof t?t:void 0}},s=a(e.data),o=null!=s?s:null===(t=e.children)||void 0===t?void 0:t.map((e=>{var t;return null===(t=at(["post","get",e]))||void 0===t?void 0:t.data})).map((e=>a(null==e?void 0:e.data))).find(Boolean);if(!o)return;const i=null===(n=at(["event","get",o]))||void 0===n?void 0:n.data;return i?Object.assign(Object.assign({},i),{get creator(){const e=at(["user","get",i.userId]);if(null==e?void 0:e.data)return Bt(e.data)},get targetCommunity(){var e;if(!i.originId)return;const t=null===(e=at(["community","get",i.originId]))||void 0===e?void 0:e.data;return t?mc(t):void 0},get coverImage(){var e;if(i.coverImageFileId)return null===(e=at(["file","get",i.coverImageFileId]))||void 0===e?void 0:e.data}}):void 0}}),_c=(e,t)=>{"message"===e?Nt("local.message.updated",{messages:[t]}):"post"===e?Nt("post.updated",{posts:[t]}):"comment"===e?Nt("comment.updated",{comments:[t]}):"story"===e&&Nt("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Bc=async(e,t,n,a)=>{var s,o,i;const r=Ye();if(r.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ve("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=at([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 Nt("local.comment.addReaction",{comment:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("post"===e)return Nt("local.post.addReaction",{post:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("story"===e)return Nt("local.story.reactionAdded",{story:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("message"===e)return it(["message","get",t],d),Nt("local.message.updated",{messages:[d]}),!0}return!0};Bc.optimistically=(e,t,n)=>{var a,s,o,i,r;const c=Ye();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const d=at([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 it([e,"get",t],l,{cachedAt:be}),_c(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 $c=(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=at(["messageMarker","get",Ze("messageMarker")(a)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},Lc=(e,t)=>{const n=t.publicId!==t.messageId;return(async(e,t,n,a)=>{var s,o;const i=Ye();if(i.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ve("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=at([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 Nt("local.comment.removeReaction",{comment:c,reactor:{reactionId:r.removedId,reactionName:n,userId:i.userId}}),!0;if("post"===e)return Nt("local.post.removeReaction",{post:c,reactor:{reactionId:r.removedId,reactionName:n,userId:i.userId}}),!0;if("story"===e)return Nt("local.story.reactionRemoved",{story:c,reactor:{userId:i.userId,reactionName:n,reactionId:r.removedId}}),!0;if("message"===e)return it(["message","get",t],c),Nt("local.message.updated",{messages:[c]}),!0}return!0})("message",n?t.publicId:t.messageId,e,n?3:5)},Qc=e=>Object.assign(Object.assign({},e),{users:e.users.map(pa)}),Vc=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=at(["event","get",e.eventId]);if(null==t?void 0:t.data)return t.data},get user(){const t=at(["user","get",e.userId]);if(null==t?void 0:t.data)return Bt(t.data)}}),Jc=e=>Object.assign(Object.assign({},e),{users:e.users.map(pa)}),Hc=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Jc(e);if(n.cache){Fn(a);const e=at(["event","get",a.events[0].eventId]);t(e.data)}else t(a.events[0])}))},Gc=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Qc(e);if(n.cache){Fn(a);const e=at(["eventResponse","get",a.eventResponses[0].userId]);t(e.data)}else t(a.eventResponses[0])}))},zc=async e=>{const t=Ye();t.log("event/getMyRSVP",e);const{data:n}=await t.http.get(`/api/v1/events/${e}/me/rsvp`),a=Qc(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:Vc(a.eventResponses[0]),cachedAt:s}};var Yc;zc.locally=e=>{const t=Ye();if(t.log("event/getMyRSVP.locally",e),!t.cache)return;const n=at(["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"}(Yc||(Yc={}));class Wc extends Cr{async getRequest(e,t){const{limit:n=ge,eventId:a}=e,s=Bn(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 Xc extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.eventResponses.map(Ze("eventResponse"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.eventResponses.map(Ze("eventResponse"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Yc.OnRSVPCreated&&(a.data=[...new Set([t.userId,...a.data])]),e===Yc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Zc=e=>Hc("event.created",e),ed=e=>Hc("event.updated",e),td=e=>Hc("event.deleted",e),nd=e=>Hc("local.event.created",e),ad=e=>Hc("local.event.updated",e),sd=e=>Hc("local.event.deleted",e),od=e=>Gc("event.rsvp.created",e),id=e=>Gc("event.rsvp.updated",e),rd=e=>Gc("local.rsvp.created",e),cd=e=>Gc("local.rsvp.updated",e);class dd extends Rr{constructor(e,t){const n=R.default(e),a=["eventResponse","collection",n];super(new Wc(e),n,a,t),this.query=e,this.queryStreamController=new Xc(this.query,this.cacheKey,this.notifyChange.bind(this),Qc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:od,action:Yc.OnRSVPCreated},{fn:id,action:Yc.OnRSVPUpdated},{fn:rd,action:Yc.OnRSVPCreated},{fn:cd,action:Yc.OnRSVPUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=s.data.map((e=>at(["eventResponse","get",e]))).filter(Pr).map((({data:e})=>Vc(e)));(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}const ld=(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getRSVPs: (tmpid: ${o}) > listen`);const i=new dd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getRSVPs (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},ud=e=>Object.assign(Object.assign({},e),{get creator(){const t=at(["user","get",e.userId]);if(null==t?void 0:t.data)return Bt(t.data)},get targetCommunity(){if(!e.originId)return;const t=at(["community","get",e.originId]);return(null==t?void 0:t.data)?mc(t.data):void 0},get coverImage(){if(!e.coverImageFileId)return;const t=at(["file","get",e.coverImageFileId]);return(null==t?void 0:t.data)?t.data:void 0},get post(){if(!e.postId)return;const t=at(["post","get",e.postId]);return(null==t?void 0:t.data)?Fc(t.data):void 0},get room(){var t;if(!e.postId)return;const n=null===(t=nt(["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?qc(n[0].data):void 0},createRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ye();n.log("event/createRSVP",e,t);const{data:a}=await n.http.post(`/api/v1/events/${e}/rsvp`,{status:t});Nt("local.rsvp.created",a);const s=Qc(a),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),{data:Vc(s.eventResponses[0]),cachedAt:o}})(e.eventId,t);return n},updateRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ye();n.log("event/updateRSVP",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}/rsvp`,{status:t});Nt("local.rsvp.updated",a);const s=Qc(a),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),{data:Vc(s.eventResponses[0]),cachedAt:o}})(e.eventId,t);return n},getMyRSVP:async()=>{const{data:t}=await zc(e.eventId);return t},getRSVPs:(t,n)=>ld(Object.assign({eventId:e.eventId},t),n)}),hd={file:Kc,ad:e=>{const t=fo(),{image9_16:n,image1_1:a}=e,s=Bn(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=at(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!a)return;const s=null===(n=at(["file","get",a.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},a),{avatar:s})},get image1_1(){const e=at(["file","get",a]);if(e)return e.data||void 0},get image9_16(){const e=at(["file","get",n]);if(e)return e.data||void 0}})},comment:Ic,post:Fc,user:Bt,category:hc,stream:bc,story:e=>{const t=fo(),n=at(["storyTarget","get",e.targetId]),a=at(["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=at(["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=at(["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 mc(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=at(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=at(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return Bt(t.data)},get storyTarget(){if(null==n?void 0:n.data)return pc(n.data)},get isSeen(){const t=at(["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:pc,message:e=>{const t=Bn(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return $c(e).readCount},get deliveredCount(){return $c(e).deliveredCount},get creator(){var t;return null===(t=at(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>bi(e),addReaction:t=>((e,t)=>{const n=t.publicId!==t.messageId;return Bc("message",n?t.publicId:t.messageId,e,n?3:5)})(t,e),removeReaction:t=>Lc(t,e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=at(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return Bt(n)}}),channel:Ds,pinnedPost:e=>{var t;const n=at(["post","get",e.referenceId]),a=null===(t=nt(["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 Fc(n.data)},get target(){const e=at(["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})=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map((e=>Bt(e))),get event(){const t=at(["event","get",e.actionReferenceId]);if(null==t?void 0:t.data)return t.data}}),community:mc,invitation:ac,joinRequest:Vr,channelMember:Na,room:qc,event:ud,eventResponse:Vc,product:Nc,poll:xc},md=async e=>{const t=Ye();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=eo(a),o=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:o}),Nt("user.fetched",a),{data:s.users.map((e=>hd.user(e))),cachedAt:o}};md.locally=e=>{var t;const n=Ye();if(n.log("user/getUsers.locally",e),!n.cache)return;const a=e.map((e=>at(["user","get",e]))).filter(Boolean),s=a.map((({data:e})=>hd.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 gd=async(e,t)=>{var n;const a=Ye();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=eo(o);return a.cache&&Fn(i),Nt("user.flagged",o),null!==(n=i.users.find((t=>t.userId===e)))&&void 0!==n?n:i.users[0]},pd=e=>co("user.updated",e),yd=e=>co("user.flagged",e),vd=e=>co("user.unflagged",e),fd=e=>co("user.flagCleared",e),bd=e=>co("user.fetched",e),Id=async e=>{const t=Ye();t.log("user/getUser",e),ea("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),a=t.cache&&Date.now(),s=eo(n);return t.cache&&Fn(s,{cachedAt:a}),Nt("user.fetched",n),{data:s.users.find((t=>t.userId===e)),cachedAt:a}}catch(t){throw Pe(null==t?void 0:t.code)&&_n("user",e),t}};Id.locally=e=>{const t=Ye();if(t.log("user/getUser.locally",e),!t.cache)return;const n=at(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Cd extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 wd extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.users.map(Ze("user"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ze("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Sd;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(Sd||(Sd={}));class Od extends Rr{constructor(e,t){const n=R.default(e),a=["user","collection",n];super(new Cd(e),n,a,t),this.query=e,this.queryStreamController=new wd(this.query,this.cacheKey,this.notifyChange.bind(this),eo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:lo,action:Sd.OnUserDeleted},{fn:pd,action:Sd.OnUserUpdated},{fn:yd,action:Sd.OnUserFlagged},{fn:vd,action:Sd.OnUserUnflagged},{fn:fd,action:Sd.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.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?Ct:St)();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 Ad extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 Td;!function(e){e.OnBlocked="onBlocked",e.OnUnblocked="onUnblocked"}(Td||(Td={}));class Rd extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.users.map(Ze("user"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ze("user"))])]}))}}reactor(e){return t=>{var n,a;const s=e===Or.OnFollowed||e===Td.OnUnblocked,o=e===Td.OnBlocked;if(s||o){const e=null===(n=at(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));st(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 Pd=(e,t,n)=>a=>e((e=>{var s;if(!e)return e;const o=[n,"get",`${e[t]}`],i=null===(s=at(o))||void 0===s?void 0:s.data;return i?a(i):void 0}));class Dd extends Rr{constructor(e,t){const n=R.default(e),a=["blockedUsers","collection",n];super(new Ad(e),n,a,t),this.query=e,this.queryStreamController=new Rd(this.query,this.cacheKey,this.notifyChange.bind(this),Ko),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:lo,action:Sd.OnUserDeleted},{fn:Pd(yr,"to","user"),action:Or.OnFollowed},{fn:Pd(rr,"to","user"),action:Or.OnFollowed},{fn:e=>Yo((t=>{var n;if(t.from!==Ye().userId)return;const a=null===(n=at(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:Td.OnBlocked},{fn:e=>Wo((t=>{var n;if(t.from!==Ye().userId)return;const a=null===(n=at(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:Td.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.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 Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.users.map(Ze("user"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ze("user"))])]}))}}reactor(e){return t=>{var n,a;if(t&&(e===Td.OnBlocked||e===Td.OnUnblocked)){const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[],i=e===Td.OnBlocked?[...new Set([...o,t.userId])]:o.filter((e=>e!==t.userId));st(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 jd extends Cr{async getRequest(e,t){const{limit:n=pe}=e,a=Bn(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 kd extends Rr{constructor(e){const t=`blocking-users-${Ye().userId}`,n={},a=["blockingUsers","collection",t];super(new jd(n),t,a,e),this.queryStreamController=new Ud(n,this.cacheKey,this.notifyChange.bind(this),$o),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:lo,action:Sd.OnUserDeleted},{fn:e=>Yo((t=>{var n;if(t.to!==Ye().userId)return;const a=null===(n=at(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:Td.OnBlocked},{fn:e=>Wo((t=>{var n;if(t.to!==Ye().userId)return;const a=null===(n=at(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:Td.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.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 Ed extends Cr{async getRequest(e,t){const{limit:n=ge,displayName:a}=e,s=Bn(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 Md extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.users.map(Ze("user"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ze("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class qd extends Rr{constructor(e,t){var n;const a=R.default(e),s=["user","collection",a];super(new Ed(e),a,s,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new Md(this.query,this.cacheKey,this.notifyChange.bind(this),eo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:lo,action:Sd.OnUserDeleted},{fn:pd,action:Sd.OnUserUpdated},{fn:yd,action:Sd.OnUserFlagged},{fn:vd,action:Sd.OnUserUnflagged},{fn:fd,action:Sd.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.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 xd=async({viewId:e,viewedType:t,limit:n,token:a})=>{const s=Ye(),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 Fn(r.data),r.data};var Nd;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(Nd||(Nd={}));var Kd=Object.freeze({__proto__:null,Relationship:xr,getUserByIds:md,updateUser:async(e,t)=>{const n=Ye();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=eo(a),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),Nt("user.updated",a),{data:s.users.find((t=>t.userId===e)),cachedAt:o}},flagUser:gd,unflagUser:async e=>{const t=Ye();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),a=eo(n);return t.cache&&Fn(a),Nt("user.unflagged",n),!!a},isUserFlaggedByMe:async e=>{const t=Ye();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},getAllBlockedUsers:async()=>{Ye().log("user/getAllBlockedUsers");const e=Bo();return await e.ensureFetched(),e.getCachedUsers()},getAllBlockingUsers:async()=>{Ye().log("user/getAllBlockingUsers");const e=Vo();return await e.ensureFetched(),e.getCachedUsers()},onUserUpdated:pd,onUserDeleted:lo,onUserFlagged:yd,onUserUnflagged:vd,onUserFlagCleared:fd,getUser:(e,t)=>qr(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?hd.user(e.data):e.data}))),"userId",Id,[bd,pd,lo,yd,vd,fd]),getUsers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`liveUsers(tmpid: ${o}) > listen`);const i=new Od(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`liveUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getBlockedUsers(tmpid: ${o}) > listen`);const i=new Dd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getBlockedUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e())),rt(c)}},getBlockingUsers:e=>{const{log:t,cache:n}=Ye();n||console.log(ve);const a=Date.now();t(`getBlockingUsers(tmpid: ${a}) > listen`);const s=new kd(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>rt(i))),()=>{t(`getBlockingUsers(tmpid: ${a}) > dispose`),o.forEach((e=>e())),rt(i)}},searchUsers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`liveSearchUsers(tmpid: ${o}) > listen`);const i=new qd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`liveSearchUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchUserByDisplayName:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`liveSearchUsers(tmpid: ${o}) > listen`);const i=new qd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`liveSearchUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:a,cache:s}=Ye(),o=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(ve);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=at(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=_e(xd,{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});$e(h,(e=>{var a,s,i,r,c;let d=null!==(i=null===(s=null===(a=at(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||[]};st(o,l),(e=>{var a,s;let o=[];(null==e?void 0:e.data)&&(o=e.data.map((e=>at(["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)}),Be(ye,2e3))},n(!0),()=>{a(`getReachUsers(tmpid: ${i}) > dispose`),rt(o)}},get AmityUserSearchMatchType(){return Nd}});const Fd=async e=>{const t=Ye();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),a=t.cache&&Date.now();return t.cache&&Fn({files:[n]},{cachedAt:a}),{data:Kc(n),cachedAt:a}};Fd.locally=e=>{const t=Ye();if(t.log("file/getFile.locally",e),!t.cache)return;const n=at(["file","get",e]);return n?{data:Kc(n.data),cachedAt:n.cachedAt}:void 0};const _d=async(e,t,n)=>{const a=Ye();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=Fi().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&&Fn({files:r},{cachedAt:c}),{data:r.map((e=>Kc(e))),cachedAt:c}},Bd=async(e,t,n)=>{const a=Ye();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=Fi().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&&Fn({files:r},{cachedAt:c}),{data:r.map((e=>Kc(e))),cachedAt:c}};var $d=Object.freeze({__proto__:null,getFile:Fd,uploadFile:async(e,t)=>{const n=Ye();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=Fi().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&&Fn({files:i},{cachedAt:r}),{data:i,cachedAt:r}},deleteFile:async e=>{const t=Ye();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),rt(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:_d,uploadImage:Bd,updateAltText:async(e,t)=>{const n=Ye();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&&Fn({files:[a]},{cachedAt:s}),!0},uploadClip:async(e,t,n)=>{const a=Ye();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=Fi().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&&Fn({files:r},{cachedAt:c}),{data:r,cachedAt:c}},uploadAudio:async(e,t)=>{const n=Ye();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=Fi().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&&Fn({files:i},{cachedAt:r}),{data:i,cachedAt:r}}});const Ld=async e=>{const t=Ye();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:a=10,queryToken:s,displayName:o,sortBy:i}=n,r=Bn(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=Bn(d,["paging"]),{roles:h}=u,m=t.cache&&Date.now();t.cache&&Fn(u,{cachedAt:m});const g=Me(l.next);return{data:h,cachedAt:m,prevPage:Me(l.previous),nextPage:g,paging:l}};Ld.locally=e=>{Ye().log("role/queryRoles.locally",e)};const Qd=async e=>{const t=Ye();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),a=t.cache&&Date.now();return t.cache&&Fn({roles:n},{cachedAt:a}),{data:n.find((t=>t.roleId===e)),cachedAt:a}};Qd.locally=e=>{const t=Ye();if(t.log("role/getRole.locally",e),!t.cache)return;const n=at(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Vd=async(e,t=!1)=>{const n=Ye();let a;n.log("message/getMessage",e),ea("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);a=await ha(t)}catch(t){throw Pe(null==t?void 0:t.code)&&_n("message",e),t}const s=n.cache&&Date.now();n.cache&&Fn(a,{cachedAt:s});const{messages:o}=a;return Nt("local.message.fetched",{messages:o}),{data:o.find((t=>t.messageId===e)),cachedAt:s}};Vd.locally=e=>{const t=Ye();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=at(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Jd{constructor(e,t,n){this.postId=e,this.latestCreatedAt=t,this.serverCommentCount=n}}class Hd{constructor(e,t,n){this.postId=e,this.commentId=t,this.createdAt=n}}class Gd{constructor(e,t){this.postId=e,this.commentId=t}}class zd{constructor(e,t){this.latestCommentCreatedAt=e,this.serverCommentCount=t,this.createdCommentIds=new Set,this.deletedCommentIds=new Set}}class Yd{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,Yd.BATCH_SIZE),t=new Set;e.forEach((e=>{let n=!1;e instanceof Jd?n=this.processResetTaskInternal(e):e instanceof Hd?n=this.processCreateTaskInternal(e):e instanceof Gd&&(n=this.processDeleteTaskInternal(e)),n&&t.add(e.postId)})),t.forEach((e=>{const t=this.computeCommentCount(e);Yd.publishUpdate(e,t)})),this.isProcessing=!1,this.tasks.length>0&&this.processCommentChangeTask()}processResetTaskInternal(e){return this.commentChangeTracker.set(e.postId,new zd(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];ot(a,{localCommentCount:t});const s=null===(n=at(a))||void 0===n?void 0:n.data;s&&Nt("local.post.updated",{posts:[s]})}}let Wd;Yd.BATCH_SIZE=50;var Xd=()=>(Wd||(Wd=new Yd),Wd);const Zd=e=>{const{posts:t,postChildren:n,videoStreamings:a}=e,s=Bn(e,["posts","postChildren","videoStreamings"]),o=Fr({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=Nr(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&&wc(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 Xd().queueCommentChangeTask(new Jd(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})},el=e=>{var{searchResult:t,polls:n}=e,a=Bn(e,["searchResult","polls"]);const s=Zd(a);return Object.assign(Object.assign({},s),{polls:n})},tl=async e=>{const t=Ye();let n;t.log("post/getPost",e),ea("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("post",e),t}const a=Zd(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{posts:o}=a;return{data:o.find((t=>t.postId===e)),cachedAt:s}};tl.locally=e=>{const t=Ye();if(t.log("post/getPost.locally",e),!t.cache)return;const n=at(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const nl=async e=>{const t=Ye();let n;t.log("comment/getComment",e),ea("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("comment",e),t}const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{comments:s}=n;return{data:hd.comment(s.find((t=>t.commentId===e))),cachedAt:a}};nl.locally=e=>{const t=Ye();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=at(["comment","get",e]);return n?{data:hd.comment(n.data),cachedAt:n.cachedAt}:void 0};const al=(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=at([o,"get",s]))||void 0===n?void 0:n.data)||void 0===a?void 0:a.myReactions)||[]},sl=(e,t,n)=>{const[a]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},a),{myReactions:n})]})},ol=(e,t,n,a=[])=>{const s=e.split(".")[1];let o=a;if(Ye().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},il=(e,t)=>{const n=e.split(".")[0],a=al(t,n),s=ol(e,t.reactor.userId,t.reactor.reactionName,a);return sl(t,`${n}s`,s)},rl=(e,t)=>{var n,a;const s=e.split(".")[0];let o=al(t,s);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(o=ol(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=sl(t,"stories",o);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return i;const r=Nr(t.communities,t.communityUsers);return Object.assign(Object.assign({},i),{communities:r})},cl=async(e,t,n)=>{var a,s,o;const i=Ye();if(i.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ve("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=at([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 Nt("local.comment.addReaction",{comment:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0;if("post"===e)return Nt("local.post.addReaction",{post:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0;if("story"===e)return Nt("local.story.reactionAdded",{story:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0}return!0};cl.optimistically=(e,t,n)=>{var a,s,o,i,r;const c=Ye();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const d=at([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 it([e,"get",t],l,{cachedAt:be}),_c(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 dl=async(e,t,n)=>{var a,s;const o=Ye();if(o.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ve("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=at([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 Nt("local.comment.removeReaction",{comment:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("post"===e)return Nt("local.post.removeReaction",{post:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("story"===e)return Nt("local.story.reactionRemoved",{story:c,reactor:{userId:o.userId,reactionName:n,reactionId:i.removedId}}),!0}return!0};dl.optimistically=(e,t,n)=>{var a,s,o,i;const r=Ye();if(r.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!r.cache)return;const c=at([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 it([e,"get",t],d,{cachedAt:be}),_c(e,d),!(null===(i=null==d?void 0:d.myReactions)||void 0===i?void 0:i.includes(n))};const ll=e=>{var t;const n=e.posts[0];if(n.parentId){const e=null===(t=at(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;if(!e)return;st(["post","get",e.postId],Object.assign(Object.assign({},e),{children:e.children.filter((e=>e!==n.postId))}))}else n.children.forEach((e=>ot(["post","get",e],{isDeleted:!0})))},ul=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{var s;if(n.cache){const o=Zd(a),{communities:i}=o;if(Fn(o,void 0,!1),(null==i?void 0:i[0])&&!["post.updated"].includes(e)&&Nt("community.updated",{communities:i,categories:[],communityUsers:o.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=a.posts[0];ll(a);try{ea("post",e)}catch(e){return}return s!==n.userId&&rt(["post","get",e]),t(a.posts[0])}const r=at(["post","get",a.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=nt(["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})=>it(e,t,{cachedAt:-1})))}"post.created"===e&&(e=>{var t;const n=e.posts[0];if(!n.parentId)return;const a=null===(t=at(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;a&&st(["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])}))},hl=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{if(n.cache){const{communities:n}=a;(null==n?void 0:n[0])&&!["local.post.updated"].includes(e)&&Nt("community.updated",{communities:n,categories:[],communityUsers:a.communityUsers,feeds:[],files:[],users:[]});const s=at(["post","get",a.posts[0].postId]);"local.post.deleted"===e&&ll(a),t(s.data)}else t(a.posts[0])}))},ml=e=>ul("post.created",e),gl=e=>ul("post.updated",e),pl=e=>ul("post.deleted",e),yl=e=>ul("post.approved",e),vl=e=>ul("post.declined",e),fl=e=>ul("post.flagged",e),bl=e=>ul("post.unflagged",e),Il=e=>{const t=Ye();return xt(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=Bn(il("post.addReaction",n),["reactor"]);Fn(t);const a=at(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},Cl=e=>{const t=Ye();return xt(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=Bn(il("post.removeReaction",n),["reactor"]);Fn(t);const a=at(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},wl=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{var s;if(n.cache){const n=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=al(e,"comment");return sl(e,"comments",t)})(a):a;Fn(n,void 0,!1);const{comments:o}=n;if(o.length>0){const n=at(["comment","get",o[0].commentId]);if(["comment.created"].includes(e)&&o[0].parentId){const e=at(["comment","get",o[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(o[0].commentId)||st(["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=at(["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))])]});st(["comment","get",o[0].parentId],t)}}const e=null===(s=nt(["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})=>it(e,t,{cachedAt:-1})))}t(hd.comment(n.data))}}else t(hd.comment(a.comments[0]))}))},Sl=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{var s,o,i,r,c;if(n.cache){const n=a;Fn(n);const{comments:d}=n;if(d.length>0){const n=at(["comment","get",d[0].commentId]);if(["local.comment.created"].includes(e)){if(d[0].parentId){const e=at(["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])]});st(["comment","get",d[0].parentId],t),setTimeout((()=>{Nt("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",d[0].referenceId],t=null===(s=at(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]});st(e,n)}}const e=null===(i=nt(["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})=>it(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(d[0].parentId){const e=at(["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))])]});st(["comment","get",d[0].parentId],t),setTimeout((()=>{Nt("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",d[0].referenceId],t=null===(r=at(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)}))});st(e,n)}}const e=null===(c=nt(["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})=>it(e,t,{cachedAt:-1})))}t(hd.comment(n.data))}}else t(hd.comment(a.comments[0]))}))},Ol=e=>wl("comment.created",e),Al=e=>wl("comment.updated",e),Tl=e=>wl("comment.deleted",e),Rl=e=>wl("comment.flagged",e),Pl=e=>wl("comment.unflagged",e),Dl=e=>{const t=Ye();return xt(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=Bn(il("comment.addReaction",n),["reactor"]);Fn(t);const a=at(["comment","get",n.comments[0].commentId]);e(hd.comment(a.data))}else e(hd.comment(n.comments[0]))}))},Ul=e=>{const t=Ye();return xt(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=Bn(il("comment.removeReaction",n),["reactor"]);Fn(t);const a=at(["comment","get",n.comments[0].commentId]);e(hd.comment(a.data))}else e(hd.comment(n.comments[0]))}))},jl=(e,t,n)=>{const a=Ye(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e){return xt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await ha(e);t.reactions[0]&&(Fn(t),Fn({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return xt(a,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=Bn(e,["reactor"]);Fn(n),Fn({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return xt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Bn(e,["reactions"]);Fn(n),Fn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return xt(a,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=Bn(e,["reactor"]);Fn(n),Fn({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},kl=(e,t,n)=>{const a=Ye(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e){return xt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await ha(e);t.reactions[0]&&(Fn(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return xt(a,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=Bn(e,["reactor"]);Fn(n),Fn({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return xt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Bn(e,["reactions"]);Fn(n),Fn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return xt(a,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=Bn(e,["reactor"]);Fn(n),Fn({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))};class El extends Cr{async getRequest(e,t){const{limit:n=ge,referenceType:a}=e,s=Bn(e,["limit","referenceType"]),o=t?{token:t}:{limit:n};Ye().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(a))throw new Ve("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 Ml extends Sr{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=Ye(),s=a.cache&&Date.now();if(a.cache){const{reactions:e}=n,a=Bn(n,["reactions"]);Fn(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)st(this.cacheKey,{data:r.map(Ze("reactor"))});else{const e=null===(o=at(this.cacheKey))||void 0===o?void 0:o.data,t=null!==(i=null==e?void 0:e.data)&&void 0!==i?i:[];st(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...r.map(Ze("reactor"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(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))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ql extends Rr{constructor(e,t){const n=R.default(e),a=["reaction","collection",n];super(new El(e),n,a,t),this.query=e,this.queryStreamController=new Ml(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=>jl(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>kl(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const a=Ye(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e)return xt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await ha(e);t.reactions[0]&&(Fn(t),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return xt(a,"local.post.removeReaction","local.post.removeReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return xt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Bn(e,["reactions"]);Fn(n),Fn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return xt(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=Ye(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e)return xt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await ha(e);t.reactions[0]&&(Fn(t),Fn({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return xt(a,"local.post.addReaction","local.post.addReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return xt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Bn(e,["reactions"]);Fn(n),Fn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return xt(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["reactor","get",e]))).filter(Boolean).map((({data:e})=>hd.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 xl=Object.freeze({__proto__:null,addReaction:cl,removeReaction:dl,onReactionAdded:(e,t,n)=>{const a=a=>{Ze(e)(a)===t&&n(a)};if("message"===e){const e=Ye(),t=async e=>{var t;const n=await ha(e),s=at(["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;Fn(n),o&&a(n.messages[0])};return xt(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?Il(a):Dl(a)},onReactionRemoved:(e,t,n)=>{const a=a=>{Ze(e)(a)===t&&n(a)};if("message"===e){const e=Ye(),t=async e=>{var t;const n=await ha(e),s=at(["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;Fn(n),o&&a(n.messages[0])};return xt(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?Cl(a):Ul(a)},onReactorAdded:jl,onReactorRemoved:kl,getReactions:(e,t,n)=>{const{log:a,cache:s}=Ye(),o=Date.now();a(`getReactions(tmpid: ${o}) > listen`);const i=new ql(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getReactions(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});function Nl(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const Kl=async()=>{var e;const t=Ye();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&&(rt(["archivedChannel","get"]),a.forEach((e=>{e.channelId&&st(["archivedChannel","get",e.channelId],e)}))),a.map((e=>e.channelId)).filter((e=>!!e))},Fl=e=>{const t=Ye(),n=[xt(t,"onMessageUpdated","message.updated",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])})),xt(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},_l=e=>{const t=Ye(),n=[xt(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])})),xt(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},Bl=e=>{const t=Ye(),n=[xt(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await fa(t);Fn(n),e(n.messageFeeds[0])})),xt(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function $l(e,t){st(["channel","get",e.channelId],Xn(e,t))}const Ll=e=>{const t=Ye();return xt(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},Ql=async(e,t=!1)=>{const n=Ye(),a=await ba(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:tt(a.data.updatedAt)});return t?setTimeout((()=>{_n("subChannel",e)}),0):it(["subChannel","get",e],s),Nt("local.message-feed.deleted",{messageFeeds:[s]}),s},Vl=e=>xt(Ye(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),Jl=()=>`LOCAL_${jn()}`;let Hl;const Gl=async(e,t)=>{const n=Ye();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)}`,ma(t)),s=await ha(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{messages:i}=s;return Nt("local.message.updated",{messages:i}),{data:hd.message(i.find((t=>t.messageId===e))),cachedAt:o}};Gl.optimistically=(e,t)=>{const n=Ye();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const a=at(["message","get",e]);if(!a)return;const s=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return it(["message","get",e],s,{cachedAt:-1}),Nt("local.message.updated",{messages:[s]}),{data:hd.message(s),cachedAt:-1}};const zl=async(e,t)=>{const n=Ye();n.log("message/editMessage",t);const{data:a}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,ma(t)),s=await ha(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{messages:i}=s;return Nt("local.message.updated",{messages:i}),{data:hd.message(i.find((t=>t.messageId===e))),cachedAt:o}};zl.optimistically=(e,t)=>{const n=Ye();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const a=at(["message","get",e]);if(!a)return;const s=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return it(["message","get",e],s,{cachedAt:-1}),Nt("local.message.updated",{messages:[s]}),{data:hd.message(s),cachedAt:-1}};const Yl=async e=>{var t;const n=Ye();if(n.log("message/deleteMessage",e),e.includes("LOCAL_")){const n=null===(t=at(["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 Nt("local.message.deleted",{messages:[a]}),hd.message(a)}const{data:a}=await n.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),s=await ha(a);return Nt("local.message.deleted",{messages:[s.messages[0]]}),hd.message(s.messages[0])};Yl.optimistically=e=>{Ye().log("message/deleteMessage.optimistically",e);const t=at(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return it(["message","get",e],n,{cachedAt:-1}),Nt("local.message.deleted",{messages:[n]}),{data:hd.message(n),cachedAt:-1}};const Wl=async e=>{const t=Ye();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await Vd(e);return Nt("local.message.deleted",{messages:[n.data]}),hd.message(n.data)};Wl.optimistically=e=>{Ye().log("message/softDeleteMessage.optimistically",e);const t=at(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return it(["message","get",e],n,{cachedAt:-1}),Nt("local.message.deleted",{messages:[n]}),{data:hd.message(n),cachedAt:-1}};const Xl=async e=>{const t=Ye();t.log("user/getReadUsers",e);const{page:n,messageId:a}=e,s=Bn(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${a}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:Ee(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:r,userFeedMarkers:c}=o,d=Bn(o,["paging","publicUserIds","userFeedMarkers"]),l=t.cache&&Date.now();if(t.cache){Fn(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)})];st(e,{users:r,paging:i})}let u=[];r.length>0&&({data:u}=await md(r));return{data:u,cachedAt:l,prevPage:Me(i.previous),nextPage:Me(i.next)}};Xl.locally=e=>{var t;const n=Ye();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:a}=e,s=Bn(e,["page"]),o=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},a)})],{data:i,cachedAt:r}=null!==(t=at(o))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=at(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:r,prevPage:Me(null==i?void 0:i.paging.previous),nextPage:Me(null==i?void 0:i.paging.next)}};const Zl=async e=>{const t=Ye();t.log("user/getDeliveredUsers",e);const{page:n,messageId:a}=e,s=Bn(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${a}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:Ee(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:r,userFeedMarkers:c}=o,d=Bn(o,["paging","publicUserIds","userFeedMarkers"]),l=t.cache&&Date.now();if(t.cache){Fn(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)})];st(e,{users:r,paging:i})}let u=[];r.length>0&&({data:u}=await md(r));return{data:u,cachedAt:l,prevPage:Me(i.previous),nextPage:Me(i.next)}};Zl.locally=e=>{var t;const n=Ye();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:a}=e,s=Bn(e,["page"]),o=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},a)})],{data:i,cachedAt:r}=null!==(t=at(o))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=at(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:r,prevPage:Me(null==i?void 0:i.paging.previous),nextPage:Me(null==i?void 0:i.paging.next)}};const eu=e=>{const t=Ye();return xt(t,"onMessageFlagged","message.flagged",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])}))},tu=e=>{const t=Ye();return xt(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])}))},nu=e=>{const t=Ye();return xt(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])}))},au=e=>{const t=Ye();return xt(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await ha(t,"message.reactionAdded");Fn(n),e(n.messages[0])}))},su=e=>{const t=Ye();return xt(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await ha(t,"message.reactionRemoved");Fn(n),e(n.messages[0])}))},ou=e=>{const t=Ye();return xt(t,"message/onMessageFetched","local.message.fetched",(t=>{Fn(t),e(t.messages[0])}))},iu=e=>{const t=Ye();return xt(t,"stream/onStreamViewerDidBan","video-streaming.viewerDidBan",(t=>{var n;const{list:a}=t;a.forEach((e=>{var t;ot(["stream","get",e.streamId],{watcherUrl:null});const n=null===(t=nt(["message","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.creatorId===e.userId));null==n||n.forEach((e=>{ot(e.key,{isDeleted:!0})}))}));const s=null===(n=at(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))};class ru extends Sr{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=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.messages.map(Ze("message")),query:this.query});else{const n=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,o=null!==(s=null==n?void 0:n.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...o,...e.messages.map(Ze("message"))])]:[...new Set([...e.messages.map(Ze("message")),...o])]}))}}reactor(e){return t=>{var n,a,s,o;if("onCreate"===e){const e=null===(n=at(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])]),st(this.cacheKey,e)}if("onDelete"===e&&"error"===t.syncState){const e=null===(o=at(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));st(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 cu extends Cr{async getRequest(e,t){const n=ga(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 du extends Rr{constructor(e,t){const n=R.default(e),a=["message","collection",n];super(new cu(e),n,a,t),this.query=e,this.queryStreamController=new ru(this.query,this.cacheKey,this.notifyChange.bind(this),ha,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ii,action:"onCreate"},{fn:Ci,action:"onCreate"},{fn:_l,action:"onDelete"},{fn:Fl,action:"onUpdate"},{fn:eu,action:"onFlagged"},{fn:tu,action:"onUnflagged"},{fn:nu,action:"onFlagCleared"},{fn:au,action:"onReactionAdded"},{fn:su,action:"onReactionRemoved"},{fn:Pd(Zi,"contentId","message"),action:"onUpdate"},{fn:Pd(er,"contentId","message"),action:"onUpdate"},{fn:Pd(iu,"channelId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>sa(e))).filter(Boolean).map((e=>hd.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=ct(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=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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 lu extends Cr{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=ge}=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 uu extends Sr{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){var t;const n=await ha(e),a=Ye(),s=a.cache&&Date.now();a.cache&&(Fn(n,{cachedAt:s}),(null===(t=e.channels)||void 0===t?void 0:t.length)&&e.channels.forEach((e=>{st(["channel","get",e.channelId],e,{cachedAt:s})})))}appendToQueryStream(e,t,n=!1){var a,s;if(n)return void st(this.cacheKey,{data:e.messages.map(Ze("message"))});const o=null===(a=at(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(Ze("message"));st(this.cacheKey,Object.assign(Object.assign({},o),{data:"prev"===t?[...new Set([...r,...i])]:[...new Set([...i,...r])]}))}}class hu extends Rr{constructor(e,t){const n=R.default(e),a=["message","search",n];super(new lu(e),n,a,t),this.queryStreamController=new uu(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>sa(e))).filter(Pr).map((e=>hd.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=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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 mu=Object.freeze({__proto__:null,createMessage:async e=>{const t=Ye();t.log("message/createMessage",e);const n=(e=>{var t,n;const a=Ye();if(!a.cache)return;Hl=e.referenceId||Jl();const s=Object.assign({messageId:Hl,uniqueId:Hl},e);a.log("message/createMessage.optimistically",s);const o=at(["subChannel","get",e.subChannelId]);if(o&&(it(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},o.data),{messageCount:o.data.messageCount+1})),o.data.channelId===o.data.subChannelId)){const e=at(["channel","get",o.data.channelId]);(null==e?void 0:e.data)&&it(["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:Ut()._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 st(["message","get",r.messageId],r,{cachedAt:-5}),Nt("local.message.created",{messages:[r]}),r})(e),a=e.referenceId||Hl||Jl();Hl=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},ma(e)),{referenceId:a})),s=await ha(n),{messages:o}=s,i=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:i}),Nt("local.message.created",{messages:[Object.assign(Object.assign({},o[0]),{syncState:"synced"})]}),{data:hd.message(o[0]),cachedAt:i}}catch(e){throw Nt("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:Gl,editMessage:zl,deleteMessage:Yl,softDeleteMessage:Wl,markAsDelivered:async(e,t)=>{const n=Ye();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=Bn(a,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Fn(Object.assign({userMarkers:s,userEntityMarkers:Vn(o),userFeedMarkers:Jn(i)},r),{cachedAt:c}),!0},getReadUsers:Xl,getDeliveredUsers:Zl,flagMessage:async(t,n)=>{const a=Ye();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 ha(i);Fn(e)}return Nt("message.flagged",i),!!i},unflagMessage:async e=>{const t=Ye();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await ha(n);Fn(e)}return Nt("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=Ye();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:Ii,onMessageCreatedLocal:Ci,onMessageUpdated:Fl,onMessageDeleted:_l,onMessageFlagged:eu,onMessageUnflagged:tu,onMessageFlagCleared:nu,onMessageReactionAdded:au,onMessageReactionRemoved:su,onMessageFetched:ou,getMessage:(e,t)=>qr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hd.message(e.data):n}))}),"messageId",Vd,[ou,Fl,_l,eu,tu,nu,au,su,Pd(Zi,"contentId","message"),Pd(er,"contentId","message"),Pd(iu,"channelId","message")]),getMessages:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMessages(tmpid: ${o}) > listen`);const i=new du(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(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}=Ye();a||console.log(ve);const s=Date.now();n(`searchMessage(tmpid: ${s}) > listen`);const o=new hu(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{rt(r)})),()=>{n(`searchMessage(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},convertFromRaw:la,prepareMessagePayload:ha,convertParams:ma,convertQueryParams:ga});const gu=e=>{const t=Ye();return xt(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class pu extends Cr{async getRequest(e,t){var n;const{limit:a=ge}=e,s=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=Bn(e,["excludeDefaultSubChannel"]);const a=Object.assign({},n);return void 0!==t&&(a.excludeDefaultMessageFeed=t),a}(Bn(e,["limit"])))&&void 0!==n?n:{},{channelId:o,includeDeleted:i}=s,r=Bn(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:oa(i),options:c})});return d}}class yu extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(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=at(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])]),st(this.cacheKey,a)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class vu extends Rr{constructor(e,t){const n=R.default(e),a=["subChannel","collection",n];super(new pu(e),n,a,t),this.query=e,this.queryStreamController=new yu(this.query,this.cacheKey,this.notifyChange.bind(this),fa),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Vl,action:"onCreate"},{fn:wi,action:"onCreate"},{fn:Si,action:"onDelete"},{fn:e=>Bl((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=Ye();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=zn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Gn(t.updatedAt)>Gn(e.subChannelUpdatedAt)&&st(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:Pd((e=>Ii((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Ca(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pd((e=>Ci((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Ca(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>Wi((t=>{var n;const a=null!==(n=t.map((({feedId:e})=>at(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==a.length&&e(a)})),action:"onUpdate"},{fn:Pd(Yi,"feedId","subChannel"),action:"onUpdate"},{fn:Pd((e=>Fl((async t=>{var n;const a=Ye();if("no-message-preview"===await a.getMessagePreviewSetting(!1))return;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;s&&s.data.includes(t.subChannelId)&&(wa(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pd((e=>_l((async t=>{const n=Ye(),a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===a?await ba(t.subChannelId):await wa(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pd(gu,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Yn))&&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=ct(e,"isDeleted",!1)),t.sort(Tt),t}isRelatedCollection(e){var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const fu={},bu=async e=>{const t=await(async e=>{const t=ba.locally(e);if(t)return t.data.channelId;const{data:n}=await ba(e);return n.channelId})(e),n=Gt({channelId:t,subChannelId:e});fu[e]=en(n)};var Iu=Object.freeze({__proto__:null,getSubChannelByIds:Ks,createSubChannel:async e=>{const t=Ye();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),a=await fa(n.data),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),Nt("message-feed.created",n.data),{data:a.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const n=Ye();n.log("channel/updateSubChannel",e,t);const a=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await fa(a.data),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),Nt("message-feed.updated",a.data),{data:s.messageFeeds[0],cachedAt:o}},deleteSubChannel:Ql,hardDeleteSubChannel:async e=>{Ye().log("channel/hardDeleteSubChannel",e);return await Ql(e,!0)},softDeleteSubChannel:async e=>{Ye().log("channel/softDeleteSubChannel",e);return await Ql(e,!1)},onSubChannelCreated:wi,onSubChannelUpdated:Bl,onSubChannelDeleted:Si,getSubChannel:(e,t)=>{const n=Ye();let a;return qr(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Yn(e.data)}),s=Bn(n,["origin"]);return Fa(a,s)?void 0:(a=s,t(n))}),"subChannelId",ba,[Vl,t=>Bl((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Aa(a),a.subChannelId===e&&t(a))})),Si,Pd(Yi,"feedId","subChannel"),t=>Wi((n=>{var a;if(!n.find((({feedId:t})=>t===e)))return;const s=null===(a=at(["subChannel","get",e]))||void 0===a?void 0:a.data;s&&t(s)})),Pd((t=>Ii((async n=>{n.subChannelId===e&&(await Ca(n),t(n))}))),"subChannelId","subChannel"),Pd((t=>Ci((async n=>{n.subChannelId===e&&(await Ca(n),t(n))}))),"subChannelId","subChannel"),Pd((t=>Fl((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&a.subChannelId===e&&(wa(a),t(a))}))),"subChannelId","subChannel"),Pd((t=>_l((async a=>{const s=await n.getMessagePreviewSetting(!1);"no-message-preview"!==s&&a.subChannelId===e&&("message-preview-include-deleted"===s&&await wa(a),"message-preview-not-include-deleted"===s&&await ba(a.subChannelId),t(a))}))),"subChannelId","subChannel"),Pd(gu,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:a,cache:s}=Ye(),o=Date.now();a(`getSubChannels(tmpid: ${o}) > listen`),s||console.log(ve);const i=new vu(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getSubChannels(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},markReadEngineOnLoginHandler:Ns,startMessageReceiptSync:async e=>(await bu(e),!0),stopMessageReceiptSync:e=>(fu[e]&&fu[e](),!0)});const Cu=e=>{const t=Ye();return xt(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},wu=e=>{const t=Ye();return xt(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class Su extends Cr{async getRequest(e,t){const{limit:n=ge,displayName:a,membership:s}=e,o=Bn(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 Ou extends Tr{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class Au extends Sr{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=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.channels.map(Ze("channel"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(Ze("channel"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(this.paginationController instanceof Ou)return this.notifyChange({origin:"event",loading:!1});if(["onCreate","onJoin","onResolveChannel","onUnarchived"].includes(e)&&(Array.isArray(t)?a.data=[...new Set([...t.map(Ze("channel")),...a.data])]:a.data=[...new Set([t.channelInternalId,...a.data])]),"onArchived"===e){const e=Array.isArray(t)?t.map(Ze("channel")):[Ze("channel")(t)];a.data=a.data.filter((t=>!e.includes(t)))}st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Tu=e=>{const t=Ye();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){Eo().resolve(e.channelId,"userMessageFeedMarker")}},Ru=e=>{const t=Ye();return xt(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))},Pu=e=>{const t=Ye();return xt(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))};class Du extends Rr{constructor(e,t){const n=R.default(e),a=["channel","collection",n],s=Du.getPaginationController(e);super(s,n,a,t),this.query=e,this.queryStreamController=new Au(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=Ye();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ka(e)}catch(e){console.error("Error while preparing unread count info",e)}return Ua(e)}),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;let i=null!==(s=o.data.map((e=>at(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Us))&&void 0!==s?s:[];this.paginationController instanceof Su&&(i=this.applyFilter(i)),(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof Su?()=>this.loadPage({direction:"next"}):void 0,data:i,hasNextPage:this.paginationController instanceof Su&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ye();let n=e;switch(n=ct(n,"isDeleted",this.query.isDeleted),n=dt(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=ut(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(Ct);break;case"lastCreated":n=n.sort(St);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(bt);break;default:n=n.sort(Tt)}return n}shouldAbort(e){var t,n;const a=null===(t=at(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 Ye().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Ou(e):new Su(e)}getSubscriptions(){const e=[{fn:Pd((e=>Ii((t=>{var n,a;const s=Eo();(null===(n=at(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||s.resolve(t.subChannelId,"userMessageFeedMarker");const o=null===(a=at(["channel","get",t.channelId]))||void 0===a?void 0:a.data;o?($l(o,{lastActivity:t.createdAt}),e(t)):s.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Ci((t=>{var n;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya,action:"onDelete"},{fn:Va,action:"onUpdate"},{fn:os,action:"onMute"},{fn:e=>Za((t=>{Tu(t),e(t)})),action:"onJoin"},{fn:e=>ns(((t,n)=>{var a,s;const{userId:o}=Ye();if("member"===this.query.membership&&o===n.userId){const e=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;st(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:cs,action:"onMemberAdded"},{fn:us,action:"onMemberRemoved"},{fn:e=>Os((t=>{const n=t.archives.map((e=>{var t;return null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>As((t=>{const n=t.archives.map((e=>{var t;return null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Pd(zi,"entityId","channel"),action:"onUpdate"},{fn:Pd(Ll,"entityId","channel"),action:"onUpdate"},{fn:Pd((e=>Ii((async t=>{var n;if("no-message-preview"===await Du.getMessagePreviewSetting())return;if(Sa(t),this.shouldAbort(t.channelId))return;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Ci((async t=>{var n;if("no-message-preview"===await Du.getMessagePreviewSetting())return;if(Sa(t),this.shouldAbort(t.channelId))return;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Fl((async t=>{"no-message-preview"!==await Du.getMessagePreviewSetting()&&(await Oa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>_l((async t=>{const n=await Du.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Oa(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await vc(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Si((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;a.data.find((e=>{const n=Hn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await vc(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Bl((async t=>{var n;if("no-message-preview"===await Du.getMessagePreviewSetting())return;(null===(n=at(this.cacheKey))||void 0===n?void 0:n.data)&&(await Aa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd(wi,"channelId","channel"),action:"onUpdate"},{fn:Ru,action:"onResolveChannel"},{fn:e=>Pu((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=at(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Pd(Cu,"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>wu((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof Cr?[...e,{fn:e=>$a((t=>{Tu(t),e(t)})),action:"onCreate"}]:e}}const Uu=()=>{var e;const t=Ye();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=nt(["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 ju extends Cr{async getRequest(e,t){var n,a;const s=null!==(n=e.limit)&&void 0!==n?n:ge,o=t?Number.parseInt(t,10):0;0===o&&await Kl();const i=(null!==(a=nt(["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 js(d.map((e=>e.channelId))),{archives:d,paging:{next:l?String(o+1):void 0,previous:void 0}}}}class ku extends Sr{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 st(this.cacheKey,{data:o,params:{}});const i=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,r=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[];st(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=at(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)))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Eu extends Rr{constructor(e,t){const n=R.default(e),a=["archivedChannel","collection",n];super(new ju(e),n,a,t),this.queryStreamController=new ku(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=>Os((t=>e(t.archives.map((e=>e.channelId))))),action:"onArchived"},{fn:e=>As((t=>e(t.archives.map((e=>e.channelId))))),action:"onUnarchived"},{fn:e=>Va((t=>e([t.channelId]))),action:"onUpdate"},{fn:e=>Ya((t=>e([t.channelId]))),action:"onDelete"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["channel","get",e]))).filter((e=>Boolean(e))).map((({data:e})=>e)).map(Us))&&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 Mu extends Cr{async getRequest(e,t){const{query:n,exactMatch:a,isMemberOnly:s,types:o,tags:i,sortBy:r,orderBy:c,limit:d=pe}=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 qu extends Sr{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){const t=await Ua(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)return void st(this.cacheKey,{data:e.channels.map(Ze("channel"))});const o=null===(a=at(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(Ze("channel"));st(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 xu=()=>Ye().getMessagePreviewSetting(!1);class Nu extends Rr{constructor(e,t){const n=R.default(e),a=["channel","search",n];super(new Mu(e),n,a,t),this.queryStreamController=new qu(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["channel","get",e]))).filter(Boolean).map((e=>Us(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=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=at(this.cacheKey))||void 0===t?void 0:t.data;return!n||!n.data.find((t=>t===e))}getSubscriptions(){return[{fn:Pd((e=>Ii((t=>{var n;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Ci((t=>{var n;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya,action:"onDelete"},{fn:Va,action:"onUpdate"},{fn:os,action:"onMute"},{fn:e=>Os((t=>{const n=t.archives.map((e=>{var t;return null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>As((t=>{const n=t.archives.map((e=>{var t;return null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Pd(zi,"entityId","channel"),action:"onUpdate"},{fn:Pd(Ll,"entityId","channel"),action:"onUpdate"},{fn:Pd((e=>Ii((async t=>{var n;if("no-message-preview"===await xu())return;if(Sa(t),this.shouldAbort(t.channelId))return;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Ci((async t=>{var n;if("no-message-preview"===await xu())return;if(Sa(t),this.shouldAbort(t.channelId))return;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Fl((async t=>{"no-message-preview"!==await xu()&&(await Oa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>_l((async t=>{const n=await xu();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Oa(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await vc(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Si((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;a.data.find((e=>{const n=Hn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await vc(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Bl((async t=>{var n;if("no-message-preview"===await xu())return;(null===(n=at(this.cacheKey))||void 0===n?void 0:n.data)&&(await Aa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:e=>Pu((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=at(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Pd(Cu,"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>wu((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}]}}class Ku extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a}=e,s=Bn(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 Fu extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>Ze("channelUsers")({channelId:e,userId:t})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>Ze("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;const s=Ze("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)),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class _u extends Rr{constructor(e,t){const n=R.default(e),a=["channelUsers","collection",n];super(new Ku(e),n,a,t),this.query=e,this.queryStreamController=new Fu(this.query,this.cacheKey,this.notifyChange.bind(this),Ua),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Za,action:"onJoin"},{fn:ns,action:"onLeft"},{fn:cs,action:"onMemberAdded"},{fn:us,action:"onMemberRemoved"},{fn:gs,action:"onChannelMemberBanned"},{fn:vs,action:"onChannelMemberUnbanned"},{fn:Is,action:"onChannelMemberRoleAdded"},{fn:Ss,action:"onChannelMemberRoleRemoved"},{fn:Ps,action:"onChannelSetUserMuted"},{fn:(e=this.query.channelId,t=>{const n=Ye();return xt(n,"user.deleted","user.deleted",(n=>{var a,s;const o=eo(n);if(0===o.users.length)return;const i=o.users[0];Fn(o);const r=Ze("channelUsers")({channelId:e,userId:i.userId}),c=null===(a=at(["channelUsers","get",r]))||void 0===a?void 0:a.data;it(["channelUsers","get",r],Object.assign(Object.assign({},c),{user:i}));const d=null===(s=at(["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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(hd.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=lt(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?St:Ct),t}}const Bu=(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new _u(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}};var $u=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ye();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=>Nt("channel.membersAdded",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const s=await Ua(a);n.cache&&Fn(s);const{channelUsers:o}=s;return!!o.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=Ye();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=>Nt("channel.membersRemoved",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const s=await Ua(a);n.cache&&Fn(s);const{channelUsers:o}=s;return!!o.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=lt(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?St:Ct),n},getMembers:Bu,searchMembers:(e,t,n)=>Bu(e,t)});var Lu=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const a=Ye();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 Ua(s);a.cache&&Fn(o),Nt("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=Ye();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 Ua(s);a.cache&&Fn(o),Nt("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=Ye();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 Ua(a),{channelUsers:o}=s,i=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:i}),Nt("channel.banned",a),{data:null==o?void 0:o.filter((e=>"banned"===e.membership)),cachedAt:i}},unbanMembers:async(e,t)=>{const n=Ye();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 Ua(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o}),Nt("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=Ye();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 Nt("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=Ye();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 Nt("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:new Date(0).toISOString(),actor:null!==(n=a.userId)&&void 0!==n?n:""}),o}}),Qu=Object.freeze({__proto__:null,Membership:$u,Moderation:Lu,getChannelByIds:js,createChannel:yc,updateChannel:async(e,t)=>{const n=Ye();n.log("channel/updateChannel",e,t);const{data:a}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await Ua(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{channels:i}=s;return{data:xa(i.find((t=>t.channelId===e))),cachedAt:o}},deleteChannel:async e=>{const t=Ye();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await vc(e);return xa(n.data)},joinChannel:async e=>{const t=Ye();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),a=await Ua(n);t.cache&&Fn(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=Ye();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),a=await Ua(n);t.cache&&Fn(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=Ye();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new Qe("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=Ye();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=Ye();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&&st(["archivedChannel","get",Ze("archivedChannel")(n)],n),Nt("local.channel.archived",{archives:[n]})},unarchiveChannel:async e=>{var t;const n=Ye();n.log("channel/unarchiveChannel",e),await n.http.delete(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const a=null===(t=at(["archivedChannel","get",e]))||void 0===t?void 0:t.data,s=null!=a?a:{channelId:e,archivedAt:(new Date).toISOString()};n.cache&&rt(["archivedChannel","get",e],!0),Nt("local.channel.unarchived",{archives:[s]})},getArchivedChannelIds:Kl,onChannelCreated:$a,onChannelUpdated:Va,onChannelDeleted:Ya,onChannelJoined:Za,onChannelLeft:ns,onChannelSetMuted:os,onChannelMemberAdded:cs,onChannelMemberRemoved:us,onChannelMemberBanned:gs,onChannelMemberUnbanned:vs,onChannelMemberRoleAdded:Is,onChannelMemberRoleRemoved:Ss,onChannelArchived:Os,onChannelUnarchived:As,getChannel:(e,t)=>{const n=Ye();let a;return qr(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Us(e.data)}),s=Bn(n,["origin"]);return Fa(a,s)?void 0:(a=s,t(n))}),"channelId",vc,[Va,Ya,Za,ns,cs,us,gs,vs,os,Pd(zi,"entityId","channel"),Pd(Ll,"entityId","channel"),Pd((t=>Ii((async a=>{await(async a=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Sa(a),a.channelId!==e)return;const o=null===(s=at(["channel","get",e]))||void 0===s?void 0:s.data;o&&($l(o,{messagePreviewId:a.messageId}),t(a))})(a),t(a)}))),"channelId","channel"),Pd((t=>Ci((async a=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Sa(a),a.channelId!==e)return;const o=null===(s=at(["channel","get",e]))||void 0===s?void 0:s.data;o&&($l(o,{messagePreviewId:a.messageId}),t(a))}))),"channelId","channel"),Pd((t=>Fl((async a=>{var s;const o=null===(s=at(["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 Oa(a),t(a))}))),"channelId","channel"),Pd((t=>_l((async a=>{var s;const o=null===(s=at(["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?(rt(["messagePreviewChannel","get",e]),await vc(a.channelId)):await Oa(a),t(a))}))),"channelId","channel"),Pd((e=>Si((async t=>{var a,s;const{channelId:o,subChannelId:i}=t,r=null===(a=at(["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 vc(o);(null===(s=at(["channel","get",o]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),Pd((t=>Bl((async a=>{var s,o;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Aa(a);const i=null===(s=at(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!i||i.subChannelId!==a.subChannelId)return;(null===(o=at(["channel","get",e]))||void 0===o?void 0:o.data)&&t(a)}))),"channelId","channel"),Pd(wi,"channelId","channel"),Pd(Cu,"channelId","channel"),Pd((e=>wu((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getChannels(tmpid: ${i}) > listen`);const r=new Du(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{rt(d)})),()=>{a(`getChannels(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=Ut();if(!t)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=Ye();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?nr(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return s.push(wu((e=>{const{data:t}=Uu();Fa(o,t)||r({loading:!1,data:t})}))),(()=>{const e=_e((async()=>Uu()));$e(e,(({error:e,data:t,loading:n,origin:a,cachedAt:o})=>{o===be?(r({data:t,origin:a,loading:!1,error:new Ve(fe,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}=Ye();a||console.log(ve);const s=Date.now();n(`getArchivedChannels(tmpid: ${s}) > listen`);const o=new Eu(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{rt(r)})),()=>{n(`getArchivedChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchChannels:(e,t)=>{const{log:n,cache:a}=Ye();a||console.log(ve);const s=Date.now();n(`searchChannels(tmpid: ${s}) > listen`);const o=new Nu(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{rt(r)})),()=>{n(`searchChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Ta,isUnreadCountSupport:Ra,convertFromRaw:Pa,preUpdateChannelCache:Da,prepareChannelPayload:Ua});const Vu=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));st(["communityUsers","collection",e],n)}))},Ju=async(e,t)=>{const n=Ye();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=_r(s),i=n.cache&&Date.now();return n.cache&&(Fn(o,{cachedAt:i}),Vu(o.communities,o.communityUsers)),{data:o.communities.map((e=>hd.community(e))),cachedAt:i}};Ju.locally=e=>{const t=Ye();if(t.log("community/getCommunities.locally",e),!t.cache)return;const n=e.map((e=>at(["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 Hu=async e=>{const t=Ye();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),a=_r(n),s=t.cache&&Date.now();t.cache&&(Fn(a,{cachedAt:s}),Vu(a.communities,a.communityUsers));const{communities:o}=a;return{data:o.find((t=>t.communityId===e)),cachedAt:s}};Hu.locally=e=>{const t=Ye();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=at(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Gu=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=_r(e);if(n.cache){Fn(a);const e=at(["community","get",a.communities[0].communityId]);t(e.data)}else t(a.communities[0])}))},zu=e=>Gu("community.created",e),Yu=e=>Gu("community.updated",e),Wu=e=>Gu("community.deleted",e);class Xu extends Cr{async getRequest(e,t){var n;const{limit:a=ge}=e,s=Bn(e,["limit"]),o=t?{token:t}:{limit:a},{data:i}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:oa(s.includeDeleted),keyword:s.displayName,filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return i}}class Zu extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communities.map(Ze("community"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ze("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var eh,th;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(eh||(eh={})),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"}(th||(th={}));class nh extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a,excludingRoles:s}=e,o=Bn(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 ah extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Ze("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Ze("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{var t;const n=Ze("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]}})),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function sh(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function oh(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=>!sh(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!sh(e,t,"ADD_COMMUNITY_USER")))}const ih=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{const s=_r(a),{communities:o,communityUsers:i}=s,r=Nr(o,i);if(s.communities=r,n.cache){Fn(s,void 0,!1);const n=at(["community","get",s.communities[0].communityId]),a=oh(e,s).map((e=>{const t=at(["communityUsers","get",Ze("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Pr);t(n.data,a)}else t(s.communities[0],oh(e,s))}))},rh=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{const s=_r(a),{communities:o,communityUsers:i}=s,r=Nr(o,i);if(s.communities=r,n.cache){Fn(s,void 0,!1);const n=at(["community","get",s.communities[0].communityId]),a=oh(e,s).map((e=>{const t=at(["communityUsers","get",Ze("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Pr);t(n.data,a)}else t(s.communities[0],oh(e,s))}))},ch=e=>ih("community.userBanned",e),dh=e=>ih("community.userChanged",e),lh=e=>ih("community.userUnbanned",e),uh=e=>ih("community.roleAdded",e),hh=e=>ih("community.roleRemoved",e),mh=e=>rh("local.community.userAdded",e),gh=e=>rh("local.community.userRemoved",e),ph=e=>ih("community.joined",e),yh=e=>ih("community.left",e),vh=e=>rh("local.community.joined",e),fh=e=>rh("local.community.left",e),bh=e=>{const t=Ye(),n=[xt(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},Ih=e=>{const t=Ye();return xt(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:a}=t;e(n[0],a.filter((e=>"member"===e.communityMembership)))}))},Ch=e=>{const t=Ye();return xt(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:a}=t;e(n[0],a.filter((e=>"member"===e.communityMembership)))}))},wh=e=>t=>{const n=Ye();return xt(n,"user.deleted","user.deleted",(n=>{var a,s;const o=eo(n);if(0===o.users.length)return;const i=o.users[0];Fn(o);const r=Ze("communityUsers")({communityId:e,userId:i.userId}),c=null===(a=at(["communityUsers","get",r]))||void 0===a?void 0:a.data;st(["communityUsers","get",r],Object.assign(Object.assign({},c),{user:i}));const d=null===(s=at(["community","get",e]))||void 0===s?void 0:s.data;t(d,[Object.assign(Object.assign({},c),{user:i})])}))};class Sh extends Rr{constructor(e,t){const n=R.default(e),a=["communityUsers","collection",n];super(new nh(e),n,a,t),this.query=e,this.queryStreamController=new ah(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:ph,action:th.OnCommunityJoined},{fn:vh,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:fh,action:th.OnCommunityLeft},{fn:ch,action:th.OnCommunityUserBanned},{fn:dh,action:th.OnCommunityUserChanged},{fn:uh,action:th.OnCommunityUserRoleAdded},{fn:hh,action:th.OnCommunityUserRoleRemoved},{fn:Ch,action:th.OnCommunityUserRoleAdded},{fn:Ih,action:th.OnCommunityUserRoleRemoved},{fn:lh,action:th.OnCommunityUserUnbanned},{fn:mh,action:th.OnCommunityUserAdded},{fn:gh,action:th.onCommunityUserRemoved},{fn:wh(this.query.communityId),action:th.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["communityUsers","get",e]))).filter(Pr).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=lt(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(Ct);else n=n.sort(St);return n}}class Oh extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a,excludingRoles:s}=e,o=Bn(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 Ah extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Ze("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Ze("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{const t=Ze("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(a.data=a.data.filter((e=>e!==t)))})),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Th;!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"}(Th||(Th={}));class Rh extends Rr{constructor(e,t){const n=R.default(e),a=["communityUsers","collection",n];super(new Oh(e),n,a,t),this.query=e,this.queryStreamController=new Ah(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:ph,action:Th.OnCommunityJoined},{fn:vh,action:Th.OnCommunityJoined},{fn:yh,action:Th.OnCommunityLeft},{fn:fh,action:Th.OnCommunityLeft},{fn:ch,action:Th.OnCommunityUserBanned},{fn:dh,action:Th.OnCommunityUserChanged},{fn:Ih,action:Th.OnCommunityUserRoleRemoved},{fn:hh,action:Th.OnCommunityUserRoleRemoved},{fn:lh,action:Th.OnCommunityUserUnbanned},{fn:wh(this.query.communityId),action:Th.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["communityUsers","get",e]))).filter(Pr).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=lt(e,"roles",this.query.roles);return this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(n=pt(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 Ph=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ye();n.log("community/moderation/addMembers",e,t);const{data:a}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});Nt("local.community.userAdded",a);const s=Ln(a,"communityUsers");n.cache&&Fn(s);const{communityUsers:o}=s;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=Ye();n.log("community/moderation/removeMembers",e,t);const{data:a}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});Nt("local.community.userRemoved",a);const s=Ln(a,"communityUsers");n.cache&&Fn(s);const{communityUsers:o}=s;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{var n;let a=lt(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?St:Ct),a},getMembers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);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((()=>{rt(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new Rh(e,(e=>{t(e)})),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},onCommunityUserAdded:e=>ih("community.userAdded",e),onCommunityUserRemoved:e=>ih("community.userRemoved",e),onCommunityUserBanned:ch,onCommunityUserChanged:dh,onCommunityUserUnbanned:lh,onCommunityUserRoleAdded:uh,onCommunityUserRoleRemoved:hh,onLocalCommunityUserAdded:mh,onLocalCommunityUserRemoved:gh,onCommunityJoined:ph,onCommunityLeft:yh,onLocalCommunityJoined:vh,onLocalCommunityLeft:fh,onLocalCommunityJoin:bh});class Dh extends Rr{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Xu(e),n,a,t),this.query=e,this.queryStreamController=new Zu(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Wu,action:eh.OnCommunityDeleted},{fn:Yu,action:eh.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:eh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["community","get",e]))).filter(Pr).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}=Ye();let n=e;return this.query.includeDeleted||(n=ct(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=mt(n,this.query.membership,t)),n}}class Uh extends Cr{async getRequest(e,t){var n;const{limit:a=ge}=e,s=Bn(e,["limit"]),o=t?{token:t}:{limit:a},{data:i}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:oa(s.includeDeleted),filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return i}}class jh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&(Fn(t,{cachedAt:a}),Vu(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communities.map(Ze("community"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ze("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var kh;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(kh||(kh={}));class Eh extends Rr{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Uh(e),n,a,t),this.query=e,this.queryStreamController=new jh(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:zu,action:kh.OnCommunityCreated},{fn:Wu,action:kh.OnCommunityDeleted},{fn:Yu,action:kh.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:kh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["community","get",e]))).filter(Pr).map((({data:e})=>mc(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}=Ye();let n=e;this.query.includeDeleted||(n=ct(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=mt(n,this.query.membership,t));const a=(()=>"firstCreated"===this.query.sortBy?Ct:St)();return n=n.sort(a),n}}class Mh extends Cr{async getRequest(e,t){const{limit:n=ge,includeDiscoverablePrivateCommunity:a}=e,s=Bn(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 qh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&(Fn(t,{cachedAt:a}),Vu(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communities.map(Ze("community"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ze("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(st(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"}(xh||(xh={}));class Nh extends Rr{constructor(e,t){const n=R.default(e),a=["trendingCommunity","collection",n];super(new Mh(e),n,a,t),this.query=e,this.queryStreamController=new qh(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Wu,action:xh.OnCommunityDeleted},{fn:Yu,action:xh.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:xh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["community","get",e]))).filter(Pr).map((({data:e})=>mc(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 Kh extends Cr{async getRequest(e,t){const{limit:n=ge,includeDiscoverablePrivateCommunity:a}=e,s=Bn(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 Fh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&(Fn(t,{cachedAt:a}),Vu(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communities.map(Ze("community"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ze("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(st(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.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(_h||(_h={}));class Bh extends Rr{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Kh(e),n,a,t),this.query=e,this.queryStreamController=new Fh(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Wu,action:_h.OnCommunityDeleted},{fn:Yu,action:_h.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:_h.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["community","get",e]))).filter(Pr).map((({data:e})=>mc(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 $h extends Cr{async getRequest(e,t){var n;const{limit:a=ge,communityMembershipStatus:s}=e,o=Bn(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 Lh(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class Qh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:Lh(e)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Lh(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Vh;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Vh||(Vh={}));class Jh extends Rr{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new $h(e),n,a,t),this.query=e,this.queryStreamController=new Qh(this.query,this.cacheKey,this.notifyChange.bind(this),Qr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Vh.OnCommunityCreated},{fn:Wu,action:Vh.OnCommunityDeleted},{fn:Yu,action:Vh.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:Vh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(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})=>at(["community","get",e]))).filter(Pr).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}=Ye();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=mt(n,this.query.communityMembershipStatus,t)),n}}class Hh extends Cr{async getRequest(e,t){const{limit:n=ge,communityIds:a}=e,s=Bn(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 Gh;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Gh||(Gh={}));class zh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.joinRequests.map((e=>Ze("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Ze("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(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===Gh.OnLocalJoinRequestUpdated){if(!a.data.find((e=>s.includes(e))))return}e===Gh.OnLocalJoinRequestCreated&&(a.data=[...new Set([...s,...a.data])]),e===Gh.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>!s.includes(e)))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Yh extends Rr{constructor(e,t){const n=R.default(e),a=["joinRequestList","collection",n];super(new Hh(e),n,a,t),this.query=e,this.queryStreamController=new zh(this.query,this.cacheKey,this.notifyChange.bind(this),Br),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:zr,action:Gh.OnLocalJoinRequestCreated},{fn:Yr,action:Gh.OnLocalJoinRequestUpdated},{fn:Wr,action:Gh.OnLocalJoinRequestUpdated},{fn:bh,action:Gh.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(s.data.map((e=>at(["joinRequest","get",e]))).filter(Pr).map((({data:e})=>e)).map(Vr));(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?Ct:St)();return t=t.sort(n),t}}var Wh;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(Wh||(Wh={}));var Xh=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const a=Ye();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=$r(s);a.cache&&Fn(o),Nt("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=Ye();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=$r(s);a.cache&&Fn(o),Nt("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=Ye();n.log("community/banMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=Ln(a,"communityUsers"),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{communityUsers:i}=s;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:o}},unbanMembers:async(e,t)=>{const n=Ye();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=Ln(a,"communityUsers"),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{communityUsers:i}=s;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:o}}}),Zh=Object.freeze({__proto__:null,Moderation:Xh,Membership:Ph,getCommunityByIds:Ju,createCommunity:async e=>{const t=Ye();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",Lr(e));Nt("community.created",n);const a=_r(n),s=t.cache&&Date.now();t.cache&&(Fn(a,{cachedAt:s}),Vu(a.communities,a.communityUsers));const{communities:o}=a;return{data:hd.community(o[0]),cachedAt:s}},updateCommunity:async(e,t)=>{const n=Ye();n.log("community/updateCommunity",e,t);const{data:a}=await n.http.put(`/api/v3/communities/${e}`,Lr(t));Nt("community.updated",a);const s=_r(a),o=n.cache&&Date.now();n.cache&&(Fn(s,{cachedAt:o}),Vu(s.communities,s.communityUsers));const{communities:i}=s;return{data:hd.community(i.find((t=>t.communityId===e))),cachedAt:o}},deleteCommunity:async e=>{const t=Ye();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await Hu(e);return Nt("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),hd.community(n.data)},joinCommunity:async e=>{const t=Ye();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);Nt("local.community.joined",n);const a=_r(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=Ye();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);Nt("local.community.left",n);const a=_r(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:zu,onCommunityUpdated:Yu,onCommunityDeleted:Wu,searchCommunities:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`searchCommunities(tmpid: ${o}) > listen`);const i=new Dh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`searchCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCommunities(tmpid: ${o}) > listen`);const i=new Eh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunity:(e,t)=>qr(e,t,"communityId",Hu,[Yu,Wu,ph,yh,vh,fh,ch,lh,dh,Pd(bh,"targetId","community")],{callbackDataSelector:e=>e?hd.community(e):e}),getTrendingCommunities:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getTrendingCommunities(tmpid: ${i}) > listen`);const r=new Nh(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>rt(d))),()=>{a(`getTrendingCommunities(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getRecommendedCommunities(tmpid: ${i}) > listen`);const r=new Bh(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>rt(d))),()=>{a(`getRecommendedCommunities(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`semanticSearchCommunities(tmpid: ${o}) > listen`);const i=new Jh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`semanticSearchCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getJoinRequestList: (tmpid: ${o}) > listen`);const i=new Yh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getJoinRequestList (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return Wh}});const em=async e=>{const t=Ye();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&&Fn(n,{cachedAt:a});const{categories:s}=n;return{data:hd.category((null!=s?s:[]).find((t=>t.categoryId===e))),cachedAt:a}};em.locally=e=>{const t=Ye();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=at(["category","get",e]);return n?{data:hd.category(n.data),cachedAt:n.cachedAt}:void 0};const tm=async e=>{const t=Ye();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:a,limit:s,includeDeleted:o}=n,i=Bn(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:oa(o),options:r})}),{paging:d}=c,l=Bn(c,["paging"]),{categories:u}=l,h=t.cache&&Date.now();if(t.cache){Fn(l,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},i),{includeDeleted:o,options:r})];st(e,{categories:null==u?void 0:u.map(Ze("category")),paging:d})}return{data:null!=u?u:[],cachedAt:h,paging:d}};tm.locally=e=>{var t,n;const a=Ye();if(a.log("category/queryCategories.locally",e),!a.cache)return;const s=null!=e?e:{},{page:o,limit:i=10}=s,r=Bn(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=at(d))&&void 0!==t?t:{};if(!(null==l?void 0:l.categories.length))return;const h=l.categories.map((e=>at(["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 nm=Object.freeze({__proto__:null,getCategory:em,getCategories:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCategories(tmpid: ${o}) > listen`);const{limit:i}=e,r=Bn(e,["limit"]),c=null!=i?i:ge,{policy:d=ye}=null!=n?n:{},l=[],u=["category","collection",{}],h=(n=!1)=>{var a,s;const o=null===(a=at(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=_e(tm,Object.assign(Object.assign({},r),{limit:n?c:void 0,page:n||null==o?void 0:o.params.page}));$e(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(Ze("category"))])]),st(u,r),(n=>{var a,s;let o=null!==(a=n.data.map((e=>at(["category","get",e]))).filter(Boolean).map((({data:e})=>hd.category(e))))&&void 0!==a?a:[];switch(e.includeDeleted||(o=ct(o,"isDeleted",!1)),e.sortBy){case"firstCreated":o=o.sort(Ct);break;case"lastCreated":o=o.sort(St);break;default:o=o.sort(It)}t({onNextPage:h,data:o,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})})(r)}),Be(d))};return l.push((()=>{})),h(!0),()=>{a(`getCategories(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}}});const am=async e=>{const t=Ye();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:a,dataTypes:s}=n,o=Bn(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=Bn(r,["paging"]),l=Ln(d,"communityUsers"),{posts:u}=l,{communities:h}=_r(l),m=t.cache&&Date.now();if(t.cache){Fn(Object.assign(Object.assign({},l),{communitis:h}));const e=["globalFeed","query",Object.assign(Object.assign({},o),{options:i})];st(e,{posts:u.map(Ze("post")),paging:c})}return{data:u.map(hd.post),cachedAt:m,paging:c}};am.locally=e=>{var t;const n=Ye();if(n.log("post/queryGlobalFeed.locally",e),!n.cache)return;const a=Bn(null!=e?e:{},[]),s=["globalFeed","query",Object.assign({},a)],{data:o,cachedAt:i}=null!==(t=at(s))&&void 0!==t?t:{};if(!(null==o?void 0:o.posts.length))return;const r=o.posts.map((e=>at(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(hd.post),{paging:c}=o;return r.length===o.posts.length?{data:r,cachedAt:i,paging:c}:void 0};class sm extends Cr{async getRequest(e,t){const{limit:n}=e,a=Bn(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 om;!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"}(om||(om={}));class im extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.posts.map(Ze("post"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ze("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===om.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===om.OnPostCreated||e===om.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===om.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const rm=async e=>{const t=Ye();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=>{Pe(null==t?void 0:t.code)&&_n("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.comments.map((e=>hd.comment(e))),cachedAt:s}};rm.locally=e=>{var t;const n=Ye();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const a=e.map((e=>at(["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=>hd.comment(e))),cachedAt:o.cachedAt}};const cm=e=>{const t=Ye();if(!t.cache)return;const n=jn();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 st(["comment","get",s.commentId],s,{cachedAt:-5}),Nt("local.comment.created",{comments:[s],commentChildren:[],users:[],files:[],communityUsers:[]}),s},dm=(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})},lm=async e=>{const t=Ye();t.log("story/getStoryByStoryId",e);const n=at(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;ea("story",e)}let a;try{const n=await t.http.get(`/api/v4/stories/${e}`);a=dm(n.data)}catch(t){throw Pe(null==t?void 0:t.code)&&_n("story",e),t}const s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.stories[0],cachedAt:s}};lm.locally=e=>{const t=Ye();t.log("story/getStorybyStoryId",e);const n=at(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;ea("story",e)}const a=t.cache&&Date.now(),s=at(["story","get",e]);if(s)return{data:s.data,cachedAt:a}};const um=async(e,t=!1)=>{var n,a,s;const o=Ye(),i=null===(n=at(["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 rt(["comment","get",e]),Nt("local.comment.deleted",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]}),t}const r=await nl(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?Mt((()=>_n("comment",e))):it(["comment","get",e],{isDeleted:!0}),"story"===r.data.referenceType){const e=await lm(r.data.referenceId);Nt("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const t=null===(a=at(["post","get",r.data.referenceId]))||void 0===a?void 0:a.data;if(t){const n=Xd();n.queueCommentChangeTask(new Gd(t.postId,e)),!c.parentId&&(null===(s=c.children)||void 0===s?void 0:s.length)>0&&c.children.forEach((e=>{n.queueCommentChangeTask(new Gd(t.postId,e))}))}}return Nt("local.comment.deleted",{comments:[c],commentChildren:[],files:[],users:[],communityUsers:[]}),c},hm=async e=>{const t=Ye();let n;t.log("comment/getComment",e),ea("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("comment",e),t}const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{comments:s}=n;return{data:s.find((t=>t.commentId===e)),cachedAt:a}};hm.locally=e=>{const t=Ye();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=at(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const mm=e=>Sl("local.comment.deleted",e),gm=e=>{const t=Ye();return xt(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(it(["comment","get",n.commentId],n),e(Ic(n))):e(n)}))},pm=e=>{const t=Ye();return xt(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(it(["comment","get",n.commentId],n),e(Ic(n))):e(n)}))};class ym extends Cr{async getRequest(e,t){var n;const{pageSize:a,limit:s,includeDeleted:o}=e,i=Bn(e,["pageSize","limit","includeDeleted"]),r=null!==(n=null!=a?a:s)&&void 0!==n?n:ge,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:oa(o),options:d})});return l}}var vm;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(vm||(vm={}));class fm extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.comments.map(Ze("comment"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(Ze("comment"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(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===vm.OnCommentCreated&&(a.data=[...new Set([t.commentId,...a.data])]),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const bm=e=>Sl("local.comment.created",e);class Im extends Rr{constructor(e,t){const n=R.default(e),a=["comments","collection",n];super(new ym(e),n,a,t),this.query=e,this.queryStreamController=new fm(this.query,this.cacheKey,this.notifyChange.bind(this),Nl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:bm,action:vm.OnCommentCreated},{fn:mm,action:vm.OnCommentDeleted},{fn:Ol,action:vm.OnCommentCreated},{fn:Al,action:vm.OnCommentUpdated},{fn:Tl,action:vm.OnCommentDeleted},{fn:Rl,action:vm.OnCommentFlagged},{fn:Pl,action:vm.OnCommentUnflagged},{fn:Dl,action:vm.OnCommentReactionAdded},{fn:Ul,action:vm.OnCommentReactionRemoved},{fn:gm,action:vm.OnCommentReactionAdded},{fn:pm,action:vm.OnCommentReactionRemoved}]);if(this.query.excludeBlockUserComments){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Yo(t),Wo(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["comment","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.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=ct(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=ft(t)),"firstCreated"===this.query.sortBy)t=t.sort(Ct);else t=t.sort(St);return t}}var Cm=Object.freeze({__proto__:null,getCommentByIds:rm,createComment:async e=>{const t=Ye();t.log("comment/createComment",e);const n=cm(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&&Fn(n,{cachedAt:o}),["post","content"].includes(e.referenceType))Xd().queueCommentChangeTask(new Hd(e.referenceId,s[0].commentId,n.comments[0].createdAt));else if("story"===e.referenceType){const t=at(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=at(["story","get",t.data]);(null==e?void 0:e.data)&&Nt("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 Nt("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:hd.comment(s[0]),cachedAt:o}}catch(e){throw n&&Nt("local.comment.created",{comments:[Object.assign(Object.assign({},n),{syncState:"error"})],commentChildren:[],users:[],files:[],communityUsers:[]}),e}},updateComment:async(e,t)=>{const n=Ye();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&&Fn(a,{cachedAt:s}),Nt("comment.updated",a);const{comments:o}=a;return{data:hd.comment(o.find((t=>t.commentId===e))),cachedAt:s}},deleteComment:um,softDeleteComment:async e=>{Ye().log("comment/softDeleteComment",e);return um(e)},hardDeleteComment:async e=>{Ye().log("comment/hardDeleteComment",e);return um(e,!0)},flagComment:async(t,n)=>{const a=Ye();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&&Fn(i),Nt("comment.flagged",i),!!i},unflagComment:async e=>{const t=Ye();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Fn(n),Nt("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=Ye();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:Ol,onCommentUpdated:Al,onCommentDeleted:Tl,onCommentFlagged:Rl,onCommentUnflagged:Pl,onCommentReactionAdded:Dl,onCommentReactionRemoved:Ul,getComment:(e,t)=>qr(e,t,"commentId",hm,[mm,Tl,Rl,Dl,Ul,Pl,Al,gm,pm]),getComments:(e,t,n)=>{const{log:a,cache:s}=Ye();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 Im(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getComments(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});const wm=e=>hl("local.post.deleted",e),Sm=e=>{const t=Ye();return xt(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(it(["post","get",n.postId],n),e(n)):e(n)}))},Om=e=>{const t=Ye();return xt(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(it(["post","get",n.postId],n),e(n)):e(n)}))},Am=e=>hl("local.post.updated",e),Tm=e=>[Ol,Tl,bm,mm].map((t=>({fn:Pd((n=>((e,t,n)=>t((async t=>{var a;const s=null===(a=at(n))||void 0===a?void 0:a.data;s&&s.data.includes(t.referenceId)&&e(t)})))(n,t,e)),"referenceId","post"),action:om.OnPostUpdated}))),Rm=e=>[{fn:ml,action:om.OnPostCreated},{fn:gl,action:om.OnPostUpdated},{fn:Am,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Sm,action:om.OnPostReactionAdded},{fn:Om,action:om.OnPostReactionRemoved},{fn:wm,action:om.OnPostDeleted},...Tm(e)];class Pm extends Rr{constructor(e,t){const n=R.default(e),a=["customRankingGlobalFeed","collection",n];super(new sm(e),n,a,t),this.query=e,this.queryStreamController=new im(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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(Rm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.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 Cr{async getRequest(e,t){const{limit:n,dataTypes:a}=e,s=Bn(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 Um extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.posts.map(Ze("post"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ze("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===om.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===om.OnPostCreated||e===om.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===om.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class jm extends Rr{constructor(e,t){const n=R.default(e),a=["globalFeed","collection",n];super(new Dm(e),n,a,t),this.query=e,this.queryStreamController=new Um(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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(Rm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class km extends Cr{async getRequest(e,t){const{userId:n,feedSources:a,dataTypes:s,includeDeleted:o,matchingOnlyParentPost:i,limit:r=ge,untilAt:c}=e,d=Bn(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:oa(o),matchingOnlyParentPost:null!=i?i:!(null==s?void 0:s.length)})});return u}}class Em extends Sr{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?Rt(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(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=>!Pt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)st(this.cacheKey,{data:o.map(Ze("post"))});else{const e=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Ze("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(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===om.OnPostCreated||e===om.OnPostApproved||e===om.OnPostUpdated)){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Pt(t.createdAt,this.validatedUntilAt,e))return}if(e===om.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=at(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),st(["post","get",e.postId],e)}if(e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e===om.OnPostCreated||e===om.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])]}st(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=async e=>{const t=Ye();let n;t.log("post/getPost",e),ea("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("post",e),t}const a=Ln(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{posts:o}=a;return{data:o.find((t=>t.postId===e)),cachedAt:s}};Mm.locally=e=>{const t=Ye();if(t.log("post/getPost.locally",e),!t.cache)return;const n=at(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class qm extends Rr{constructor(e,t){const n=R.default(e),a=["userFeed","collection",n];super(new km(e),n,a,t),this.query=e,this.queryStreamController=new Em(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ml,action:om.OnPostCreated},{fn:gl,action:om.OnPostUpdated},{fn:Am,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Sm,action:om.OnPostReactionAdded},{fn:Om,action:om.OnPostReactionRemoved},{fn:wm,action:om.OnPostDeleted},{fn:Pd((e=>Ol((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Mm(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated},{fn:Pd((e=>Tl((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Mm(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[],r=this.applyFilter(i).map(hd.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=ct(n,"isDeleted",!1)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=gt(n,this.query.dataTypes)),this.query.untilAt){const e=Rt(this.query.untilAt),t="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";n=n.filter((n=>!Pt(n.createdAt,e,t)))}if("firstCreated"===this.query.sortBy)n=n.sort(Ct);else n=n.sort(St);return n}}class xm extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a,communityId:s,untilAt:o}=e,i=Bn(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:oa(a),matchingOnlyParentPost:!0,options:r})});return c}}class Nm extends Sr{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?Rt(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(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=>!Pt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)st(this.cacheKey,{data:o.map(Ze("post"))});else{const e=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Ze("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===om.OnPostCreated||e===om.OnPostApproved)&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Pt(t.createdAt,this.validatedUntilAt,e))return}if(e===om.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=at(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),st(["post","get",e.postId],e)}e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==om.OnPostCreated&&e!==om.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),st(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=({cacheKey:e,resolveId:t})=>[Ol,Tl,bm,mm].map((n=>({fn:Pd((a=>((e,t,n,a)=>t((async t=>{var s;const o=null===(s=at(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:om.OnPostUpdated}))),Fm=e=>[{fn:ml,action:om.OnPostCreated},{fn:gl,action:om.OnPostUpdated},{fn:Am,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Sm,action:om.OnPostReactionAdded},{fn:Om,action:om.OnPostReactionRemoved},{fn:wm,action:om.OnPostDeleted},...Km({cacheKey:e})],_m=(e,t)=>{var n;return null!==(n=e.map((e=>{const n=t.find((t=>t.postId===e.referenceId));return n?Ze("post")({postId:null==n?void 0:n.postId}):void 0})).filter(Pr))&&void 0!==n?n:[]};class Bm extends Rr{constructor(e,t){const n=R.default(e),a=["communityFeed","collection",n];super(new xm(e),n,a,t),this.query=e,this.queryStreamController=new Nm(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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(Fm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.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=ct(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=Rt(this.query.untilAt),n="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";t=t.filter((t=>!Pt(t.createdAt,e,n)))}switch(this.query.sortBy){case"firstCreated":t=t.sort(Ct);break;case"firstUpdated":t=t.sort(Ot);break;case"lastUpdated":t=t.sort(At);break;default:t=t.sort(St)}return t}}class $m extends Ve{constructor(e="For You feed is not enabled for this network"){super(e,400400,"error"),this.type="AmityForYouFeedDisabledError"}}class Lm extends Cr{constructor(e){super(e),this.checkedDisk=!1,this.hasDeliveredPost=!1,this.cursor=Xo.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&&Xo.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:pe};e&&(t.token=e);try{const{data:e}=await this.http.get(we,{params:{options:t}});return e}catch(t){if(t instanceof Ve&&400300===t.code)throw new $m;if(t instanceof Ve&&400322===t.code&&void 0!==e){this.cursor&&await this.cursor.clear();const{data:e}=await this.http.get(we,{params:{options:{limit:pe}}});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 Qm extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.posts.map(Ze("post"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ze("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.parentPostId&&!a.data.includes(t.parentPostId)||(e!==om.OnPostDeleted&&e!==om.OnPostDeclined||(a.data=a.data.filter((e=>e!==t.postId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Vm=["forYouFeed","collection"];class Jm extends Rr{constructor(e){const t=`for-you-feed-${Ye().userId}`,n={};super(new Lm(n),t,Vm,e),this.queryStreamController=new Qm(n,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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(Rm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Hm=Object.freeze({__proto__:null,queryGlobalFeed:am,getCustomRankingGlobalFeed:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCustomRankingGlobalFeed(tmpid: ${o}) > listen`);const i=new Pm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getCustomRankingGlobalFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getGlobalFeed:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getGlobalFeed(tmpid: ${o}) > listen`);const i=new jm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getGlobalFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getUserFeed:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getUserFeed(tmpid: ${o}) > listen`);const i=new qm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getUserFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunityFeed:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCommunityFeed(tmpid: ${o}) > listen`);const i=new Bm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getCommunityFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getForYouFeed:e=>{const{log:t,cache:n}=Ye();n||console.log(ve);const a=Date.now();t(`getForYouFeed(tmpid: ${a}) > listen`);const s=new Jm(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>rt(i))),()=>{t(`getForYouFeed(tmpid: ${a}) > dispose`),o.forEach((e=>e()))}},AmityForYouFeedDisabledError:$m});const Gm=async e=>{const t=Ye();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=>{Pe(null==t?void 0:t.code)&&_n("post",e)})),t}const s=Ln(a,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:o}),{data:s.posts.map(hd.post),cachedAt:o}};Gm.locally=e=>{var t;const n=Ye();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const a=e.map((e=>at(["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(hd.post),cachedAt:o.cachedAt}};const zm=async(e,t=!1)=>{var n;const a=Ye(),s=await tl(e);if(await a.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await Hu(s.data.targetId),t=(null!==(n=nt(["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));Nt("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const o=Object.assign(Object.assign({},s.data),{isDeleted:!0});return t?setTimeout((()=>{_n("post",e)}),0):it(["post","get",e],{isDeleted:!0}),Nt("local.post.deleted",{posts:[o],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),hd.post(o)};class Ym extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a,matchingOnlyParentPost:s,untilAt:o}=e,i=Bn(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:oa(a),matchingOnlyParentPost:null!=s?s:!(null==r?void 0:r.length),options:d})});return l}}class Wm extends Sr{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?Rt(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(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=>!Pt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)st(this.cacheKey,{data:o.map(Ze("post"))});else{const e=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Ze("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===om.OnPostCreated||e===om.OnPostApproved)){const e=this.query.sortBy||"lastCreated";if(Pt(t.createdAt,this.validatedUntilAt,e))return}if(t.parentPostId&&t.isDeleted){const e=null===(a=at(["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)),st(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==om.OnPostCreated&&e!==om.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),st(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 Xm extends Rr{constructor(e,t){const n=R.default(e),a=["posts","collection",n];super(new Ym(e),n,a,t),this.query=e,this.queryStreamController=new Wm(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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(Fm(this.cacheKey));if(this.query.excludeBlockUserPosts){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Yo(t),Wo(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.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=ct(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=ht(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=gt(n,this.query.dataTypes)),this.query.untilAt){const e=Rt(this.query.untilAt),t=this.query.sortBy||"lastCreated";n=n.filter((n=>!Pt(n.createdAt,e,t)))}if(this.query.excludeBlockUserPosts&&(n=vt(n)),"firstCreated"===this.query.sortBy)n=n.sort(Ct);else n=n.sort(St);return n}}class Zm extends Cr{async getRequest(e,t){const n=Bn(e,["limit"]),{communityId:a,placement:s}=n,o=Bn(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 eg extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(pa):[]});Fn(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.pins.map(Ze("pin"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Ze("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===om.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class tg extends Rr{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=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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(Km({cacheKey:this.cacheKey,resolveId:e=>`${this.query.placement}#${e}`}))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;let i=(null!==(s=o.data.map((e=>at(["pin","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.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})=>St({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class ng extends Cr{async getRequest(e,t){const n=Bn(e,["limit"]),{data:a}=await this.http.get("/api/v1/pinned-posts/global",{params:Object.assign({},n)});return a}}class ag extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(pa)});Fn(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.pins.map(Ze("pin"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Ze("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===om.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class sg extends Rr{constructor(e,t){const n=R.default(e),a=["pinnedPosts","collection",n];super(new ng(e),n,a,t),this.query=e,this.queryStreamController=new ag(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:wm,action:om.OnPostDeleted},{fn:pl,action:om.OnPostDeleted},...Km({cacheKey:this.cacheKey,resolveId:e=>`global#${e}`})])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["pin","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.pinnedPost);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}}class og extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 ig(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function rg(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class cg extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:ig(e)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...ig(e)])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(a=at(["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)),st(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==om.OnPostCreated&&e!==om.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),st(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class dg extends Rr{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 og(n),a,s,t),this.query=n,this.queryStreamController=new cg(this.query,this.cacheKey,this.notifyChange.bind(this),el),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:gl,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Pd((e=>Ol((async t=>{const n=at(this.cacheKey);rg(null==n?void 0:n.data).includes(t.referenceId)||(await tl(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated},{fn:Pd((e=>Tl((async t=>{const n=at(this.cacheKey);rg(null==n?void 0:n.data).includes(t.referenceId)||(await tl(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(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})=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.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=gt(t,this.query.dataTypes)),t}}class lg extends Cr{async getRequest(e,t){const{limit:n=ge,matchingOnlyParentPost:a,hashtags:s,dataTypes:o,targetType:i="all"}=e,r=Bn(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 ug extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.posts.map(Ze("post"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ze("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(a=at(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),st(["post","get",e.postId],e)}e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==om.OnPostCreated&&e!==om.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),st(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class hg extends Rr{constructor(e,t){const n=R.default(e),a=["posts","collection",n];super(new lg(e),n,a,t),this.query=e,this.queryStreamController=new ug(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ml,action:om.OnPostCreated},{fn:gl,action:om.OnPostUpdated},{fn:Am,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Sm,action:om.OnPostReactionAdded},{fn:Om,action:om.OnPostReactionRemoved},{fn:wm,action:om.OnPostDeleted},{fn:Pd((e=>Ol((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Mm(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated},{fn:Pd((e=>Tl((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Mm(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.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=gt(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(Ct);else n=n.sort(St);return n}}class mg extends Tr{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 gg extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:_m(e.rooms,e.posts)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,..._m(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&st(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 pg=e=>{const t=Ye();return xt(t,"room/onRoomStartBroadcasting","room.startBroadcasting",(t=>{Fn(t),e(t.rooms[0])}))},yg=e=>{const t=Ye();return xt(t,"room/onRoomWaitingReconnect","room.waitingReconnect",(t=>{Fn(t),e(t.rooms[0])}))},vg=e=>{const t=Ye();return xt(t,"room/onRoomEndBroadcasting","room.endBroadcasting",(t=>{Fn(t),e(t.rooms[0])}))},fg=e=>{const t=Ye();return xt(t,"room/onRoomRecordedAvailable","room.recordedAvailable",(t=>{Fn(t),e(t.rooms[0])}))},bg=e=>{const t=Ye();return xt(t,"room/onRoomCoHostInvited","room.didCohostInvite",(t=>{const n=nc(t);Fn(n),e(n.invitations)}))},Ig=async e=>{const t=Ye();let n;t.log("room/getRoomById",e),ea("room",e);try{n=(await t.http.get(`/api/v1/rooms/${e}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("room",e),t}const a=t.cache&&Date.now();return t.cache&&Fn(n,{cachedAt:a}),{data:n.rooms[0],cachedAt:a}};Ig.locally=e=>{const t=Ye();t.log("room/getRoomById.locally",e),ea("room",e);const n=t.cache&&Date.now(),a=at(["room","get",e]);if(a)return{data:a.data,cachedAt:n}};const Cg=e=>{const t=Ye();return xt(t,"room/onRoomCoHostInviteAccepted","room.didCohostInviteAccept",(async t=>{var n;const a=nc(t);await Ig(null===(n=a.invitations)||void 0===n?void 0:n[0].targetId),Fn(a),e(a.invitations[0])}))},wg=e=>{const t=Ye();return xt(t,"room/onRoomCoHostInviteRejected","room.didCohostInviteReject",(t=>{const n=nc(t);Fn(n),e(n.invitations)}))},Sg=e=>{const t=Ye();return xt(t,"room/onRoomCoHostInviteCanceled","room.didCohostInviteCancel",(t=>{const n=nc(t);Fn(n),e(n.invitations)}))},Og=e=>{const t=Ye();return xt(t,"room/onRoomParticipantJoined","room.participantJoined",(t=>{const{rooms:n,users:a}=t;Fn({rooms:n,users:a}),e({room:qc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Ag=e=>{const t=Ye();return xt(t,"room/onRoomParticipantLeft","room.participantLeft",(t=>{var n;const{rooms:a,users:s}=t;Fn({rooms:a,users:s});const o=t.eventActor.userInternalId;e({room:qc(a[0]),actorInternalId:o,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===o)))||void 0===n?void 0:n.userId})}))},Tg=e=>{const t=Ye();return xt(t,"room/onRoomParticipantStageJoined","room.participantStageJoined",(t=>{const{rooms:n,users:a}=t;Fn({rooms:n,users:a}),e({room:qc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Rg=e=>{const t=Ye();return xt(t,"room/onRoomTerminated","room.terminated",(t=>{Fn(t),e(t.rooms[0])}))},Pg=e=>{const t=Ye();return xt(t,"room/onRoomDidUpdate","local.room.didUpdate",(t=>{Fn(t),e(t.rooms[0])}))},Dg=e=>{const t=Ye();return xt(t,"room/onRoomParticipantRemoved","room.participantRemoved",(t=>{var n;const{rooms:a,users:s}=t;Fn({rooms:a,users:s});const o=t.eventActor.userInternalId;e({room:qc(a[0]),actorInternalId:o,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===o)))||void 0===n?void 0:n.userId})}))},Ug=e=>{const t=Ye();return xt(t,"room/onLocalRoomDidUpdate","room.didUpdate",(t=>{Fn(t),e(t.rooms[0])}))},jg=e=>{const t=Ye();return xt(t,"room/onRoomParticipantRemoved","local.room.participantRemoved",(t=>{Fn(t),e(t.rooms[0])}))};var kg;!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"}(kg||(kg={}));const Eg=e=>t=>e((e=>{t(e.room)}));class Mg extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a}=e,s=Bn(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:oa(a),options:i})});return r}}class qg extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.rooms.map(Ze("room"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.rooms.map(Ze("room"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===kg.OnRoomDeleted&&(a.data=a.data.filter((e=>e!==t._id))),e===kg.OnRoomCreated&&(a.data=[...new Set([t._id,...a.data])]),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class xg extends Rr{constructor(e,t){const n=R.default(e),a=["rooms","collection",n];super(new Mg(e),n,a,t),this.query=e,this.queryStreamController=new qg(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:pg,action:kg.OnRoomStartBroadcasting},{fn:vg,action:kg.OnRoomEndBroadcasting},{fn:fg,action:kg.OnRoomUpdated},{fn:yg,action:kg.OnRoomUpdated},{fn:Rg,action:kg.OnRoomUpdated},{fn:Eg(Og),action:kg.OnRoomUpdated},{fn:Eg(Ag),action:kg.OnRoomUpdated},{fn:Eg(Dg),action:kg.OnRoomUpdated},{fn:jg,action:kg.OnRoomUpdated},{fn:Eg(Tg),action:kg.OnRoomUpdated},{fn:Pd(Cg,"targetId","room"),action:kg.OnRoomUpdated},{fn:Pg,action:kg.OnRoomDidUpdate},{fn:Ug,action:kg.OnRoomDidUpdate}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["room","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(qc);(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=ct(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=ct(t,"type",this.query.type)),"firstCreated"===this.query.sortBy)t=t.sort(Ct);else t=t.sort(St);return t}}var Ng=Object.freeze({__proto__:null,createRoom:async e=>{const t=Ye();t.log("room/createRoom",e);const{data:n}=await t.http.post("/api/v1/rooms",e);Nt("local.room.created",n);const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{rooms:s}=n;return{data:qc(s[0]),cachedAt:a}},updateRoom:async(e,t)=>{const n=Ye();n.log("room/updateRoom",{roomId:e,bundle:t});const{data:a}=await n.http.put(`/api/v1/rooms/${e}`,t);Nt("local.room.updated",a);const s=n.cache&&Date.now();n.cache&&Fn(a,{cachedAt:s});const{rooms:o}=a;return{data:qc(o[0]),cachedAt:s}},deleteRoom:async e=>{const t=Ye();t.log("room/deleteRoom",{roomId:e}),await t.http.delete(`/api/v1/rooms/${e}`),Nt("local.room.deleted",{rooms:[{_id:e}]})},stopRoom:async e=>{const t=Ye();t.log("room/stopRoom",{roomId:e});const{data:n}=await t.http.post(`/api/v1/rooms/${e}/stop`);Nt("local.room.stopped",n);const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{rooms:s}=n;return{data:s[0],cachedAt:a}},getBroadcasterData:async e=>{const t=Ye();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=Ye();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=Ye();n.log("room/removeParticipant",{roomId:e,participantUserId:t}),await n.http.delete(`/api/v1/rooms/${e}/participants/${t}`),Nt("local.room.participantRemoved",{rooms:[{_id:e}],users:[{_id:t}]})},leaveRoom:async e=>{const t=Ye();t.log("room/leaveRoom",{roomId:e}),await t.http.post(`/api/v1/rooms/${e}/leave`),Nt("local.room.left",{rooms:[{_id:e}]})},AmityRoomAnalytics:Mc,WatchSessionStorage:Sc,getWatchSessionStorage:Ac,syncWatchSessions:kc,updateCohostPermission:async(e,t,n)=>{const a=Ye();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});Nt("local.room.didUpdate",s);const o=a.cache&&Date.now();a.cache&&Fn(s,{cachedAt:o});const{rooms:i}=s;return{data:qc(i[0]),cachedAt:o}},onRoomStartBroadcasting:pg,onRoomWaitingReconnect:yg,onRoomEndBroadcasting:vg,onRoomRecordedAvailable:fg,onRoomCoHostInvited:bg,onRoomCoHostInviteAccepted:Cg,onRoomCoHostInviteRejected:wg,onRoomCoHostInviteCanceled:Sg,onRoomParticipantJoined:Og,onRoomParticipantLeft:Ag,onRoomParticipantStageLeft:e=>{const t=Ye();return xt(t,"room/onRoomParticipantStageLeft","room.participantStageLeft",(t=>{const{rooms:n,users:a}=t;Fn({rooms:n,users:a}),e({room:qc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},onRoomParticipantStageJoined:Tg,onRoomTerminated:Rg,onRoomDidUpdate:Pg,onRoomCreated:e=>{const t=Ye();return xt(t,"room/onRoomCreated","local.room.created",(t=>{Fn(t),e(t.rooms[0])}))},onRoomUpdated:e=>{const t=Ye();return xt(t,"room/onRoomUpdated","local.room.updated",(t=>{Fn(t),e(t.rooms[0])}))},onRoomDeleted:e=>{const t=Ye();return xt(t,"room/onRoomDeleted","local.room.deleted",(t=>{Fn(t),e(t.rooms[0])}))},onRoomStopped:e=>{const t=Ye();return xt(t,"room/onRoomStopped","local.room.stopped",(t=>{Fn(t),e(t.rooms[0])}))},onRoomParticipantRemoved:Dg,onRoomLeft:e=>{const t=Ye();return xt(t,"room/onRoomLeft","local.room.left",(t=>{Fn(t),e(t.rooms[0])}))},onLocalRoomDidUpdate:Ug,getRoom:(e,t)=>qr(e,t,"_id",Ig,[vg,pg,yg,Rg,fg,Eg(Og),Eg(Ag),Eg(Dg),jg,Eg(Tg),Pd(Cg,"targetId","room"),Pg,Ug],{callbackDataSelector:e=>e?hd.room(e):e}),getRooms:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getRooms(tmpid: ${o}) > listen`);const i=new xg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getRooms(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});class Kg extends Rr{constructor(e){const t={limit:100},n=R.default(t),a=["liveRoomPosts","collection",n];super(new mg(t),n,a,e),this.query=t,this.queryStreamController=new gg(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:vg,action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){return e}}class Fg extends Tr{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 _g extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:_m(e.rooms,e.posts)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,..._m(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&st(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 Bg extends Rr{constructor(e,t){const n=R.default(e),a=["communityLiveRoomPosts","collection",n];super(new Fg(e),n,a,t),this.query=e,this.queryStreamController=new _g(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:vg,action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){return e}}var $g=Object.freeze({__proto__:null,getPostByIds:Gm,createPost:async e=>{const t=Ye();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{attachments:n,attachmentProductTags:a}=e,s=Bn(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}));Nt("post.created",i);const r=Zd(i),c=t.cache&&Date.now();t.cache&&Fn(r,{cachedAt:c});const{posts:d}=r;return{data:hd.post(d[0]),cachedAt:c}},editPost:async(e,t)=>{const n=Ye();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=Ln(o,"communityUsers"),r=n.cache&&Date.now();n.cache&&Fn(i,{cachedAt:r}),Nt("local.post.updated",i);const{posts:c}=i;return{data:hd.post(c.find((t=>t.postId===e))),cachedAt:r}},deletePost:zm,softDeletePost:async e=>{Ye().log("post/softDeletePost",e);const t=await zm(e,!1);return hd.post(t)},hardDeletePost:async e=>{Ye().log("post/hardDeletePost",e);const t=await zm(e,!0);return hd.post(t)},approvePost:async e=>{const t=Ye();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);Nt("post.approved",n),"community"===n.posts[0].targetType&&Nt("community.updated",n);const a=Ln(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:hd.post(a.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=Ye();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&Nt("community.updated",n),Nt("post.declined",n);const a=Ln(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:hd.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async(t,n)=>{const a=Ye();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&&Fn(Ln(i,"communityUsers")),Nt("post.flagged",i),!!i},unflagPost:async e=>{const t=Ye();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Fn(Ln(n,"communityUsers")),Nt("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=Ye();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=Ye();t.log("post/createPost",e);const{attachments:n,attachmentProductTags:a}=e,s=Bn(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}));Nt("post.created",i);const r=Ln(i,"communityUsers"),c=t.cache&&Date.now();t.cache&&Fn(r,{cachedAt:c});const{posts:d}=r;return{data:hd.post(d[0]),cachedAt:c}},createAudioPost:async e=>{const t=Ye();t.log("post/createAudioPost",e);const{attachments:n,attachmentProductTags:a}=e,s=Bn(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}));Nt("post.created",i);const r=Zd(i),c=t.cache&&Date.now();return t.cache&&Fn(r,{cachedAt:c}),{data:Fc(null==r?void 0:r.posts[0]),cachedAt:c}},createMixedMediaPost:async e=>{var t;const n=Ye();n.log("post/createMixedMediaPost",e);const{attachments:a,attachmentProductTags:s}=e,o=Bn(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}));Nt("post.created",r);const c=Zd(r),d=n.cache&&Date.now();return n.cache&&Fn(c,{cachedAt:d}),{data:Fc(null===(t=null==c?void 0:c.posts)||void 0===t?void 0:t[0]),cachedAt:d}},createRoomPost:async e=>{const t=Ye();t.log("post/createRoomPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"room"}));Nt("post.created",n);const a=Zd(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{posts:o}=a;return{data:hd.post(o[0]),cachedAt:s}},createEventPost:async e=>{const t=Ye();t.log("post/createEventPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"event"}));Nt("post.created",n);const a=Zd(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{posts:o}=a;return{data:hd.post(o[0]),cachedAt:s}},pinProduct:async(e,t)=>{const n=Ye();n.log("post/pinProduct",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:t}),s=Zd(a),o=n.cache&&Date.now();return n.cache&&Fn(a,{cachedAt:o}),Nt("local.post.updated",a),{data:Fc(null==s?void 0:s.posts[0]),cachedAt:o}},unpinProduct:async e=>{const t=Ye();t.log("post/unpinProduct",e);const{data:n}=await t.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:null}),a=Zd(n),s=t.cache&&Date.now();return t.cache&&Fn(n,{cachedAt:s}),Nt("local.post.updated",n),{data:Fc(null==a?void 0:a.posts[0]),cachedAt:s}},updateProductTags:async(e,t)=>{const n=Ye();n.log("post/updateProductTags",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{productTags:t}),s=Zd(a),o=n.cache&&Date.now();return n.cache&&Fn(a,{cachedAt:o}),Nt("local.post.updated",a),{data:Fc(null==s?void 0:s.posts[0]),cachedAt:o}},onPostCreated:ml,onPostUpdated:gl,onPostDeleted:pl,onPostApproved:yl,onPostDeclined:vl,onPostFlagged:fl,onPostUnflagged:bl,onPostReactionAdded:Il,onPostReactionRemoved:Cl,getPost:(e,t)=>qr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hd.post(e.data):n}))}),"postId",tl,[yl,vl,Sm,Om,t=>pl((n=>{var a;let s=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(a=at(["post","get",n.parentPostId]))||void 0===a?void 0:a.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),st(["post","get",e.postId],e),s=e)}t(s)})),fl,e=>Il((t=>{e(t)})),e=>Cl((t=>{e(t)})),bl,gl,Am,wm,Pd((t=>Ol((async n=>{n.referenceId===e&&(await tl(e),t(n))}))),"referenceId","post"),Pd((t=>Tl((async n=>{n.referenceId===e&&(await tl(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getPosts(tmpid: ${o}) > listen`);const i=new Xm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getPinnedPosts(tmpid: ${o}) > listen`);const i=new tg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getPinnedPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:a,cache:s}=Ye(),o=Date.now();a(`getGlobalPinnedPosts(tmpid: ${o}) > listen`);const i=new sg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getGlobalPinnedPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`semanticSearchPosts(tmpid: ${o}) > listen`);const i=new dg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`semanticSearchPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchPostsByHashtag:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`searchPostsByHashtag(tmpid: ${o}) > listen`);const i=new hg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`searchPostsByHashtag(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getLiveRoomPosts:e=>{const{log:t,cache:n}=Ye();n||console.log(ve);const a=Date.now();t(`getLiveRoomPosts(tmpid: ${a}) > listen`);const s=new Kg(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>rt(i))),()=>{t(`getLiveRoomPosts(tmpid: ${a}) > dispose`),o.forEach((e=>e()))}},getCommunityLiveRoomPosts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCommunityLiveRoomPosts(tmpid: ${o}) > listen`);const i=new Bg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getCommunityLiveRoomPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});const Lg=async e=>{const t=Ye();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:a}};Lg.locally=e=>{const t=Ye();if(t.log("stream/getStream",e),!t.cache)return;const n=at(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Qg=e=>{const t=Ye();return xt(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Fn(t),e(t.videoStreamings[0])}))},Vg=e=>{const t=Ye();return xt(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Fn(t),e(t.videoStreamings[0])}))},Jg=e=>{const t=Ye();return xt(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Fn(t),e(t.videoStreamings[0])}))},Hg=e=>{const t=Ye();return xt(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Fn(t),e(t.videoStreamings[0])}))},Gg=e=>{const t=Ye();return xt(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Fn(t),e(t.videoStreamings[0])}))},zg=(e,t)=>qr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hd.stream(e.data):n}))}),"streamId",Lg,[Jg,Qg,Vg,Hg,Gg,iu]);zg.locally=e=>{const t=Ye();if(t.log("stream/getStreamById",e),!t.cache)return;const n=at(["stream","get",e]);return n?{data:hd.stream(n.data),cachedAt:n.cachedAt}:void 0};const Yg=async e=>{const t=Ye();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:a,limit:s}=n,o=Bn(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&&Fn(d,{cachedAt:u}),{data:l,cachedAt:u,paging:c}};var Wg=Object.freeze({__proto__:null,createStream:async e=>{const t=Ye();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:hd.stream(s[0]),cachedAt:a}},updateStream:async(e,t)=>{const n=Ye();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&&Fn(a,{cachedAt:s});const{videoStreamings:o}=a;return{data:hd.stream(o.find((t=>t.streamId===e))),cachedAt:s}},deleteStream:async e=>{const t=Ye();t.log("stream/deleteStream",e);const n=await Lg(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 it(["stream","get",e],o),s},disposeStream:async e=>{const t=Ye();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&&Fn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:a}},editStream:async(e,t)=>{const n=Ye();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&&Fn(a,{cachedAt:s});const{videoStreamings:o}=a;return{data:hd.stream(o.find((t=>t.streamId===e))),cachedAt:s}},onStreamStarted:Qg,onStreamStopped:Vg,onStreamRecorded:Jg,onStreamFlagged:Hg,onStreamTerminated:Gg,onStreamViewerBanned:iu,onStreamViewerUnbanned:e=>{const t=Ye();return xt(t,"stream/onStreamViewerDidUnban","video-streaming.viewerDidUnban",(async t=>{var n;const{list:a}=t;await Promise.all(a.map((({streamId:e})=>Lg(e))));const s=null===(n=at(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))},getStreamById:zg,getStreams:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getStreams(tmpid: ${o}) > listen`);const{limit:i}=e,r=Bn(e,["limit"]),c=null!=i?i:ge,{policy:d=ye}=null!=n?n:{},l=[],u=["streams","collection",e],h=t=>{let n=ct(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?St:Ct),n},m=(e,n=!1)=>{var a,s;const o=null!==(a=e.data.map((e=>at(["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=at(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],st(u,n),m(n,!0))},p=(e=!1)=>{var t,n;const a=null===(t=at(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=_e(Yg,Object.assign(Object.assign({},r),{limit:e?c:void 0,page:e||null==a?void 0:a.params.page}));$e(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(Ze("stream"))])]),st(u,o),m(o)}),Be(d))};return l.push(Jg(g()),Qg(g()),Vg(g())),p(!0),()=>{a(`getStreams(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}}});const Xg=async()=>{const e=Ye();e.log("presence/getPresenceSetting");const{data:t}=await e.http.get("/api/v1/presence/settings");return st(["get","presenceSetting"],t),t};class Zg{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 Zg.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 Xg()}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=Ye();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 ep=new Map,tp=e=>{let t=ep.get(e);return t||(t=new Zg(e),ep.set(e,t)),t};var np=Object.freeze({__proto__:null,getRoomOnlineUsers:async e=>{var t,n,a;const s=Ye();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=>md(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=Ye();t.log("roomPresence/getRoomUserCount",{roomId:e});const{data:n}=await t.http.get(`/api/v1/presence/rooms/${e}/users/count`);return st(["get","watchingCount",e],n),n},startHeartbeat:e=>{tp(e).start()},stopHeartbeat:e=>{tp(e).stop(),(e=>{const t=ep.get(e);t&&(t.destroy(),ep.delete(e))})(e)}});const ap=async e=>{const t=Ye();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{polls:s}=n,o=s.find((t=>t.pollId===e));return{data:xc(o),cachedAt:a}};ap.locally=e=>{const t=Ye();if(t.log("poll/getPoll",e),!t.cache)return;const n=at(["poll","get",e]);return n?{data:xc(n.data),cachedAt:n.cachedAt}:void 0};const sp=e=>{const t=Ye();return xt(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Fn(n),e(n.polls[0])}))},op=e=>{const t=Ye();return xt(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Fn(n),e(n.polls[0])}))};var ip=Object.freeze({__proto__:null,createPoll:async e=>{const t=Ye();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{polls:s}=n;return{data:xc(s[0]),cachedAt:a}},closePoll:async e=>{const t=Ye();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&&Fn(n,{cachedAt:a}),Nt("poll.updated",n);const{polls:s}=n,o=s.find((t=>t.pollId===e));return{data:xc(o),cachedAt:a}},deletePoll:async e=>{const t=Ye();t.log("poll/deletePoll",e);const n=await ap(e),{data:a}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=a,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return it(["poll","get",e],o),Nt("poll.deleted",{polls:[o],users:[]}),s},votePoll:async(e,t)=>{const n=Ye();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&&Fn(a,{cachedAt:s});const{polls:o}=a,i=o.find((t=>t.pollId===e));return Nt("poll.updated",a),{data:xc(i),cachedAt:s}},unvotePoll:async e=>{const t=Ye();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&&Fn(n,{cachedAt:a}),Nt("poll.updated",n)},onPollUpdated:sp,onPollDeleted:op,getPoll:(e,t)=>qr(e,t,"pollId",ap,[sp,op])});class rp{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 jc({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=Ye();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 cp=null;class dp{constructor(e,t,n){this._SDKUnsubscribers=[],this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=cp||(cp=new rp,cp),this._usageCollector.registerStream(e.id),this._sessionId=String(A.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(iu((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 lp=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 Lg(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 dp(r,i,t).registerEvents(),r}});const up=e=>{const t=(e=>{var t;const n=Ye(),a=new Date,s=a.getTime()+31536e6,o=new Date(s).toISOString();let i=null===(t=at(["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()},Fn({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 Fn(t),t},hp=({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(up(o))}return a(up(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},mp=async e=>{const t=Ye();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),a=dm(n.data);t.cache&&Fn(a),st(["story-sync-state",e.targetId],"synced"),Nt("local.story.created",a);const s=t.cache&&Date.now();return{data:a.stories.length>0?a.stories[0]:void 0,cachedAt:s}},gp=async({targetId:e,targetType:t})=>{var n,a;if(!at(["storyTarget","get",e])){let s={targetId:e,targetType:t};if("community"===t){const t=await Hu(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 Id(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(a=t.data.updatedAt)&&void 0!==a?a:(new Date).toISOString()})}st(["storyTarget","get",e],s)}},pp=e=>e?at(["story","get",e]):{data:void 0,cachedAt:void 0},yp=async(e,t=!1)=>{var n,a,s;const o=Ye();let i;if(o.log("story/deleteStory",e),o.cache&&(i=pp(e),null==i?void 0:i.data)){const{data:o}=i;if(Nt("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},o),{isDeleted:!0})]}),"synced"!==o.syncState){t?rt(["story","get",e]):st(["story","get",e],Object.assign(Object.assign({},i.data),{isDeleted:!0}));const a=null===(n=nt(["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));st(["story-expire",i.data.targetId],e.toISOString())}else rt(["story-expire",i.data.targetId]);return!0}const r=null===(a=at(["storyTarget","get",o.targetId]))||void 0===a?void 0:a.data,c=null===(s=nt(["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&&st(["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},vp=e=>{const t=Ye(),n=[xt(t,"onStoryUpdated","story.updated",(async t=>{const n=dm(t);Fn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},fp=e=>{const t=Ye(),n=[xt(t,"onStoryUpdated","local.story.updated",(async t=>{Fn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},bp=e=>{const t=Ye(),n=[xt(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,a=Bn(t,["reactions"]),s=dm(a),o=rl("story.reactionAdded",Object.assign(Object.assign({},s),{reactions:n}));Fn(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},Ip=e=>{const t=Ye(),n=[xt(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Fn({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Cp=e=>{const t=Ye(),n=[xt(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,a=Bn(t,["reactions"]),s=dm(a),o=rl("story.reactionRemoved",Object.assign(Object.assign({},s),{reactions:n}));Fn(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},wp=e=>{const t=Ye(),n=[xt(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Fn({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Sp=e=>{e.forEach((e=>{const t=at(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||st(["story-expire",e.targetId],n.toISOString())}))},Op=e=>{e.forEach((e=>{st(["story-reference",e.storyId],e.referenceId)}))},Ap=async({targetType:e,targetId:t,options:n})=>{const a=Ye();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=dm(o.data);return a.cache&&(Fn(i),Sp(i.stories),Op(i.stories)),{data:i.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},Tp=e=>{const t=Ye(),n=[xt(t,"onStoryCreated","story.created",(async t=>{const n=dm(t,!0);Fn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Rp=e=>{const t=Ye(),n=[xt(t,"onStoryCreated","local.story.created",(async t=>{Fn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Pp=e=>{const t=Ye(),n=[xt(t,"onStoryDeleted","story.deleted",(async t=>{const n=dm(t);Fn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Dp=e=>{const t=Ye(),n=[xt(t,"onStoryDeleted","local.story.deleted",(async t=>{Fn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Up=e=>{const t=Ye();return xt(t,"onStoryError","local.story.error",(async t=>{Fn(t),e(t.stories)}))},jp=e=>t=>e((e=>t(e[0]))),kp=async e=>{const t=Ye();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:a}=n;return t.cache&&Fn(n.data),{data:a.storyTargets,cachedAt:Date.now()}};class Ep extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.paginationController=a}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now(),a=dm(e);t.cache&&(Fn(a,{cachedAt:n}),Sp(a.stories),Op(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)st(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(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=at(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])],st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Mp extends Tr{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class qp extends Rr{constructor(e,t){const n=R.default(e),a=["story-target-ids","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),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;let o=s.data.map((e=>at(["story","get",e]))).filter(Boolean).map((e=>hd.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(Ct):a.sort(St)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Tp,action:"onCreate"},{fn:vp,action:"onUpdate"},{fn:Pp,action:"onDelete"},{fn:Up,action:"onError"}])}}const xp=(e,t)=>{var n,a;const s=null===(n=at(e))||void 0===n?void 0:n.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[];st(e,Object.assign(Object.assign({},s),{data:[...new Set([...o,...t])]}))};class Np extends Sr{constructor(e,t,n,a,s){super(e,t),this.notifyChange=n,this.paginationController=a,this.preparePayload=s}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now(),a=this.preparePayload(e);t.cache&&Fn(a,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?st(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):xp(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&xp(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 Kp extends Cr{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 Fp extends Rr{constructor(e,t){const n=R.default(e),a=["story-global-feed","collection",n],s=new Kp(e);super(s,n,a,t),this.query=e,this.queryStreamController=new Np(this.query,this.cacheKey,this.notifyChange.bind(this),s,(e=>{const t=Bn(_r(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=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=s.data,i=nt(["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=>at(["storyTarget","get",e]))).filter(Boolean).map((e=>hd.storyTarget(e.data)));(this.shouldNotify(r)||"event"!==e)&&(r=this.applyFilter(r).filter((({localSortingDate:e})=>!!e)).map((e=>Bn(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(wt);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(wt)||[],a=t.unseen.sort(wt)||[],s=t.seen.sort(wt)||[];return n.concat(a,s)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Tp,action:"onCreate"},{fn:vp,action:"onUpdate"},{fn:Pp,action:"onDelete"},{fn:Rp,action:"onCreate"},{fn:fp,action:"onUpdate"},{fn:Dp,action:"onDelete"},{fn:Up,action:"onError"}])}}var _p=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:jn(),dataType:"image",items:o,targetType:e,targetId:t,metadata:a};const r=new Date;st(["story-sync-state",t],"syncing"),st(["story-expire",t],new Date(r.setFullYear(r.getFullYear()+1))),hp({payload:i,formData:n},(e=>{Nt("local.story.created",e)}));try{const{data:a}=await Bd(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})}),gp({targetId:t,targetType:e}),hp({payload:i,formData:n},(e=>{Nt("local.story.created",e)}));const o=await mp(i);return o.data?Object.assign(Object.assign({},o),{data:hd.story(o.data)}):o}catch(e){throw st(["story-sync-state",t],"error"),hp({payload:Object.assign(Object.assign({},i),{syncState:"error"}),formData:n},(e=>{Nt("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:jn(),dataType:"video",items:s,targetType:e,targetId:t,metadata:a};const i=new Date;st(["story-sync-state",t],"syncing"),st(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),gp({targetId:t,targetType:e}),hp({payload:o,formData:n,isVideo:!0},(e=>{Nt("local.story.created",e)}));try{const{data:e}=await _d(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}})}),hp({payload:o,formData:n,isVideo:!0},(e=>{Nt("local.story.created",e)}));const a=await mp(o);return a.data?Object.assign(Object.assign({},a),{data:hd.story(a.data)}):a}catch(e){throw st(["story-sync-state",t],"error"),hp({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n,isVideo:!0},(e=>{Nt("local.story.error",e)})),e}},hardDeleteStory:async e=>await yp(e,!0),softDeleteStory:async e=>await yp(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:a}=Ye(),s=[],o=["story-target","collection",e],i=Date.now();n(`getActiveStoriesByTarget(tmpid: ${i}) > listen`),a||console.log(ve);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(Ct):t.sort(St):"asc"===o?t.sort(Ot):t.sort(At)},c=e=>{var n;const a=e.data.map((e=>{const t=pp(e);if(null==t?void 0:t.data)return hd.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=at(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(Ze("story")):[...new Set([...l.data,...t.map(Ze("story"))])];const u=null===(r=nt(["story","get"]))||void 0===r?void 0:r.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>Ze("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{l.data.includes(e)||l.data.push(e)})),st(o,l.data),c(l)},l=e=>t=>{d(t,e)};return(t=>{const n=_e(Ap,e);$e(n,(({data:e,error:n,loading:a})=>{d(e,"fetch",t,a,n)}))})(!0),s.push(Tp(l("onCreate")),vp(l("onUpdate")),Pp(l("onDelete")),bp(l("onReactionAdded")),Cp(l("onReactionRemoved")),Up(l("onError")),Rp(l("onCreate")),fp(l("onUpdate")),Dp(l("onDelete")),Ip(l("onReactionAdded")),wp(l("onReactionRemoved")),(e=>{const t=Ye();return xt(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=at(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)})),(()=>rt(o))),()=>{n(`getActiveStoriesByTarget(tmpid: ${i}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>qr(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:hd.story(e.data)})):t(e)}),"storyId",lm,[jp(vp),jp(Pp),jp(bp),jp(Cp),jp(Up),jp(fp),jp(Dp),jp(Ip),jp(wp)]),getTargetById:(e,t)=>qr(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:hd.storyTarget(e.data[0])})):t(e)}),"query",(e=>kp([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:a}=Ye(),s=[],o=["storyTargets","collection",e],i=Date.now();n(`getTargetsByTargetIds(tmpid: ${i}) > listen`),a||console.log(ve);const r=(e,n=!1,a=!1,s=!1)=>{const i=at(o),r={loading:a,error:s,params:{page:void 0},data:[]};e&&(r.data=n?e.map(Ze("storyTarget")):[...new Set([...(null==i?void 0:i.data)||[],...e.map(Ze("storyTarget"))])]),st(o,r.data),(e=>{var n;const a=e.data.map((e=>{const t=at(["storyTarget","get",e]);if(null==t?void 0:t.data)return hd.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=_e(kp,e);$e(n,(({data:e,error:n,loading:a})=>{r(e,t,a,n)}))})(!0),s.push((()=>rt(o))),()=>{n(`getTargetsByTargetIds(tmpid: ${i}) > dispose`),s.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getStoriesByTargetIds(tmpid: ${i}) > listen`);const r=new qp(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{rt(d)})),()=>{a(`getStoriesByTargetIds(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getGlobalStoryTarget(tmpid: ${i}) > listen`);const r=new Fp(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{rt(d)})),()=>{a(`getGlobalStoryTarget(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}}});const Bp=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),$p=e=>Object.assign({},e);var Lp=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(Bp),a=t.advertisers.map($p);return Fn({ads:n,advertisers:a,files:t.files}),st(["ad","setting"],t.settings),{ads:n.map(hd.ad),settings:t.settings}}});const Qp=async()=>{const e=Ye();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];st(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}};Qp.locally=()=>{var e;const t=Ye();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:a}=null!==(e=at(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:a}:void 0};const Vp=e=>{const t=Ye(),n=[xt(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Jp extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 Hp extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.notificationTrayItems.map(Ze("notificationTrayItem"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(Ze("notificationTrayItem"))])]}))}}}const Gp=e=>{const t=e.users.map(pa);return Object.assign(Object.assign({},e),{users:t})};class zp extends Rr{constructor(e,t){const n=R.default(e),a=["notificationTrayItem","collection",n];super(new Jp(e),n,a,t),this.query=e,this.queryStreamController=new Hp(this.query,this.cacheKey,this.notifyChange.bind(this),Gp),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["notificationTrayItem","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.notificationTray);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Yp=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=Ut();return qr(t,e,"userId",Qp,[Vp],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Gn(e.lastTraySeenAt)>Gn(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}=Ye();s||console.log(ve);const o=Date.now();a(`getNotificationTrayItems(tmpid: ${o}) > listen`);const i=new zp(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getNotificationTrayItems(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},markItemsSeen:async e=>{const t=Ye();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=at(["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();st(["notificationTrayItem","get"],s,{cachedAt:e})}return s})).filter(Boolean);Nt("local.notificationTrayItem.updated",{notificationTrayItems:a})},markTraySeen:async e=>{var t;const n=Ye();n.log("notificationTray/markTraySeen",{});const{data:a}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),s=null===(t=at(["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&&st(["notificationTraySeen","get",n.userId],i,{cachedAt:r}),Nt("local.notificationTraySeen.updated",o),{data:a,cachedAt:r}},onNotificationTraySeenUpdated:Vp});class Wp extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 Ju(i),o}}class Xp extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.invitations.map(Ze("invitation"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Ze("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===oc.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}if(e===oc.OnLocalInvitationCreated){const e=Ye(),n=t.filter((t=>t.invitedUserId===e.userId));a.data=[...new Set([...n.map((e=>e.invitationId)),...a.data])]}e===oc.OnLocalInvitationCanceled&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Zp extends Rr{constructor(e,t){const n=R.default(e),a=["invitation","collection",n];super(new Wp(e),n,a,t),this.query=e,this.queryStreamController=new Xp(this.query,this.cacheKey,this.notifyChange.bind(this),nc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:cc,action:oc.OnLocalInvitationCreated},{fn:dc,action:oc.OnLocalInvitationUpdated},{fn:lc,action:oc.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["invitation","get",e]))).filter(Pr).map((({data:e})=>ac(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?Ct:St)();return t=t.sort(n),t}}var ey=Object.freeze({__proto__:null,cancelInvitation:async e=>{var t;const n=Ye();n.log("invitation/cancelInvitation",e);const{data:a}=await n.http.delete(`/api/v1/invitations/${e}`),s=null===(t=at(["invitation","get",e]))||void 0===t?void 0:t.data;return _n("invitation",e),s&&Nt("local.invitation.canceled",[s]),a.success},onLocalInvitationCreated:cc,onLocalInvitationUpdated:dc,onLocalInvitationCanceled:lc,getMyCommunityInvitations:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMyCommunityInvitations: (tmpid: ${o}) > listen`);const i=new Zp(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getInvitations (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getInvitations:(e,t)=>{const{_id:n}=$t();if(!n)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=Ye(),{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(hd.invitation))})(a)};return"room"===o&&(r.push(bg(c)),r.push(Cg(c)),r.push(wg(c)),r.push(Sg(c))),()=>{a(`getInvitations(tmpid: ${i}) > dispose for ${o}: ${s}`),r.forEach((e=>e()))}}});const ty=e=>{const t=Ye();return xt(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 ny=Object.freeze({__proto__:null,createReaction:async({referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:s})=>{const o=Ye();if(o.log("live_reaction/createReaction",{referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:s}),!a&&!s)throw new Qe("You have to specify either streamId or roomId",800110,"error");const i=No(),r={reactionName:n,referencePublicId:e,referenceType:t,roomId:s,streamId:a,occurredAt:(new Date).toISOString()};return i.createLiveReaction(r),Nt("local.liveReaction.created",[Object.assign(Object.assign({},r),{userId:o.userId,referenceId:e})]),!0},onLiveReactionCreated:ty,getReactions:(e,t)=>{const{_id:n}=Ut();if(!n)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=Ye();a(`getReactions(tmpid: ${Date.now()}) > listen`);const s=[],o=n=>{(e=>{t(e)})(n.filter((({referenceId:t})=>t===e)))};return s.push(ty(o)),s.push((e=>{const t=Ye();return xt(t,"live_reaction/onLiveReactionCreated","local.liveReaction.created",e)})(o)),()=>{s.forEach((e=>e()))}}});const ay=async e=>{const t=Ye();t.log("event/getEvent",e);try{const{data:n}=await t.http.get(`/api/v1/events/${e}`),a=Jc(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.events.find((t=>t.eventId===e)),cachedAt:s}}catch(n){if(Pe(null==n?void 0:n.code)){const a=ay.locally(e);if(!a)throw n;const s=Object.assign(Object.assign({},null==a?void 0:a.data),{isDeleted:!0});it(["event","get",e],s);return{data:s,cachedAt:t.cache&&Date.now()}}throw n}};ay.locally=e=>{const t=Ye();if(t.log("event/getEvent.locally",e),!t.cache)return;const n=at(["event","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class sy extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 oy extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.events.map(Ze("event"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(Ze("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Yc.OnEventCreated&&(a.data=[...new Set([t.eventId,...a.data])]),e===Yc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class iy extends Rr{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),Jc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Zc,action:Yc.OnEventCreated},{fn:ed,action:Yc.OnEventUpdated},{fn:td,action:Yc.OnEventDeleted},{fn:nd,action:Yc.OnEventCreated},{fn:ad,action:Yc.OnEventUpdated},{fn:sd,action:Yc.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["event","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.event);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}class ry extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 cy extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.events.map(Ze("event"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(Ze("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Yc.OnEventCreated){if(Ye().userId!==t.userId)return;a.data=[...new Set([t.eventId,...a.data])]}e===Yc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class dy extends Rr{constructor(e,t){const n=R.default(e),a=["event","collection",n];super(new ry(e),n,a,t),this.query=e,this.queryStreamController=new cy(this.query,this.cacheKey,this.notifyChange.bind(this),Jc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Zc,action:Yc.OnEventCreated},{fn:ed,action:Yc.OnEventUpdated},{fn:td,action:Yc.OnEventDeleted},{fn:nd,action:Yc.OnEventCreated},{fn:ad,action:Yc.OnEventUpdated},{fn:sd,action:Yc.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["event","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.event);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}var ly=Object.freeze({__proto__:null,createEvent:async e=>{const t=Ye();t.log("event/createEvent",e);const{data:n}=await t.http.post("/api/v1/events",e);Nt("local.event.created",n);const a=Jc(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:ud(a.events[0]),cachedAt:s}},updateEvent:async(e,t)=>{const n=Ye();n.log("event/updateEvent",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}`,t);Nt("local.event.updated",a);const s=Jc(a),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),{data:ud(s.events.find((t=>t.eventId===e))),cachedAt:o}},deleteEvent:async e=>{const t=Ye();t.log("event/deleteEvent",e);const n=await ay(e);await t.http.delete(`/api/v1/events/${e}`);const a=Object.assign(Object.assign({},n.data),{isDeleted:!0});it(["event","get",e],a),Nt("local.event.deleted",{users:[],files:[],communities:[],posts:[],rooms:[],events:[a]})},onEventCreated:Zc,onEventUpdated:ed,onEventDeleted:td,onLocalEventCreated:nd,onLocalEventUpdated:ad,onLocalEventDeleted:sd,onRSVPCreated:od,onRSVPUpdated:id,onLocalRSVPCreated:rd,onLocalRSVPUpdated:cd,getEvent:(e,t)=>qr(e,t,"eventId",ay,[ed,td,ad,sd],{callbackDataSelector:e=>e?ud(e):e}),getEvents:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getEvents: (tmpid: ${o}) > listen`);const i=new iy(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getEvents (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getMyEvents:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMyEvents: (tmpid: ${o}) > listen`);const i=new dy(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getMyEvents (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getRSVPs:ld});const uy=async e=>{const t=Ye();let n;t.log("product/getProduct",e),ea("product",e);try{n=(await t.http.get(`/api/v1/products/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("product",e),t}const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{products:s}=n;return{data:s.find((t=>t.productId===e)),cachedAt:a}};uy.locally=e=>{const t=Ye();if(t.log("product/getProduct.locally",e),!t.cache)return;const n=at(["product","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class hy extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 my extends Sr{constructor(e,t,n){super(e,t),this.notifyChange=n}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();t.cache&&Fn(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.products.map(Ze("product"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.products.map(Ze("product"))])]}))}}}class gy extends Rr{constructor(e,t){const n=R.default(e),a=["products","collection",n];super(new hy(e),n,a,t),this.query=e,this.queryStreamController=new my(this.query,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["product","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.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 py=Object.freeze({__proto__:null,getProduct:(e,t)=>qr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hd.product(n):n}))}),"productId",uy,[]),searchProducts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`searchProducts(tmpid: ${o}) > listen`);const i=new gy(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`searchProducts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});return e.API_REGIONS=on,e.AdRepository=Lp,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=nm,e.ChannelRepository=Qu,e.Client=sr,e.CommentRepository=Cm,e.CommunityPostSettingMaps=x,e.CommunityPostSettings=q,e.CommunityRepository=Zh,e.ContentFeedType=F,e.DefaultCommunityPostSetting=N,e.EventRepository=ly,e.FeedRepository=Hm,e.FileRepository=$d,e.FileType=D,e.GET_WATCHER_URLS=fc,e.InvitationRepository=ey,e.LiveReactionRepository=ny,e.LiveStreamPlayer=lp,e.MessageContentType=B,e.MessageRepository=mu,e.PollRepository=ip,e.PostContentType=$,e.PostRepository=$g,e.PostStructureType=L,e.ProductRepository=py,e.ReactionRepository=xl,e.RoomPresenceRepository=np,e.RoomRepository=Ng,e.StoryRepository=_p,e.StreamRepository=Wg,e.SubChannelRepository=Iu,e.UserRepository=Kd,e.VERSION=me,e.VideoResolution=U,e.VideoSize=k,e.VideoTranscodingStatus=j,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:a,userId:s}=Ye();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=_e,e.createReport=async(e,t,n)=>{const a=Ye();return a.log("report/createReport",{referenceType:e,referenceId:t,options:n}),"user"===e?(async({referenceId:e,options:t})=>!!await gd(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 ha(n);Fn(e)}return Nt("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 Zd(n);Fn(e)}return Nt("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 Nl(n);Fn(e)}return Nt("comment.flagged",n),!!n})({client:a,referenceId:t})},e.createUserToken=async(e,t,n)=>{const a=await En(),s=Mn(),o=yn(cn("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=Ye();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 eo(n);Fn(e)}return Nt("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 ha(n);Fn(e)}return Nt("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 Zd(n);Fn(e)}return Nt("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 Nl(n);Fn(e)}return Nt("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=Ye();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=rt,e.enableCache=(e={},t)=>{const n=Ye();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.exceedsUntilAtBoundary=Pt,e.filterByChannelMembership=ut,e.filterByCommunityMembership=mt,e.filterByFeedType=ht,e.filterByPostDataTypes=gt,e.filterByPropEquality=ct,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=lt,e.filterBySearchTerm=pt,e.filterByStringComparePartially=dt,e.filterByUntilAt=(e,t,n)=>{const a=new Date(t).valueOf();return"firstCreated"===n?e.filter((e=>new Date(e.createdAt).valueOf()<a)):e.filter((e=>new Date(e.createdAt).valueOf()>a))},e.filterCommentsByBlockUsers=ft,e.filterPostsByBlockUsers=vt,e.getBlockUsersId=yt,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=Ut();return`${Vt(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>Qt(t,n),e.getLiveReactionTopic=e=>`${e.path}/liveReaction`,e.getLiveStreamTopic=Zt,e.getMarkedMessageTopic=Gt,e.getMarkerUserFeedTopic=()=>{const e=Ut();return`${Vt(e)}/marker/user/${e._id}`},e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=Jt,e.getMyFollowingsTopic=Ht,e.getNetworkId=Vt,e.getNetworkTopic=zt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Qd,e.getRoomStreamerTopic=e=>{const t=$t();return`${Vt(t)}/room/${e.roomId}/streamer`},e.getRoomWatcherTopic=e=>{const t=$t();return`${Vt(t)}/room/${e._id}`},e.getSmartFeedChannelTopic=Yt,e.getSmartFeedMessageTopic=Xt,e.getSmartFeedSubChannelTopic=Wt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const a=Ut();return`${Vt(a)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=({path:t},n=e.SubscriptionLevels.USER)=>Qt(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),e.isAfterBefore=Ue,e.isAfterBeforeRaw=je,e.isCachable=Ke,e.isFetcher=qe,e.isFresh=Fe,e.isLocal=e=>Ke(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=xe,e.isOffline=Ne,e.isPaged=ke,e.isReportedByMe=async(e,t)=>{const n=Ye();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=De,e.mergeInCache=ot,e.notificationTray=Yp,e.onChannelMarkerFetched=zi,e.onFeedMarkerFetched=e=>{const t=Ye();return xt(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=Ye();return xt(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Fn(t),e(t.feedMarkers[0])}))},e.onMessageMarked=er,e.onMessageMarkerFetched=Zi,e.onSubChannelMarkerFetched=Yi,e.onSubChannelMarkerUpdated=Wi,e.onUserMarkerFetched=Xi,e.onUserMarkerFetchedLegacy=e=>{const t=Ye();return xt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=at,e.pushToCache=st,e.queryCache=nt,e.queryOptions=Be,e.queryRoles=Ld,e.restoreCache=async(e="amitySdk")=>{var t;const n=Ye();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=$e,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=bt,e.sortByFirstCreated=Ct,e.sortByFirstUpdated=Ot,e.sortByLastActivity=Tt,e.sortByLastCreated=St,e.sortByLastUpdated=At,e.sortByLocalSortingDate=wt,e.sortByName=It,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=en,e.toPage=Me,e.toPageRaw=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return je(n)?n:void 0},e.toToken=Ee,e.upsertInCache=it,e.validateUntilAt=Rt,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:a}=Ye();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}}),N="ONLY_ADMIN_CAN_POST";var K;e.AmityCommunityType=void 0,(K=e.AmityCommunityType||(e.AmityCommunityType={})).Default="default",K.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",EVENT:"event"}),L=Object.freeze({TEXT:"text",IMAGE:"image",VIDEO:"video",FILE:"file",AUDIO:"audio",MIXED:"mixed",EVENT:"event"});var Q,V,J,H,G,z,Y,W,X,Z,ee,te,ne,ae,se,oe,ie,re,ce,de,le,ue,he;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,(G=e.JoinRequestStatusEnum||(e.JoinRequestStatusEnum={})).Pending="pending",G.Approved="approved",G.Rejected="rejected",G.Cancelled="cancelled",e.JoinResultStatusEnum=void 0,(z=e.JoinResultStatusEnum||(e.JoinResultStatusEnum={})).Success="success",z.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",e.AmityLiveViewerCountMode=void 0,(he=e.AmityLiveViewerCountMode||(e.AmityLiveViewerCountMode={})).ALWAYS_SHOW="always",he.HIDE_ENTIRELY="hidden",he.SHOW_ABOVE_MINIMUM="above-minimum";const me=function(){try{return"v7.27.0-umd"}catch(e){return"__dev__"}}(),ge=5,pe=20,ye="cache_then_server",ve="For using Live Collection feature you need to enable Cache!",fe="Observing unsynced object is not supported by Live Object.",be=-5,Ie=1e3,Ce=6e5,we="/api/v1/feeds/for-you",Se="dead",Oe=6e4,Te=e=>JSON.stringify(e,((e,t)=>{return null!==t&&"object"==typeof t?(n=t,Object.keys(n).sort().reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:n[t]})),{})):t;var n})),Ae=e=>JSON.parse(e),Re=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>Re(e[n],t[n])))),Pe=e=>[400400,400300].includes(e),De=e=>["skip"].some((t=>t in e)),Ue=e=>["after","before","first","last","limit"].some((t=>t in e)),ke=e=>"limit"in e,je=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),Ee=(e,n)=>{var a;if(!e||!Object.keys(e).length)return;let s={};return"skiplimit"===n?s={skip:null!==(a=e.after)&&void 0!==a?a:0,limit:e.limit}:"afterbefore"===n&&Ue(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},Me=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(De(n))return{after:n.skip,limit:n.limit};if(Ue(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},qe=e=>"locally"in e,xe=e=>"optimistically"in e,Ne=e=>qe(e)||xe(e),Ke=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),Fe=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},_e=(e,...t)=>({func:e,args:t}),Be=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<Oe?Oe:t},$e=({func:e,args:t},n,a=Be("cache_then_server"))=>{let s;const{lifeSpan:o}=Be("cache_then_server",a.lifeSpan);if(Ne(e)){try{s=xe(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(Le(void 0,{origin:"local",loading:!1,error:e}))}const a=Ke(s)&&Fe(s,o);if(null==n||n(Le(s,{origin:"local",loading:!(qe(e)&&a)})),a)return}else null==n||n(Le(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(Le(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(Le(void 0,{origin:"server",loading:!1,error:e}))}))};function Le(e,t){return je(e)||Ke(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}class Qe 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,Qe)}}class Ve extends Qe{constructor(e,t,n){super(e,t,n)}}class Je extends Qe{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class He extends Qe{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class Ge extends Qe{constructor(e){super(e,800110,"error")}}let ze=null;const Ye=()=>{if(!ze)throw new Qe("There is no active client",8e5,"fatal");return ze},We=e=>{ze=e},Xe={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},Ze=e=>Xe[e],et={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 tt(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}const nt=e=>{const{log:t,cache:n}=Ye();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=Ae(t);return Re(e,n)})).map((e=>n.data[e]))},at=e=>{const{log:t,cache:n}=Ye();if(!n)return;t("cache/api/pullFromCache",e);const a=Te(e);return n.data[a]?n.data[a]:void 0},st=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:s}=Ye();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=Te(e);return s.data[o]=Object.assign({key:e,data:t},n),!0},ot=(e,t,n)=>{const{log:a,cache:s}=Ye();if(!s)return!1;a("cache/api/mergeInCache",{key:e,mutation:t});const o=at(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))&&(st(e,i,n),!0);var r,c},it=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:s}=Ye();if(!s)return!1;a("cache/api/upsertInCache",{key:e,data:t,options:n});return at(e)?ot(e,t,n):st(e,t,n)},rt=(e,t=!1)=>{const{log:n,cache:a}=Ye();if(!a)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(a.data).map((e=>Ae(e))).filter((t=>Re(e,t))).map((e=>rt(e,!0))).every((e=>e));const s=Te(e);return s in a.data&&(delete a.data[s],!0)},ct=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,dt=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,lt=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,ut=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;if("community"===e.type)return!0;const s=Ze("channelUsers")({channelId:e.channelPublicId,userId:n}),o=null===(a=at(["channelUsers","get",s]))||void 0===a?void 0:a.data;return"member"===t?o&&"none"!==o.membership:!o||"none"===o.membership})),ht=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var a;const s=null===(a=at(["feed","get",Ze("feed")({targetId:e,feedId:n})]))||void 0===a?void 0:a.data;return s&&s.feedType===t})),mt=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;const s=Ze("communityUsers")({communityId:e.communityId,userId:n}),o=null===(a=at(["communityUsers","get",s]))||void 0===a?void 0:a.data;return"member"===t?o&&"member"===o.communityMembership:!o||"none"!==o.communityMembership})),gt=(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=at(["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}),[]),pt=(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))}))},yt=()=>{var e;const{userId:t}=Ye(),n=new Set;return(null!==(e=nt(["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},vt=e=>{const t=yt();return 0===t.size?e:e.filter((e=>{var n,a;if(t.has(e.postedUserId))return!1;return!(null!==(a=null===(n=e.mentionees)||void 0===n?void 0:n.flatMap((e=>"user"===e.type?e.userIds:[])))&&void 0!==a?a:[]).some((e=>t.has(e)))}))},ft=e=>{const t=yt();return 0===t.size?e:e.filter((e=>!t.has(e.userId)))},bt=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,It=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,Ct=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),wt=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),St=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),Ot=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Tt=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),At=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf(),Rt=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")},Pt=(e,t,n)=>{const a=new Date(e).valueOf(),s=new Date(t).valueOf();return"firstCreated"===n?a>=s:a<=s};let Dt=null;const Ut=()=>{if(!Dt)throw new Qe("Connect client first",8e5,"fatal");return Dt},kt=e=>{Dt={_id:e._id,userId:e.userId,path:e.path}};let jt,Et=[];const Mt=e=>{clearTimeout(jt),Et.push(e),jt=setTimeout((()=>{Et.forEach((e=>e())),Et=[]}),0)},qt=["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"],xt=(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)}},Nt=(e,t)=>{const{emitter:n}=Ye();Mt((()=>{n.emit(e,t)}))};let Kt,Ft;async function _t(){var e;const{mqtt:t,emitter:n,token:a}=Ye();if(!t)return;const s=null!==(e=null==a?void 0:a.accessToken)&&void 0!==e?e:"",o=Ut();Kt===s&&Ft===o._id||(Kt=s,Ft=o._id,await t.connect({accessToken:Kt,userId:Ft}),((e,t)=>{qt.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 Bt=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=at(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),$t=()=>{var e;const t=Ye();if(!t)throw new Qe("Connect client first",8e5,"fatal");const n=null===(e=at(["user","get",t.userId]))||void 0===e?void 0:e.data;return n?Bt(n):null};var Lt;e.SubscriptionLevels=void 0,(Lt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",Lt.POST="post",Lt.COMMENT="comment",Lt.POST_AND_COMMENT="post_and_comment",Lt.USER="user";const Qt=(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}},Vt=e=>e.path.split("/user/")[0],Jt=()=>{const e=Ut();return`${Vt(e)}/membership/${e._id}/+/+`},Ht=()=>{const e=Ut();return`${Vt(e)}/membership/+/${e._id}/+`},Gt=({channelId:e,subChannelId:t})=>{const n=Ut();return`${Vt(n)}/marker/channel/${e}/message/${t}`},zt=()=>Vt(Ut()),Yt=()=>{const e=Ut();return`${Vt(e)}/smartfeed/${e._id}/channels`},Wt=()=>{const e=Ut();return`${Vt(e)}/smartfeed/${e._id}/messagefeeds`},Xt=()=>{const e=Ut();return`${Vt(e)}/smartfeed/${e._id}/messages`},Zt=()=>{const e=Ut();return`${Vt(e)}/videostreaming`};function en(e,t){const{mqtt:n}=Ye();return n?(_t(),n.subscribe(e,t)):()=>null}var tn;const nn="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:an={}}=nn,sn="production"===(null===(tn=an.env)||void 0===tn?void 0:tn.NODE_ENV),on={EU:"eu",SG:"sg",US:"us"},rn={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function cn(e,t){return rn[e].replace("{region}",t)}class dn{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 ln;var un,hn=()=>(ln||(ln=new dn),ln);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(un||(un={}));let mn=new AbortController;const gn=e=>{switch(e){case un.UserGlobalBanned:throw new Qe(e,400312,"fatal");case un.UserDeleted:throw new Qe(e,400100,"fatal");case un.TokenExpired:throw Nt("tokenExpired","tokenExpired"),new Qe(e,800403,"fatal");default:throw new Qe("Request Aborted",8e5,"error")}};let pn=0;const yn=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:mn.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&&(mn.abort(),gn(un.UserGlobalBanned)),a&&(mn.abort(),gn(un.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),hn().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)&&Nt("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-pn<2e3||(pn=e,Nt("visitorUsageLimitReached",void 0))}(),new Qe("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 Ve(e.message,e.code,"error")})(null==s?void 0:s.data),mn.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 vn{constructor(){this._sessionState="notLoggedIn",this._listener=new Map}onSessionStateChange(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setSessionState(e,t){this._sessionState!==e&&(this._sessionState=e,this._listener.forEach((n=>n(e,t))))}destroy(){this._listener.clear()}}let fn;var bn=()=>(fn||(fn=new vn),fn);const In=e=>bn().onSessionStateChange(e),Cn={[e.AmityAutoSubscription.NETWORK]:[zt],[e.AmityAutoSubscription.CHAT]:[Yt,Wt,Xt],[e.AmityAutoSubscription.LIVESTREAM]:[Zt],[e.AmityAutoSubscription.BLOCK]:[Jt,Ht]},wn=[e.AmityAutoSubscription.CHAT,e.AmityAutoSubscription.NETWORK,e.AmityAutoSubscription.LIVESTREAM,e.AmityAutoSubscription.BLOCK],Sn=Object.values(e.AmityAutoSubscription);class On{constructor(){this.refCountByFeature=new Map,this.disposers=new Map,this.seed()}seed(){this.refCountByFeature.clear(),wn.forEach((e=>this.refCountByFeature.set(e,1)))}isActive(e){var t;return(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)>0}subscribeTopics(e){this.unsubscribeTopics(e),this.disposers.set(e,Cn[e].map((e=>en(e()))))}unsubscribeTopics(e){var t;(null!==(t=this.disposers.get(e))&&void 0!==t?t:[]).forEach((e=>e())),this.disposers.delete(e)}initialize(){Sn.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 Sn.map((e=>({feature:e,isActive:this.isActive(e),isSystem:!0,topicCount:Cn[e].length})))}reset(){Sn.forEach((e=>this.unsubscribeTopics(e))),this.disposers.clear(),this.seed()}}let Tn=null;const An=()=>(Tn||(Tn=new On),Tn);class Rn{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 Pn=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new Rn},Dn=async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await O.default.setItem(e,t),!0):new Promise((n=>{Pn().localStorage.setItem(e,t),n(!0)})),Un=async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){return await O.default.getItem(e)}return new Promise((t=>{t(Pn().localStorage.getItem(e))}))},kn=()=>T.default.v4().toString();let jn=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=kn(),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:jn}),"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&&(jn=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const En=async()=>{var e;const t=`${null!==(e=Ye().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await Un(t);if(n)return n;const a=`ascWebSdk#${kn()}`;return await Dn(t,a),a},Mn=()=>{const e=(()=>{var e,t;return(null===(e=an.versions)||void 0===e?void 0:e.node)?an.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:me}},qn=1e3;var xn;!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"}(xn||(xn={}));const Nn=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 Qe(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 En()}_${e}_${jn}`)(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:qn,resubscribe:!0,keepalive:30,properties:{sessionExpiryInterval:1800}},e)}({username:n.userId,password:n.accessToken,clientId:a})),t.on("connect",(()=>{t.options.reconnectPeriod=qn,s("connected"),An().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||qn),8e3)})),t.on("close",(()=>{o.forEach((({timer:e})=>clearTimeout(e))),o.clear()})),new Promise((e=>t.once("connect",(()=>e()))))},async disconnect(e){if(this.connected)return(null==e?void 0:e.endSession)?new Promise((e=>null==t?void 0:t.end(!1,{reasonCode:0,properties:{sessionExpiryInterval:0}},(()=>e())))):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 Qe("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=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t},Fn=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,a])=>{const s=et[e];if(!s)return;const o=Ze(s);o&&a&&a.forEach((e=>{(n?st:it)([s,"get",o(e)],e,t)}))}))},_n=(e,t)=>{const{log:n,cache:a}=Ye(),s=[e,Se,t],o={cachedAt:Date.now()};a&&(n("cache/api/pushToTombstone",{cacheKey:s,data:o}),rt([e,"get",t],!0),st(s,o))};function Bn(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 $n=(e,t="userId",n="user")=>{var a;return null!==(a=null==e?void 0:e.map((e=>((e,t="userId",n="user")=>e[n]?e:Object.assign({get[n](){var n;if(!Ye().cache)return;return(null===(n=at(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==a?a:e},Ln=(e,t,n="userId",a="user")=>{const s=e,o=t,i=s[o],r=Bn(s,["symbol"==typeof o?o:o+""]),c=$n(i,n,a);return Object.assign(Object.assign({},r),{[t]:c})};function Qn(e){return e.map((e=>{var{isMentioned:t}=e,n=Bn(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function Vn(e){return Qn(e)}function Jn(e){return Qn(e)}const Hn=e=>{var t,n;return null!==(n=null===(t=at(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Gn=e=>new Date(e).getTime(),zn=e=>{var t,n;return null!==(n=null===(t=at(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Yn=e=>{var t;const n=e.messagePreviewId?zn(e.subChannelId):null,a=n?Object.assign(Object.assign({},n),{user:null===(t=at(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:a})},Wn=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:[]};Fn(a)};function Xn(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function Zn(e,t,n){st(["subChannel","get",e],Xn(t,n))}const ea=(e,t)=>{const{log:n,cache:a}=Ye(),s=[e,Se,t];if(!a)return;n("cache/api/isInTombstone",s);const o=at(s),{lifeSpan:i}=Be("cache_then_server",18e4);if(o&&Fe(o.data,i))throw new Ve("Item not found!",400400,"error")},ta=e=>{var t;const n=["channelUnreadInfo","get",e],a=null===(t=at(n))||void 0===t?void 0:t.data,s=nt(["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 st(n,r),r},na=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};Fn({subChannelUnreadInfo:[s]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{ta(e)}))}},aa=async()=>{const e=Ye();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&&Fn({userMarkers:n},{cachedAt:a}),Nt("local.userMarker.fetched",{userMarkers:n});return{data:n.reduce(((e,t)=>null==e||new Date(e.lastSyncAt).getTime()<new Date(t.lastSyncAt).getTime()?t:e),void 0),cachedAt:a}},sa=e=>{var t,n;const a=null===(t=at(["message","get",e]))||void 0===t?void 0:t.data;if(a)return a;const s=nt(["message","get"]);return null===(n=null==s?void 0:s.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data},oa=e=>!0===e&&void 0;function ia(e,t,n){var a,s;if(n)return n.hasMentioned;const o=Ye();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(a=at(["subChannelUnreadInfo","get",t]))||void 0===a?void 0:a.data;return!!e&&e.isMentioned}const i={entityId:e,feedId:t,userId:Ut()._id},r=null===(s=at(["subChannelMarker","get",Ze("subChannelMarker")(i)]))||void 0===s?void 0:s.data;return!!r&&r.hasMentioned}const ra=["broadcast","conversation","community"],ca=({channelType:e})=>ra.includes(e);function da(e){var{channelId:t,channelPublicId:n,channelType:a,childCount:s,creatorId:o,creatorPublicId:i,lastMessageId:r,lastMessageTimestamp:c,messageFeedId:d,name:l}=e,u=Bn(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=Ye();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(a=at(["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:Ut()._id},r=null===(s=at(["subChannelMarker","get",Ze("subChannelMarker")(i)]))||void 0===s?void 0:s.data;return r?r.unreadCount:0}(t,d)},get hasMentioned(){return ia(t,d)},get isMentioned(){return ia(t,d)}},u),{channelId:n,creatorId:i,displayName:l,lastActivity:c,latestMessageId:r,messageCount:s,subChannelId:d,isUnreadCountSupport:ca({channelType:a})})}function la(e,t,n){var a;const s=(e=>{var t,n,a;const s=null===(n=null===(t=nt(["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=Bn(s,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let f;m&&(f=at(["message","get",m])),f||(f=at(["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=Ye(),s=sa(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 ua={},ha=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Fn({messages:(a=e).messages.map((e=>la(e,a.reactions)))});const t=n.join("");ua[t]&&clearTimeout(ua[t]),ua[t]=setTimeout((()=>{try{(async e=>{const t=Ye();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&&Fn({contentMarkers:a,feedMarkers:s,userMarkers:o},{cachedAt:i}),Nt("local.feedMarker.fetched",{feedMarkers:s}),Nt("local.messageMarker.fetched",{contentMarkers:a}),Nt("local.userMarker.fetched",{userMarkers:o})})(n)}catch(e){}}),2e3)}var a;const{messageFeeds:s}=e,o=Bn(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,n;const a=null!==(n=null===(t=at(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},s=Bn(da(e),["unreadCount","isMentioned"]);Zn(e.messageFeedId,a,s)}))),Object.assign(Object.assign({},o),{messages:e.messages.map((n=>la(n,e.reactions,t)))})};function ma(e){var{subChannelId:t,mentionees:n,dataType:a,data:s}=e,o=Bn(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 ga(e){var{sortBy:t,subChannelId:n,includingTags:a,excludingTags:s,includeDeleted:o,aroundMessageId:i,limit:r,type:c}=e,d=Bn(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const l=Object.assign(Object.assign({},d),{messageFeedId:n,isDeleted:oa(o),options:{sortBy:t,limit:r||ge,around:i}});return a&&(l.includeTags=a),c&&(l.dataType=c),s&&(l.excludeTags=s),l}function pa(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const ya=["broadcast","conversation","community"],va=({channelType:e})=>ya.includes(e),fa=async e=>{const t=e.messageFeeds.filter(va).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Fn({messageFeeds:e.messageFeeds.map((e=>da(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=Ye();n.log("channel/getSubChannelMarkers",e,t);const{data:a}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:Ee(t,"skiplimit")}}}),{paging:s}=a,o=Bn(a,["paging"]),{userEntityMarkers:i,userFeedMarkers:r,userMarkers:c,feedMarkers:d}=o;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&na({feedMarkers:d,userFeedMarkers:r});const l=Vn(i),u=Jn(r),h=n.cache&&Date.now();n.cache&&Fn({userEntityMarkers:l,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),Nt("local.channelMarker.fetched",{userEntityMarkers:l}),Nt("local.subChannelMarker.fetched",{userFeedMarkers:u}),Nt("local.userMarker.fetched",{userMarkers:c});const m=Me(s.next);return{data:u,cachedAt:h,prevPage:Me(s.previous),nextPage:m}})(t)}catch(e){}}Wn(e);const n=e.messageFeeds.map(da),a=e.messages.map((e=>la(e))),s=e.users.map(pa);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:a,users:s})};const ba=async e=>{const t=Ye();t.log("channel/getSubChannel",e),ea("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),a=await fa(n.data),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),Nt("local.message-feed.fetched",a),{data:a.messageFeeds[0],cachedAt:s}}catch(t){throw Pe(null==t?void 0:t.code)&&_n("subChannel",e),t}};ba.locally=e=>{const t=Ye();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=at(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ia=async e=>{var t;let n=null===(t=at(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await ba(e)).data),n},Ca=async e=>{const t=await(async()=>Ye().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 Ia(d);"no-message-preview"!==t?(e=>{var t;const n=null===(t=at(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Gn(n.createdAt)<=Gn(e.createdAt)})(e)&&(st(["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}),Zn(e.subChannelId,h,{lastActivity:o,messagePreviewId:a})):Gn(h.lastActivity)<Gn(o)&&Zn(e.subChannelId,h,{lastActivity:o})},wa=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=at(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Ia(d);st(["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})}},Sa=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=at(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Gn(n.createdAt)<=Gn(e.createdAt)})(e)){const u=await Ia(c);st(["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})}},Oa=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=at(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Ia(d);st(["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})}},Ta=async e=>{var t,n,a,s;const{channelId:o,subChannelId:i}=e,r=null===(t=at(["messagePreviewChannel","get",o]))||void 0===t?void 0:t.data;if((null==r?void 0:r.subChannelId)===i){const e=null===(n=at(["subChannel","get",i]))||void 0===n?void 0:n.data;st(["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=at(["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=at(["subChannel","get",i]))||void 0===s?void 0:s.data;st(["messagePreviewSubChannel","get",i],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Aa=["broadcast","conversation","community"],Ra=({type:e})=>Aa.includes(e);function Pa(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:a}=e;const s=null===(n=at(["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:Ra(e),messagePreviewId:a})}const Da=(e,t={isMessagePreviewUpdated:!0})=>{Fn({channels:e.channels.map((e=>Pa(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Ua=async(e,t={isMessagePreviewUpdated:!0})=>{const n=Ye(),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=at(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Gn(n.createdAt)<=Gn(e.createdAt)}));0!==n.length&&Fn({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(Ra(t[i])){const r=["channelUnread","get",t[i].channelId],c=n.find((n=>n.channelId===t[i].channelId&&n.userId===e)),d=null===(a=at(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};st(r,p),o.push(p)}o.length>0&&Nt("local.channelUnread.updated",o)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(Ra).map((({channelInternalId:e})=>e));if(n.length>0){Da(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=Ye();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=Vn(a),i=t.cache&&Date.now();return t.cache&&Fn({userEntityMarkers:o,userMarkers:s},{cachedAt:i}),Nt("local.channelMarker.fetched",{userEntityMarkers:o}),Nt("local.userMarker.fetched",{userMarkers:s}),{data:o,cachedAt:i}})(n)}catch(e){}}}const s=e.channels.map((e=>Pa(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),o=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(Ye().cache)return(null===(e=at(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),i=e.users.map(pa),r=Bn(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},r),{users:i,channels:s,channelUsers:o})},ka=async e=>{const t=Ye();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return Nt("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},ja=async e=>{const t=Ye(),n=await ka(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:a,userFeedMarkers:s}=n;na({feedMarkers:a,userFeedMarkers:s}),t.log("channel/prepareUnreadCountInfo",e.channels)},Ea=(e,t)=>{var n,a,s,o;const i=Ye();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=at(["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:Ut()._id};return null===(t=at(["channelMarker","get",Ze("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===s?void 0:s.hasMentioned)&&void 0!==o&&o},Ma=(e,t)=>{var n,a,s,o,i;const r=Ye();return r.isUnreadCountEnabled&&r.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=at(["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:Ut()._id};return null===(t=at(["channelMarker","get",Ze("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===o?void 0:o.unreadCount)&&void 0!==i?i:0},qa=e=>{var t;return null===(t=at(["channelUnread","get",e]))||void 0===t?void 0:t.data},xa=e=>{const t=Ye(),n=Bn(e,["messageCount"]);return Xn(n,{get unreadCount(){var e,t;return null!==(t=null===(e=qa(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Ma(n)},get isMentioned(){var e,a;return t.useLegacyUnreadCount?null!==(a=null===(e=qa(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==a&&a:Ea(n)}})},Na=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],a=null===(t=at(n))||void 0===t?void 0:t.data;return a?Bt(a):void 0})()}}),Ka=e=>{const t=Ye();t.log("channel/getMyMembership.locally");const n=at(["channelUsers","get",`${e}#${t.userId}`]);if(!n)throw new Ve("Item not found!",400400,"error");return{data:n.data,cachedAt:n.cachedAt}};function Fa(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(!Fa(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=>Fa(e[n],t[n])))}const _a=[];let Ba=null;const $a=e=>{if(0===_a.length){const e=Ye();Ba=xt(e,"onChannelCreated","channel.created",(async e=>{const t=await Ua(e);Fn(t),_a.forEach((e=>e(t.channels[0])))}))}return _a.push(e),()=>(e=>{const t=_a.indexOf(e);t>-1&&_a.splice(t,1),0===_a.length&&(null==Ba||Ba())})(e)},La=[],Qa=[],Va=e=>{const t=Ye();if(0===La.length){const e=async e=>{const t=await Ua(e);Fn(t),La.forEach((e=>e(t.channels[0])))};Qa.push(xt(t,"onChannelUpdated","channel.updated",e)),Qa.push(xt(t,"onChannelUpdated","local.channel.updated",(e=>La.forEach((t=>t(e.channels[0]))))))}return La.push(e),()=>(e=>{const t=La.indexOf(e);t>-1&&La.splice(t,1),0===La.length&&Qa.forEach((e=>e()))})(e)},Ja=e=>{const t=nt(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{st(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Ha=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=at(n))||void 0===t?void 0:t.data)&&rt(n)},Ga=[];let za=null;const Ya=e=>{if(0===Ga.length){const e=Ye(),t=async t=>{const n=await Ua(t),a=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,s=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(a)Ja(e.channelId),Ha(e.channelId);else if(s){const t=["channelUnread","get",e.channelId],n=at(t);n&&st(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Fn(n),Ga.forEach((e=>e(n.channels[0])))};za=xt(e,"onChannelDeleted","channel.deleted",t)}return Ga.push(e),()=>(e=>{const t=Ga.indexOf(e);t>-1&&Ga.splice(t,1),0===Ga.length&&(null==za||za())})(e)},Wa=[];let Xa=null;const Za=e=>{if(0===Wa.length){const e=Ye();Xa=xt(e,"onChannelJoined","channel.joined",(async e=>{const t=await Ua(e),{channels:n,channelUsers:a}=t;Fn(t),Wa.forEach((e=>e(n[0],a[0])))}))}return Wa.push(e),()=>(e=>{const t=Wa.indexOf(e);t>-1&&Wa.splice(t,1),0===Wa.length&&(null==Xa||Xa())})(e)},es=[];let ts=null;const ns=e=>{if(0===es.length){const e=Ye(),t=async t=>{const{userId:n}=Ye(),{channelUsers:a}=t,s=a.some((e=>e.userId===n)),o=await Ua(t,{isMessagePreviewUpdated:s}),i=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,r=e.useLegacyUnreadCount;s&&o.channels.forEach((e=>{i?(Ja(e.channelId),Ha(e.channelId)):r&&rt(["channelUnread","get",e.channelId])}));const{channels:c,channelUsers:d}=o;Fn(o),es.forEach((e=>e(c[0],d[0])))};ts=xt(e,"onChannelLeft","channel.left",t)}return es.push(e),()=>(e=>{const t=es.indexOf(e);t>-1&&es.splice(t,1),0===es.length&&(null==ts||ts())})(e)},as=[];let ss=null;const os=e=>{if(0===as.length){const e=Ye(),t=async e=>{var t;it(["channel","get",e.channelId],{isMuted:Date.parse(e.muteTimeout)>Date.now()});const n=null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data;n&&as.forEach((e=>e(n)))};ss=xt(e,"onChannelMute","channel.setMuted",t)}return as.push(e),()=>(e=>{const t=as.indexOf(e);t>-1&&as.splice(t,1),0===as.length&&(null==ss||ss())})(e)},is=[];let rs=null;const cs=e=>{if(0===is.length){const e=Ye();rs=xt(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await Ua(e),{channels:n,channelUsers:a}=t;Fn(t),is.forEach((e=>e(n[0],a.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==rs||rs())})(e)},ds=[];let ls=null;const us=e=>{if(0===ds.length){const e=Ye();ls=xt(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await Ua(e),{channels:n,channelUsers:a}=t;Fn(t),ds.forEach((e=>e(n[0],a[0])))}))}return ds.push(e),()=>(e=>{const t=ds.indexOf(e);t>-1&&ds.splice(t,1),0===ds.length&&(null==ls||ls())})(e)},hs=[];let ms=null;const gs=e=>{const t=Ye();return ms=xt(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await Ua(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),Ha(e.channelId)})),Fn(n),hs.forEach((e=>e(a[0],s.find((e=>"banned"===e.membership)))))})),hs.push(e),()=>(e=>{const t=hs.indexOf(e);t>-1&&hs.splice(t,1),0===hs.length&&(null==ms||ms())})(e)},ps=[];let ys=null;const vs=e=>{if(0===ps.length){const e=Ye();ys=xt(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await Ua(e),{channels:n,channelUsers:a}=t;Fn(t),ps.forEach((e=>e(n[0],a.find((e=>"none"===e.membership)))))}))}return ps.push(e),()=>(e=>{const t=ps.indexOf(e);t>-1&&ps.splice(t,1),0===ps.length&&(null==ys||ys())})(e)},fs=[];let bs=null;const Is=e=>{if(0===fs.length){const e=Ye();bs=xt(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;fs.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return fs.push(e),()=>(e=>{const t=fs.indexOf(e);t>-1&&fs.splice(t,1),0===fs.length&&(null==bs||bs())})(e)},Cs=[];let ws=null;const Ss=e=>{if(0===Cs.length){const e=Ye();ws=xt(e,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async e=>{const{channels:t,channelUsers:n}=e;Cs.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return Cs.push(e),()=>(e=>{const t=Cs.indexOf(e);t>-1&&Cs.splice(t,1),0===Cs.length&&(null==ws||ws())})(e)},Os=e=>{const t=Ye();return xt(t,"onChannelArchived","local.channel.archived",(async t=>{e(t)}))},Ts=e=>{const t=Ye();return xt(t,"onChannelUnarchived","local.channel.unarchived",(async t=>{e(t)}))},As=[];let Rs=null;const Ps=e=>{if(0===As.length){const e=Ye(),t=async e=>{var t,n,a;e.userIds.forEach((t=>it(["channelUsers","get",`${e.channelId}#${t}`],{isMuted:Date.parse(e.muteTimeout)>Date.now()})));const s=null===(n=null===(t=nt(["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=at(["channelUsers","get",`${e.channelId}#${e.userIds[0]}`]))||void 0===a?void 0:a.data;s&&o&&As.forEach((e=>e(s,o)))};Rs=xt(e,"onChannelUserMute","channel.setMutedUsers",t)}return As.push(e),()=>(e=>{const t=As.indexOf(e);t>-1&&As.splice(t,1),0===As.length&&(null==Rs||Rs())})(e)},Ds=e=>{var t;let n=[];if(["conversation","community"].includes(e.type)){const a=nt(["channelUsers","get"]);a&&(null==a?void 0:a.length)>0&&(n=(null!==(t=null==a?void 0:a.filter((({data:t})=>t.channelId===e.channelId&&"none"!==t.membership)))&&void 0!==t?t:[]).sort(((e,t)=>e.data.userInternalId.localeCompare(t.data.userInternalId))).slice(0,4).map((({data:e})=>Na(e))))}return Xn(e,{markAsRead:()=>(async e=>{const t=Ye();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=Bn(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),r=t.cache&&Date.now(),c=Vn(s),d=Jn(o);return t.cache&&Fn(Object.assign({userMarkers:a,userEntityMarkers:c,userFeedMarkers:d},i),{cachedAt:r}),Nt("local.channelMarker.updated",{userEntityMarkers:c}),Nt("local.subChannelMarker.updated",{userFeedMarkers:d}),!0})(e.channelInternalId),previewMembers:n,myMembership:t=>((e,t)=>{const{_id:n}=Ut();if(!n)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:a,cache:s}=Ye();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?Na(e.data):e.data}))},c=(t,n)=>{const{data:a}=Ka(e);Fa(void 0,a)||r({loading:!1,data:a})};return o.push(gs(c)),o.push(vs(c)),o.push(Ps(c)),(()=>{const t=_e((async()=>Ka(e)));$e(t,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{s===be?(r({data:t,origin:a,loading:!1,error:new Ve(fe,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=at(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}})},Us=e=>Ds(xa((e=>{var t;const n=e.messagePreviewId?Hn(e.channelId):null,a=null===(t=at(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,s=n?Object.assign(Object.assign({},n),{user:a?Bt(a):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})})(e))),ks=async e=>{const t=Ye();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=>{Pe(null==t?void 0:t.code)&&_n("channel",e)})),t}const s=await Ua(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ja(a);const o=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:o}),Nt("local.channel.fetched",s.channels),{data:s.channels.map((e=>Us(e))),cachedAt:o}};ks.locally=e=>{var t,n;const a=Ye();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const s=null===(t=nt(["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=>Us(e))),cachedAt:i.cachedAt}};const js=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let Es=!1;const Ms={},qs=async()=>{const e=Object.entries(Ms).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=Ye();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=Vn(a),c=Jn(s),d=t.cache&&Date.now();return t.cache&&Fn({userEntityMarkers:r,userFeedMarkers:c,feedMarkers:o,userMarkers:i},{cachedAt:d}),Nt("local.feedMarker.fetched",{feedMarkers:o}),Nt("local.channelMarker.fetched",{userEntityMarkers:r}),Nt("local.subChannelMarker.fetched",{userFeedMarkers:c}),Nt("local.userMarker.fetched",{userMarkers:i}),!0})(e)},xs=()=>{Es=!1},Ns=()=>(Es=!0,In((e=>{"notLoggedIn"===e&&xs()})),()=>{xs()});js((async()=>{Es&&await qs()}),3e4);const Ks=async e=>{const t=Ye();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),a=await fa(n.data),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),Nt("local.message-feed.fetched",a),{data:a.messageFeeds,cachedAt:s}};Ks.locally=e=>{var t;const n=Ye();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const a=e.map((e=>at(["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 Fs=async(e=!0)=>{var t;const n=null===(t=at(["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"},_s=async()=>{var e;const t=await Fs();if(t===(null===(e=at(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;st(["MessagePreviewSetting"],t);const n=[],a=[];if("no-message-preview"===t){const e=nt(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{rt(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=nt(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(rt(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&a.push(t.subChannelId))})),0!==n.length&&await ks(n),0!==a.length&&await Ks(a)}},Bs=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},$s=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/users");return t},Ls={mode:e.AmityLiveViewerCountMode.ALWAYS_SHOW,threshold:50},Qs=async()=>{var t,n;const a=Ye(),{data:s}=await a.http.get("/api/v3/network-settings/video-streaming"),o=null===(t=null==s?void 0:s.videoStreaming)||void 0===t?void 0:t.viewerCountDisplayMode,i=null===(n=null==s?void 0:s.videoStreaming)||void 0===n?void 0:n.viewerCountDisplayMinimum;return(r=o)!==e.AmityLiveViewerCountMode.ALWAYS_SHOW&&r!==e.AmityLiveViewerCountMode.HIDE_ENTIRELY&&r!==e.AmityLiveViewerCountMode.SHOW_ABOVE_MINIMUM||!(e=>"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=1e3)(i)?(a.log("client/getLiveViewerCountConfig","malformed videoStreaming settings, falling back to default",{mode:o,threshold:i}),Ls):{mode:o,threshold:i};var r},Vs=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/product");return t},Js=async()=>{var e,t;const n=Ye(),{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}}},Hs=(e,t)=>{var n;const a=null===(n=at(["user","get",e]))||void 0===n?void 0:n.data;return!!a&&a.permissions.some((e=>e===t))},Gs=e=>{const{userId:t}=Ye();return{currentUser:()=>Hs(t,e),community:n=>((e,t,n)=>{var a;if(!e)return!1;const s=null===(a=at(["communityUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!s&&(!!s.permissions.some((e=>e===t))||Hs(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var a;if(!e)return!1;const s=null===(a=at(["channelUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!s&&(!!s.permissions.some((e=>e===t))||Hs(e,t))})(t,e,n)}},zs=async e=>{const t=Ye();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},Ys=async e=>{const t=Ye();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},Ws=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Xs={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Zs=(e,t)=>{const n=Ye();n.log("client/api/setSessionState",e,t);const{sessionState:a}=n;if(a===e)return!1;if(!((e,t)=>Xs[e].includes(t))(a,e))throw new Qe(`Session state cannot change from ${a} to ${e}`,8e5,"error");return n.sessionState=e,bn().setSessionState(e,t),!0};function eo(e){return{users:e.users.map(pa),files:e.files}}const to=async e=>{const t=Ye();Zs("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getToken",e);const a=Mn(),{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},Zs("established"),Fn(eo({users:a,files:r})),{accessToken:n,users:a,userType:i}},no=async e=>{const t=Ye();Zs("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getVisitorToken",e);const a=Mn(),{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},Zs("established"),Fn(eo({users:a,files:r})),{accessToken:n,users:a,userType:i}},ao=async()=>{var e;const t=Ye();return t.log("client/api/disconnectClient"),t.mqtt&&t.mqtt.connected&&await t.mqtt.disconnect({endSession:!0}),"established"===t.sessionState&&Zs("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.isGloballyBanned=!1,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},so=e=>{const t=Ye();Zs("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,ao()};let oo=null;const io=e=>{oo=e},ro=({user:e,userType:t})=>{kt(e),io(t)},co=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=eo(e);n.cache&&Fn(a),t(a.users[0])}))},lo=e=>co("user.deleted",e),uo=["analytic","normal-priority"],ho=["analytic","high-priority"],mo=async e=>{const t=Ye(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class go{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=at(uo);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await mo(t),rt(uo)}catch(e){this.stop(),rt(uo)}}async syncHighPriorityCapturedEvent(){try{const e=at(ho);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await mo(t),rt(ho)}catch(e){this.stop(),rt(ho)}}}class po{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=at(uo);(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),it(uo,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=at(["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=at(ho);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()}),it(ho,s),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;st(["story-seen","get",e.storyId],(new Date).toISOString());const i=at(["story-last-seen",e.targetId]);(null==i?void 0:i.data)?new Date(i.data).getTime()<new Date(e.expiresAt).getTime()&&st(["story-last-seen",e.targetId],e.expiresAt):st(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),Nt("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},rt(uo),rt(ho)}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 yo{constructor(){this._client=Ye(),this._eventCapturer=new po,this._eventSyncer=new go}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 vo;var fo=()=>(vo||(vo=new yo),vo),bo=()=>{const e=fo();return e.established(),In((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}};class Io{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ye(),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=nt(["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=at(["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=Ye();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=at(a))||void 0===t?void 0:t.data;st(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=at(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),st(a,s),Nt("local.channelUnread.updated",[s])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=at(["readReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)st(["readReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{st(["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 Co=null;var wo=()=>(Co||(Co=new Io),Co),So=()=>{const e=wo();return e.startSyncReadReceipt(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Oo{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ye(),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=nt(["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=at(["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=Ye();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=at(["legacyReadReceipt",a]))||void 0===t?void 0:t.data;st(["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=at(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=ta(s.channelId);Nt("local.channelUnreadInfo.updated",e),st(a,s),Nt("local.subChannelUnread.updated",s)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=at(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)st(["legacyReadReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{st(["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 To=null;var Ao=()=>(To||(To=new Oo),To),Ro=()=>{const e=Ao();return e.startSyncReadReceipt(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const Po=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")},Do=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")},Uo=async e=>{const t=Ye();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=>{Pe(null==t?void 0:t.code)&&_n("channel",e)})),t}const s=await Ua(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ja(a);const o=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:o}),Nt("local.channel.fetched",s.channels),{data:s.channels,cachedAt:o}};Uo.locally=e=>{var t,n;const a=Ye();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const s=null===(t=nt(["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 ko{constructor(){this.TIMER_INTERVAL_MS=Ie,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(Po((()=>{this.isConnected=!0}))),this.connectionListener.push(Do((()=>{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 Uo(e);const s=null!==(a=null===(n=null===(t=nt(["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:[];Nt("local.channel.resolved",s)})(e),t.length>0&&(async e=>{const t=await ka(e),{feedMarkers:n,userFeedMarkers:a}=t;na({feedMarkers:n,userFeedMarkers:a}),Nt("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 jo=null;var Eo=()=>(jo||(jo=new ko),jo),Mo=()=>{const e=Eo();return e.startResolver(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class qo{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(Po((()=>{this.isConnected=!0}))),this.connectionListener.push(Do((()=>{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=Bn(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=Ye();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 xo;var No=()=>(xo||(xo=new qo),xo);function Ko(e){const{users:t,follows:n}=e,a=Bn(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:pa(n)})})),users:t.map(pa)})}class Fo{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=Ye(),{data:t}=await e.http.get("/api/v4/me/user-blocks",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=Ko(t);e.cache&&Fn(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ye();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=nt(["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=at(["user","get",e.to]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(Bt)}}let _o=null;var Bo=()=>(_o||(_o=new Fo),_o);function $o(e){const{users:t,follows:n}=e,a=Bn(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:pa(n)})})),users:t.map(pa)})}class Lo{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=Ye(),{data:t}=await e.http.get("/api/v4/me/blockers",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=$o(t);e.cache&&Fn(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ye();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=nt(["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=at(["user","get",e.from]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(Bt)}}let Qo=null;var Vo=()=>(Qo||(Qo=new Lo),Qo);function Jo(e){const{users:t,follows:n}=e,a=Bn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(pa)})}function Ho(e){const{users:t,follows:n}=e,a=Bn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(pa)})}function Go(e){const{follows:t}=e,n=Bn(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const zo=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Jo(e);n.cache&&Fn(a),t(a.follows[0])}))},Yo=e=>zo("user.didBlock",e),Wo=e=>zo("user.didUnblock",e);class Xo{constructor(e,t){this.networkId=e,this.userId=t}static current(){try{const e=$t();if(!e)return null;const t=Vt(e),{userId:n}=e;return t&&n?new Xo(t,n):null}catch(e){return null}}static isExpired(e){return Date.now()>=e}static clearOnLogout(){return In((e=>{var t;"terminated"===e&&(null===(t=Xo.current())||void 0===t||t.clear())}))}get key(){return`amity:forYouFeed:cursor:${this.networkId}:${this.userId}`}async get(){const e=await Un(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 Dn(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 Dn(this.key,"")}}const Zo=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],ei=e=>{const t=Ye(),n=Zo.map((n=>xt(t,`client/onConnectionError(${n})`,n,(t=>{const a=(null==t?void 0:t.code)?new Qe(t.message,t.code,"fatal"):new He(n);e(a)}))));return()=>{n.forEach((e=>e()))}},ti=e=>{const t=Ye();return xt(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},ni=e=>{const t=Ye();return xt(t,"client/onTokenExpired","tokenExpired",e)},ai=e=>{const t=Ye();return xt(t,"client/onTokenTerminated","tokenTerminated",e)},si=e=>{const t=Ze("channelMarker")({userId:Ut()._id,entityId:e.channelId});rt(["channelMarker","get",t],!0)},oi=e=>{const t=Ye(),n=[];return n.push(ti((t=>{so("globalBan"),n.forEach((e=>e())),e()})),ai((t=>{so(),n.forEach((e=>e())),e()})),lo((a=>{a.userId===t.userId&&(so("userDeleted"),n.forEach((e=>e())),e())})),ni((e=>{bn().setSessionState(e),ao(),n.forEach((e=>e()))})),Ya(si),gs(si),Ns(),bo(),Mo(),(()=>{const e=No();return e.startReactionsSync(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=Bo();return In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=Vo();return In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=[Yo((()=>{})),Wo((()=>{}))];return()=>e.forEach((e=>e()))})(),In((e=>{"established"!==e&&An().reset()})),Xo.clearOnLogout()),t.useLegacyUnreadCount?n.push(So()):n.push(Ro()),n};let ii=[];const ri=async(e,t,n)=>{const a=Ye();let s;a.log("client/api/connectClient",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&a.userId!==e.userId&&(await ao(),ii.forEach((e=>e())),ii=[]);const o=await En();try{const{users:n,userType:i}=await to({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 Qe(`${e.userId} has not been founded`,8e5,"error");if(r.isDeleted)return so("userDeleted"),!1;if(r.isGlobalBan)return so("globalBan"),!1;a.userId=r.userId,a.sessionHandler=t,a.loginType="userId",s=a.accessTokenExpiryWatcher(),ro({user:r,userType:i})}catch(e){throw bn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await _t()}(),await _s(),0===ii.length&&(ii=oi(s)),!0},ci=[],di=async e=>{const t=Ye();let n;t.log("client/api/connectClient",Object.assign({apiKey:t.apiKey,sessionState:t.sessionState},e));const a=await En();let s;try{const{users:o,userType:i}=await no({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(),ro({user:s,userType:i})}catch(e){throw bn().setSessionState("notLoggedIn"),e}return await _s(),0===ci.length&&ci.push(ai((e=>{so(),ci.forEach((e=>e())),n()})),ni((e=>{bn().setSessionState(e),ao(),ci.forEach((e=>e()))}))),!0},li=()=>{let e,t=!1;const n=Ye();n.log("initiating access token renewal");const a=async a=>{const{userId:s,displayName:o}=Ut(),i={userId:s,displayName:o,authToken:a,deviceId:await En()};"tokenExpired"===n.sessionState&&n.sessionHandler?await ri(i,n.sessionHandler):await to({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(li())}),Ce)},renewWithAuthSignature:a=>{t?console.log("'renew' method can be called only once per renewal instance"):(async({authSignature:a,authSignatureExpiresAt:s})=>{const o=await En();"tokenExpired"===n.sessionState&&n.sessionHandler?await di({sessionHandler:n.sessionHandler}):await no({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(li())}),Ce)}}},ui=async({token:e,userId:t})=>{const n=Ye(),{data:a}=await n.http.get("/api/v4/sessions",{headers:{Authorization:`Bearer ${e.accessToken}`}}),{users:s,files:o,userType:i}=a,[r]=s;return t&&(null==r?void 0:r.userId)&&t!==r.userId&&n.log("client/api/validateAccessToken",{message:"session userId does not match the token userId; using the server value",tokenUserId:t,sessionUserId:r.userId}),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,Fn(eo({users:s,files:o})),io(i),r},hi=e=>{var t;const n=Ye(),a=A.default(e);return(null===(t=null==a?void 0:a.user)||void 0===t?void 0:t.publicUserId)===n.userId};let mi=[];const gi=async e=>{var t,n;const a=Ye();let s,o;if(a.log("client/api/loginWithAccessToken",{apiKey:a.apiKey,sessionState:a.sessionState}),!e||"string"!=typeof e||""===e.trim())throw new Qe("Access token must be a non-empty string",8e5,"error");try{o=A.default(e)}catch(e){throw new Qe("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 Qe("Access token does not contain userId",400100,"error");if(a.userId){hi(e)||await ao()}try{Zs("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 ui({token:t,userId:i});if(null==n)throw Zs("notLoggedIn"),new Qe(`User ${i} has not been found`,8e5,"error");a.userId=n.userId,a.loginType="accessToken",kt(n),s=a.accessTokenExpiryWatcher(),Zs("established")}catch(e){if(Zs("notLoggedIn"),e instanceof Qe)throw 400312===e.code&&(a.isGloballyBanned=!0),e;throw new Qe((e instanceof Error?e.message:void 0)||"Login with access token failed",400100,"error")}return async function(){await _t()}(),await _s(),0===mi.length&&(mi=oi(s)),!0},pi=async e=>{var t,n;const a=Ye();if(a.log("initiating access token renewal"),!e||"string"!=typeof e||""===e.trim())throw new Qe("Access token must be a non-empty string",8e5,"error");let s;try{s=A.default(e)}catch(e){throw new Qe("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 Qe("Access token does not contain userId",400100,"error");if(a.userId){hi(e)||await ao()}const i={accessToken:e,issuedAt:s.iat?new Date(1e3*s.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*s.exp).toISOString()};if("tokenExpired"===a.sessionState&&a.sessionHandler)await gi(e);else try{await ui({token:i,userId:o})}catch(e){throw e instanceof Qe&&400312===e.code&&(a.isGloballyBanned=!0),e}},yi=async({useScheduledTask:e=!1})=>{const t=Ye();if(t.userId&&t.accessTokenHandler&&!t.isGloballyBanned)try{const n=await t.accessTokenHandler.onTokenRenew(t.userId);e?Mt((()=>pi(n))):pi(n)}catch(e){t.log("Proactive token renewal failed, will retry when token expires",e)}},vi=3e5,fi=()=>{const e=setInterval((async()=>{const e=Ye(),{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)-vi)(o))return Nt("tokenExpired","tokenExpired"),void("accessToken"===a&&n?await yi({useScheduledTask:!1}):"userId"===a&&t&&Mt((()=>t.sessionWillRenewAccessToken(li()))));(e=>{const{expiresAt:t,issuedAt:n}=e,a=Date.parse(t),s=Date.parse(n),o=Date.now();return o>s+.8*(a-s-vi)&&o<a})({expiresAt:o,issuedAt:s})&&("accessToken"===a&&n?await yi({useScheduledTask:!1}):"userId"===a&&t&&t.sessionWillRenewAccessToken(li()))}),Ce);return()=>clearInterval(e)},bi=e=>{if(Ye().useLegacyUnreadCount){wo().markRead(e.channelId,e.channelSegment)}else{Ao().markRead(e.subChannelId,e.channelSegment)}},Ii=e=>{const t=Ye(),n=Ut(),a=[xt(t,"message/onMessageCreated","message.created",(async a=>{const s=await ha(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messages.forEach((e=>{(e=>{var t;const n=Ye(),a=["subChannelUnreadInfo","get",e.messageFeedId],s=null===(t=at(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)});st(a,c)})(e),ta(e.channelId)})),t.useLegacyUnreadCount&&a.messages.forEach((e=>{var n,a,s;const o=null===(n=at(["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});st(["channelUnread","get",e.channelId],d),Nt("local.channelUnread.updated",[d])})),Fn(s),s.messages.forEach((t=>{t.creatorPrivateId===n._id&&bi(t),e(t)}))}))];return()=>{a.forEach((e=>e()))}},Ci=e=>{const t=Ye(),n=[xt(t,"message/onMessageCreated","local.message.created",(async t=>(Fn(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},wi=e=>{const t=Ye();return xt(t,"onSubChannelCreated","message-feed.created",(async n=>{const a=await fa(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};st(["subChannelUnreadInfo","get",o.subChannelId],o)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Fn(a),e(a.messageFeeds[0])}))},Si=e=>{const t=Ye(),n=[xt(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const a=await fa(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],a=null===(t=at(n))||void 0===t?void 0:t.data;a&&st(n,Object.assign(Object.assign({},a),{isDeleted:!0}))})(e.subChannelId),ta(e.channelId)})),Fn(a),e(a.messageFeeds[0])})),xt(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Oi=async e=>{const t=Ye();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=Vn(a),c=Jn(s),d=t.cache&&Date.now();return t.cache&&Fn({userEntityMarkers:r,userFeedMarkers:c,feedMarkers:o,userMarkers:i},{cachedAt:d}),Nt("local.feedMarker.fetched",{feedMarkers:o}),Nt("local.channelMarker.fetched",{userEntityMarkers:r}),Nt("local.subChannelMarker.fetched",{userFeedMarkers:c}),Nt("local.userMarker.fetched",{userMarkers:i}),{data:n,hasMore:n.feedMarkers.length>0}};let Ti=!1,Ai=[],Ri=!1;let Pi=null;let Di=[];const Ui=e=>{Di=e},ki=async()=>{var e;if(!Ri&&0!==Di.length)try{Ri=!0,Di=[];const t=await Oi((null==Pi?new Date:Pi).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)&&(!Pi||e.getTime()>Pi.getTime())&&(Pi=e),t.hasMore&&Di.push("has_more")}catch(e){}finally{Ri&&(Ri=!1)}};js((async()=>{Ti&&await ki()}),2e3);const ji=()=>true,Ei=e=>{var t;const n=Ye();if(n.mqtt)return null===(t=n.mqtt)||void 0===t?void 0:t.listen(e)},Mi=async()=>{const e=Ye(),t=await En(),{data:{status:n,error:a}}=await e.http.delete("/v1/notification",{params:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(a)throw new Ve(a,5e5,"error");return"success"===n};let qi=[];var xi;class Ni{constructor(){xi.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,xi,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,xi,"f")}}let Ki;xi=new WeakMap;var Fi=()=>(Ki||(Ki=new Ni),Ki);const _i={[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"}},Bi=async e=>{const t=Ye();Zs("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getBotToken");const a=Mn(),{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},Zs("established"),Fn(eo({users:a,files:r})),{accessToken:n,users:a,userType:i}},$i=[];function Li(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 Qi(t){return(null==t?void 0:t.type)===e.NotificationRolesFilterTypeEnum.ONLY?{listenFromRoleIds:t.roleIds}:{listenFromRoleIds:[]}}class Vi{constructor(e){this.channelId=e}async enable(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!0};await t.http.post("/api/v3/notification/setting",n)}async disable(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!1};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){const t=Ye(),{data:n}=await t.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.CHANNEL}&channelId=${encodeURIComponent(this.channelId)}`);return{isEnabled:n.isPushNotifiable}}}class Ji{async enable(t){var n;const a=Ye(),s=null!==(n=null==t?void 0:t.map((e=>Object.assign({moduleName:e.moduleName,isPushNotifiable:e.isEnabled},Qi(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=Ye(),n={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=Ye(),{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:Li(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,modules:o}}}class Hi{constructor(e){this.communityId=e}async enable(t){var n;const a=Ye(),s=null!==(n=null==t?void 0:t.map((t=>Object.assign({moduleName:e.UserNotificationModuleNameEnum.SOCIAL,name:t.eventName,isPushNotifiable:t.isEnabled},Qi(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=Ye(),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=Ye(),{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:Li(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,events:o}}}class Gi{user(){return new Ji}community(e){return new Hi(e)}channel(e){return new Vi(e)}}const zi=e=>{const t=Ye();return xt(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},Yi=e=>{const t=Ye();return xt(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},Wi=e=>{const t=Ye();return xt(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},Xi=e=>{const t=Ye();return xt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},Zi=e=>{const t=Ye();return xt(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},er=e=>{const t=Ye();return xt(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,a,s;Fn(t);const o=nt(["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=>at(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==s?s:[]).forEach((e=>{var t,n;const a=["messageMarker","get",Ze("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],s=null===(t=at(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});st(a,e)}}))}}e(t.contentMarkers[0])}))};function tr(e){return"object"==typeof e&&null!==e}const nr=e=>{if(!tr(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)},ar=e=>{if(!tr(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var sr=Object.freeze({__proto__:null,getActiveClient:Ye,getActiveUser:Ut,setActiveUser:kt,createClient:(e,t=on.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&&!sn,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:cn("http",t),u=null!==(r=null==a?void 0:a.upload)&&void 0!==r?r:cn("upload",t),h=null!==(c=null==a?void 0:a.mqtt)&&void 0!==c?c:cn("mqtt",t),m=yn(l),g=yn(u);let p;o&&(p=Nn(h));const y=b.default(),v={version:`${me}`,apiKey:e,log:d,cache:{data:{}},http:m,ws:undefined,mqtt:p,upload:g,emitter:y,sessionState:"notLoggedIn",accessTokenExpiryWatcher:fi,sessionHandler:undefined,hasPermission:Gs,validateUrls:zs,validateTexts:Ys,getFeedSettings:Ws,getCoreUserSettings:$s,getSocialSettings:Bs,getChatSettings:Kn,getLiveViewerCountConfig:Qs,getVisitorDeviceId:En,getMessagePreviewSetting:Fs,onRTEConnectionStateChange:Ei,use:()=>We(v),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:ji,getProductCatalogueSetting:Vs,getForYouFeedSetting:Js,prefixDeviceIdKey:s};try{const t=Ye();if(t.apiKey===e)return t;We(v)}catch(e){We(v)}return v},login:ri,loginWithAccessToken:gi,logout:ao,secureLogout:async()=>{const e=Ye();try{await Mi()}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 ao()},resumeSession:async(e,t,n)=>{const a=Ye();let s;a.log("client/api/resumeSession",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&(a.userId===e.userId&&hi(e.token.accessToken)?(a.mqtt&&a.mqtt.connected&&a.mqtt.disconnect(),qi.forEach((e=>e())),qi=[]):(await ao(),qi.forEach((e=>e())),qi=[]));try{Zs("establishing");const n=await ui(e);if(null==n)throw new Qe(`${e.userId} has not been found`,8e5,"error");a.userId=n.userId,a.sessionHandler=t,s=a.accessTokenExpiryWatcher(),kt(n)}catch(e){throw bn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await _t()}(),await _s(),0===qi.length&&(qi.push(ti((e=>{so("globalBan"),qi.forEach((e=>e())),s()})),ai((e=>{so(),qi.forEach((e=>e())),s()})),lo((e=>{e.userId===a.userId&&(so("userDeleted"),qi.forEach((e=>e())),s())})),ni((e=>{bn().setSessionState(e),ao(),qi.forEach((e=>e()))})),Ya(si),gs(si),Ns(),bo(),Mo()),a.useLegacyUnreadCount?qi.push(So()):qi.push(Ro())),!0},isConnected:()=>{var e,t;const n=Ye();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:Ws,renewal:li,markerSync:Oi,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){Fi().setFileAccessType(e)},registerPushNotification:async e=>{const t=Ye();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new Ge("Unsupported platform");n=l.Platform.OS;const a=await En(),{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 Ve(o,5e5,"error");return"success"===s},unregisterPushNotification:Mi,onRTEConnectionStateChange:Ei,fetchLinkPreview:async e=>{const t=Ye();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=Ye(),{data:n}=await t.http.get(`/api/v1/link-preview?url=${e}`);return n},getSocialSettings:Bs,getShareableLinkConfiguration:async()=>{var e,t;const n=Ye(),{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}=_i[e];return!!s&&!!o[t]},getPattern(e){const{key:t}=_i[e];return o[t]||null},generateLink(e,t){const{key:n,placeholder:a}=_i[e];return s&&o[n]?s+o[n].replace(`{${a}}`,t):null}}},getProductCatalogueSetting:Vs,getForYouFeedSetting:Js,loginAsVisitor:di,loginAsBot:async e=>{const t=Ye();let n;t.log("client/api/connectClient",{apiKey:t.apiKey,sessionState:t.sessionState});const a=await En();let s;try{const{users:o,userType:i}=await Bi({params:{deviceId:a},options:{setAccessTokenCookie:!0}});[s]=o,t.userId=s.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),ro({user:s,userType:i})}catch(e){throw bn().setSessionState("notLoggedIn"),e}return await _s(),0===$i.length&&$i.push(ai((e=>{so(),$i.forEach((e=>e())),n()})),ni((e=>{bn().setSessionState(e),ao(),$i.forEach((e=>e()))}))),!0},getCurrentUser:$t,getCurrentUserType:()=>{if(!oo)throw new Qe("Connect client first",8e5,"fatal");return oo},setCurrentUserType:io,setAccessTokenHandler:e=>{const t=Ye();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,getLiveViewerCountConfig:Qs,getCoreUserSettings:$s,notifications:()=>new Gi,enableAutoSubscriptions:e=>{const t=An();e.forEach((e=>t.subscribe(e)))},disableAutoSubscriptions:e=>{const t=An();e.forEach((e=>t.unsubscribe(e)))},autoSubscriptions:()=>An().subscriptions(),onConnectionError:ei,onClientDisconnected:e=>ei((({code:t})=>{800211===t&&e()})),onClientBanned:ti,onSessionStateChange:In,onNetworkActivities:e=>hn().onNetworkActivities(e),onVisitorUsageLimitReached:e=>{const t=Ye();return xt(t,"client/onVisitorUsageLimitReached","visitorUsageLimitReached",e)},getUserUnread:e=>{const{_id:t}=Ut();if(!t)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=Ye();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?nr(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return s.push(Xi((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))};Fa(o,i)||r({loading:!1,data:i})})(e)))),(()=>{const e=_e(aa);$e(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===be?(r({data:t,origin:a,loading:!1,error:new Ve(fe,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:()=>Di,setMarkerSyncEvents:Ui,pushMarkerSyncEvent:e=>Di.push(e),markerSyncTrigger:ki,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{Ti=!1,Ui([]),Ai.forEach((e=>e())),Ai=[]},getMarkerSyncConsistentMode:ji});const or=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Jo(e);n.cache?(Fn(a),t(a.follows[0])):t(a.follows[0])}))},ir=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Go(e);n.cache?(Fn(a),t(a.follows[0])):t(a.follows[0])}))},rr=e=>or("follow.created",e),cr=e=>or("follow.unfollowed",e),dr=e=>or("follow.followerDeleted",e),lr=e=>or("follow.requested",e),ur=e=>or("follow.requestCanceled",e),hr=e=>or("follow.accepted",e),mr=e=>or("follow.requestDeclined",e),gr=async e=>{var t,n;const a=Ye();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&&st(["followInfo","get",e],i,{cachedAt:o}),{data:i,cachedAt:o}};gr.locally=e=>{const t=Ye();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=at(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const pr=e=>{const t=async t=>{const[{data:n},{data:a}]=await Promise.all([gr(t.from),gr(t.to)]);e(n),e(a)},n=[or("follow.created",t),or("follow.requested",t),or("follow.accepted",t),or("follow.unfollowed",t),or("follow.requestCanceled",t),or("follow.requestDeclined",t),or("follow.followerDeleted",t),ir("local.follow.created",t),ir("local.follow.requested",t),ir("local.follow.accepted",t),ir("local.follow.unfollowed",t),ir("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},yr=e=>ir("local.follow.created",e),vr=e=>ir("local.follow.unfollowed",e),fr=e=>ir("local.follow.requested",e),br=e=>ir("local.follow.accepted",e),Ir=e=>ir("local.follow.requestDeclined",e);class Cr{constructor(e){const{http:t}=Ye();this.queryParams=e,this.http=t}loadFirstPage(){return this.onFetch("first")}loadNextPage(){return this.onFetch("next")}loadPreviousPage(){return this.onFetch("prev")}async onFetch(e="first"){var t,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 wr extends Cr{async getRequest(e,t){const{limit:n=ge,userId:a}=e,s=Bn(e,["limit","userId"]),o=t?{token:t}:{limit:n},i=Ye().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 Sr{constructor(e,t){this.query=e,this.cacheKey=t}}var Or;!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"}(Or||(Or={}));class Tr extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.follows.map(Ze("follow"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Ze("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&a){switch(e){case Or.OnDeclined:case Or.OnCanceled:case Or.OnUnfollowed:case Or.OnDeleted:a.data=a.data.filter((e=>e!==Ze("follow")(t)));break;case Or.OnRequested:case Or.OnAccepted:case Or.OnFollowed:a.data=[...new Set([Ze("follow")(t),...a.data])]}st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ar{constructor(e){const{http:t}=Ye();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class Rr{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 Ar?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 Ar)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 Ar)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(nr).map(ar);return!Fa(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function Pr(e){return null!=e}const Dr=({userId:e})=>t=>{const n=Ye();return xt(n,"user.deleted","user.deleted",(n=>{const a=eo(n);Fn(a);const s=at(["follow","get",Ze("follow")({from:a.users[0].userId,to:e})]);s&&t(null==s?void 0:s.data)}))};class Ur extends Rr{constructor(e,t){const n=R.default(Object.assign(Object.assign({},e),{type:"follower"})),a=["follow","collection",n];super(new wr(e),n,a,t),this.query=e,this.queryStreamController=new Tr(this.query,this.cacheKey,this.notifyChange.bind(this),Jo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Or.OnFollowed},{fn:cr,action:Or.OnUnfollowed},{fn:hr,action:Or.OnAccepted},{fn:mr,action:Or.OnDeclined},{fn:ur,action:Or.OnCanceled},{fn:dr,action:Or.OnDeleted},{fn:br,action:Or.OnAccepted},{fn:Ir,action:Or.OnDeclined},{fn:yr,action:Or.OnFollowed},{fn:vr,action:Or.OnUnfollowed},{fn:Dr({userId:this.query.userId}),action:Or.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["follow","get",e]))).filter(Pr).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=at(["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 kr extends Cr{async getRequest(e,t){const{limit:n=ge,userId:a}=e,s=Bn(e,["limit","userId"]),o=t?{token:t}:{limit:n},i=Ye().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 jr extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.follows.map(Ze("follow"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Ze("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&a){switch(e){case Or.OnDeclined:case Or.OnCanceled:case Or.OnUnfollowed:case Or.OnDeleted:a.data=a.data.filter((e=>e!==Ze("follow")(t)));break;case Or.OnRequested:case Or.OnAccepted:case Or.OnFollowed:a.data=[...new Set([Ze("follow")(t),...a.data])]}st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Er=({userId:e})=>t=>{const n=Ye();return xt(n,"user.deleted","user.deleted",(n=>{const a=eo(n);Fn(a);const s=at(["follow","get",Ze("follow")({from:e,to:a.users[0].userId})]);s&&t(null==s?void 0:s.data)}))};class Mr extends Rr{constructor(e,t){const n=R.default(Object.assign(Object.assign({},e),{type:"following"})),a=["follow","collection",n];super(new kr(e),n,a,t),this.query=e,this.queryStreamController=new jr(this.query,this.cacheKey,this.notifyChange.bind(this),Ho),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:lr,action:Or.OnRequested},{fn:hr,action:Or.OnAccepted},{fn:mr,action:Or.OnDeclined},{fn:ur,action:Or.OnCanceled},{fn:rr,action:Or.OnFollowed},{fn:cr,action:Or.OnUnfollowed},{fn:dr,action:Or.OnDeleted},{fn:fr,action:Or.OnRequested},{fn:br,action:Or.OnAccepted},{fn:Ir,action:Or.OnDeclined},{fn:yr,action:Or.OnFollowed},{fn:vr,action:Or.OnUnfollowed},{fn:Er({userId:this.query.userId}),action:Or.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["follow","get",e]))).filter(Pr).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=at(["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 qr=(e,t,n,a,s,o)=>{const{forceDispatch:i,callbackDataSelector:r,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},o),{cache:d}=Ye();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=Bn(e,["data"]);c&&!c(n,l)||t(Object.assign({data:r(n)},a)),l=nr(n)};return h.push(...s.map((t=>t((t=>((t,a=!1)=>{e===t[n]&&(l&&!a&&Fa(l,t)||m({loading:!1,data:t,origin:"event"}))})(t,i)))))),(()=>{const t=_e(a,e,!0);$e(t,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{s===be?(m({data:t,origin:a,loading:!1,error:new Ve(fe,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 xr=Object.freeze({__proto__:null,blockUser:async e=>{const t=Ye();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&&(Fn(i,{cachedAt:a}),it(["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=Go(r);return Nt("local.follow.unfollowed",c),n},unBlockUser:async e=>{const t=Ye();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&&(Fn(i,{cachedAt:a}),it(["followInfo","get",e],o[0],{cachedAt:a}));const r=Go(i);return Nt("local.follow.created",r),n},onUserDidBlock:Yo,onUserDidUnblock:Wo,follow:async e=>{const t=Ye();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const s=Go(n);return"accepted"===n.follows[0].status?Nt("local.follow.created",s):Nt("local.follow.requested",s),{data:n.follows[0],cachedAt:a}},unfollow:async e=>{const t=Ye();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Fn(n);const a=Go(n);return Nt("local.follow.unfollowed",a),!0},acceptMyFollower:async e=>{const t=Ye();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Fn(n);const a=Go(n);return Nt("local.follow.accepted",a),!0},declineMyFollower:async e=>{const t=Ye();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Fn(n);const a=Go(n);return Nt("local.follow.requestDeclined",a),!0},onUserFollowed:rr,onUserUnfollowed:cr,onFollowerDeleted:dr,onFollowerRequested:lr,onFollowRequestCanceled:ur,onFollowRequestAccepted:hr,onFollowRequestDeclined:mr,onFollowInfoUpdated:pr,onLocalUserFollowed:yr,onLocalUserUnfollowed:vr,onLocalFollowerRequested:fr,onLocalFollowRequestAccepted:br,onLocalFollowRequestDeclined:Ir,getFollowers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getFollowers(tmpid: ${o}) > listen`);const i=new Ur(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getFollowers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:a,cache:s}=Ye();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 Mr(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getFollowings(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getFollowInfo:(e,t)=>qr(e,t,"userId",gr,[pr],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=Ut();return qr(t,e,"userId",gr,[pr],{forceDispatch:!0})}});function Nr(e,t){return e.map((e=>{const n=at(["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}=Ut();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:a})}))}const Kr=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:N};function Fr({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,a=Bn(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:Kr({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},a)}))}const _r=e=>{const t=Fr({communities:e.communities}),n=e.users.map(pa),a=e.communityUsers.map((e=>{const t=n.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),s=Nr(t,a);return Object.assign(Object.assign({},e),{users:e.users.map(pa),communities:s,communityUsers:a})},Br=e=>{const t=e.joinRequests.map((e=>Object.assign(Object.assign({},e),{joinRequestId:e._id}))),n=e.users.map(pa);return Object.assign(Object.assign({},e),{joinRequests:t,users:n})},$r=e=>{const t=Fr({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=Nr(t,n);return Object.assign(Object.assign({},e),{communities:a,communityUsers:n})},Lr=e=>{const{postSetting:t,storySetting:n}=e,a=Bn(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})},Qr=e=>{var t=Bn(e,["searchResult"]);const n=_r(t);return Object.assign({},n)},Vr=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=at(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return Bt(n)},cancel:async()=>{await(async e=>{var t;const n=Ye();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:a}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),s=null===(t=at(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(it(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),Nt("local.joinRequest.deleted",[s])),a.success})(e)},approve:async()=>{await(async e=>{var t;const n=Ye();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=at(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(it(["joinRequest","get",e.joinRequestId],{status:"approved"}),Nt("local.joinRequest.updated",[s])),a.success})(e)},reject:async()=>{await(async e=>{var t;const n=Ye();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=at(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(it(["joinRequest","get",e.joinRequestId],{status:"rejected"}),Nt("local.joinRequest.updated",[s])),a.success})(e)}});class Jr extends Cr{async getRequest(e,t){const{limit:n=20,communityId:a}=e,s=Bn(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 Hr;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Hr||(Hr={}));class Gr extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.joinRequests.map((e=>Ze("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Ze("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Hr.OnLocalJoinRequestUpdated){if(!a.data.find((e=>e===t[0].joinRequestId)))return}e===Hr.OnLocalJoinRequestCreated&&(a.data=[...new Set([...t.map((e=>e.joinRequestId)),...a.data])]),e===Hr.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>e!==t[0].joinRequestId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const zr=e=>{const t=Ye(),n=[xt(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Yr=e=>{const t=Ye(),n=[xt(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Wr=e=>{const t=Ye(),n=[xt(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Xr extends Rr{constructor(e,t){const n=R.default(e),a=["joinRequest","collection",n];super(new Jr(e),n,a,t),this.query=e,this.queryStreamController=new Gr(this.query,this.cacheKey,this.notifyChange.bind(this),Br),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:zr,action:Hr.OnLocalJoinRequestCreated},{fn:Yr,action:Hr.OnLocalJoinRequestUpdated},{fn:Wr,action:Hr.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(s.data.map((e=>at(["joinRequest","get",e]))).filter(Pr).map((({data:e})=>e)).map(Vr));(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?Ct:St)();return t=t.sort(n),t}}const Zr=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),ec=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map(Zr),users:e.users.map(pa)}),tc=async e=>{const t=Ye();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),a=ec(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),Nt("local.invitation.created",a.invitations),{data:a.invitations,cachedAt:s}},nc=e=>Object.assign(Object.assign({},e),{users:e.users.map(pa),invitations:e.invitations.map(Zr)}),ac=e=>Object.assign(Object.assign({},e),{get user(){const t=at(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return Bt(t.data)},get createdBy(){const t=at(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return Bt(t.data)},get target(){if("community"===e.targetType){const t=at(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=Ye();n.log("invitation/acceptInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/accept`),s=null===(t=at(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(it(["invitation","get",e],{status:"approved"}),Nt("local.invitation.updated",[s])),a.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=Ye();n.log("invitation/rejectInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/reject`),s=null===(t=at(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(it(["invitation","get",e],{status:"rejected"}),Nt("local.invitation.updated",[s])),a.success})(e._id)}}),sc=async e=>{const t=Ye();t.log("invitation/getInvitation",e.targetType,e.targetId,e.type);const{data:n}=await t.http.get("/api/v1/invitations/me",{params:e}),a=nc(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.invitations[0]?ac(a.invitations[0]):void 0,cachedAt:s}};var oc;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationCanceled="onLocalInvitationCanceled"}(oc||(oc={}));class ic extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 rc extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.invitations.map(Ze("invitation"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Ze("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===oc.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}e===oc.OnLocalInvitationCreated&&(a.data=[...new Set([...t.map((e=>e.invitationId)),...a.data])]),e===oc.OnLocalInvitationDeleted&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const cc=e=>{const t=Ye(),n=[xt(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},dc=e=>{const t=Ye(),n=[xt(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},lc=e=>{const t=Ye(),n=[xt(t,"onLocalInvitationCanceled","local.invitation.canceled",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class uc extends Rr{constructor(e,t){const n=R.default(e),a=["invitation","collection",n];super(new ic(e),n,a,t),this.query=e,this.queryStreamController=new rc(this.query,this.cacheKey,this.notifyChange.bind(this),ec),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:cc,action:oc.OnLocalInvitationCreated},{fn:dc,action:oc.OnLocalInvitationUpdated},{fn:lc,action:oc.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["invitation","get",e]))).filter(Pr).map((({data:e})=>ac(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?Ct:St)();return t=t.sort(n),t}}const hc=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=at(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),mc=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=at(["category","get",e]);if(null==t?void 0:t.data)return hc(t.data)})).filter((e=>!!e))},get avatar(){var t;if(!e.avatarFileId)return;return null===(t=at(["file","get",e.avatarFileId]))||void 0===t?void 0:t.data},createInvitations:async t=>{await tc({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getInvitations: (tmpid: ${o}) > listen`);const i=new uc(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(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 sc({targetType:"community",targetId:e.communityId});return t},join:async()=>(async e=>{var t;const n=Ye();n.log("community/joinRequest",e);const{data:a}=await n.http.post(`/api/v4/communities/${e}/join`),s=Br(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const i="approved"===s.joinRequests[0].status?"success":"pending";if("success"===i&&n.cache){const n=null===(t=at(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});it(["community","get",e],t)}}return Nt("v4.local.community.joined",s.joinRequests),"success"===i?{status:i}:{status:i,request:Vr(s.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getJoinRequests: (tmpid: ${o}) > listen`);const i=new Xr(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(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=Ye();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),a=Br(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.joinRequests[0]?Vr(a.joinRequests[0]):void 0,cachedAt:s}})(e.communityId);return t}});class gc{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=at(["story-expire",this._targetId]),this.cacheStoreSeenTime=at(["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=at(["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 at(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=nt(["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 pc=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:a,lastStorySeenExpiresAt:s,targetUpdatedAt:o,localFilter:i}=e,r=new gc(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()}},yc=async e=>{const t=Ye();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=Bn(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 Ua(n.data),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{channels:o}=a;return{data:Us(o[0]),cachedAt:s}},vc=async e=>{const t=Ye();let n;t.log("channel/getChannel",e),ea("channel",e);try{const{data:a}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await Ua(a),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&ja(a)}catch(t){throw Pe(null==t?void 0:t.code)&&_n("channel",e),t}const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{channels:s}=n;return{data:s.find((t=>t.channelId===e)),cachedAt:a}};vc.locally=e=>{var t;const n=Ye();if(n.log("channel/getChannel.locally",e),!n.cache)return;const a=null===(t=nt(["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 fc=Symbol("getWatcherUrls"),bc=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=at(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=at(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=at(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=at(["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=at(["stream","get",e]))||void 0===t?void 0:t.data;if(n)return bc(n)})).filter(Pr):[]},getLiveChat:()=>(async e=>{var t;const n=Ye();if(n.log("stream/getLiveChat",e.streamId),e.channelId){const n=null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data;if(n)return Ds(Us(n));const{data:a}=await vc(e.channelId);return Ds(Us(a))}if(e.userId===n.userId){const{data:t}=await yc({type:"live",postId:e.postId,videoStreamId:e.streamId});return ot(["stream","get",e.streamId],{channelId:t.channelId}),t}})(e),isBanned:!e.watcherUrl,watcherUrl:null,get[fc](){return e.watcherUrl}}),Ic=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=at(["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=at(["user","get",e.userId]);if(null==t?void 0:t.data)return Bt(t.data)},get childrenComment(){return e.children.map((e=>{const t=at(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(Pr).map((e=>Ic(e)))}});function Cc(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}function wc(e){return!(!e.data||"string"==typeof e.data||!("streamId"in e.data)||"liveStream"!==e.dataType)}class Sc{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 Oc=null;const Tc=()=>(Oc||(Oc=new Sc),Oc),Ac={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},Rc="-----BEGIN PRIVATE KEY-----";function Pc(e){const n=new Uint8Array(e);let a="";return n.forEach((e=>{a+=String.fromCharCode(e)})),t.btoa(a)}function Dc(e){return e<128?new Uint8Array([e]):e<256?new Uint8Array([129,e]):new Uint8Array([130,e>>8&255,255&e])}async function Uc(e){let n=e;n=e.includes(Rc)?e.substring(Rc.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=Dc(e.length),s=n.length+t.length+1+a.length+e.length,o=Dc(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,Ac,!1,["sign"])}async function kc({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}×tamp=${e}&data=${n}==`,o=(new TextEncoder).encode(s),i=await Uc("-----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:Pc(await crypto.subtle.sign(Ac,i,o)),nonceStr:a}}async function jc(){const e=Tc(),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 kc({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=Ye();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 Ec=["live","recorded"];class Mc{constructor(e){this.storage=Tc(),this.client=Ye(),this.room=e}async createWatchSession(e){if(!Ec.includes(this.room.status))throw new Ve("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 jc(),this.client.log("room/RoomAnalytics: syncWatchSessions completed")}catch(e){console.error("Failed to sync watch sessions:",e)}}),e)}}const qc=e=>Object.assign(Object.assign({},e),{get post(){var t;if("post"===e.referenceType)return null===(t=at(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=at(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;const n=null===(t=at(["user","get",e.createdBy]))||void 0===t?void 0:t.data;return n?Bt(n):n},get childRooms(){return e.childRoomIds&&0!==e.childRoomIds.length?e.childRoomIds.map((e=>{var t;const n=null===(t=at(["room","get",e]))||void 0===t?void 0:t.data;if(n)return qc(n)})).filter(Pr):[]},participants:e.participants.map((e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=at(["user","get",e.userId]))||void 0===t?void 0:t.data;return n?Bt(n):n}}))),getLiveChat:()=>(async e=>{var t;const n=Ye();if(n.log("room/getLiveChat",e.roomId),e.liveChannelId){const n=null===(t=at(["channel","get",e.liveChannelId]))||void 0===t?void 0:t.data;if(n)return Ds(Us(n));const{data:a}=await vc(e.liveChannelId);return Ds(Us(a))}if(e.createdBy===n.userId){const{data:t}=await yc({type:"live",postId:e.referenceId,roomId:e.roomId});return ot(["room","get",e.roomId],{liveChannelId:t.channelId}),t}})(e),createInvitation:t=>tc({type:"livestreamCohostInvite",targetType:"room",targetId:e.roomId,userIds:[t]}),getInvitations:async()=>{const{data:t}=await sc({targetId:e.roomId,targetType:"room",type:"livestreamCohostInvite"});return t},analytics(){return new Mc(this)}}),xc=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=at(["file","get",e.fileId]))||void 0===t?void 0:t.data}})))}),Nc=e=>{const t=fo();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)}}})},Kc=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},Fc=e=>Xn(e,{childrenPosts:e.children.map((e=>{var t;return null===(t=at(["post","get",e]))||void 0===t?void 0:t.data})).filter(Pr).map(Fc),analytics:{markAsViewed:()=>{fo().markPostAsViewed(e.postId)},markAsMeaningfullyViewed:t=>{fo().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=at(["product","get",e.productId]))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{product:n?Nc(n):void 0})})(e))))&&void 0!==n?n:[]},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=at(["comment","get",e]))||void 0===t?void 0:t.data;return n?Ic(n):null})).filter(Boolean)||[]},get creator(){if(!e.postedUserId)return;const t=at(["user","get",e.postedUserId]);return(null==t?void 0:t.data)?Bt(t.data):void 0},get targetCommunity(){var t;if(!e.targetId)return;const n=null===(t=at(["community","get",e.targetId]))||void 0===t?void 0:t.data;return n?mc(n):void 0},getImageInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return Kc(null===(n=at(["file","get",e.data.fileId]))||void 0===n?void 0:n.data)},getVideoInfo(){var t,n,a;const s=Cc(e)?null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original:void 0;if(s)return Kc(null===(a=at(["file","get",s]))||void 0===a?void 0:a.data)},getVideoThumbnailInfo(){var t,n;const a=Cc(e)?null===(t=e.data)||void 0===t?void 0:t.thumbnailFileId:void 0;if(a)return Kc(null===(n=at(["file","get",a]))||void 0===n?void 0:n.data)},getFileInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"file"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=at(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getLivestreamInfo(){var t,n;if(!wc(e)||!(null===(t=e.data)||void 0===t?void 0:t.streamId))return;const a=null===(n=at(["stream","get",e.data.streamId]))||void 0===n?void 0:n.data;return a?bc(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)||!(null===(t=e.data)||void 0===t?void 0:t.pollId))return;const a=null===(n=at(["poll","get",e.data.pollId]))||void 0===n?void 0:n.data;return a?xc(a):void 0},getClipInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"clip"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=at(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getAudioInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"audio"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=at(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getRoomInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("roomId"in e.data)||"room"!==e.dataType)}(e)||!(null===(t=e.data)||void 0===t?void 0:t.roomId))return;const a=null===(n=at(["room","get",e.data.roomId]))||void 0===n?void 0:n.data;return a?qc(a):void 0},getEventInfo(){var t,n;if(!function(e){return"event"===e.dataType||"event"===e.structureType}(e))return;const a=e=>{if(e&&"object"==typeof e&&"eventId"in e){const t=e.eventId;return"string"==typeof t?t:void 0}},s=a(e.data),o=null!=s?s:null===(t=e.children)||void 0===t?void 0:t.map((e=>{var t;return null===(t=at(["post","get",e]))||void 0===t?void 0:t.data})).map((e=>a(null==e?void 0:e.data))).find(Boolean);if(!o)return;const i=null===(n=at(["event","get",o]))||void 0===n?void 0:n.data;return i?Object.assign(Object.assign({},i),{get creator(){const e=at(["user","get",i.userId]);if(null==e?void 0:e.data)return Bt(e.data)},get targetCommunity(){var e;if(!i.originId)return;const t=null===(e=at(["community","get",i.originId]))||void 0===e?void 0:e.data;return t?mc(t):void 0},get coverImage(){var e;if(i.coverImageFileId)return null===(e=at(["file","get",i.coverImageFileId]))||void 0===e?void 0:e.data}}):void 0}}),_c=(e,t)=>{"message"===e?Nt("local.message.updated",{messages:[t]}):"post"===e?Nt("post.updated",{posts:[t]}):"comment"===e?Nt("comment.updated",{comments:[t]}):"story"===e&&Nt("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Bc=async(e,t,n,a)=>{var s,o,i;const r=Ye();if(r.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ve("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=at([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 Nt("local.comment.addReaction",{comment:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("post"===e)return Nt("local.post.addReaction",{post:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("story"===e)return Nt("local.story.reactionAdded",{story:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("message"===e)return it(["message","get",t],d),Nt("local.message.updated",{messages:[d]}),!0}return!0};Bc.optimistically=(e,t,n)=>{var a,s,o,i,r;const c=Ye();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const d=at([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 it([e,"get",t],l,{cachedAt:be}),_c(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 $c=(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=at(["messageMarker","get",Ze("messageMarker")(a)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},Lc=(e,t)=>{const n=t.publicId!==t.messageId;return(async(e,t,n,a)=>{var s,o;const i=Ye();if(i.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ve("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=at([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 Nt("local.comment.removeReaction",{comment:c,reactor:{reactionId:r.removedId,reactionName:n,userId:i.userId}}),!0;if("post"===e)return Nt("local.post.removeReaction",{post:c,reactor:{reactionId:r.removedId,reactionName:n,userId:i.userId}}),!0;if("story"===e)return Nt("local.story.reactionRemoved",{story:c,reactor:{userId:i.userId,reactionName:n,reactionId:r.removedId}}),!0;if("message"===e)return it(["message","get",t],c),Nt("local.message.updated",{messages:[c]}),!0}return!0})("message",n?t.publicId:t.messageId,e,n?3:5)},Qc=e=>Object.assign(Object.assign({},e),{users:e.users.map(pa)}),Vc=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=at(["event","get",e.eventId]);if(null==t?void 0:t.data)return t.data},get user(){const t=at(["user","get",e.userId]);if(null==t?void 0:t.data)return Bt(t.data)}}),Jc=e=>Object.assign(Object.assign({},e),{users:e.users.map(pa)}),Hc=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Jc(e);if(n.cache){Fn(a);const e=at(["event","get",a.events[0].eventId]);t(e.data)}else t(a.events[0])}))},Gc=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Qc(e);if(n.cache){Fn(a);const e=at(["eventResponse","get",a.eventResponses[0].userId]);t(e.data)}else t(a.eventResponses[0])}))},zc=async e=>{const t=Ye();t.log("event/getMyRSVP",e);const{data:n}=await t.http.get(`/api/v1/events/${e}/me/rsvp`),a=Qc(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:Vc(a.eventResponses[0]),cachedAt:s}};var Yc;zc.locally=e=>{const t=Ye();if(t.log("event/getMyRSVP.locally",e),!t.cache)return;const n=at(["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"}(Yc||(Yc={}));class Wc extends Cr{async getRequest(e,t){const{limit:n=ge,eventId:a}=e,s=Bn(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 Xc extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.eventResponses.map(Ze("eventResponse"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.eventResponses.map(Ze("eventResponse"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Yc.OnRSVPCreated&&(a.data=[...new Set([t.userId,...a.data])]),e===Yc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Zc=e=>Hc("event.created",e),ed=e=>Hc("event.updated",e),td=e=>Hc("event.deleted",e),nd=e=>Hc("local.event.created",e),ad=e=>Hc("local.event.updated",e),sd=e=>Hc("local.event.deleted",e),od=e=>Gc("event.rsvp.created",e),id=e=>Gc("event.rsvp.updated",e),rd=e=>Gc("local.rsvp.created",e),cd=e=>Gc("local.rsvp.updated",e);class dd extends Rr{constructor(e,t){const n=R.default(e),a=["eventResponse","collection",n];super(new Wc(e),n,a,t),this.query=e,this.queryStreamController=new Xc(this.query,this.cacheKey,this.notifyChange.bind(this),Qc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:od,action:Yc.OnRSVPCreated},{fn:id,action:Yc.OnRSVPUpdated},{fn:rd,action:Yc.OnRSVPCreated},{fn:cd,action:Yc.OnRSVPUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=s.data.map((e=>at(["eventResponse","get",e]))).filter(Pr).map((({data:e})=>Vc(e)));(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}const ld=(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getRSVPs: (tmpid: ${o}) > listen`);const i=new dd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getRSVPs (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},ud=e=>Object.assign(Object.assign({},e),{get creator(){const t=at(["user","get",e.userId]);if(null==t?void 0:t.data)return Bt(t.data)},get targetCommunity(){if(!e.originId)return;const t=at(["community","get",e.originId]);return(null==t?void 0:t.data)?mc(t.data):void 0},get coverImage(){if(!e.coverImageFileId)return;const t=at(["file","get",e.coverImageFileId]);return(null==t?void 0:t.data)?t.data:void 0},get post(){if(!e.postId)return;const t=at(["post","get",e.postId]);return(null==t?void 0:t.data)?Fc(t.data):void 0},get room(){var t;if(!e.postId)return;const n=null===(t=nt(["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?qc(n[0].data):void 0},createRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ye();n.log("event/createRSVP",e,t);const{data:a}=await n.http.post(`/api/v1/events/${e}/rsvp`,{status:t});Nt("local.rsvp.created",a);const s=Qc(a),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),{data:Vc(s.eventResponses[0]),cachedAt:o}})(e.eventId,t);return n},updateRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ye();n.log("event/updateRSVP",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}/rsvp`,{status:t});Nt("local.rsvp.updated",a);const s=Qc(a),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),{data:Vc(s.eventResponses[0]),cachedAt:o}})(e.eventId,t);return n},getMyRSVP:async()=>{const{data:t}=await zc(e.eventId);return t},getRSVPs:(t,n)=>ld(Object.assign({eventId:e.eventId},t),n)}),hd={file:Kc,ad:e=>{const t=fo(),{image9_16:n,image1_1:a}=e,s=Bn(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=at(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!a)return;const s=null===(n=at(["file","get",a.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},a),{avatar:s})},get image1_1(){const e=at(["file","get",a]);if(e)return e.data||void 0},get image9_16(){const e=at(["file","get",n]);if(e)return e.data||void 0}})},comment:Ic,post:Fc,user:Bt,category:hc,stream:bc,story:e=>{const t=fo(),n=at(["storyTarget","get",e.targetId]),a=at(["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=at(["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=at(["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 mc(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=at(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=at(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return Bt(t.data)},get storyTarget(){if(null==n?void 0:n.data)return pc(n.data)},get isSeen(){const t=at(["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:pc,message:e=>{const t=Bn(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return $c(e).readCount},get deliveredCount(){return $c(e).deliveredCount},get creator(){var t;return null===(t=at(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>bi(e),addReaction:t=>((e,t)=>{const n=t.publicId!==t.messageId;return Bc("message",n?t.publicId:t.messageId,e,n?3:5)})(t,e),removeReaction:t=>Lc(t,e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=at(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return Bt(n)}}),channel:Ds,pinnedPost:e=>{var t;const n=at(["post","get",e.referenceId]),a=null===(t=nt(["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 Fc(n.data)},get target(){const e=at(["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})=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map((e=>Bt(e))),get event(){const t=at(["event","get",e.actionReferenceId]);if(null==t?void 0:t.data)return t.data}}),community:mc,invitation:ac,joinRequest:Vr,channelMember:Na,room:qc,event:ud,eventResponse:Vc,product:Nc,poll:xc},md=async e=>{const t=Ye();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=eo(a),o=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:o}),Nt("user.fetched",a),{data:s.users.map((e=>hd.user(e))),cachedAt:o}};md.locally=e=>{var t;const n=Ye();if(n.log("user/getUsers.locally",e),!n.cache)return;const a=e.map((e=>at(["user","get",e]))).filter(Boolean),s=a.map((({data:e})=>hd.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 gd=async(e,t)=>{var n;const a=Ye();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=eo(o);return a.cache&&Fn(i),Nt("user.flagged",o),null!==(n=i.users.find((t=>t.userId===e)))&&void 0!==n?n:i.users[0]},pd=e=>co("user.updated",e),yd=e=>co("user.flagged",e),vd=e=>co("user.unflagged",e),fd=e=>co("user.flagCleared",e),bd=e=>co("user.fetched",e),Id=async e=>{const t=Ye();t.log("user/getUser",e),ea("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),a=t.cache&&Date.now(),s=eo(n);return t.cache&&Fn(s,{cachedAt:a}),Nt("user.fetched",n),{data:s.users.find((t=>t.userId===e)),cachedAt:a}}catch(t){throw Pe(null==t?void 0:t.code)&&_n("user",e),t}};Id.locally=e=>{const t=Ye();if(t.log("user/getUser.locally",e),!t.cache)return;const n=at(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Cd extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 wd extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.users.map(Ze("user"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ze("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Sd;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(Sd||(Sd={}));class Od extends Rr{constructor(e,t){const n=R.default(e),a=["user","collection",n];super(new Cd(e),n,a,t),this.query=e,this.queryStreamController=new wd(this.query,this.cacheKey,this.notifyChange.bind(this),eo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:lo,action:Sd.OnUserDeleted},{fn:pd,action:Sd.OnUserUpdated},{fn:yd,action:Sd.OnUserFlagged},{fn:vd,action:Sd.OnUserUnflagged},{fn:fd,action:Sd.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.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?Ct:St)();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 Td extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 Ad;!function(e){e.OnBlocked="onBlocked",e.OnUnblocked="onUnblocked"}(Ad||(Ad={}));class Rd extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.users.map(Ze("user"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ze("user"))])]}))}}reactor(e){return t=>{var n,a;const s=e===Or.OnFollowed||e===Ad.OnUnblocked,o=e===Ad.OnBlocked;if(s||o){const e=null===(n=at(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));st(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 Pd=(e,t,n)=>a=>e((e=>{var s;if(!e)return e;const o=[n,"get",`${e[t]}`],i=null===(s=at(o))||void 0===s?void 0:s.data;return i?a(i):void 0}));class Dd extends Rr{constructor(e,t){const n=R.default(e),a=["blockedUsers","collection",n];super(new Td(e),n,a,t),this.query=e,this.queryStreamController=new Rd(this.query,this.cacheKey,this.notifyChange.bind(this),Ko),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:lo,action:Sd.OnUserDeleted},{fn:Pd(yr,"to","user"),action:Or.OnFollowed},{fn:Pd(rr,"to","user"),action:Or.OnFollowed},{fn:e=>Yo((t=>{var n;if(t.from!==Ye().userId)return;const a=null===(n=at(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:Ad.OnBlocked},{fn:e=>Wo((t=>{var n;if(t.from!==Ye().userId)return;const a=null===(n=at(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:Ad.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.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 Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.users.map(Ze("user"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ze("user"))])]}))}}reactor(e){return t=>{var n,a;if(t&&(e===Ad.OnBlocked||e===Ad.OnUnblocked)){const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[],i=e===Ad.OnBlocked?[...new Set([...o,t.userId])]:o.filter((e=>e!==t.userId));st(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 kd extends Cr{async getRequest(e,t){const{limit:n=pe}=e,a=Bn(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 jd extends Rr{constructor(e){const t=`blocking-users-${Ye().userId}`,n={},a=["blockingUsers","collection",t];super(new kd(n),t,a,e),this.queryStreamController=new Ud(n,this.cacheKey,this.notifyChange.bind(this),$o),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:lo,action:Sd.OnUserDeleted},{fn:e=>Yo((t=>{var n;if(t.to!==Ye().userId)return;const a=null===(n=at(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:Ad.OnBlocked},{fn:e=>Wo((t=>{var n;if(t.to!==Ye().userId)return;const a=null===(n=at(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:Ad.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.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 Ed extends Cr{async getRequest(e,t){const{limit:n=ge,displayName:a}=e,s=Bn(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 Md extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.users.map(Ze("user"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ze("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class qd extends Rr{constructor(e,t){var n;const a=R.default(e),s=["user","collection",a];super(new Ed(e),a,s,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new Md(this.query,this.cacheKey,this.notifyChange.bind(this),eo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:lo,action:Sd.OnUserDeleted},{fn:pd,action:Sd.OnUserUpdated},{fn:yd,action:Sd.OnUserFlagged},{fn:vd,action:Sd.OnUserUnflagged},{fn:fd,action:Sd.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.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 xd=async({viewId:e,viewedType:t,limit:n,token:a})=>{const s=Ye(),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 Fn(r.data),r.data};var Nd;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(Nd||(Nd={}));var Kd=Object.freeze({__proto__:null,Relationship:xr,getUserByIds:md,updateUser:async(e,t)=>{const n=Ye();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=eo(a),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),Nt("user.updated",a),{data:s.users.find((t=>t.userId===e)),cachedAt:o}},flagUser:gd,unflagUser:async e=>{const t=Ye();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),a=eo(n);return t.cache&&Fn(a),Nt("user.unflagged",n),!!a},isUserFlaggedByMe:async e=>{const t=Ye();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},getAllBlockedUsers:async()=>{Ye().log("user/getAllBlockedUsers");const e=Bo();return await e.ensureFetched(),e.getCachedUsers()},getAllBlockingUsers:async()=>{Ye().log("user/getAllBlockingUsers");const e=Vo();return await e.ensureFetched(),e.getCachedUsers()},onUserUpdated:pd,onUserDeleted:lo,onUserFlagged:yd,onUserUnflagged:vd,onUserFlagCleared:fd,getUser:(e,t)=>qr(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?hd.user(e.data):e.data}))),"userId",Id,[bd,pd,lo,yd,vd,fd]),getUsers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`liveUsers(tmpid: ${o}) > listen`);const i=new Od(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`liveUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getBlockedUsers(tmpid: ${o}) > listen`);const i=new Dd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getBlockedUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e())),rt(c)}},getBlockingUsers:e=>{const{log:t,cache:n}=Ye();n||console.log(ve);const a=Date.now();t(`getBlockingUsers(tmpid: ${a}) > listen`);const s=new jd(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>rt(i))),()=>{t(`getBlockingUsers(tmpid: ${a}) > dispose`),o.forEach((e=>e())),rt(i)}},searchUsers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`liveSearchUsers(tmpid: ${o}) > listen`);const i=new qd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`liveSearchUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchUserByDisplayName:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`liveSearchUsers(tmpid: ${o}) > listen`);const i=new qd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`liveSearchUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:a,cache:s}=Ye(),o=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(ve);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=at(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=_e(xd,{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});$e(h,(e=>{var a,s,i,r,c;let d=null!==(i=null===(s=null===(a=at(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||[]};st(o,l),(e=>{var a,s;let o=[];(null==e?void 0:e.data)&&(o=e.data.map((e=>at(["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)}),Be(ye,2e3))},n(!0),()=>{a(`getReachUsers(tmpid: ${i}) > dispose`),rt(o)}},get AmityUserSearchMatchType(){return Nd}});const Fd=async e=>{const t=Ye();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),a=t.cache&&Date.now();return t.cache&&Fn({files:[n]},{cachedAt:a}),{data:Kc(n),cachedAt:a}};Fd.locally=e=>{const t=Ye();if(t.log("file/getFile.locally",e),!t.cache)return;const n=at(["file","get",e]);return n?{data:Kc(n.data),cachedAt:n.cachedAt}:void 0};const _d=async(e,t,n)=>{const a=Ye();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=Fi().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&&Fn({files:r},{cachedAt:c}),{data:r.map((e=>Kc(e))),cachedAt:c}},Bd=async(e,t,n)=>{const a=Ye();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=Fi().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&&Fn({files:r},{cachedAt:c}),{data:r.map((e=>Kc(e))),cachedAt:c}};var $d=Object.freeze({__proto__:null,getFile:Fd,uploadFile:async(e,t)=>{const n=Ye();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=Fi().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&&Fn({files:i},{cachedAt:r}),{data:i,cachedAt:r}},deleteFile:async e=>{const t=Ye();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),rt(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:_d,uploadImage:Bd,updateAltText:async(e,t)=>{const n=Ye();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&&Fn({files:[a]},{cachedAt:s}),!0},uploadClip:async(e,t,n)=>{const a=Ye();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=Fi().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&&Fn({files:r},{cachedAt:c}),{data:r,cachedAt:c}},uploadAudio:async(e,t)=>{const n=Ye();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=Fi().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&&Fn({files:i},{cachedAt:r}),{data:i,cachedAt:r}}});const Ld=async e=>{const t=Ye();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:a=10,queryToken:s,displayName:o,sortBy:i}=n,r=Bn(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=Bn(d,["paging"]),{roles:h}=u,m=t.cache&&Date.now();t.cache&&Fn(u,{cachedAt:m});const g=Me(l.next);return{data:h,cachedAt:m,prevPage:Me(l.previous),nextPage:g,paging:l}};Ld.locally=e=>{Ye().log("role/queryRoles.locally",e)};const Qd=async e=>{const t=Ye();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),a=t.cache&&Date.now();return t.cache&&Fn({roles:n},{cachedAt:a}),{data:n.find((t=>t.roleId===e)),cachedAt:a}};Qd.locally=e=>{const t=Ye();if(t.log("role/getRole.locally",e),!t.cache)return;const n=at(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Vd=async(e,t=!1)=>{const n=Ye();let a;n.log("message/getMessage",e),ea("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);a=await ha(t)}catch(t){throw Pe(null==t?void 0:t.code)&&_n("message",e),t}const s=n.cache&&Date.now();n.cache&&Fn(a,{cachedAt:s});const{messages:o}=a;return Nt("local.message.fetched",{messages:o}),{data:o.find((t=>t.messageId===e)),cachedAt:s}};Vd.locally=e=>{const t=Ye();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=at(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Jd{constructor(e,t,n){this.postId=e,this.latestCreatedAt=t,this.serverCommentCount=n}}class Hd{constructor(e,t,n){this.postId=e,this.commentId=t,this.createdAt=n}}class Gd{constructor(e,t){this.postId=e,this.commentId=t}}class zd{constructor(e,t){this.latestCommentCreatedAt=e,this.serverCommentCount=t,this.createdCommentIds=new Set,this.deletedCommentIds=new Set}}class Yd{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,Yd.BATCH_SIZE),t=new Set;e.forEach((e=>{let n=!1;e instanceof Jd?n=this.processResetTaskInternal(e):e instanceof Hd?n=this.processCreateTaskInternal(e):e instanceof Gd&&(n=this.processDeleteTaskInternal(e)),n&&t.add(e.postId)})),t.forEach((e=>{const t=this.computeCommentCount(e);Yd.publishUpdate(e,t)})),this.isProcessing=!1,this.tasks.length>0&&this.processCommentChangeTask()}processResetTaskInternal(e){return this.commentChangeTracker.set(e.postId,new zd(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];ot(a,{localCommentCount:t});const s=null===(n=at(a))||void 0===n?void 0:n.data;s&&Nt("local.post.updated",{posts:[s]})}}let Wd;Yd.BATCH_SIZE=50;var Xd=()=>(Wd||(Wd=new Yd),Wd);const Zd=e=>{const{posts:t,postChildren:n,videoStreamings:a}=e,s=Bn(e,["posts","postChildren","videoStreamings"]),o=Fr({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=Nr(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&&wc(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 Xd().queueCommentChangeTask(new Jd(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})},el=e=>{var{searchResult:t,polls:n}=e,a=Bn(e,["searchResult","polls"]);const s=Zd(a);return Object.assign(Object.assign({},s),{polls:n})},tl=async e=>{const t=Ye();let n;t.log("post/getPost",e),ea("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("post",e),t}const a=Zd(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{posts:o}=a;return{data:o.find((t=>t.postId===e)),cachedAt:s}};tl.locally=e=>{const t=Ye();if(t.log("post/getPost.locally",e),!t.cache)return;const n=at(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const nl=async e=>{const t=Ye();let n;t.log("comment/getComment",e),ea("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("comment",e),t}const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{comments:s}=n;return{data:hd.comment(s.find((t=>t.commentId===e))),cachedAt:a}};nl.locally=e=>{const t=Ye();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=at(["comment","get",e]);return n?{data:hd.comment(n.data),cachedAt:n.cachedAt}:void 0};const al=(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=at([o,"get",s]))||void 0===n?void 0:n.data)||void 0===a?void 0:a.myReactions)||[]},sl=(e,t,n)=>{const[a]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},a),{myReactions:n})]})},ol=(e,t,n,a=[])=>{const s=e.split(".")[1];let o=a;if(Ye().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},il=(e,t)=>{const n=e.split(".")[0],a=al(t,n),s=ol(e,t.reactor.userId,t.reactor.reactionName,a);return sl(t,`${n}s`,s)},rl=(e,t)=>{var n,a;const s=e.split(".")[0];let o=al(t,s);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(o=ol(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=sl(t,"stories",o);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return i;const r=Nr(t.communities,t.communityUsers);return Object.assign(Object.assign({},i),{communities:r})},cl=async(e,t,n)=>{var a,s,o;const i=Ye();if(i.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ve("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=at([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 Nt("local.comment.addReaction",{comment:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0;if("post"===e)return Nt("local.post.addReaction",{post:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0;if("story"===e)return Nt("local.story.reactionAdded",{story:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0}return!0};cl.optimistically=(e,t,n)=>{var a,s,o,i,r;const c=Ye();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const d=at([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 it([e,"get",t],l,{cachedAt:be}),_c(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 dl=async(e,t,n)=>{var a,s;const o=Ye();if(o.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ve("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=at([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 Nt("local.comment.removeReaction",{comment:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("post"===e)return Nt("local.post.removeReaction",{post:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("story"===e)return Nt("local.story.reactionRemoved",{story:c,reactor:{userId:o.userId,reactionName:n,reactionId:i.removedId}}),!0}return!0};dl.optimistically=(e,t,n)=>{var a,s,o,i;const r=Ye();if(r.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!r.cache)return;const c=at([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 it([e,"get",t],d,{cachedAt:be}),_c(e,d),!(null===(i=null==d?void 0:d.myReactions)||void 0===i?void 0:i.includes(n))};const ll=e=>{var t;const n=e.posts[0];if(n.parentId){const e=null===(t=at(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;if(!e)return;st(["post","get",e.postId],Object.assign(Object.assign({},e),{children:e.children.filter((e=>e!==n.postId))}))}else n.children.forEach((e=>ot(["post","get",e],{isDeleted:!0})))},ul=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{var s;if(n.cache){const o=Zd(a),{communities:i}=o;if(Fn(o,void 0,!1),(null==i?void 0:i[0])&&!["post.updated"].includes(e)&&Nt("community.updated",{communities:i,categories:[],communityUsers:o.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=a.posts[0];ll(a);try{ea("post",e)}catch(e){return}return s!==n.userId&&rt(["post","get",e]),t(a.posts[0])}const r=at(["post","get",a.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=nt(["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})=>it(e,t,{cachedAt:-1})))}"post.created"===e&&(e=>{var t;const n=e.posts[0];if(!n.parentId)return;const a=null===(t=at(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;a&&st(["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])}))},hl=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{if(n.cache){const{communities:n}=a;(null==n?void 0:n[0])&&!["local.post.updated"].includes(e)&&Nt("community.updated",{communities:n,categories:[],communityUsers:a.communityUsers,feeds:[],files:[],users:[]});const s=at(["post","get",a.posts[0].postId]);"local.post.deleted"===e&&ll(a),t(s.data)}else t(a.posts[0])}))},ml=e=>ul("post.created",e),gl=e=>ul("post.updated",e),pl=e=>ul("post.deleted",e),yl=e=>ul("post.approved",e),vl=e=>ul("post.declined",e),fl=e=>ul("post.flagged",e),bl=e=>ul("post.unflagged",e),Il=e=>{const t=Ye();return xt(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=Bn(il("post.addReaction",n),["reactor"]);Fn(t);const a=at(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},Cl=e=>{const t=Ye();return xt(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=Bn(il("post.removeReaction",n),["reactor"]);Fn(t);const a=at(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},wl=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{var s;if(n.cache){const n=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=al(e,"comment");return sl(e,"comments",t)})(a):a;Fn(n,void 0,!1);const{comments:o}=n;if(o.length>0){const n=at(["comment","get",o[0].commentId]);if(["comment.created"].includes(e)&&o[0].parentId){const e=at(["comment","get",o[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(o[0].commentId)||st(["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=at(["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))])]});st(["comment","get",o[0].parentId],t)}}const e=null===(s=nt(["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})=>it(e,t,{cachedAt:-1})))}t(hd.comment(n.data))}}else t(hd.comment(a.comments[0]))}))},Sl=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{var s,o,i,r,c;if(n.cache){const n=a;Fn(n);const{comments:d}=n;if(d.length>0){const n=at(["comment","get",d[0].commentId]);if(["local.comment.created"].includes(e)){if(d[0].parentId){const e=at(["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])]});st(["comment","get",d[0].parentId],t),setTimeout((()=>{Nt("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",d[0].referenceId],t=null===(s=at(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]});st(e,n)}}const e=null===(i=nt(["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})=>it(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(d[0].parentId){const e=at(["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))])]});st(["comment","get",d[0].parentId],t),setTimeout((()=>{Nt("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",d[0].referenceId],t=null===(r=at(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)}))});st(e,n)}}const e=null===(c=nt(["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})=>it(e,t,{cachedAt:-1})))}t(hd.comment(n.data))}}else t(hd.comment(a.comments[0]))}))},Ol=e=>wl("comment.created",e),Tl=e=>wl("comment.updated",e),Al=e=>wl("comment.deleted",e),Rl=e=>wl("comment.flagged",e),Pl=e=>wl("comment.unflagged",e),Dl=e=>{const t=Ye();return xt(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=Bn(il("comment.addReaction",n),["reactor"]);Fn(t);const a=at(["comment","get",n.comments[0].commentId]);e(hd.comment(a.data))}else e(hd.comment(n.comments[0]))}))},Ul=e=>{const t=Ye();return xt(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=Bn(il("comment.removeReaction",n),["reactor"]);Fn(t);const a=at(["comment","get",n.comments[0].commentId]);e(hd.comment(a.data))}else e(hd.comment(n.comments[0]))}))},kl=(e,t,n)=>{const a=Ye(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e){return xt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await ha(e);t.reactions[0]&&(Fn(t),Fn({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return xt(a,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=Bn(e,["reactor"]);Fn(n),Fn({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return xt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Bn(e,["reactions"]);Fn(n),Fn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return xt(a,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=Bn(e,["reactor"]);Fn(n),Fn({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},jl=(e,t,n)=>{const a=Ye(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e){return xt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await ha(e);t.reactions[0]&&(Fn(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return xt(a,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=Bn(e,["reactor"]);Fn(n),Fn({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return xt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Bn(e,["reactions"]);Fn(n),Fn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return xt(a,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=Bn(e,["reactor"]);Fn(n),Fn({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))};class El extends Cr{async getRequest(e,t){const{limit:n=ge,referenceType:a}=e,s=Bn(e,["limit","referenceType"]),o=t?{token:t}:{limit:n};Ye().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(a))throw new Ve("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 Ml extends Sr{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=Ye(),s=a.cache&&Date.now();if(a.cache){const{reactions:e}=n,a=Bn(n,["reactions"]);Fn(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)st(this.cacheKey,{data:r.map(Ze("reactor"))});else{const e=null===(o=at(this.cacheKey))||void 0===o?void 0:o.data,t=null!==(i=null==e?void 0:e.data)&&void 0!==i?i:[];st(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...r.map(Ze("reactor"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(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))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ql extends Rr{constructor(e,t){const n=R.default(e),a=["reaction","collection",n];super(new El(e),n,a,t),this.query=e,this.queryStreamController=new Ml(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=>kl(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>jl(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const a=Ye(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e)return xt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await ha(e);t.reactions[0]&&(Fn(t),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return xt(a,"local.post.removeReaction","local.post.removeReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return xt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Bn(e,["reactions"]);Fn(n),Fn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return xt(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=Ye(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e)return xt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await ha(e);t.reactions[0]&&(Fn(t),Fn({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return xt(a,"local.post.addReaction","local.post.addReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return xt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Bn(e,["reactions"]);Fn(n),Fn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return xt(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["reactor","get",e]))).filter(Boolean).map((({data:e})=>hd.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 xl=Object.freeze({__proto__:null,addReaction:cl,removeReaction:dl,onReactionAdded:(e,t,n)=>{const a=a=>{Ze(e)(a)===t&&n(a)};if("message"===e){const e=Ye(),t=async e=>{var t;const n=await ha(e),s=at(["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;Fn(n),o&&a(n.messages[0])};return xt(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?Il(a):Dl(a)},onReactionRemoved:(e,t,n)=>{const a=a=>{Ze(e)(a)===t&&n(a)};if("message"===e){const e=Ye(),t=async e=>{var t;const n=await ha(e),s=at(["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;Fn(n),o&&a(n.messages[0])};return xt(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?Cl(a):Ul(a)},onReactorAdded:kl,onReactorRemoved:jl,getReactions:(e,t,n)=>{const{log:a,cache:s}=Ye(),o=Date.now();a(`getReactions(tmpid: ${o}) > listen`);const i=new ql(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getReactions(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});function Nl(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const Kl=async()=>{var e;const t=Ye();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&&(rt(["archivedChannel","get"]),a.forEach((e=>{e.channelId&&st(["archivedChannel","get",e.channelId],e)}))),a.map((e=>e.channelId)).filter((e=>!!e))},Fl=e=>{const t=Ye(),n=[xt(t,"onMessageUpdated","message.updated",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])})),xt(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},_l=e=>{const t=Ye(),n=[xt(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])})),xt(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},Bl=e=>{const t=Ye(),n=[xt(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await fa(t);Fn(n),e(n.messageFeeds[0])})),xt(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function $l(e,t){st(["channel","get",e.channelId],Xn(e,t))}const Ll=e=>{const t=Ye();return xt(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},Ql=async(e,t=!1)=>{const n=Ye(),a=await ba(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:tt(a.data.updatedAt)});return t?setTimeout((()=>{_n("subChannel",e)}),0):it(["subChannel","get",e],s),Nt("local.message-feed.deleted",{messageFeeds:[s]}),s},Vl=e=>xt(Ye(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),Jl=()=>`LOCAL_${kn()}`;let Hl;const Gl=async(e,t)=>{const n=Ye();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)}`,ma(t)),s=await ha(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{messages:i}=s;return Nt("local.message.updated",{messages:i}),{data:hd.message(i.find((t=>t.messageId===e))),cachedAt:o}};Gl.optimistically=(e,t)=>{const n=Ye();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const a=at(["message","get",e]);if(!a)return;const s=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return it(["message","get",e],s,{cachedAt:-1}),Nt("local.message.updated",{messages:[s]}),{data:hd.message(s),cachedAt:-1}};const zl=async(e,t)=>{const n=Ye();n.log("message/editMessage",t);const{data:a}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,ma(t)),s=await ha(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{messages:i}=s;return Nt("local.message.updated",{messages:i}),{data:hd.message(i.find((t=>t.messageId===e))),cachedAt:o}};zl.optimistically=(e,t)=>{const n=Ye();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const a=at(["message","get",e]);if(!a)return;const s=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return it(["message","get",e],s,{cachedAt:-1}),Nt("local.message.updated",{messages:[s]}),{data:hd.message(s),cachedAt:-1}};const Yl=async e=>{var t;const n=Ye();if(n.log("message/deleteMessage",e),e.includes("LOCAL_")){const n=null===(t=at(["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 Nt("local.message.deleted",{messages:[a]}),hd.message(a)}const{data:a}=await n.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),s=await ha(a);return Nt("local.message.deleted",{messages:[s.messages[0]]}),hd.message(s.messages[0])};Yl.optimistically=e=>{Ye().log("message/deleteMessage.optimistically",e);const t=at(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return it(["message","get",e],n,{cachedAt:-1}),Nt("local.message.deleted",{messages:[n]}),{data:hd.message(n),cachedAt:-1}};const Wl=async e=>{const t=Ye();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await Vd(e);return Nt("local.message.deleted",{messages:[n.data]}),hd.message(n.data)};Wl.optimistically=e=>{Ye().log("message/softDeleteMessage.optimistically",e);const t=at(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return it(["message","get",e],n,{cachedAt:-1}),Nt("local.message.deleted",{messages:[n]}),{data:hd.message(n),cachedAt:-1}};const Xl=async e=>{const t=Ye();t.log("user/getReadUsers",e);const{page:n,messageId:a}=e,s=Bn(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${a}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:Ee(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:r,userFeedMarkers:c}=o,d=Bn(o,["paging","publicUserIds","userFeedMarkers"]),l=t.cache&&Date.now();if(t.cache){Fn(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)})];st(e,{users:r,paging:i})}let u=[];r.length>0&&({data:u}=await md(r));return{data:u,cachedAt:l,prevPage:Me(i.previous),nextPage:Me(i.next)}};Xl.locally=e=>{var t;const n=Ye();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:a}=e,s=Bn(e,["page"]),o=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},a)})],{data:i,cachedAt:r}=null!==(t=at(o))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=at(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:r,prevPage:Me(null==i?void 0:i.paging.previous),nextPage:Me(null==i?void 0:i.paging.next)}};const Zl=async e=>{const t=Ye();t.log("user/getDeliveredUsers",e);const{page:n,messageId:a}=e,s=Bn(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${a}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:Ee(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:r,userFeedMarkers:c}=o,d=Bn(o,["paging","publicUserIds","userFeedMarkers"]),l=t.cache&&Date.now();if(t.cache){Fn(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)})];st(e,{users:r,paging:i})}let u=[];r.length>0&&({data:u}=await md(r));return{data:u,cachedAt:l,prevPage:Me(i.previous),nextPage:Me(i.next)}};Zl.locally=e=>{var t;const n=Ye();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:a}=e,s=Bn(e,["page"]),o=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},a)})],{data:i,cachedAt:r}=null!==(t=at(o))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=at(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:r,prevPage:Me(null==i?void 0:i.paging.previous),nextPage:Me(null==i?void 0:i.paging.next)}};const eu=e=>{const t=Ye();return xt(t,"onMessageFlagged","message.flagged",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])}))},tu=e=>{const t=Ye();return xt(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])}))},nu=e=>{const t=Ye();return xt(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])}))},au=e=>{const t=Ye();return xt(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await ha(t,"message.reactionAdded");Fn(n),e(n.messages[0])}))},su=e=>{const t=Ye();return xt(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await ha(t,"message.reactionRemoved");Fn(n),e(n.messages[0])}))},ou=e=>{const t=Ye();return xt(t,"message/onMessageFetched","local.message.fetched",(t=>{Fn(t),e(t.messages[0])}))},iu=e=>{const t=Ye();return xt(t,"stream/onStreamViewerDidBan","video-streaming.viewerDidBan",(t=>{var n;const{list:a}=t;a.forEach((e=>{var t;ot(["stream","get",e.streamId],{watcherUrl:null});const n=null===(t=nt(["message","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.creatorId===e.userId));null==n||n.forEach((e=>{ot(e.key,{isDeleted:!0})}))}));const s=null===(n=at(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))};class ru extends Sr{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=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.messages.map(Ze("message")),query:this.query});else{const n=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,o=null!==(s=null==n?void 0:n.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...o,...e.messages.map(Ze("message"))])]:[...new Set([...e.messages.map(Ze("message")),...o])]}))}}reactor(e){return t=>{var n,a,s,o;if("onCreate"===e){const e=null===(n=at(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])]),st(this.cacheKey,e)}if("onDelete"===e&&"error"===t.syncState){const e=null===(o=at(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));st(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 cu extends Cr{async getRequest(e,t){const n=ga(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 du extends Rr{constructor(e,t){const n=R.default(e),a=["message","collection",n];super(new cu(e),n,a,t),this.query=e,this.queryStreamController=new ru(this.query,this.cacheKey,this.notifyChange.bind(this),ha,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ii,action:"onCreate"},{fn:Ci,action:"onCreate"},{fn:_l,action:"onDelete"},{fn:Fl,action:"onUpdate"},{fn:eu,action:"onFlagged"},{fn:tu,action:"onUnflagged"},{fn:nu,action:"onFlagCleared"},{fn:au,action:"onReactionAdded"},{fn:su,action:"onReactionRemoved"},{fn:Pd(Zi,"contentId","message"),action:"onUpdate"},{fn:Pd(er,"contentId","message"),action:"onUpdate"},{fn:Pd(iu,"channelId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>sa(e))).filter(Boolean).map((e=>hd.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=ct(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=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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 lu extends Cr{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=ge}=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 uu extends Sr{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){var t;const n=await ha(e),a=Ye(),s=a.cache&&Date.now();a.cache&&(Fn(n,{cachedAt:s}),(null===(t=e.channels)||void 0===t?void 0:t.length)&&e.channels.forEach((e=>{st(["channel","get",e.channelId],e,{cachedAt:s})})))}appendToQueryStream(e,t,n=!1){var a,s;if(n)return void st(this.cacheKey,{data:e.messages.map(Ze("message"))});const o=null===(a=at(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(Ze("message"));st(this.cacheKey,Object.assign(Object.assign({},o),{data:"prev"===t?[...new Set([...r,...i])]:[...new Set([...i,...r])]}))}}class hu extends Rr{constructor(e,t){const n=R.default(e),a=["message","search",n];super(new lu(e),n,a,t),this.queryStreamController=new uu(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>sa(e))).filter(Pr).map((e=>hd.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=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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 mu=Object.freeze({__proto__:null,createMessage:async e=>{const t=Ye();t.log("message/createMessage",e);const n=(e=>{var t,n;const a=Ye();if(!a.cache)return;Hl=e.referenceId||Jl();const s=Object.assign({messageId:Hl,uniqueId:Hl},e);a.log("message/createMessage.optimistically",s);const o=at(["subChannel","get",e.subChannelId]);if(o&&(it(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},o.data),{messageCount:o.data.messageCount+1})),o.data.channelId===o.data.subChannelId)){const e=at(["channel","get",o.data.channelId]);(null==e?void 0:e.data)&&it(["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:Ut()._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 st(["message","get",r.messageId],r,{cachedAt:-5}),Nt("local.message.created",{messages:[r]}),r})(e),a=e.referenceId||Hl||Jl();Hl=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},ma(e)),{referenceId:a})),s=await ha(n),{messages:o}=s,i=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:i}),Nt("local.message.created",{messages:[Object.assign(Object.assign({},o[0]),{syncState:"synced"})]}),{data:hd.message(o[0]),cachedAt:i}}catch(e){throw Nt("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:Gl,editMessage:zl,deleteMessage:Yl,softDeleteMessage:Wl,markAsDelivered:async(e,t)=>{const n=Ye();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=Bn(a,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Fn(Object.assign({userMarkers:s,userEntityMarkers:Vn(o),userFeedMarkers:Jn(i)},r),{cachedAt:c}),!0},getReadUsers:Xl,getDeliveredUsers:Zl,flagMessage:async(t,n)=>{const a=Ye();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 ha(i);Fn(e)}return Nt("message.flagged",i),!!i},unflagMessage:async e=>{const t=Ye();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await ha(n);Fn(e)}return Nt("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=Ye();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:Ii,onMessageCreatedLocal:Ci,onMessageUpdated:Fl,onMessageDeleted:_l,onMessageFlagged:eu,onMessageUnflagged:tu,onMessageFlagCleared:nu,onMessageReactionAdded:au,onMessageReactionRemoved:su,onMessageFetched:ou,getMessage:(e,t)=>qr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hd.message(e.data):n}))}),"messageId",Vd,[ou,Fl,_l,eu,tu,nu,au,su,Pd(Zi,"contentId","message"),Pd(er,"contentId","message"),Pd(iu,"channelId","message")]),getMessages:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMessages(tmpid: ${o}) > listen`);const i=new du(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(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}=Ye();a||console.log(ve);const s=Date.now();n(`searchMessage(tmpid: ${s}) > listen`);const o=new hu(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{rt(r)})),()=>{n(`searchMessage(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},convertFromRaw:la,prepareMessagePayload:ha,convertParams:ma,convertQueryParams:ga});const gu=e=>{const t=Ye();return xt(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class pu extends Cr{async getRequest(e,t){var n;const{limit:a=ge}=e,s=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=Bn(e,["excludeDefaultSubChannel"]);const a=Object.assign({},n);return void 0!==t&&(a.excludeDefaultMessageFeed=t),a}(Bn(e,["limit"])))&&void 0!==n?n:{},{channelId:o,includeDeleted:i}=s,r=Bn(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:oa(i),options:c})});return d}}class yu extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(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=at(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])]),st(this.cacheKey,a)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class vu extends Rr{constructor(e,t){const n=R.default(e),a=["subChannel","collection",n];super(new pu(e),n,a,t),this.query=e,this.queryStreamController=new yu(this.query,this.cacheKey,this.notifyChange.bind(this),fa),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Vl,action:"onCreate"},{fn:wi,action:"onCreate"},{fn:Si,action:"onDelete"},{fn:e=>Bl((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=Ye();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=zn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Gn(t.updatedAt)>Gn(e.subChannelUpdatedAt)&&st(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:Pd((e=>Ii((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Ca(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pd((e=>Ci((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Ca(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>Wi((t=>{var n;const a=null!==(n=t.map((({feedId:e})=>at(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==a.length&&e(a)})),action:"onUpdate"},{fn:Pd(Yi,"feedId","subChannel"),action:"onUpdate"},{fn:Pd((e=>Fl((async t=>{var n;const a=Ye();if("no-message-preview"===await a.getMessagePreviewSetting(!1))return;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;s&&s.data.includes(t.subChannelId)&&(wa(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pd((e=>_l((async t=>{const n=Ye(),a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===a?await ba(t.subChannelId):await wa(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pd(gu,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Yn))&&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=ct(e,"isDeleted",!1)),t.sort(At),t}isRelatedCollection(e){var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const fu={},bu=async e=>{const t=await(async e=>{const t=ba.locally(e);if(t)return t.data.channelId;const{data:n}=await ba(e);return n.channelId})(e),n=Gt({channelId:t,subChannelId:e});fu[e]=en(n)};var Iu=Object.freeze({__proto__:null,getSubChannelByIds:Ks,createSubChannel:async e=>{const t=Ye();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),a=await fa(n.data),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),Nt("message-feed.created",n.data),{data:a.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const n=Ye();n.log("channel/updateSubChannel",e,t);const a=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await fa(a.data),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),Nt("message-feed.updated",a.data),{data:s.messageFeeds[0],cachedAt:o}},deleteSubChannel:Ql,hardDeleteSubChannel:async e=>{Ye().log("channel/hardDeleteSubChannel",e);return await Ql(e,!0)},softDeleteSubChannel:async e=>{Ye().log("channel/softDeleteSubChannel",e);return await Ql(e,!1)},onSubChannelCreated:wi,onSubChannelUpdated:Bl,onSubChannelDeleted:Si,getSubChannel:(e,t)=>{const n=Ye();let a;return qr(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Yn(e.data)}),s=Bn(n,["origin"]);return Fa(a,s)?void 0:(a=s,t(n))}),"subChannelId",ba,[Vl,t=>Bl((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Ta(a),a.subChannelId===e&&t(a))})),Si,Pd(Yi,"feedId","subChannel"),t=>Wi((n=>{var a;if(!n.find((({feedId:t})=>t===e)))return;const s=null===(a=at(["subChannel","get",e]))||void 0===a?void 0:a.data;s&&t(s)})),Pd((t=>Ii((async n=>{n.subChannelId===e&&(await Ca(n),t(n))}))),"subChannelId","subChannel"),Pd((t=>Ci((async n=>{n.subChannelId===e&&(await Ca(n),t(n))}))),"subChannelId","subChannel"),Pd((t=>Fl((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&a.subChannelId===e&&(wa(a),t(a))}))),"subChannelId","subChannel"),Pd((t=>_l((async a=>{const s=await n.getMessagePreviewSetting(!1);"no-message-preview"!==s&&a.subChannelId===e&&("message-preview-include-deleted"===s&&await wa(a),"message-preview-not-include-deleted"===s&&await ba(a.subChannelId),t(a))}))),"subChannelId","subChannel"),Pd(gu,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:a,cache:s}=Ye(),o=Date.now();a(`getSubChannels(tmpid: ${o}) > listen`),s||console.log(ve);const i=new vu(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getSubChannels(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},markReadEngineOnLoginHandler:Ns,startMessageReceiptSync:async e=>(await bu(e),!0),stopMessageReceiptSync:e=>(fu[e]&&fu[e](),!0)});const Cu=e=>{const t=Ye();return xt(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},wu=e=>{const t=Ye();return xt(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class Su extends Cr{async getRequest(e,t){const{limit:n=ge,displayName:a,membership:s}=e,o=Bn(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 Ou extends Ar{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class Tu extends Sr{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=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.channels.map(Ze("channel"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(Ze("channel"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(this.paginationController instanceof Ou)return this.notifyChange({origin:"event",loading:!1});if(["onCreate","onJoin","onResolveChannel","onUnarchived"].includes(e)&&(Array.isArray(t)?a.data=[...new Set([...t.map(Ze("channel")),...a.data])]:a.data=[...new Set([t.channelInternalId,...a.data])]),"onArchived"===e){const e=Array.isArray(t)?t.map(Ze("channel")):[Ze("channel")(t)];a.data=a.data.filter((t=>!e.includes(t)))}st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Au=e=>{const t=Ye();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){Eo().resolve(e.channelId,"userMessageFeedMarker")}},Ru=e=>{const t=Ye();return xt(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))},Pu=e=>{const t=Ye();return xt(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))};class Du extends Rr{constructor(e,t){const n=R.default(e),a=["channel","collection",n],s=Du.getPaginationController(e);super(s,n,a,t),this.query=e,this.queryStreamController=new Tu(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=Ye();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ja(e)}catch(e){console.error("Error while preparing unread count info",e)}return Ua(e)}),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;let i=null!==(s=o.data.map((e=>at(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Us))&&void 0!==s?s:[];this.paginationController instanceof Su&&(i=this.applyFilter(i)),(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof Su?()=>this.loadPage({direction:"next"}):void 0,data:i,hasNextPage:this.paginationController instanceof Su&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ye();let n=e;switch(n=ct(n,"isDeleted",this.query.isDeleted),n=dt(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=ut(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(Ct);break;case"lastCreated":n=n.sort(St);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(bt);break;default:n=n.sort(At)}return n}shouldAbort(e){var t,n;const a=null===(t=at(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 Ye().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Ou(e):new Su(e)}getSubscriptions(){const e=[{fn:Pd((e=>Ii((t=>{var n,a;const s=Eo();(null===(n=at(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||s.resolve(t.subChannelId,"userMessageFeedMarker");const o=null===(a=at(["channel","get",t.channelId]))||void 0===a?void 0:a.data;o?($l(o,{lastActivity:t.createdAt}),e(t)):s.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Ci((t=>{var n;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya,action:"onDelete"},{fn:Va,action:"onUpdate"},{fn:os,action:"onMute"},{fn:e=>Za((t=>{Au(t),e(t)})),action:"onJoin"},{fn:e=>ns(((t,n)=>{var a,s;const{userId:o}=Ye();if("member"===this.query.membership&&o===n.userId){const e=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;st(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:cs,action:"onMemberAdded"},{fn:us,action:"onMemberRemoved"},{fn:e=>Os((t=>{const n=t.archives.map((e=>{var t;return null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>Ts((t=>{const n=t.archives.map((e=>{var t;return null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Pd(zi,"entityId","channel"),action:"onUpdate"},{fn:Pd(Ll,"entityId","channel"),action:"onUpdate"},{fn:Pd((e=>Ii((async t=>{var n;if("no-message-preview"===await Du.getMessagePreviewSetting())return;if(Sa(t),this.shouldAbort(t.channelId))return;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Ci((async t=>{var n;if("no-message-preview"===await Du.getMessagePreviewSetting())return;if(Sa(t),this.shouldAbort(t.channelId))return;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Fl((async t=>{"no-message-preview"!==await Du.getMessagePreviewSetting()&&(await Oa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>_l((async t=>{const n=await Du.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Oa(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&(rt(["messagePreviewChannel","get",t.channelId]),await vc(t.channelId)),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Si((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;a.data.find((e=>{const n=Hn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await vc(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Bl((async t=>{var n;if("no-message-preview"===await Du.getMessagePreviewSetting())return;(null===(n=at(this.cacheKey))||void 0===n?void 0:n.data)&&(await Ta(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd(wi,"channelId","channel"),action:"onUpdate"},{fn:Ru,action:"onResolveChannel"},{fn:e=>Pu((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=at(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Pd(Cu,"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>wu((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof Cr?[...e,{fn:e=>$a((t=>{Au(t),e(t)})),action:"onCreate"}]:e}}const Uu=()=>{var e;const t=Ye();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=nt(["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 ku extends Cr{async getRequest(e,t){var n,a;const s=null!==(n=e.limit)&&void 0!==n?n:ge,o=t?Number.parseInt(t,10):0;0===o&&await Kl();const i=(null!==(a=nt(["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 ks(d.map((e=>e.channelId))),{archives:d,paging:{next:l?String(o+1):void 0,previous:void 0}}}}class ju extends Sr{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 st(this.cacheKey,{data:o,params:{}});const i=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,r=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[];st(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=at(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)))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Eu extends Rr{constructor(e,t){const n=R.default(e),a=["archivedChannel","collection",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})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=>Os((t=>e(t.archives.map((e=>e.channelId))))),action:"onArchived"},{fn:e=>Ts((t=>e(t.archives.map((e=>e.channelId))))),action:"onUnarchived"},{fn:e=>Va((t=>e([t.channelId]))),action:"onUpdate"},{fn:e=>Ya((t=>e([t.channelId]))),action:"onDelete"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["channel","get",e]))).filter((e=>Boolean(e))).map((({data:e})=>e)).map(Us))&&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 Mu extends Cr{async getRequest(e,t){const{query:n,exactMatch:a,isMemberOnly:s,types:o,tags:i,sortBy:r,orderBy:c,limit:d=pe}=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 qu extends Sr{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){const t=await Ua(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)return void st(this.cacheKey,{data:e.channels.map(Ze("channel"))});const o=null===(a=at(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(Ze("channel"));st(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 xu=()=>Ye().getMessagePreviewSetting(!1);class Nu extends Rr{constructor(e,t){const n=R.default(e),a=["channel","search",n];super(new Mu(e),n,a,t),this.queryStreamController=new qu(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["channel","get",e]))).filter(Boolean).map((e=>Us(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=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=at(this.cacheKey))||void 0===t?void 0:t.data;return!n||!n.data.find((t=>t===e))}getSubscriptions(){return[{fn:Pd((e=>Ii((t=>{var n;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Ci((t=>{var n;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya,action:"onDelete"},{fn:Va,action:"onUpdate"},{fn:os,action:"onMute"},{fn:e=>Os((t=>{const n=t.archives.map((e=>{var t;return null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>Ts((t=>{const n=t.archives.map((e=>{var t;return null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Pd(zi,"entityId","channel"),action:"onUpdate"},{fn:Pd(Ll,"entityId","channel"),action:"onUpdate"},{fn:Pd((e=>Ii((async t=>{var n;if("no-message-preview"===await xu())return;if(Sa(t),this.shouldAbort(t.channelId))return;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Ci((async t=>{var n;if("no-message-preview"===await xu())return;if(Sa(t),this.shouldAbort(t.channelId))return;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Fl((async t=>{"no-message-preview"!==await xu()&&(await Oa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>_l((async t=>{const n=await xu();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Oa(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&(rt(["messagePreviewChannel","get",t.channelId]),await vc(t.channelId)),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Si((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;a.data.find((e=>{const n=Hn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await vc(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Bl((async t=>{var n;if("no-message-preview"===await xu())return;(null===(n=at(this.cacheKey))||void 0===n?void 0:n.data)&&(await Ta(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:e=>Pu((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=at(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Pd(Cu,"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>wu((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}]}}class Ku extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a}=e,s=Bn(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 Fu extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>Ze("channelUsers")({channelId:e,userId:t})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>Ze("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;const s=Ze("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)),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class _u extends Rr{constructor(e,t){const n=R.default(e),a=["channelUsers","collection",n];super(new Ku(e),n,a,t),this.query=e,this.queryStreamController=new Fu(this.query,this.cacheKey,this.notifyChange.bind(this),Ua),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Za,action:"onJoin"},{fn:ns,action:"onLeft"},{fn:cs,action:"onMemberAdded"},{fn:us,action:"onMemberRemoved"},{fn:gs,action:"onChannelMemberBanned"},{fn:vs,action:"onChannelMemberUnbanned"},{fn:Is,action:"onChannelMemberRoleAdded"},{fn:Ss,action:"onChannelMemberRoleRemoved"},{fn:Ps,action:"onChannelSetUserMuted"},{fn:(e=this.query.channelId,t=>{const n=Ye();return xt(n,"user.deleted","user.deleted",(n=>{var a,s;const o=eo(n);if(0===o.users.length)return;const i=o.users[0];Fn(o);const r=Ze("channelUsers")({channelId:e,userId:i.userId}),c=null===(a=at(["channelUsers","get",r]))||void 0===a?void 0:a.data;it(["channelUsers","get",r],Object.assign(Object.assign({},c),{user:i}));const d=null===(s=at(["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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(hd.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=lt(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?St:Ct),t}}const Bu=(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new _u(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}};var $u=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ye();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=>Nt("channel.membersAdded",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const s=await Ua(a);n.cache&&Fn(s);const{channelUsers:o}=s;return!!o.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=Ye();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=>Nt("channel.membersRemoved",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const s=await Ua(a);n.cache&&Fn(s);const{channelUsers:o}=s;return!!o.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=lt(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?St:Ct),n},getMembers:Bu,searchMembers:(e,t,n)=>Bu(e,t)});var Lu=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const a=Ye();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 Ua(s);a.cache&&Fn(o),Nt("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=Ye();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 Ua(s);a.cache&&Fn(o),Nt("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=Ye();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 Ua(a),{channelUsers:o}=s,i=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:i}),Nt("channel.banned",a),{data:null==o?void 0:o.filter((e=>"banned"===e.membership)),cachedAt:i}},unbanMembers:async(e,t)=>{const n=Ye();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 Ua(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o}),Nt("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=Ye();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 Nt("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=Ye();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 Nt("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:new Date(0).toISOString(),actor:null!==(n=a.userId)&&void 0!==n?n:""}),o}}),Qu=Object.freeze({__proto__:null,Membership:$u,Moderation:Lu,getChannelByIds:ks,createChannel:yc,updateChannel:async(e,t)=>{const n=Ye();n.log("channel/updateChannel",e,t);const{data:a}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await Ua(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{channels:i}=s;return{data:xa(i.find((t=>t.channelId===e))),cachedAt:o}},deleteChannel:async e=>{const t=Ye();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await vc(e);return xa(n.data)},joinChannel:async e=>{const t=Ye();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),a=await Ua(n);t.cache&&Fn(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=Ye();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),a=await Ua(n);t.cache&&Fn(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=Ye();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new Qe("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=Ye();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=Ye();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&&st(["archivedChannel","get",Ze("archivedChannel")(n)],n),Nt("local.channel.archived",{archives:[n]})},unarchiveChannel:async e=>{var t;const n=Ye();n.log("channel/unarchiveChannel",e),await n.http.delete(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const a=null===(t=at(["archivedChannel","get",e]))||void 0===t?void 0:t.data,s=null!=a?a:{channelId:e,archivedAt:(new Date).toISOString()};n.cache&&rt(["archivedChannel","get",e],!0),Nt("local.channel.unarchived",{archives:[s]})},getArchivedChannelIds:Kl,onChannelCreated:$a,onChannelUpdated:Va,onChannelDeleted:Ya,onChannelJoined:Za,onChannelLeft:ns,onChannelSetMuted:os,onChannelMemberAdded:cs,onChannelMemberRemoved:us,onChannelMemberBanned:gs,onChannelMemberUnbanned:vs,onChannelMemberRoleAdded:Is,onChannelMemberRoleRemoved:Ss,onChannelArchived:Os,onChannelUnarchived:Ts,getChannel:(e,t)=>{const n=Ye();let a;return qr(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Us(e.data)}),s=Bn(n,["origin"]);return Fa(a,s)?void 0:(a=s,t(n))}),"channelId",vc,[Va,Ya,Za,ns,cs,us,gs,vs,os,Pd(zi,"entityId","channel"),Pd(Ll,"entityId","channel"),Pd((t=>Ii((async a=>{await(async a=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Sa(a),a.channelId!==e)return;const o=null===(s=at(["channel","get",e]))||void 0===s?void 0:s.data;o&&($l(o,{messagePreviewId:a.messageId}),t(a))})(a),t(a)}))),"channelId","channel"),Pd((t=>Ci((async a=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Sa(a),a.channelId!==e)return;const o=null===(s=at(["channel","get",e]))||void 0===s?void 0:s.data;o&&($l(o,{messagePreviewId:a.messageId}),t(a))}))),"channelId","channel"),Pd((t=>Fl((async a=>{var s;const o=null===(s=at(["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 Oa(a),t(a))}))),"channelId","channel"),Pd((t=>_l((async a=>{var s;const o=null===(s=at(["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?(rt(["messagePreviewChannel","get",e]),await vc(a.channelId)):await Oa(a),t(a))}))),"channelId","channel"),Pd((e=>Si((async t=>{var a,s;const{channelId:o,subChannelId:i}=t,r=null===(a=at(["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 vc(o);(null===(s=at(["channel","get",o]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),Pd((t=>Bl((async a=>{var s,o;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Ta(a);const i=null===(s=at(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!i||i.subChannelId!==a.subChannelId)return;(null===(o=at(["channel","get",e]))||void 0===o?void 0:o.data)&&t(a)}))),"channelId","channel"),Pd(wi,"channelId","channel"),Pd(Cu,"channelId","channel"),Pd((e=>wu((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getChannels(tmpid: ${i}) > listen`);const r=new Du(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{rt(d)})),()=>{a(`getChannels(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=Ut();if(!t)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=Ye();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?nr(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return s.push(wu((e=>{const{data:t}=Uu();Fa(o,t)||r({loading:!1,data:t})}))),(()=>{const e=_e((async()=>Uu()));$e(e,(({error:e,data:t,loading:n,origin:a,cachedAt:o})=>{o===be?(r({data:t,origin:a,loading:!1,error:new Ve(fe,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}=Ye();a||console.log(ve);const s=Date.now();n(`getArchivedChannels(tmpid: ${s}) > listen`);const o=new Eu(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{rt(r)})),()=>{n(`getArchivedChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchChannels:(e,t)=>{const{log:n,cache:a}=Ye();a||console.log(ve);const s=Date.now();n(`searchChannels(tmpid: ${s}) > listen`);const o=new Nu(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{rt(r)})),()=>{n(`searchChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Aa,isUnreadCountSupport:Ra,convertFromRaw:Pa,preUpdateChannelCache:Da,prepareChannelPayload:Ua});const Vu=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));st(["communityUsers","collection",e],n)}))},Ju=async(e,t)=>{const n=Ye();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=_r(s),i=n.cache&&Date.now();return n.cache&&(Fn(o,{cachedAt:i}),Vu(o.communities,o.communityUsers)),{data:o.communities.map((e=>hd.community(e))),cachedAt:i}};Ju.locally=e=>{const t=Ye();if(t.log("community/getCommunities.locally",e),!t.cache)return;const n=e.map((e=>at(["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 Hu=async e=>{const t=Ye();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),a=_r(n),s=t.cache&&Date.now();t.cache&&(Fn(a,{cachedAt:s}),Vu(a.communities,a.communityUsers));const{communities:o}=a;return{data:o.find((t=>t.communityId===e)),cachedAt:s}};Hu.locally=e=>{const t=Ye();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=at(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Gu=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=_r(e);if(n.cache){Fn(a);const e=at(["community","get",a.communities[0].communityId]);t(e.data)}else t(a.communities[0])}))},zu=e=>Gu("community.created",e),Yu=e=>Gu("community.updated",e),Wu=e=>Gu("community.deleted",e);class Xu extends Cr{async getRequest(e,t){var n;const{limit:a=ge}=e,s=Bn(e,["limit"]),o=t?{token:t}:{limit:a},{data:i}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:oa(s.includeDeleted),keyword:s.displayName,filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return i}}class Zu extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communities.map(Ze("community"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ze("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var eh,th;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(eh||(eh={})),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"}(th||(th={}));class nh extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a,excludingRoles:s}=e,o=Bn(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 ah extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Ze("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Ze("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{var t;const n=Ze("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]}})),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function sh(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function oh(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=>!sh(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!sh(e,t,"ADD_COMMUNITY_USER")))}const ih=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{const s=_r(a),{communities:o,communityUsers:i}=s,r=Nr(o,i);if(s.communities=r,n.cache){Fn(s,void 0,!1);const n=at(["community","get",s.communities[0].communityId]),a=oh(e,s).map((e=>{const t=at(["communityUsers","get",Ze("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Pr);t(n.data,a)}else t(s.communities[0],oh(e,s))}))},rh=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{const s=_r(a),{communities:o,communityUsers:i}=s,r=Nr(o,i);if(s.communities=r,n.cache){Fn(s,void 0,!1);const n=at(["community","get",s.communities[0].communityId]),a=oh(e,s).map((e=>{const t=at(["communityUsers","get",Ze("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Pr);t(n.data,a)}else t(s.communities[0],oh(e,s))}))},ch=e=>ih("community.userBanned",e),dh=e=>ih("community.userChanged",e),lh=e=>ih("community.userUnbanned",e),uh=e=>ih("community.roleAdded",e),hh=e=>ih("community.roleRemoved",e),mh=e=>rh("local.community.userAdded",e),gh=e=>rh("local.community.userRemoved",e),ph=e=>ih("community.joined",e),yh=e=>ih("community.left",e),vh=e=>rh("local.community.joined",e),fh=e=>rh("local.community.left",e),bh=e=>{const t=Ye(),n=[xt(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},Ih=e=>{const t=Ye();return xt(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:a}=t;e(n[0],a.filter((e=>"member"===e.communityMembership)))}))},Ch=e=>{const t=Ye();return xt(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:a}=t;e(n[0],a.filter((e=>"member"===e.communityMembership)))}))},wh=e=>t=>{const n=Ye();return xt(n,"user.deleted","user.deleted",(n=>{var a,s;const o=eo(n);if(0===o.users.length)return;const i=o.users[0];Fn(o);const r=Ze("communityUsers")({communityId:e,userId:i.userId}),c=null===(a=at(["communityUsers","get",r]))||void 0===a?void 0:a.data;st(["communityUsers","get",r],Object.assign(Object.assign({},c),{user:i}));const d=null===(s=at(["community","get",e]))||void 0===s?void 0:s.data;t(d,[Object.assign(Object.assign({},c),{user:i})])}))};class Sh extends Rr{constructor(e,t){const n=R.default(e),a=["communityUsers","collection",n];super(new nh(e),n,a,t),this.query=e,this.queryStreamController=new ah(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:ph,action:th.OnCommunityJoined},{fn:vh,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:fh,action:th.OnCommunityLeft},{fn:ch,action:th.OnCommunityUserBanned},{fn:dh,action:th.OnCommunityUserChanged},{fn:uh,action:th.OnCommunityUserRoleAdded},{fn:hh,action:th.OnCommunityUserRoleRemoved},{fn:Ch,action:th.OnCommunityUserRoleAdded},{fn:Ih,action:th.OnCommunityUserRoleRemoved},{fn:lh,action:th.OnCommunityUserUnbanned},{fn:mh,action:th.OnCommunityUserAdded},{fn:gh,action:th.onCommunityUserRemoved},{fn:wh(this.query.communityId),action:th.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["communityUsers","get",e]))).filter(Pr).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=lt(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(Ct);else n=n.sort(St);return n}}class Oh extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a,excludingRoles:s}=e,o=Bn(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 Th extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Ze("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Ze("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{const t=Ze("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(a.data=a.data.filter((e=>e!==t)))})),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Ah;!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"}(Ah||(Ah={}));class Rh extends Rr{constructor(e,t){const n=R.default(e),a=["communityUsers","collection",n];super(new Oh(e),n,a,t),this.query=e,this.queryStreamController=new Th(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:ph,action:Ah.OnCommunityJoined},{fn:vh,action:Ah.OnCommunityJoined},{fn:yh,action:Ah.OnCommunityLeft},{fn:fh,action:Ah.OnCommunityLeft},{fn:ch,action:Ah.OnCommunityUserBanned},{fn:dh,action:Ah.OnCommunityUserChanged},{fn:Ih,action:Ah.OnCommunityUserRoleRemoved},{fn:hh,action:Ah.OnCommunityUserRoleRemoved},{fn:lh,action:Ah.OnCommunityUserUnbanned},{fn:wh(this.query.communityId),action:Ah.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["communityUsers","get",e]))).filter(Pr).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=lt(e,"roles",this.query.roles);return this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(n=pt(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 Ph=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ye();n.log("community/moderation/addMembers",e,t);const{data:a}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});Nt("local.community.userAdded",a);const s=Ln(a,"communityUsers");n.cache&&Fn(s);const{communityUsers:o}=s;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=Ye();n.log("community/moderation/removeMembers",e,t);const{data:a}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});Nt("local.community.userRemoved",a);const s=Ln(a,"communityUsers");n.cache&&Fn(s);const{communityUsers:o}=s;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{var n;let a=lt(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?St:Ct),a},getMembers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);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((()=>{rt(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new Rh(e,(e=>{t(e)})),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},onCommunityUserAdded:e=>ih("community.userAdded",e),onCommunityUserRemoved:e=>ih("community.userRemoved",e),onCommunityUserBanned:ch,onCommunityUserChanged:dh,onCommunityUserUnbanned:lh,onCommunityUserRoleAdded:uh,onCommunityUserRoleRemoved:hh,onLocalCommunityUserAdded:mh,onLocalCommunityUserRemoved:gh,onCommunityJoined:ph,onCommunityLeft:yh,onLocalCommunityJoined:vh,onLocalCommunityLeft:fh,onLocalCommunityJoin:bh});class Dh extends Rr{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Xu(e),n,a,t),this.query=e,this.queryStreamController=new Zu(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Wu,action:eh.OnCommunityDeleted},{fn:Yu,action:eh.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:eh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["community","get",e]))).filter(Pr).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}=Ye();let n=e;return this.query.includeDeleted||(n=ct(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=mt(n,this.query.membership,t)),n}}class Uh extends Cr{async getRequest(e,t){var n;const{limit:a=ge}=e,s=Bn(e,["limit"]),o=t?{token:t}:{limit:a},{data:i}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:oa(s.includeDeleted),filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return i}}class kh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&(Fn(t,{cachedAt:a}),Vu(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communities.map(Ze("community"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ze("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],st(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.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(jh||(jh={}));class Eh extends Rr{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Uh(e),n,a,t),this.query=e,this.queryStreamController=new kh(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:jh.OnCommunityCreated},{fn:Wu,action:jh.OnCommunityDeleted},{fn:Yu,action:jh.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:jh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["community","get",e]))).filter(Pr).map((({data:e})=>mc(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}=Ye();let n=e;this.query.includeDeleted||(n=ct(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=mt(n,this.query.membership,t));const a=(()=>"firstCreated"===this.query.sortBy?Ct:St)();return n=n.sort(a),n}}class Mh extends Cr{async getRequest(e,t){const{limit:n=ge,includeDiscoverablePrivateCommunity:a}=e,s=Bn(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 qh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&(Fn(t,{cachedAt:a}),Vu(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communities.map(Ze("community"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ze("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(st(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"}(xh||(xh={}));class Nh extends Rr{constructor(e,t){const n=R.default(e),a=["trendingCommunity","collection",n];super(new Mh(e),n,a,t),this.query=e,this.queryStreamController=new qh(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Wu,action:xh.OnCommunityDeleted},{fn:Yu,action:xh.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:xh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["community","get",e]))).filter(Pr).map((({data:e})=>mc(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 Kh extends Cr{async getRequest(e,t){const{limit:n=ge,includeDiscoverablePrivateCommunity:a}=e,s=Bn(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 Fh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&(Fn(t,{cachedAt:a}),Vu(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communities.map(Ze("community"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ze("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(st(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.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(_h||(_h={}));class Bh extends Rr{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Kh(e),n,a,t),this.query=e,this.queryStreamController=new Fh(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Wu,action:_h.OnCommunityDeleted},{fn:Yu,action:_h.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:_h.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["community","get",e]))).filter(Pr).map((({data:e})=>mc(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 $h extends Cr{async getRequest(e,t){var n;const{limit:a=ge,communityMembershipStatus:s}=e,o=Bn(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 Lh(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class Qh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:Lh(e)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Lh(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Vh;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Vh||(Vh={}));class Jh extends Rr{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new $h(e),n,a,t),this.query=e,this.queryStreamController=new Qh(this.query,this.cacheKey,this.notifyChange.bind(this),Qr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Vh.OnCommunityCreated},{fn:Wu,action:Vh.OnCommunityDeleted},{fn:Yu,action:Vh.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:Vh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(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})=>at(["community","get",e]))).filter(Pr).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}=Ye();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=mt(n,this.query.communityMembershipStatus,t)),n}}class Hh extends Cr{async getRequest(e,t){const{limit:n=ge,communityIds:a}=e,s=Bn(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 Gh;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Gh||(Gh={}));class zh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.joinRequests.map((e=>Ze("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Ze("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(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===Gh.OnLocalJoinRequestUpdated){if(!a.data.find((e=>s.includes(e))))return}e===Gh.OnLocalJoinRequestCreated&&(a.data=[...new Set([...s,...a.data])]),e===Gh.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>!s.includes(e)))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Yh extends Rr{constructor(e,t){const n=R.default(e),a=["joinRequestList","collection",n];super(new Hh(e),n,a,t),this.query=e,this.queryStreamController=new zh(this.query,this.cacheKey,this.notifyChange.bind(this),Br),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:zr,action:Gh.OnLocalJoinRequestCreated},{fn:Yr,action:Gh.OnLocalJoinRequestUpdated},{fn:Wr,action:Gh.OnLocalJoinRequestUpdated},{fn:bh,action:Gh.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(s.data.map((e=>at(["joinRequest","get",e]))).filter(Pr).map((({data:e})=>e)).map(Vr));(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?Ct:St)();return t=t.sort(n),t}}var Wh;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(Wh||(Wh={}));var Xh=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const a=Ye();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=$r(s);a.cache&&Fn(o),Nt("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=Ye();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=$r(s);a.cache&&Fn(o),Nt("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=Ye();n.log("community/banMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=Ln(a,"communityUsers"),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{communityUsers:i}=s;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:o}},unbanMembers:async(e,t)=>{const n=Ye();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=Ln(a,"communityUsers"),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{communityUsers:i}=s;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:o}}}),Zh=Object.freeze({__proto__:null,Moderation:Xh,Membership:Ph,getCommunityByIds:Ju,createCommunity:async e=>{const t=Ye();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",Lr(e));Nt("community.created",n);const a=_r(n),s=t.cache&&Date.now();t.cache&&(Fn(a,{cachedAt:s}),Vu(a.communities,a.communityUsers));const{communities:o}=a;return{data:hd.community(o[0]),cachedAt:s}},updateCommunity:async(e,t)=>{const n=Ye();n.log("community/updateCommunity",e,t);const{data:a}=await n.http.put(`/api/v3/communities/${e}`,Lr(t));Nt("community.updated",a);const s=_r(a),o=n.cache&&Date.now();n.cache&&(Fn(s,{cachedAt:o}),Vu(s.communities,s.communityUsers));const{communities:i}=s;return{data:hd.community(i.find((t=>t.communityId===e))),cachedAt:o}},deleteCommunity:async e=>{const t=Ye();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await Hu(e);return Nt("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),hd.community(n.data)},joinCommunity:async e=>{const t=Ye();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);Nt("local.community.joined",n);const a=_r(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=Ye();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);Nt("local.community.left",n);const a=_r(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:zu,onCommunityUpdated:Yu,onCommunityDeleted:Wu,searchCommunities:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`searchCommunities(tmpid: ${o}) > listen`);const i=new Dh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`searchCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCommunities(tmpid: ${o}) > listen`);const i=new Eh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunity:(e,t)=>qr(e,t,"communityId",Hu,[Yu,Wu,ph,yh,vh,fh,ch,lh,dh,Pd(bh,"targetId","community")],{callbackDataSelector:e=>e?hd.community(e):e}),getTrendingCommunities:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getTrendingCommunities(tmpid: ${i}) > listen`);const r=new Nh(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>rt(d))),()=>{a(`getTrendingCommunities(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getRecommendedCommunities(tmpid: ${i}) > listen`);const r=new Bh(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>rt(d))),()=>{a(`getRecommendedCommunities(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`semanticSearchCommunities(tmpid: ${o}) > listen`);const i=new Jh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`semanticSearchCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getJoinRequestList: (tmpid: ${o}) > listen`);const i=new Yh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getJoinRequestList (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return Wh}});const em=async e=>{const t=Ye();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&&Fn(n,{cachedAt:a});const{categories:s}=n;return{data:hd.category((null!=s?s:[]).find((t=>t.categoryId===e))),cachedAt:a}};em.locally=e=>{const t=Ye();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=at(["category","get",e]);return n?{data:hd.category(n.data),cachedAt:n.cachedAt}:void 0};const tm=async e=>{const t=Ye();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:a,limit:s,includeDeleted:o}=n,i=Bn(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:oa(o),options:r})}),{paging:d}=c,l=Bn(c,["paging"]),{categories:u}=l,h=t.cache&&Date.now();if(t.cache){Fn(l,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},i),{includeDeleted:o,options:r})];st(e,{categories:null==u?void 0:u.map(Ze("category")),paging:d})}return{data:null!=u?u:[],cachedAt:h,paging:d}};tm.locally=e=>{var t,n;const a=Ye();if(a.log("category/queryCategories.locally",e),!a.cache)return;const s=null!=e?e:{},{page:o,limit:i=10}=s,r=Bn(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=at(d))&&void 0!==t?t:{};if(!(null==l?void 0:l.categories.length))return;const h=l.categories.map((e=>at(["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 nm=Object.freeze({__proto__:null,getCategory:em,getCategories:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCategories(tmpid: ${o}) > listen`);const{limit:i}=e,r=Bn(e,["limit"]),c=null!=i?i:ge,{policy:d=ye}=null!=n?n:{},l=[],u=["category","collection",{}],h=(n=!1)=>{var a,s;const o=null===(a=at(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=_e(tm,Object.assign(Object.assign({},r),{limit:n?c:void 0,page:n||null==o?void 0:o.params.page}));$e(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(Ze("category"))])]),st(u,r),(n=>{var a,s;let o=null!==(a=n.data.map((e=>at(["category","get",e]))).filter(Boolean).map((({data:e})=>hd.category(e))))&&void 0!==a?a:[];switch(e.includeDeleted||(o=ct(o,"isDeleted",!1)),e.sortBy){case"firstCreated":o=o.sort(Ct);break;case"lastCreated":o=o.sort(St);break;default:o=o.sort(It)}t({onNextPage:h,data:o,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})})(r)}),Be(d))};return l.push((()=>{})),h(!0),()=>{a(`getCategories(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}}});const am=async e=>{const t=Ye();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:a,dataTypes:s}=n,o=Bn(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=Bn(r,["paging"]),l=Ln(d,"communityUsers"),{posts:u}=l,{communities:h}=_r(l),m=t.cache&&Date.now();if(t.cache){Fn(Object.assign(Object.assign({},l),{communitis:h}));const e=["globalFeed","query",Object.assign(Object.assign({},o),{options:i})];st(e,{posts:u.map(Ze("post")),paging:c})}return{data:u.map(hd.post),cachedAt:m,paging:c}};am.locally=e=>{var t;const n=Ye();if(n.log("post/queryGlobalFeed.locally",e),!n.cache)return;const a=Bn(null!=e?e:{},[]),s=["globalFeed","query",Object.assign({},a)],{data:o,cachedAt:i}=null!==(t=at(s))&&void 0!==t?t:{};if(!(null==o?void 0:o.posts.length))return;const r=o.posts.map((e=>at(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(hd.post),{paging:c}=o;return r.length===o.posts.length?{data:r,cachedAt:i,paging:c}:void 0};class sm extends Cr{async getRequest(e,t){const{limit:n}=e,a=Bn(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 om;!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"}(om||(om={}));class im extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.posts.map(Ze("post"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ze("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===om.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===om.OnPostCreated||e===om.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===om.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const rm=async e=>{const t=Ye();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=>{Pe(null==t?void 0:t.code)&&_n("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.comments.map((e=>hd.comment(e))),cachedAt:s}};rm.locally=e=>{var t;const n=Ye();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const a=e.map((e=>at(["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=>hd.comment(e))),cachedAt:o.cachedAt}};const cm=e=>{const t=Ye();if(!t.cache)return;const n=kn();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 st(["comment","get",s.commentId],s,{cachedAt:-5}),Nt("local.comment.created",{comments:[s],commentChildren:[],users:[],files:[],communityUsers:[]}),s},dm=(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})},lm=async e=>{const t=Ye();t.log("story/getStoryByStoryId",e);const n=at(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;ea("story",e)}let a;try{const n=await t.http.get(`/api/v4/stories/${e}`);a=dm(n.data)}catch(t){throw Pe(null==t?void 0:t.code)&&_n("story",e),t}const s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.stories[0],cachedAt:s}};lm.locally=e=>{const t=Ye();t.log("story/getStorybyStoryId",e);const n=at(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;ea("story",e)}const a=t.cache&&Date.now(),s=at(["story","get",e]);if(s)return{data:s.data,cachedAt:a}};const um=async(e,t=!1)=>{var n,a,s;const o=Ye(),i=null===(n=at(["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 rt(["comment","get",e]),Nt("local.comment.deleted",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]}),t}const r=await nl(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?Mt((()=>_n("comment",e))):it(["comment","get",e],{isDeleted:!0}),"story"===r.data.referenceType){const e=await lm(r.data.referenceId);Nt("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const t=null===(a=at(["post","get",r.data.referenceId]))||void 0===a?void 0:a.data;if(t){const n=Xd();n.queueCommentChangeTask(new Gd(t.postId,e)),!c.parentId&&(null===(s=c.children)||void 0===s?void 0:s.length)>0&&c.children.forEach((e=>{n.queueCommentChangeTask(new Gd(t.postId,e))}))}}return Nt("local.comment.deleted",{comments:[c],commentChildren:[],files:[],users:[],communityUsers:[]}),c},hm=async e=>{const t=Ye();let n;t.log("comment/getComment",e),ea("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("comment",e),t}const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{comments:s}=n;return{data:s.find((t=>t.commentId===e)),cachedAt:a}};hm.locally=e=>{const t=Ye();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=at(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const mm=e=>Sl("local.comment.deleted",e),gm=e=>{const t=Ye();return xt(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(it(["comment","get",n.commentId],n),e(Ic(n))):e(n)}))},pm=e=>{const t=Ye();return xt(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(it(["comment","get",n.commentId],n),e(Ic(n))):e(n)}))};class ym extends Cr{async getRequest(e,t){var n;const{pageSize:a,limit:s,includeDeleted:o}=e,i=Bn(e,["pageSize","limit","includeDeleted"]),r=null!==(n=null!=a?a:s)&&void 0!==n?n:ge,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:oa(o),options:d})});return l}}var vm;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(vm||(vm={}));class fm extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.comments.map(Ze("comment"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(Ze("comment"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(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===vm.OnCommentCreated&&(a.data=[...new Set([t.commentId,...a.data])]),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const bm=e=>Sl("local.comment.created",e);class Im extends Rr{constructor(e,t){const n=R.default(e),a=["comments","collection",n];super(new ym(e),n,a,t),this.query=e,this.queryStreamController=new fm(this.query,this.cacheKey,this.notifyChange.bind(this),Nl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:bm,action:vm.OnCommentCreated},{fn:mm,action:vm.OnCommentDeleted},{fn:Ol,action:vm.OnCommentCreated},{fn:Tl,action:vm.OnCommentUpdated},{fn:Al,action:vm.OnCommentDeleted},{fn:Rl,action:vm.OnCommentFlagged},{fn:Pl,action:vm.OnCommentUnflagged},{fn:Dl,action:vm.OnCommentReactionAdded},{fn:Ul,action:vm.OnCommentReactionRemoved},{fn:gm,action:vm.OnCommentReactionAdded},{fn:pm,action:vm.OnCommentReactionRemoved}]);if(this.query.excludeBlockUserComments){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Yo(t),Wo(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["comment","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.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=ct(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=ft(t)),"firstCreated"===this.query.sortBy)t=t.sort(Ct);else t=t.sort(St);return t}}var Cm=Object.freeze({__proto__:null,getCommentByIds:rm,createComment:async e=>{const t=Ye();t.log("comment/createComment",e);const n=cm(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&&Fn(n,{cachedAt:o}),["post","content"].includes(e.referenceType))Xd().queueCommentChangeTask(new Hd(e.referenceId,s[0].commentId,n.comments[0].createdAt));else if("story"===e.referenceType){const t=at(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=at(["story","get",t.data]);(null==e?void 0:e.data)&&Nt("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 Nt("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:hd.comment(s[0]),cachedAt:o}}catch(e){throw n&&Nt("local.comment.created",{comments:[Object.assign(Object.assign({},n),{syncState:"error"})],commentChildren:[],users:[],files:[],communityUsers:[]}),e}},updateComment:async(e,t)=>{const n=Ye();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&&Fn(a,{cachedAt:s}),Nt("comment.updated",a);const{comments:o}=a;return{data:hd.comment(o.find((t=>t.commentId===e))),cachedAt:s}},deleteComment:um,softDeleteComment:async e=>{Ye().log("comment/softDeleteComment",e);return um(e)},hardDeleteComment:async e=>{Ye().log("comment/hardDeleteComment",e);return um(e,!0)},flagComment:async(t,n)=>{const a=Ye();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&&Fn(i),Nt("comment.flagged",i),!!i},unflagComment:async e=>{const t=Ye();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Fn(n),Nt("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=Ye();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:Ol,onCommentUpdated:Tl,onCommentDeleted:Al,onCommentFlagged:Rl,onCommentUnflagged:Pl,onCommentReactionAdded:Dl,onCommentReactionRemoved:Ul,getComment:(e,t)=>qr(e,t,"commentId",hm,[mm,Al,Rl,Dl,Ul,Pl,Tl,gm,pm]),getComments:(e,t,n)=>{const{log:a,cache:s}=Ye();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 Im(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getComments(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});const wm=e=>hl("local.post.deleted",e),Sm=e=>{const t=Ye();return xt(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(it(["post","get",n.postId],n),e(n)):e(n)}))},Om=e=>{const t=Ye();return xt(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(it(["post","get",n.postId],n),e(n)):e(n)}))},Tm=e=>hl("local.post.updated",e),Am=e=>[Ol,Al,bm,mm].map((t=>({fn:Pd((n=>((e,t,n)=>t((async t=>{var a;const s=null===(a=at(n))||void 0===a?void 0:a.data;s&&s.data.includes(t.referenceId)&&e(t)})))(n,t,e)),"referenceId","post"),action:om.OnPostUpdated}))),Rm=e=>[{fn:ml,action:om.OnPostCreated},{fn:gl,action:om.OnPostUpdated},{fn:Tm,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Sm,action:om.OnPostReactionAdded},{fn:Om,action:om.OnPostReactionRemoved},{fn:wm,action:om.OnPostDeleted},...Am(e)];class Pm extends Rr{constructor(e,t){const n=R.default(e),a=["customRankingGlobalFeed","collection",n];super(new sm(e),n,a,t),this.query=e,this.queryStreamController=new im(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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(Rm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.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 Cr{async getRequest(e,t){const{limit:n,dataTypes:a}=e,s=Bn(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 Um extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.posts.map(Ze("post"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ze("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===om.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===om.OnPostCreated||e===om.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===om.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class km extends Rr{constructor(e,t){const n=R.default(e),a=["globalFeed","collection",n];super(new Dm(e),n,a,t),this.query=e,this.queryStreamController=new Um(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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(Rm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class jm extends Cr{async getRequest(e,t){const{userId:n,feedSources:a,dataTypes:s,includeDeleted:o,matchingOnlyParentPost:i,limit:r=ge,untilAt:c}=e,d=Bn(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:oa(o),matchingOnlyParentPost:null!=i?i:!(null==s?void 0:s.length)})});return u}}class Em extends Sr{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?Rt(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(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=>!Pt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)st(this.cacheKey,{data:o.map(Ze("post"))});else{const e=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Ze("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(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===om.OnPostCreated||e===om.OnPostApproved||e===om.OnPostUpdated)){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Pt(t.createdAt,this.validatedUntilAt,e))return}if(e===om.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=at(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),st(["post","get",e.postId],e)}if(e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e===om.OnPostCreated||e===om.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])]}st(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=async e=>{const t=Ye();let n;t.log("post/getPost",e),ea("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("post",e),t}const a=Ln(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{posts:o}=a;return{data:o.find((t=>t.postId===e)),cachedAt:s}};Mm.locally=e=>{const t=Ye();if(t.log("post/getPost.locally",e),!t.cache)return;const n=at(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class qm extends Rr{constructor(e,t){const n=R.default(e),a=["userFeed","collection",n];super(new jm(e),n,a,t),this.query=e,this.queryStreamController=new Em(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ml,action:om.OnPostCreated},{fn:gl,action:om.OnPostUpdated},{fn:Tm,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Sm,action:om.OnPostReactionAdded},{fn:Om,action:om.OnPostReactionRemoved},{fn:wm,action:om.OnPostDeleted},{fn:Pd((e=>Ol((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Mm(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated},{fn:Pd((e=>Al((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Mm(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[],r=this.applyFilter(i).map(hd.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=ct(n,"isDeleted",!1)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=gt(n,this.query.dataTypes)),this.query.untilAt){const e=Rt(this.query.untilAt),t="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";n=n.filter((n=>!Pt(n.createdAt,e,t)))}if("firstCreated"===this.query.sortBy)n=n.sort(Ct);else n=n.sort(St);return n}}class xm extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a,communityId:s,untilAt:o}=e,i=Bn(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:oa(a),matchingOnlyParentPost:!0,options:r})});return c}}class Nm extends Sr{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?Rt(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(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=>!Pt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)st(this.cacheKey,{data:o.map(Ze("post"))});else{const e=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Ze("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===om.OnPostCreated||e===om.OnPostApproved)&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Pt(t.createdAt,this.validatedUntilAt,e))return}if(e===om.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=at(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),st(["post","get",e.postId],e)}e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==om.OnPostCreated&&e!==om.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),st(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=({cacheKey:e,resolveId:t})=>[Ol,Al,bm,mm].map((n=>({fn:Pd((a=>((e,t,n,a)=>t((async t=>{var s;const o=null===(s=at(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:om.OnPostUpdated}))),Fm=e=>[{fn:ml,action:om.OnPostCreated},{fn:gl,action:om.OnPostUpdated},{fn:Tm,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Sm,action:om.OnPostReactionAdded},{fn:Om,action:om.OnPostReactionRemoved},{fn:wm,action:om.OnPostDeleted},...Km({cacheKey:e})],_m=(e,t)=>{var n;return null!==(n=e.map((e=>{const n=t.find((t=>t.postId===e.referenceId));return n?Ze("post")({postId:null==n?void 0:n.postId}):void 0})).filter(Pr))&&void 0!==n?n:[]};class Bm extends Rr{constructor(e,t){const n=R.default(e),a=["communityFeed","collection",n];super(new xm(e),n,a,t),this.query=e,this.queryStreamController=new Nm(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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(Fm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.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=ct(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=Rt(this.query.untilAt),n="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";t=t.filter((t=>!Pt(t.createdAt,e,n)))}switch(this.query.sortBy){case"firstCreated":t=t.sort(Ct);break;case"firstUpdated":t=t.sort(Ot);break;case"lastUpdated":t=t.sort(Tt);break;default:t=t.sort(St)}return t}}class $m extends Ve{constructor(e="For You feed is not enabled for this network"){super(e,400400,"error"),this.type="AmityForYouFeedDisabledError"}}class Lm extends Cr{constructor(e){super(e),this.checkedDisk=!1,this.hasDeliveredPost=!1,this.cursor=Xo.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&&Xo.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:pe};e&&(t.token=e);try{const{data:e}=await this.http.get(we,{params:{options:t}});return e}catch(t){if(t instanceof Ve&&400300===t.code)throw new $m;if(t instanceof Ve&&400322===t.code&&void 0!==e){this.cursor&&await this.cursor.clear();const{data:e}=await this.http.get(we,{params:{options:{limit:pe}}});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 Qm extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.posts.map(Ze("post"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ze("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.parentPostId&&!a.data.includes(t.parentPostId)||(e!==om.OnPostDeleted&&e!==om.OnPostDeclined||(a.data=a.data.filter((e=>e!==t.postId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Vm=["forYouFeed","collection"];class Jm extends Rr{constructor(e){const t=`for-you-feed-${Ye().userId}`,n={};super(new Lm(n),t,Vm,e),this.queryStreamController=new Qm(n,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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(Rm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Hm=Object.freeze({__proto__:null,queryGlobalFeed:am,getCustomRankingGlobalFeed:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCustomRankingGlobalFeed(tmpid: ${o}) > listen`);const i=new Pm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getCustomRankingGlobalFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getGlobalFeed:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getGlobalFeed(tmpid: ${o}) > listen`);const i=new km(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getGlobalFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getUserFeed:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getUserFeed(tmpid: ${o}) > listen`);const i=new qm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getUserFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunityFeed:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCommunityFeed(tmpid: ${o}) > listen`);const i=new Bm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getCommunityFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getForYouFeed:e=>{const{log:t,cache:n}=Ye();n||console.log(ve);const a=Date.now();t(`getForYouFeed(tmpid: ${a}) > listen`);const s=new Jm(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>rt(i))),()=>{t(`getForYouFeed(tmpid: ${a}) > dispose`),o.forEach((e=>e()))}},AmityForYouFeedDisabledError:$m});const Gm=async e=>{const t=Ye();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=>{Pe(null==t?void 0:t.code)&&_n("post",e)})),t}const s=Ln(a,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:o}),{data:s.posts.map(hd.post),cachedAt:o}};Gm.locally=e=>{var t;const n=Ye();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const a=e.map((e=>at(["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(hd.post),cachedAt:o.cachedAt}};const zm=async(e,t=!1)=>{var n;const a=Ye(),s=await tl(e);if(await a.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await Hu(s.data.targetId),t=(null!==(n=nt(["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));Nt("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const o=Object.assign(Object.assign({},s.data),{isDeleted:!0});return t?setTimeout((()=>{_n("post",e)}),0):it(["post","get",e],{isDeleted:!0}),Nt("local.post.deleted",{posts:[o],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),hd.post(o)};class Ym extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a,matchingOnlyParentPost:s,untilAt:o}=e,i=Bn(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:oa(a),matchingOnlyParentPost:null!=s?s:!(null==r?void 0:r.length),options:d})});return l}}class Wm extends Sr{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?Rt(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(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=>!Pt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)st(this.cacheKey,{data:o.map(Ze("post"))});else{const e=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Ze("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===om.OnPostCreated||e===om.OnPostApproved)){const e=this.query.sortBy||"lastCreated";if(Pt(t.createdAt,this.validatedUntilAt,e))return}if(t.parentPostId&&t.isDeleted){const e=null===(a=at(["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)),st(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==om.OnPostCreated&&e!==om.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),st(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 Xm extends Rr{constructor(e,t){const n=R.default(e),a=["posts","collection",n];super(new Ym(e),n,a,t),this.query=e,this.queryStreamController=new Wm(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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(Fm(this.cacheKey));if(this.query.excludeBlockUserPosts){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Yo(t),Wo(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.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=ct(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=ht(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=gt(n,this.query.dataTypes)),this.query.untilAt){const e=Rt(this.query.untilAt),t=this.query.sortBy||"lastCreated";n=n.filter((n=>!Pt(n.createdAt,e,t)))}if(this.query.excludeBlockUserPosts&&(n=vt(n)),"firstCreated"===this.query.sortBy)n=n.sort(Ct);else n=n.sort(St);return n}}class Zm extends Cr{async getRequest(e,t){const n=Bn(e,["limit"]),{communityId:a,placement:s}=n,o=Bn(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 eg extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(pa):[]});Fn(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.pins.map(Ze("pin"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Ze("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===om.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class tg extends Rr{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=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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(Km({cacheKey:this.cacheKey,resolveId:e=>`${this.query.placement}#${e}`}))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;let i=(null!==(s=o.data.map((e=>at(["pin","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.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})=>St({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class ng extends Cr{async getRequest(e,t){const n=Bn(e,["limit"]),{data:a}=await this.http.get("/api/v1/pinned-posts/global",{params:Object.assign({},n)});return a}}class ag extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(pa)});Fn(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.pins.map(Ze("pin"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Ze("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===om.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class sg extends Rr{constructor(e,t){const n=R.default(e),a=["pinnedPosts","collection",n];super(new ng(e),n,a,t),this.query=e,this.queryStreamController=new ag(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:wm,action:om.OnPostDeleted},{fn:pl,action:om.OnPostDeleted},...Km({cacheKey:this.cacheKey,resolveId:e=>`global#${e}`})])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["pin","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.pinnedPost);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}}class og extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 ig(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function rg(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class cg extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:ig(e)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...ig(e)])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(a=at(["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)),st(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==om.OnPostCreated&&e!==om.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),st(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class dg extends Rr{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 og(n),a,s,t),this.query=n,this.queryStreamController=new cg(this.query,this.cacheKey,this.notifyChange.bind(this),el),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:gl,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Pd((e=>Ol((async t=>{const n=at(this.cacheKey);rg(null==n?void 0:n.data).includes(t.referenceId)||(await tl(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated},{fn:Pd((e=>Al((async t=>{const n=at(this.cacheKey);rg(null==n?void 0:n.data).includes(t.referenceId)||(await tl(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(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})=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.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=gt(t,this.query.dataTypes)),t}}class lg extends Cr{async getRequest(e,t){const{limit:n=ge,matchingOnlyParentPost:a,hashtags:s,dataTypes:o,targetType:i="all"}=e,r=Bn(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 ug extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.posts.map(Ze("post"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ze("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(a=at(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),st(["post","get",e.postId],e)}e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==om.OnPostCreated&&e!==om.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),st(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class hg extends Rr{constructor(e,t){const n=R.default(e),a=["posts","collection",n];super(new lg(e),n,a,t),this.query=e,this.queryStreamController=new ug(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ml,action:om.OnPostCreated},{fn:gl,action:om.OnPostUpdated},{fn:Tm,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Sm,action:om.OnPostReactionAdded},{fn:Om,action:om.OnPostReactionRemoved},{fn:wm,action:om.OnPostDeleted},{fn:Pd((e=>Ol((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Mm(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated},{fn:Pd((e=>Al((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Mm(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.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=gt(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(Ct);else n=n.sort(St);return n}}class mg extends Ar{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 gg extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:_m(e.rooms,e.posts)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,..._m(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&st(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 pg=e=>{const t=Ye();return xt(t,"room/onRoomStartBroadcasting","room.startBroadcasting",(t=>{Fn(t),e(t.rooms[0])}))},yg=e=>{const t=Ye();return xt(t,"room/onRoomWaitingReconnect","room.waitingReconnect",(t=>{Fn(t),e(t.rooms[0])}))},vg=e=>{const t=Ye();return xt(t,"room/onRoomEndBroadcasting","room.endBroadcasting",(t=>{Fn(t),e(t.rooms[0])}))},fg=e=>{const t=Ye();return xt(t,"room/onRoomRecordedAvailable","room.recordedAvailable",(t=>{Fn(t),e(t.rooms[0])}))},bg=e=>{const t=Ye();return xt(t,"room/onRoomCoHostInvited","room.didCohostInvite",(t=>{const n=nc(t);Fn(n),e(n.invitations)}))},Ig=async e=>{const t=Ye();let n;t.log("room/getRoomById",e),ea("room",e);try{n=(await t.http.get(`/api/v1/rooms/${e}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("room",e),t}const a=t.cache&&Date.now();return t.cache&&Fn(n,{cachedAt:a}),{data:n.rooms[0],cachedAt:a}};Ig.locally=e=>{const t=Ye();t.log("room/getRoomById.locally",e),ea("room",e);const n=t.cache&&Date.now(),a=at(["room","get",e]);if(a)return{data:a.data,cachedAt:n}};const Cg=e=>{const t=Ye();return xt(t,"room/onRoomCoHostInviteAccepted","room.didCohostInviteAccept",(async t=>{var n;const a=nc(t);await Ig(null===(n=a.invitations)||void 0===n?void 0:n[0].targetId),Fn(a),e(a.invitations[0])}))},wg=e=>{const t=Ye();return xt(t,"room/onRoomCoHostInviteRejected","room.didCohostInviteReject",(t=>{const n=nc(t);Fn(n),e(n.invitations)}))},Sg=e=>{const t=Ye();return xt(t,"room/onRoomCoHostInviteCanceled","room.didCohostInviteCancel",(t=>{const n=nc(t);Fn(n),e(n.invitations)}))},Og=e=>{const t=Ye();return xt(t,"room/onRoomParticipantJoined","room.participantJoined",(t=>{const{rooms:n,users:a}=t;Fn({rooms:n,users:a}),e({room:qc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Tg=e=>{const t=Ye();return xt(t,"room/onRoomParticipantLeft","room.participantLeft",(t=>{var n;const{rooms:a,users:s}=t;Fn({rooms:a,users:s});const o=t.eventActor.userInternalId;e({room:qc(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=Ye();return xt(t,"room/onRoomParticipantStageJoined","room.participantStageJoined",(t=>{const{rooms:n,users:a}=t;Fn({rooms:n,users:a}),e({room:qc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Rg=e=>{const t=Ye();return xt(t,"room/onRoomTerminated","room.terminated",(t=>{Fn(t),e(t.rooms[0])}))},Pg=e=>{const t=Ye();return xt(t,"room/onRoomDidUpdate","local.room.didUpdate",(t=>{Fn(t),e(t.rooms[0])}))},Dg=e=>{const t=Ye();return xt(t,"room/onRoomParticipantRemoved","room.participantRemoved",(t=>{var n;const{rooms:a,users:s}=t;Fn({rooms:a,users:s});const o=t.eventActor.userInternalId;e({room:qc(a[0]),actorInternalId:o,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===o)))||void 0===n?void 0:n.userId})}))},Ug=e=>{const t=Ye();return xt(t,"room/onLocalRoomDidUpdate","room.didUpdate",(t=>{Fn(t),e(t.rooms[0])}))},kg=e=>{const t=Ye();return xt(t,"room/onRoomParticipantRemoved","local.room.participantRemoved",(t=>{Fn(t),e(t.rooms[0])}))};var jg;!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"}(jg||(jg={}));const Eg=e=>t=>e((e=>{t(e.room)}));class Mg extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a}=e,s=Bn(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:oa(a),options:i})});return r}}class qg extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.rooms.map(Ze("room"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.rooms.map(Ze("room"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===jg.OnRoomDeleted&&(a.data=a.data.filter((e=>e!==t._id))),e===jg.OnRoomCreated&&(a.data=[...new Set([t._id,...a.data])]),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class xg extends Rr{constructor(e,t){const n=R.default(e),a=["rooms","collection",n];super(new Mg(e),n,a,t),this.query=e,this.queryStreamController=new qg(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:pg,action:jg.OnRoomStartBroadcasting},{fn:vg,action:jg.OnRoomEndBroadcasting},{fn:fg,action:jg.OnRoomUpdated},{fn:yg,action:jg.OnRoomUpdated},{fn:Rg,action:jg.OnRoomUpdated},{fn:Eg(Og),action:jg.OnRoomUpdated},{fn:Eg(Tg),action:jg.OnRoomUpdated},{fn:Eg(Dg),action:jg.OnRoomUpdated},{fn:kg,action:jg.OnRoomUpdated},{fn:Eg(Ag),action:jg.OnRoomUpdated},{fn:Pd(Cg,"targetId","room"),action:jg.OnRoomUpdated},{fn:Pg,action:jg.OnRoomDidUpdate},{fn:Ug,action:jg.OnRoomDidUpdate}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["room","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(qc);(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=ct(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=ct(t,"type",this.query.type)),"firstCreated"===this.query.sortBy)t=t.sort(Ct);else t=t.sort(St);return t}}var Ng=Object.freeze({__proto__:null,createRoom:async e=>{const t=Ye();t.log("room/createRoom",e);const{data:n}=await t.http.post("/api/v1/rooms",e);Nt("local.room.created",n);const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{rooms:s}=n;return{data:qc(s[0]),cachedAt:a}},updateRoom:async(e,t)=>{const n=Ye();n.log("room/updateRoom",{roomId:e,bundle:t});const{data:a}=await n.http.put(`/api/v1/rooms/${e}`,t);Nt("local.room.updated",a);const s=n.cache&&Date.now();n.cache&&Fn(a,{cachedAt:s});const{rooms:o}=a;return{data:qc(o[0]),cachedAt:s}},deleteRoom:async e=>{const t=Ye();t.log("room/deleteRoom",{roomId:e}),await t.http.delete(`/api/v1/rooms/${e}`),Nt("local.room.deleted",{rooms:[{_id:e}]})},stopRoom:async e=>{const t=Ye();t.log("room/stopRoom",{roomId:e});const{data:n}=await t.http.post(`/api/v1/rooms/${e}/stop`);Nt("local.room.stopped",n);const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{rooms:s}=n;return{data:s[0],cachedAt:a}},getBroadcasterData:async e=>{const t=Ye();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=Ye();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=Ye();n.log("room/removeParticipant",{roomId:e,participantUserId:t}),await n.http.delete(`/api/v1/rooms/${e}/participants/${t}`),Nt("local.room.participantRemoved",{rooms:[{_id:e}],users:[{_id:t}]})},leaveRoom:async e=>{const t=Ye();t.log("room/leaveRoom",{roomId:e}),await t.http.post(`/api/v1/rooms/${e}/leave`),Nt("local.room.left",{rooms:[{_id:e}]})},AmityRoomAnalytics:Mc,WatchSessionStorage:Sc,getWatchSessionStorage:Tc,syncWatchSessions:jc,updateCohostPermission:async(e,t,n)=>{const a=Ye();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});Nt("local.room.didUpdate",s);const o=a.cache&&Date.now();a.cache&&Fn(s,{cachedAt:o});const{rooms:i}=s;return{data:qc(i[0]),cachedAt:o}},onRoomStartBroadcasting:pg,onRoomWaitingReconnect:yg,onRoomEndBroadcasting:vg,onRoomRecordedAvailable:fg,onRoomCoHostInvited:bg,onRoomCoHostInviteAccepted:Cg,onRoomCoHostInviteRejected:wg,onRoomCoHostInviteCanceled:Sg,onRoomParticipantJoined:Og,onRoomParticipantLeft:Tg,onRoomParticipantStageLeft:e=>{const t=Ye();return xt(t,"room/onRoomParticipantStageLeft","room.participantStageLeft",(t=>{const{rooms:n,users:a}=t;Fn({rooms:n,users:a}),e({room:qc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},onRoomParticipantStageJoined:Ag,onRoomTerminated:Rg,onRoomDidUpdate:Pg,onRoomCreated:e=>{const t=Ye();return xt(t,"room/onRoomCreated","local.room.created",(t=>{Fn(t),e(t.rooms[0])}))},onRoomUpdated:e=>{const t=Ye();return xt(t,"room/onRoomUpdated","local.room.updated",(t=>{Fn(t),e(t.rooms[0])}))},onRoomDeleted:e=>{const t=Ye();return xt(t,"room/onRoomDeleted","local.room.deleted",(t=>{Fn(t),e(t.rooms[0])}))},onRoomStopped:e=>{const t=Ye();return xt(t,"room/onRoomStopped","local.room.stopped",(t=>{Fn(t),e(t.rooms[0])}))},onRoomParticipantRemoved:Dg,onRoomLeft:e=>{const t=Ye();return xt(t,"room/onRoomLeft","local.room.left",(t=>{Fn(t),e(t.rooms[0])}))},onLocalRoomDidUpdate:Ug,getRoom:(e,t)=>qr(e,t,"_id",Ig,[vg,pg,yg,Rg,fg,Eg(Og),Eg(Tg),Eg(Dg),kg,Eg(Ag),Pd(Cg,"targetId","room"),Pg,Ug],{callbackDataSelector:e=>e?hd.room(e):e}),getRooms:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getRooms(tmpid: ${o}) > listen`);const i=new xg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getRooms(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});class Kg extends Rr{constructor(e){const t={limit:100},n=R.default(t),a=["liveRoomPosts","collection",n];super(new mg(t),n,a,e),this.query=t,this.queryStreamController=new gg(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:vg,action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){return e}}class Fg extends Ar{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 _g extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:_m(e.rooms,e.posts)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,..._m(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&st(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 Bg extends Rr{constructor(e,t){const n=R.default(e),a=["communityLiveRoomPosts","collection",n];super(new Fg(e),n,a,t),this.query=e,this.queryStreamController=new _g(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:vg,action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){return e}}var $g=Object.freeze({__proto__:null,getPostByIds:Gm,createPost:async e=>{const t=Ye();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{attachments:n,attachmentProductTags:a}=e,s=Bn(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}));Nt("post.created",i);const r=Zd(i),c=t.cache&&Date.now();t.cache&&Fn(r,{cachedAt:c});const{posts:d}=r;return{data:hd.post(d[0]),cachedAt:c}},editPost:async(e,t)=>{const n=Ye();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=Ln(o,"communityUsers"),r=n.cache&&Date.now();n.cache&&Fn(i,{cachedAt:r}),Nt("local.post.updated",i);const{posts:c}=i;return{data:hd.post(c.find((t=>t.postId===e))),cachedAt:r}},deletePost:zm,softDeletePost:async e=>{Ye().log("post/softDeletePost",e);const t=await zm(e,!1);return hd.post(t)},hardDeletePost:async e=>{Ye().log("post/hardDeletePost",e);const t=await zm(e,!0);return hd.post(t)},approvePost:async e=>{const t=Ye();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);Nt("post.approved",n),"community"===n.posts[0].targetType&&Nt("community.updated",n);const a=Ln(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:hd.post(a.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=Ye();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&Nt("community.updated",n),Nt("post.declined",n);const a=Ln(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:hd.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async(t,n)=>{const a=Ye();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&&Fn(Ln(i,"communityUsers")),Nt("post.flagged",i),!!i},unflagPost:async e=>{const t=Ye();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Fn(Ln(n,"communityUsers")),Nt("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=Ye();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=Ye();t.log("post/createPost",e);const{attachments:n,attachmentProductTags:a}=e,s=Bn(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}));Nt("post.created",i);const r=Ln(i,"communityUsers"),c=t.cache&&Date.now();t.cache&&Fn(r,{cachedAt:c});const{posts:d}=r;return{data:hd.post(d[0]),cachedAt:c}},createAudioPost:async e=>{const t=Ye();t.log("post/createAudioPost",e);const{attachments:n,attachmentProductTags:a}=e,s=Bn(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}));Nt("post.created",i);const r=Zd(i),c=t.cache&&Date.now();return t.cache&&Fn(r,{cachedAt:c}),{data:Fc(null==r?void 0:r.posts[0]),cachedAt:c}},createMixedMediaPost:async e=>{var t;const n=Ye();n.log("post/createMixedMediaPost",e);const{attachments:a,attachmentProductTags:s}=e,o=Bn(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}));Nt("post.created",r);const c=Zd(r),d=n.cache&&Date.now();return n.cache&&Fn(c,{cachedAt:d}),{data:Fc(null===(t=null==c?void 0:c.posts)||void 0===t?void 0:t[0]),cachedAt:d}},createRoomPost:async e=>{const t=Ye();t.log("post/createRoomPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"room"}));Nt("post.created",n);const a=Zd(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{posts:o}=a;return{data:hd.post(o[0]),cachedAt:s}},createEventPost:async e=>{const t=Ye();t.log("post/createEventPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"event"}));Nt("post.created",n);const a=Zd(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{posts:o}=a;return{data:hd.post(o[0]),cachedAt:s}},pinProduct:async(e,t)=>{const n=Ye();n.log("post/pinProduct",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:t}),s=Zd(a),o=n.cache&&Date.now();return n.cache&&Fn(a,{cachedAt:o}),Nt("local.post.updated",a),{data:Fc(null==s?void 0:s.posts[0]),cachedAt:o}},unpinProduct:async e=>{const t=Ye();t.log("post/unpinProduct",e);const{data:n}=await t.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:null}),a=Zd(n),s=t.cache&&Date.now();return t.cache&&Fn(n,{cachedAt:s}),Nt("local.post.updated",n),{data:Fc(null==a?void 0:a.posts[0]),cachedAt:s}},updateProductTags:async(e,t)=>{const n=Ye();n.log("post/updateProductTags",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{productTags:t}),s=Zd(a),o=n.cache&&Date.now();return n.cache&&Fn(a,{cachedAt:o}),Nt("local.post.updated",a),{data:Fc(null==s?void 0:s.posts[0]),cachedAt:o}},onPostCreated:ml,onPostUpdated:gl,onPostDeleted:pl,onPostApproved:yl,onPostDeclined:vl,onPostFlagged:fl,onPostUnflagged:bl,onPostReactionAdded:Il,onPostReactionRemoved:Cl,getPost:(e,t)=>qr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hd.post(e.data):n}))}),"postId",tl,[yl,vl,Sm,Om,t=>pl((n=>{var a;let s=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(a=at(["post","get",n.parentPostId]))||void 0===a?void 0:a.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),st(["post","get",e.postId],e),s=e)}t(s)})),fl,e=>Il((t=>{e(t)})),e=>Cl((t=>{e(t)})),bl,gl,Tm,wm,Pd((t=>Ol((async n=>{n.referenceId===e&&(await tl(e),t(n))}))),"referenceId","post"),Pd((t=>Al((async n=>{n.referenceId===e&&(await tl(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getPosts(tmpid: ${o}) > listen`);const i=new Xm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getPinnedPosts(tmpid: ${o}) > listen`);const i=new tg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getPinnedPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:a,cache:s}=Ye(),o=Date.now();a(`getGlobalPinnedPosts(tmpid: ${o}) > listen`);const i=new sg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getGlobalPinnedPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`semanticSearchPosts(tmpid: ${o}) > listen`);const i=new dg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`semanticSearchPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchPostsByHashtag:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`searchPostsByHashtag(tmpid: ${o}) > listen`);const i=new hg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`searchPostsByHashtag(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getLiveRoomPosts:e=>{const{log:t,cache:n}=Ye();n||console.log(ve);const a=Date.now();t(`getLiveRoomPosts(tmpid: ${a}) > listen`);const s=new Kg(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>rt(i))),()=>{t(`getLiveRoomPosts(tmpid: ${a}) > dispose`),o.forEach((e=>e()))}},getCommunityLiveRoomPosts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCommunityLiveRoomPosts(tmpid: ${o}) > listen`);const i=new Bg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getCommunityLiveRoomPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});const Lg=async e=>{const t=Ye();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:a}};Lg.locally=e=>{const t=Ye();if(t.log("stream/getStream",e),!t.cache)return;const n=at(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Qg=e=>{const t=Ye();return xt(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Fn(t),e(t.videoStreamings[0])}))},Vg=e=>{const t=Ye();return xt(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Fn(t),e(t.videoStreamings[0])}))},Jg=e=>{const t=Ye();return xt(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Fn(t),e(t.videoStreamings[0])}))},Hg=e=>{const t=Ye();return xt(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Fn(t),e(t.videoStreamings[0])}))},Gg=e=>{const t=Ye();return xt(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Fn(t),e(t.videoStreamings[0])}))},zg=(e,t)=>qr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hd.stream(e.data):n}))}),"streamId",Lg,[Jg,Qg,Vg,Hg,Gg,iu]);zg.locally=e=>{const t=Ye();if(t.log("stream/getStreamById",e),!t.cache)return;const n=at(["stream","get",e]);return n?{data:hd.stream(n.data),cachedAt:n.cachedAt}:void 0};const Yg=async e=>{const t=Ye();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:a,limit:s}=n,o=Bn(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&&Fn(d,{cachedAt:u}),{data:l,cachedAt:u,paging:c}};var Wg=Object.freeze({__proto__:null,createStream:async e=>{const t=Ye();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:hd.stream(s[0]),cachedAt:a}},updateStream:async(e,t)=>{const n=Ye();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&&Fn(a,{cachedAt:s});const{videoStreamings:o}=a;return{data:hd.stream(o.find((t=>t.streamId===e))),cachedAt:s}},deleteStream:async e=>{const t=Ye();t.log("stream/deleteStream",e);const n=await Lg(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 it(["stream","get",e],o),s},disposeStream:async e=>{const t=Ye();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&&Fn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:a}},editStream:async(e,t)=>{const n=Ye();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&&Fn(a,{cachedAt:s});const{videoStreamings:o}=a;return{data:hd.stream(o.find((t=>t.streamId===e))),cachedAt:s}},onStreamStarted:Qg,onStreamStopped:Vg,onStreamRecorded:Jg,onStreamFlagged:Hg,onStreamTerminated:Gg,onStreamViewerBanned:iu,onStreamViewerUnbanned:e=>{const t=Ye();return xt(t,"stream/onStreamViewerDidUnban","video-streaming.viewerDidUnban",(async t=>{var n;const{list:a}=t;await Promise.all(a.map((({streamId:e})=>Lg(e))));const s=null===(n=at(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))},getStreamById:zg,getStreams:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getStreams(tmpid: ${o}) > listen`);const{limit:i}=e,r=Bn(e,["limit"]),c=null!=i?i:ge,{policy:d=ye}=null!=n?n:{},l=[],u=["streams","collection",e],h=t=>{let n=ct(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?St:Ct),n},m=(e,n=!1)=>{var a,s;const o=null!==(a=e.data.map((e=>at(["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=at(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],st(u,n),m(n,!0))},p=(e=!1)=>{var t,n;const a=null===(t=at(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=_e(Yg,Object.assign(Object.assign({},r),{limit:e?c:void 0,page:e||null==a?void 0:a.params.page}));$e(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(Ze("stream"))])]),st(u,o),m(o)}),Be(d))};return l.push(Jg(g()),Qg(g()),Vg(g())),p(!0),()=>{a(`getStreams(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}}});const Xg=async()=>{const e=Ye();e.log("presence/getPresenceSetting");const{data:t}=await e.http.get("/api/v1/presence/settings");return st(["get","presenceSetting"],t),t};class Zg{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 Zg.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 Xg()}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=Ye();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 ep=new Map,tp=e=>{let t=ep.get(e);return t||(t=new Zg(e),ep.set(e,t)),t};var np=Object.freeze({__proto__:null,getRoomOnlineUsers:async e=>{var t,n,a;const s=Ye();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=>md(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=Ye();t.log("roomPresence/getRoomUserCount",{roomId:e});const{data:n}=await t.http.get(`/api/v1/presence/rooms/${e}/users/count`);return st(["get","watchingCount",e],n),n},startHeartbeat:e=>{tp(e).start()},stopHeartbeat:e=>{tp(e).stop(),(e=>{const t=ep.get(e);t&&(t.destroy(),ep.delete(e))})(e)}});const ap=async e=>{const t=Ye();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{polls:s}=n,o=s.find((t=>t.pollId===e));return{data:xc(o),cachedAt:a}};ap.locally=e=>{const t=Ye();if(t.log("poll/getPoll",e),!t.cache)return;const n=at(["poll","get",e]);return n?{data:xc(n.data),cachedAt:n.cachedAt}:void 0};const sp=e=>{const t=Ye();return xt(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Fn(n),e(n.polls[0])}))},op=e=>{const t=Ye();return xt(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Fn(n),e(n.polls[0])}))};var ip=Object.freeze({__proto__:null,createPoll:async e=>{const t=Ye();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{polls:s}=n;return{data:xc(s[0]),cachedAt:a}},closePoll:async e=>{const t=Ye();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&&Fn(n,{cachedAt:a}),Nt("poll.updated",n);const{polls:s}=n,o=s.find((t=>t.pollId===e));return{data:xc(o),cachedAt:a}},deletePoll:async e=>{const t=Ye();t.log("poll/deletePoll",e);const n=await ap(e),{data:a}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=a,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return it(["poll","get",e],o),Nt("poll.deleted",{polls:[o],users:[]}),s},votePoll:async(e,t)=>{const n=Ye();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&&Fn(a,{cachedAt:s});const{polls:o}=a,i=o.find((t=>t.pollId===e));return Nt("poll.updated",a),{data:xc(i),cachedAt:s}},unvotePoll:async e=>{const t=Ye();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&&Fn(n,{cachedAt:a}),Nt("poll.updated",n)},onPollUpdated:sp,onPollDeleted:op,getPoll:(e,t)=>qr(e,t,"pollId",ap,[sp,op])});class rp{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 kc({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=Ye();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 cp=null;class dp{constructor(e,t,n){this._SDKUnsubscribers=[],this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=cp||(cp=new rp,cp),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(iu((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 lp=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 Lg(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 dp(r,i,t).registerEvents(),r}});const up=e=>{const t=(e=>{var t;const n=Ye(),a=new Date,s=a.getTime()+31536e6,o=new Date(s).toISOString();let i=null===(t=at(["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()},Fn({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 Fn(t),t},hp=({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(up(o))}return a(up(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},mp=async e=>{const t=Ye();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),a=dm(n.data);t.cache&&Fn(a),st(["story-sync-state",e.targetId],"synced"),Nt("local.story.created",a);const s=t.cache&&Date.now();return{data:a.stories.length>0?a.stories[0]:void 0,cachedAt:s}},gp=async({targetId:e,targetType:t})=>{var n,a;if(!at(["storyTarget","get",e])){let s={targetId:e,targetType:t};if("community"===t){const t=await Hu(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 Id(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(a=t.data.updatedAt)&&void 0!==a?a:(new Date).toISOString()})}st(["storyTarget","get",e],s)}},pp=e=>e?at(["story","get",e]):{data:void 0,cachedAt:void 0},yp=async(e,t=!1)=>{var n,a,s;const o=Ye();let i;if(o.log("story/deleteStory",e),o.cache&&(i=pp(e),null==i?void 0:i.data)){const{data:o}=i;if(Nt("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},o),{isDeleted:!0})]}),"synced"!==o.syncState){t?rt(["story","get",e]):st(["story","get",e],Object.assign(Object.assign({},i.data),{isDeleted:!0}));const a=null===(n=nt(["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));st(["story-expire",i.data.targetId],e.toISOString())}else rt(["story-expire",i.data.targetId]);return!0}const r=null===(a=at(["storyTarget","get",o.targetId]))||void 0===a?void 0:a.data,c=null===(s=nt(["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&&st(["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},vp=e=>{const t=Ye(),n=[xt(t,"onStoryUpdated","story.updated",(async t=>{const n=dm(t);Fn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},fp=e=>{const t=Ye(),n=[xt(t,"onStoryUpdated","local.story.updated",(async t=>{Fn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},bp=e=>{const t=Ye(),n=[xt(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,a=Bn(t,["reactions"]),s=dm(a),o=rl("story.reactionAdded",Object.assign(Object.assign({},s),{reactions:n}));Fn(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},Ip=e=>{const t=Ye(),n=[xt(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Fn({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Cp=e=>{const t=Ye(),n=[xt(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,a=Bn(t,["reactions"]),s=dm(a),o=rl("story.reactionRemoved",Object.assign(Object.assign({},s),{reactions:n}));Fn(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},wp=e=>{const t=Ye(),n=[xt(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Fn({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Sp=e=>{e.forEach((e=>{const t=at(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||st(["story-expire",e.targetId],n.toISOString())}))},Op=e=>{e.forEach((e=>{st(["story-reference",e.storyId],e.referenceId)}))},Tp=async({targetType:e,targetId:t,options:n})=>{const a=Ye();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=dm(o.data);return a.cache&&(Fn(i),Sp(i.stories),Op(i.stories)),{data:i.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},Ap=e=>{const t=Ye(),n=[xt(t,"onStoryCreated","story.created",(async t=>{const n=dm(t,!0);Fn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Rp=e=>{const t=Ye(),n=[xt(t,"onStoryCreated","local.story.created",(async t=>{Fn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Pp=e=>{const t=Ye(),n=[xt(t,"onStoryDeleted","story.deleted",(async t=>{const n=dm(t);Fn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Dp=e=>{const t=Ye(),n=[xt(t,"onStoryDeleted","local.story.deleted",(async t=>{Fn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Up=e=>{const t=Ye();return xt(t,"onStoryError","local.story.error",(async t=>{Fn(t),e(t.stories)}))},kp=e=>t=>e((e=>t(e[0]))),jp=async e=>{const t=Ye();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:a}=n;return t.cache&&Fn(n.data),{data:a.storyTargets,cachedAt:Date.now()}};class Ep extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.paginationController=a}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now(),a=dm(e);t.cache&&(Fn(a,{cachedAt:n}),Sp(a.stories),Op(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)st(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(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=at(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])],st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Mp extends Ar{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class qp extends Rr{constructor(e,t){const n=R.default(e),a=["story-target-ids","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),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;let o=s.data.map((e=>at(["story","get",e]))).filter(Boolean).map((e=>hd.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(Ct):a.sort(St)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ap,action:"onCreate"},{fn:vp,action:"onUpdate"},{fn:Pp,action:"onDelete"},{fn:Up,action:"onError"}])}}const xp=(e,t)=>{var n,a;const s=null===(n=at(e))||void 0===n?void 0:n.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[];st(e,Object.assign(Object.assign({},s),{data:[...new Set([...o,...t])]}))};class Np extends Sr{constructor(e,t,n,a,s){super(e,t),this.notifyChange=n,this.paginationController=a,this.preparePayload=s}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now(),a=this.preparePayload(e);t.cache&&Fn(a,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?st(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):xp(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&xp(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 Kp extends Cr{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 Fp extends Rr{constructor(e,t){const n=R.default(e),a=["story-global-feed","collection",n],s=new Kp(e);super(s,n,a,t),this.query=e,this.queryStreamController=new Np(this.query,this.cacheKey,this.notifyChange.bind(this),s,(e=>{const t=Bn(_r(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=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=s.data,i=nt(["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=>at(["storyTarget","get",e]))).filter(Boolean).map((e=>hd.storyTarget(e.data)));(this.shouldNotify(r)||"event"!==e)&&(r=this.applyFilter(r).filter((({localSortingDate:e})=>!!e)).map((e=>Bn(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(wt);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(wt)||[],a=t.unseen.sort(wt)||[],s=t.seen.sort(wt)||[];return n.concat(a,s)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ap,action:"onCreate"},{fn:vp,action:"onUpdate"},{fn:Pp,action:"onDelete"},{fn:Rp,action:"onCreate"},{fn:fp,action:"onUpdate"},{fn:Dp,action:"onDelete"},{fn:Up,action:"onError"}])}}var _p=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:kn(),dataType:"image",items:o,targetType:e,targetId:t,metadata:a};const r=new Date;st(["story-sync-state",t],"syncing"),st(["story-expire",t],new Date(r.setFullYear(r.getFullYear()+1))),hp({payload:i,formData:n},(e=>{Nt("local.story.created",e)}));try{const{data:a}=await Bd(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})}),gp({targetId:t,targetType:e}),hp({payload:i,formData:n},(e=>{Nt("local.story.created",e)}));const o=await mp(i);return o.data?Object.assign(Object.assign({},o),{data:hd.story(o.data)}):o}catch(e){throw st(["story-sync-state",t],"error"),hp({payload:Object.assign(Object.assign({},i),{syncState:"error"}),formData:n},(e=>{Nt("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:kn(),dataType:"video",items:s,targetType:e,targetId:t,metadata:a};const i=new Date;st(["story-sync-state",t],"syncing"),st(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),gp({targetId:t,targetType:e}),hp({payload:o,formData:n,isVideo:!0},(e=>{Nt("local.story.created",e)}));try{const{data:e}=await _d(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}})}),hp({payload:o,formData:n,isVideo:!0},(e=>{Nt("local.story.created",e)}));const a=await mp(o);return a.data?Object.assign(Object.assign({},a),{data:hd.story(a.data)}):a}catch(e){throw st(["story-sync-state",t],"error"),hp({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n,isVideo:!0},(e=>{Nt("local.story.error",e)})),e}},hardDeleteStory:async e=>await yp(e,!0),softDeleteStory:async e=>await yp(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:a}=Ye(),s=[],o=["story-target","collection",e],i=Date.now();n(`getActiveStoriesByTarget(tmpid: ${i}) > listen`),a||console.log(ve);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(Ct):t.sort(St):"asc"===o?t.sort(Ot):t.sort(Tt)},c=e=>{var n;const a=e.data.map((e=>{const t=pp(e);if(null==t?void 0:t.data)return hd.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=at(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(Ze("story")):[...new Set([...l.data,...t.map(Ze("story"))])];const u=null===(r=nt(["story","get"]))||void 0===r?void 0:r.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>Ze("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{l.data.includes(e)||l.data.push(e)})),st(o,l.data),c(l)},l=e=>t=>{d(t,e)};return(t=>{const n=_e(Tp,e);$e(n,(({data:e,error:n,loading:a})=>{d(e,"fetch",t,a,n)}))})(!0),s.push(Ap(l("onCreate")),vp(l("onUpdate")),Pp(l("onDelete")),bp(l("onReactionAdded")),Cp(l("onReactionRemoved")),Up(l("onError")),Rp(l("onCreate")),fp(l("onUpdate")),Dp(l("onDelete")),Ip(l("onReactionAdded")),wp(l("onReactionRemoved")),(e=>{const t=Ye();return xt(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=at(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)})),(()=>rt(o))),()=>{n(`getActiveStoriesByTarget(tmpid: ${i}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>qr(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:hd.story(e.data)})):t(e)}),"storyId",lm,[kp(vp),kp(Pp),kp(bp),kp(Cp),kp(Up),kp(fp),kp(Dp),kp(Ip),kp(wp)]),getTargetById:(e,t)=>qr(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:hd.storyTarget(e.data[0])})):t(e)}),"query",(e=>jp([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:a}=Ye(),s=[],o=["storyTargets","collection",e],i=Date.now();n(`getTargetsByTargetIds(tmpid: ${i}) > listen`),a||console.log(ve);const r=(e,n=!1,a=!1,s=!1)=>{const i=at(o),r={loading:a,error:s,params:{page:void 0},data:[]};e&&(r.data=n?e.map(Ze("storyTarget")):[...new Set([...(null==i?void 0:i.data)||[],...e.map(Ze("storyTarget"))])]),st(o,r.data),(e=>{var n;const a=e.data.map((e=>{const t=at(["storyTarget","get",e]);if(null==t?void 0:t.data)return hd.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=_e(jp,e);$e(n,(({data:e,error:n,loading:a})=>{r(e,t,a,n)}))})(!0),s.push((()=>rt(o))),()=>{n(`getTargetsByTargetIds(tmpid: ${i}) > dispose`),s.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getStoriesByTargetIds(tmpid: ${i}) > listen`);const r=new qp(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{rt(d)})),()=>{a(`getStoriesByTargetIds(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getGlobalStoryTarget(tmpid: ${i}) > listen`);const r=new Fp(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{rt(d)})),()=>{a(`getGlobalStoryTarget(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}}});const Bp=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),$p=e=>Object.assign({},e);var Lp=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(Bp),a=t.advertisers.map($p);return Fn({ads:n,advertisers:a,files:t.files}),st(["ad","setting"],t.settings),{ads:n.map(hd.ad),settings:t.settings}}});const Qp=async()=>{const e=Ye();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];st(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}};Qp.locally=()=>{var e;const t=Ye();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:a}=null!==(e=at(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:a}:void 0};const Vp=e=>{const t=Ye(),n=[xt(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Jp extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 Hp extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.notificationTrayItems.map(Ze("notificationTrayItem"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(Ze("notificationTrayItem"))])]}))}}}const Gp=e=>{const t=e.users.map(pa);return Object.assign(Object.assign({},e),{users:t})};class zp extends Rr{constructor(e,t){const n=R.default(e),a=["notificationTrayItem","collection",n];super(new Jp(e),n,a,t),this.query=e,this.queryStreamController=new Hp(this.query,this.cacheKey,this.notifyChange.bind(this),Gp),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["notificationTrayItem","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.notificationTray);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Yp=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=Ut();return qr(t,e,"userId",Qp,[Vp],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Gn(e.lastTraySeenAt)>Gn(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}=Ye();s||console.log(ve);const o=Date.now();a(`getNotificationTrayItems(tmpid: ${o}) > listen`);const i=new zp(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getNotificationTrayItems(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},markItemsSeen:async e=>{const t=Ye();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=at(["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();st(["notificationTrayItem","get"],s,{cachedAt:e})}return s})).filter(Boolean);Nt("local.notificationTrayItem.updated",{notificationTrayItems:a})},markTraySeen:async e=>{var t;const n=Ye();n.log("notificationTray/markTraySeen",{});const{data:a}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),s=null===(t=at(["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&&st(["notificationTraySeen","get",n.userId],i,{cachedAt:r}),Nt("local.notificationTraySeen.updated",o),{data:a,cachedAt:r}},onNotificationTraySeenUpdated:Vp});class Wp extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 Ju(i),o}}class Xp extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.invitations.map(Ze("invitation"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Ze("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===oc.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}if(e===oc.OnLocalInvitationCreated){const e=Ye(),n=t.filter((t=>t.invitedUserId===e.userId));a.data=[...new Set([...n.map((e=>e.invitationId)),...a.data])]}e===oc.OnLocalInvitationCanceled&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Zp extends Rr{constructor(e,t){const n=R.default(e),a=["invitation","collection",n];super(new Wp(e),n,a,t),this.query=e,this.queryStreamController=new Xp(this.query,this.cacheKey,this.notifyChange.bind(this),nc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:cc,action:oc.OnLocalInvitationCreated},{fn:dc,action:oc.OnLocalInvitationUpdated},{fn:lc,action:oc.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["invitation","get",e]))).filter(Pr).map((({data:e})=>ac(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?Ct:St)();return t=t.sort(n),t}}var ey=Object.freeze({__proto__:null,cancelInvitation:async e=>{var t;const n=Ye();n.log("invitation/cancelInvitation",e);const{data:a}=await n.http.delete(`/api/v1/invitations/${e}`),s=null===(t=at(["invitation","get",e]))||void 0===t?void 0:t.data;return _n("invitation",e),s&&Nt("local.invitation.canceled",[s]),a.success},onLocalInvitationCreated:cc,onLocalInvitationUpdated:dc,onLocalInvitationCanceled:lc,getMyCommunityInvitations:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMyCommunityInvitations: (tmpid: ${o}) > listen`);const i=new Zp(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getInvitations (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getInvitations:(e,t)=>{const{_id:n}=$t();if(!n)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=Ye(),{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(hd.invitation))})(a)};return"room"===o&&(r.push(bg(c)),r.push(Cg(c)),r.push(wg(c)),r.push(Sg(c))),()=>{a(`getInvitations(tmpid: ${i}) > dispose for ${o}: ${s}`),r.forEach((e=>e()))}}});const ty=e=>{const t=Ye();return xt(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 ny=Object.freeze({__proto__:null,createReaction:async({referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:s})=>{const o=Ye();if(o.log("live_reaction/createReaction",{referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:s}),!a&&!s)throw new Qe("You have to specify either streamId or roomId",800110,"error");const i=No(),r={reactionName:n,referencePublicId:e,referenceType:t,roomId:s,streamId:a,occurredAt:(new Date).toISOString()};return i.createLiveReaction(r),Nt("local.liveReaction.created",[Object.assign(Object.assign({},r),{userId:o.userId,referenceId:e})]),!0},onLiveReactionCreated:ty,getReactions:(e,t)=>{const{_id:n}=Ut();if(!n)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=Ye();a(`getReactions(tmpid: ${Date.now()}) > listen`);const s=[],o=n=>{(e=>{t(e)})(n.filter((({referenceId:t})=>t===e)))};return s.push(ty(o)),s.push((e=>{const t=Ye();return xt(t,"live_reaction/onLiveReactionCreated","local.liveReaction.created",e)})(o)),()=>{s.forEach((e=>e()))}}});const ay=async e=>{const t=Ye();t.log("event/getEvent",e);try{const{data:n}=await t.http.get(`/api/v1/events/${e}`),a=Jc(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.events.find((t=>t.eventId===e)),cachedAt:s}}catch(n){if(Pe(null==n?void 0:n.code)){const a=ay.locally(e);if(!a)throw n;const s=Object.assign(Object.assign({},null==a?void 0:a.data),{isDeleted:!0});it(["event","get",e],s);return{data:s,cachedAt:t.cache&&Date.now()}}throw n}};ay.locally=e=>{const t=Ye();if(t.log("event/getEvent.locally",e),!t.cache)return;const n=at(["event","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class sy extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 oy extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.events.map(Ze("event"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(Ze("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Yc.OnEventCreated&&(a.data=[...new Set([t.eventId,...a.data])]),e===Yc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class iy extends Rr{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),Jc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Zc,action:Yc.OnEventCreated},{fn:ed,action:Yc.OnEventUpdated},{fn:td,action:Yc.OnEventDeleted},{fn:nd,action:Yc.OnEventCreated},{fn:ad,action:Yc.OnEventUpdated},{fn:sd,action:Yc.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["event","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.event);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}class ry extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 cy extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.events.map(Ze("event"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(Ze("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Yc.OnEventCreated){if(Ye().userId!==t.userId)return;a.data=[...new Set([t.eventId,...a.data])]}e===Yc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class dy extends Rr{constructor(e,t){const n=R.default(e),a=["event","collection",n];super(new ry(e),n,a,t),this.query=e,this.queryStreamController=new cy(this.query,this.cacheKey,this.notifyChange.bind(this),Jc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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:Zc,action:Yc.OnEventCreated},{fn:ed,action:Yc.OnEventUpdated},{fn:td,action:Yc.OnEventDeleted},{fn:nd,action:Yc.OnEventCreated},{fn:ad,action:Yc.OnEventUpdated},{fn:sd,action:Yc.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["event","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.event);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}var ly=Object.freeze({__proto__:null,createEvent:async e=>{const t=Ye();t.log("event/createEvent",e);const{data:n}=await t.http.post("/api/v1/events",e);Nt("local.event.created",n);const a=Jc(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:ud(a.events[0]),cachedAt:s}},updateEvent:async(e,t)=>{const n=Ye();n.log("event/updateEvent",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}`,t);Nt("local.event.updated",a);const s=Jc(a),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),{data:ud(s.events.find((t=>t.eventId===e))),cachedAt:o}},deleteEvent:async e=>{const t=Ye();t.log("event/deleteEvent",e);const n=await ay(e);await t.http.delete(`/api/v1/events/${e}`);const a=Object.assign(Object.assign({},n.data),{isDeleted:!0});it(["event","get",e],a),Nt("local.event.deleted",{users:[],files:[],communities:[],posts:[],rooms:[],events:[a]})},onEventCreated:Zc,onEventUpdated:ed,onEventDeleted:td,onLocalEventCreated:nd,onLocalEventUpdated:ad,onLocalEventDeleted:sd,onRSVPCreated:od,onRSVPUpdated:id,onLocalRSVPCreated:rd,onLocalRSVPUpdated:cd,getEvent:(e,t)=>qr(e,t,"eventId",ay,[ed,td,ad,sd],{callbackDataSelector:e=>e?ud(e):e}),getEvents:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getEvents: (tmpid: ${o}) > listen`);const i=new iy(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getEvents (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getMyEvents:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMyEvents: (tmpid: ${o}) > listen`);const i=new dy(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getMyEvents (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getRSVPs:ld});const uy=async e=>{const t=Ye();let n;t.log("product/getProduct",e),ea("product",e);try{n=(await t.http.get(`/api/v1/products/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("product",e),t}const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{products:s}=n;return{data:s.find((t=>t.productId===e)),cachedAt:a}};uy.locally=e=>{const t=Ye();if(t.log("product/getProduct.locally",e),!t.cache)return;const n=at(["product","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class hy extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(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 my extends Sr{constructor(e,t,n){super(e,t),this.notifyChange=n}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();t.cache&&Fn(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.products.map(Ze("product"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.products.map(Ze("product"))])]}))}}}class gy extends Rr{constructor(e,t){const n=R.default(e),a=["products","collection",n];super(new hy(e),n,a,t),this.query=e,this.queryStreamController=new my(this.query,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(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=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["product","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.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 py=Object.freeze({__proto__:null,getProduct:(e,t)=>qr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hd.product(n):n}))}),"productId",uy,[]),searchProducts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`searchProducts(tmpid: ${o}) > listen`);const i=new gy(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`searchProducts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});return e.API_REGIONS=on,e.AdRepository=Lp,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=nm,e.ChannelRepository=Qu,e.Client=sr,e.CommentRepository=Cm,e.CommunityPostSettingMaps=x,e.CommunityPostSettings=q,e.CommunityRepository=Zh,e.ContentFeedType=F,e.DefaultCommunityPostSetting=N,e.EventRepository=ly,e.FeedRepository=Hm,e.FileRepository=$d,e.FileType=D,e.GET_WATCHER_URLS=fc,e.InvitationRepository=ey,e.LiveReactionRepository=ny,e.LiveStreamPlayer=lp,e.MessageContentType=B,e.MessageRepository=mu,e.PollRepository=ip,e.PostContentType=$,e.PostRepository=$g,e.PostStructureType=L,e.ProductRepository=py,e.ReactionRepository=xl,e.RoomPresenceRepository=np,e.RoomRepository=Ng,e.StoryRepository=_p,e.StreamRepository=Wg,e.SubChannelRepository=Iu,e.UserRepository=Kd,e.VERSION=me,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}=Ye();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=_e,e.createReport=async(e,t,n)=>{const a=Ye();return a.log("report/createReport",{referenceType:e,referenceId:t,options:n}),"user"===e?(async({referenceId:e,options:t})=>!!await gd(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 ha(n);Fn(e)}return Nt("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 Zd(n);Fn(e)}return Nt("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 Nl(n);Fn(e)}return Nt("comment.flagged",n),!!n})({client:a,referenceId:t})},e.createUserToken=async(e,t,n)=>{const a=await En(),s=Mn(),o=yn(cn("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=Ye();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 eo(n);Fn(e)}return Nt("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 ha(n);Fn(e)}return Nt("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 Zd(n);Fn(e)}return Nt("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 Nl(n);Fn(e)}return Nt("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=Ye();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=rt,e.enableCache=(e={},t)=>{const n=Ye();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.exceedsUntilAtBoundary=Pt,e.filterByChannelMembership=ut,e.filterByCommunityMembership=mt,e.filterByFeedType=ht,e.filterByPostDataTypes=gt,e.filterByPropEquality=ct,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=lt,e.filterBySearchTerm=pt,e.filterByStringComparePartially=dt,e.filterByUntilAt=(e,t,n)=>{const a=new Date(t).valueOf();return"firstCreated"===n?e.filter((e=>new Date(e.createdAt).valueOf()<a)):e.filter((e=>new Date(e.createdAt).valueOf()>a))},e.filterCommentsByBlockUsers=ft,e.filterPostsByBlockUsers=vt,e.getBlockUsersId=yt,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=Ut();return`${Vt(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>Qt(t,n),e.getLiveReactionTopic=e=>`${e.path}/liveReaction`,e.getLiveStreamTopic=Zt,e.getMarkedMessageTopic=Gt,e.getMarkerUserFeedTopic=()=>{const e=Ut();return`${Vt(e)}/marker/user/${e._id}`},e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=Jt,e.getMyFollowingsTopic=Ht,e.getNetworkId=Vt,e.getNetworkTopic=zt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Qd,e.getRoomStreamerTopic=e=>{const t=$t();return`${Vt(t)}/room/${e.roomId}/streamer`},e.getRoomWatcherTopic=e=>{const t=$t();return`${Vt(t)}/room/${e._id}`},e.getSmartFeedChannelTopic=Yt,e.getSmartFeedMessageTopic=Xt,e.getSmartFeedSubChannelTopic=Wt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const a=Ut();return`${Vt(a)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=({path:t},n=e.SubscriptionLevels.USER)=>Qt(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),e.isAfterBefore=Ue,e.isAfterBeforeRaw=ke,e.isCachable=Ke,e.isFetcher=qe,e.isFresh=Fe,e.isLocal=e=>Ke(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=xe,e.isOffline=Ne,e.isPaged=je,e.isReportedByMe=async(e,t)=>{const n=Ye();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=De,e.mergeInCache=ot,e.notificationTray=Yp,e.onChannelMarkerFetched=zi,e.onFeedMarkerFetched=e=>{const t=Ye();return xt(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=Ye();return xt(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Fn(t),e(t.feedMarkers[0])}))},e.onMessageMarked=er,e.onMessageMarkerFetched=Zi,e.onSubChannelMarkerFetched=Yi,e.onSubChannelMarkerUpdated=Wi,e.onUserMarkerFetched=Xi,e.onUserMarkerFetchedLegacy=e=>{const t=Ye();return xt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=at,e.pushToCache=st,e.queryCache=nt,e.queryOptions=Be,e.queryRoles=Ld,e.restoreCache=async(e="amitySdk")=>{var t;const n=Ye();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=$e,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=bt,e.sortByFirstCreated=Ct,e.sortByFirstUpdated=Ot,e.sortByLastActivity=At,e.sortByLastCreated=St,e.sortByLastUpdated=Tt,e.sortByLocalSortingDate=wt,e.sortByName=It,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=en,e.toPage=Me,e.toPageRaw=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return ke(n)?n:void 0},e.toToken=Ee,e.upsertInCache=it,e.validateUntilAt=Rt,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:a}=Ye();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);
|