UNPKG

@amityco/ts-sdk-react-native

Version:

Amity Social Cloud Typescript SDK

1 lines 594 kB
var Amity=function(e,t,n,r,a,s,o,i,c,l,d,u){"use strict";function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p,f=h(n),m=h(r),g=h(a),y=h(s),v=h(o),b=h(i),w=h(c),C=h(d),I=h(u);e.MembershipAcceptanceTypeEnum=void 0,(p=e.MembershipAcceptanceTypeEnum||(e.MembershipAcceptanceTypeEnum={})).AUTOMATIC="automatic",p.INVITATION="invitation";const S=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video",CLIP:"clip"}),_=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),k=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),O=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var T;e.FileAccessTypeEnum=void 0,(T=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",T.NETWORK="network";const E=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),A=Object.freeze({ONLY_ADMIN_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!0},ADMIN_REVIEW_POST_REQUIRED:{needApprovalOnPostCreation:!0,onlyAdminCanPost:!1},ANYONE_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!1}}),R="ONLY_ADMIN_CAN_POST",P=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"});var M;e.ContentFlagReasonEnum=void 0,(M=e.ContentFlagReasonEnum||(e.ContentFlagReasonEnum={})).CommunityGuidelines="Against community guidelines",M.HarassmentOrBullying="Harassment or bullying",M.SelfHarmOrSuicide="Self-harm or suicide",M.ViolenceOrThreateningContent="Violence or threatening content",M.SellingRestrictedItems="Selling and promoting restricted items",M.SexualContentOrNudity="Sexual message or nudity",M.SpamOrScams="Spam or scams",M.FalseInformation="False information or misinformation",M.Others="Others";const j=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),U=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll",CLIP:"clip"});var x,D,q,N,B,L,F,K;e.InvitationTypeEnum=void 0,(x=e.InvitationTypeEnum||(e.InvitationTypeEnum={})).CommunityMemberInvite="communityMemberInvite",x.LivestreamInvite="livestreamInvite",e.InvitationStatusEnum=void 0,(D=e.InvitationStatusEnum||(e.InvitationStatusEnum={})).Pending="pending",D.Approved="approved",D.Rejected="rejected",D.Cancelled="cancelled",e.InvitationSortByEnum=void 0,(q=e.InvitationSortByEnum||(e.InvitationSortByEnum={})).FirstCreated="firstCreated",q.LastCreated="lastCreated",e.JoinRequestStatusEnum=void 0,(N=e.JoinRequestStatusEnum||(e.JoinRequestStatusEnum={})).Pending="pending",N.Approved="approved",N.Rejected="rejected",N.Cancelled="cancelled",e.JoinResultStatusEnum=void 0,(B=e.JoinResultStatusEnum||(e.JoinResultStatusEnum={})).Success="success",B.Pending="pending",e.FeedDataTypeEnum=void 0,(L=e.FeedDataTypeEnum||(e.FeedDataTypeEnum={})).Text="text",L.Video="video",L.Image="image",L.File="file",L.LiveStream="liveStream",L.Clip="clip",L.Poll="poll",e.FeedSortByEnum=void 0,(F=e.FeedSortByEnum||(e.FeedSortByEnum={})).LastCreated="lastCreated",F.FirstCreated="firstCreated",F.LastUpdated="lastUpdated",F.FirstUpdated="firstUpdated",e.FeedSourceEnum=void 0,(K=e.FeedSourceEnum||(e.FeedSourceEnum={})).Community="community",K.User="user";const $=function(){try{return"v7.9.1-umd"}catch(e){return"__dev__"}}(),Q=5,z="cache_then_server",V="For using Live Collection feature you need to enable Cache!",H="Observing unsynced object is not supported by Live Object.",J=-5,W=1e3,G=6e5,Y="dead",Z=6e4,X=e=>JSON.stringify(e,((e,t)=>{return"object"==typeof t?(n=t,Object.keys(n).sort().reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:n[t]})),{})):t;var n})),ee=e=>JSON.parse(e),te=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>te(e[n],t[n])))),ne=e=>[400400,400300].includes(e),re=e=>["skip"].some((t=>t in e)),ae=e=>["after","before","first","last","limit"].some((t=>t in e)),se=e=>"limit"in e,oe=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),ie=(e,n)=>{var r;if(!e||!Object.keys(e).length)return;let a={};return"skiplimit"===n?a={skip:null!==(r=e.after)&&void 0!==r?r:0,limit:e.limit}:"afterbefore"===n&&ae(e)?((null==e?void 0:e.before)&&(a=Object.assign(Object.assign({},a),{before:e.before})),(null==e?void 0:e.after)&&(a=Object.assign(Object.assign({},a),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(a=Object.assign(Object.assign({},a),{limit:e.limit}))):"afterbeforeraw"===n&&(a=e),Object.keys(a).length?t.encode(JSON.stringify(a)):void 0},ce=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(re(n))return{after:n.skip,limit:n.limit};if(ae(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},le=e=>"locally"in e,de=e=>"optimistically"in e,ue=e=>le(e)||de(e),he=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),pe=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},fe=(e,...t)=>({func:e,args:t}),me=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<Z?Z:t},ge=({func:e,args:t},n,r=me("cache_then_server"))=>{let a;const{lifeSpan:s}=me("cache_then_server",r.lifeSpan);if(ue(e)){try{a=de(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(ye(void 0,{origin:"local",loading:!1,error:e}))}const r=he(a)&&pe(a,s);if(null==n||n(ye(a,{origin:"local",loading:!(le(e)&&r)})),r)return}else null==n||n(ye(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(ye(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(ye(void 0,{origin:"server",loading:!1,error:e}))}))};function ye(e,t){return oe(e)||he(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}const ve={user:({userId:e})=>e,file:({fileId:e})=>e,role:({roleId:e})=>e,channel:({channelInternalId:e})=>e,subChannel:({subChannelId:e})=>e,channelUsers:({channelId:e,userId:t})=>`${e}#${t}`,message:({messageId:e,referenceId:t})=>null!=t?t:e,messagePreviewChannel:({channelId:e})=>`${e}`,messagePreviewSubChannel:({subChannelId:e})=>`${e}`,channelUnreadInfo:({channelId:e})=>e,subChannelUnreadInfo:({subChannelId:e})=>e,channelUnread:({channelId:e})=>e,channelMarker:({entityId:e,userId:t})=>`${e}#${t}`,subChannelMarker:({entityId:e,feedId:t,userId:n})=>`${e}#${t}#${n}`,messageMarker:({feedId:e,contentId:t,creatorId:n})=>`${e}#${t}#${n}`,feedMarker:({feedId:e,entityId:t})=>`${e}#${t}`,userMarker:({userId:e})=>e,community:({communityId:e})=>e,category:({categoryId:e})=>e,communityUsers:({communityId:e,userId:t})=>`${e}#${t}`,post:({postId:e})=>e,comment:({commentId:e})=>e,commentChildren:({commentId:e})=>e,poll:({pollId:e})=>e,reaction:({referenceType:e,referenceId:t})=>`${e}#${t}`,reactor:({reactionId:e})=>e,stream:({streamId:e})=>e,streamModeration:({streamId:e})=>e,follow:({from:e,to:t})=>`${e}#${t}`,followInfo:({userId:e})=>e,followCount:({userId:e})=>e,feed:({targetId:e,feedId:t})=>`${e}#${t}`,story:({referenceId:e})=>e,storyTarget:({targetId:e})=>e,ad:({adId:e})=>e,advertiser:({advertiserId:e})=>e,pin:({placement:e,referenceId:t})=>`${e}#${t}`,pinTarget:({targetId:e})=>e,notificationTrayItem:({_id:e})=>e,notificationTraySeen:({userId:e})=>e,invitation:({_id:e})=>e,joinRequest:({joinRequestId:e})=>e},be=e=>ve[e],we={users:"user",files:"file",roles:"role",stories:"story",storyTargets:"storyTarget",channels:"channel",messageFeeds:"subChannel",channelUsers:"channelUsers",messages:"message",messagePreviewChannel:"messagePreviewChannel",messagePreviewSubChannel:"messagePreviewSubChannel",channelUnreadInfo:"channelUnreadInfo",subChannelUnreadInfo:"subChannelUnreadInfo",userEntityMarkers:"channelMarker",userFeedMarkers:"subChannelMarker",contentMarkers:"messageMarker",feedMarkers:"feedMarker",userMarkers:"userMarker",communities:"community",categories:"category",communityUsers:"communityUsers",posts:"post",postChildren:"post",comments:"comment",commentChildren:"comment",polls:"poll",reactors:"reactor",reactions:"reaction",videoStreamings:"stream",videoStreamingChildren:"stream",videoStreamModerations:"streamModeration",follows:"follow",followCounts:"followCount",feeds:"feed",ads:"ad",advertisers:"advertiser",pinTargets:"pinTarget",pins:"pin",notificationTrayItems:"notificationTrayItem",invitations:"invitation",joinRequests:"joinRequest"};function Ce(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}class Ie 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,Ie)}}class Se extends Ie{constructor(e,t,n){super(e,t,n)}}class _e extends Ie{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class ke extends Ie{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class Oe extends Ie{constructor(e){super(e,800110,"error")}}let Te=null;const Ee=()=>{if(!Te)throw new Ie("There is no active client",8e5,"fatal");return Te},Ae=e=>{Te=e},Re=e=>{const{log:t,cache:n}=Ee();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=ee(t);return te(e,n)})).map((e=>n.data[e]))},Pe=e=>{const{log:t,cache:n}=Ee();if(!n)return;t("cache/api/pullFromCache",e);const r=X(e);return n.data[r]?n.data[r]:void 0},Me=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:a}=Ee();if(!a)return!1;r("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&a.persistIf&&(n.offline=a.persistIf(e,t));const s=X(e);return a.data[s]=Object.assign({key:e,data:t},n),!0},je=(e,t,n)=>{const{log:r,cache:a}=Ee();if(!a)return!1;r("cache/api/mergeInCache",{key:e,mutation:t});const s=Pe(e);if(!s)return!1;const o="function"==typeof t?t(s.data):Object.assign(Object.assign({},s.data),t);return i=s.data,!("updatedAt"in(c=o)&&"updatedAt"in i&&new Date(c.updatedAt)<new Date(i.updatedAt))&&(Me(e,o,n),!0);var i,c},Ue=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:a}=Ee();if(!a)return!1;r("cache/api/upsertInCache",{key:e,data:t,options:n});return Pe(e)?je(e,t,n):Me(e,t,n)},xe=(e,t=!1)=>{const{log:n,cache:r}=Ee();if(!r)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(r.data).map((e=>ee(e))).filter((t=>te(e,t))).map((e=>xe(e,!0))).every((e=>e));const a=X(e);return a in r.data&&(delete r.data[a],!0)},De=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,qe=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,Ne=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,Be=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;if("community"===e.type)return!0;const a=be("channelUsers")({channelId:e.channelPublicId,userId:n}),s=null===(r=Pe(["channelUsers","get",a]))||void 0===r?void 0:r.data;return"member"===t?s&&"none"!==s.membership:!s||"none"===s.membership})),Le=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var r;const a=null===(r=Pe(["feed","get",be("feed")({targetId:e,feedId:n})]))||void 0===r?void 0:r.data;return a&&a.feedType===t})),Fe=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;const a=be("communityUsers")({communityId:e.communityId,userId:n}),s=null===(r=Pe(["communityUsers","get",a]))||void 0===r?void 0:r.data;return"member"===t?s&&"member"===s.communityMembership:!s||"none"!==s.communityMembership})),Ke=(e,t)=>e.reduce(((e,n)=>{var r;if(null==t?void 0:t.includes(n.dataType))return[...e,n];if(((null==n?void 0:n.children)||[]).length>0){const a=null===(r=Pe(["post","get",n.children[0]]))||void 0===r?void 0:r.data;return(null==t?void 0:t.includes(null==a?void 0:a.dataType))?e:[...e,n]}return e}),[]),$e=(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))}))},Qe=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,ze=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,Ve=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),He=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),Je=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),We=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Ge=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),Ye=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf();let Ze=null;const Xe=()=>{if(!Ze)throw new Ie("Connect client first",8e5,"fatal");return Ze},et=e=>{Ze={_id:e._id,userId:e.userId,path:e.path}};let tt,nt=[];const rt=e=>{clearTimeout(tt),nt.push(e),tt=setTimeout((()=>{nt.forEach((e=>e())),nt=[]}),0)},at=["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"],st=(e,t,n,r)=>{const{log:a,emitter:s}=e,o=Date.now();a(`${t}(tmpid: ${o}) > listen`);const i=(...e)=>{a(`${t}(tmpid: ${o}) > trigger`,e);try{r(...e)}catch(e){a(`${t}(tmpid: ${o}) > error`,e)}};return s.on(n,i),()=>{a(`${t}(tmpid: ${o}) > dispose`),s.off(n,i)}},ot=(e,t)=>{const{emitter:n}=Ee();rt((()=>{n.emit(e,t)}))};let it,ct;async function lt(){var e;const{mqtt:t,emitter:n,token:r}=Ee();if(!t)return;const a=null!==(e=null==r?void 0:r.accessToken)&&void 0!==e?e:"",s=Xe();it===a&&ct===s._id||(it=a,ct=s._id,await t.connect({accessToken:it,userId:ct}),((e,t)=>{at.forEach((n=>{null==e||e.on(n,((...e)=>{t.emit(n,1===e.length?e[0]:e)}))})),e.on("message",((e,n)=>{const r=JSON.parse(n.toString());t.emit(r.eventType,r.data)}))})(t,n))}var dt;e.SubscriptionLevels=void 0,(dt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",dt.POST="post",dt.COMMENT="comment",dt.POST_AND_COMMENT="post_and_comment",dt.USER="user";const ut=(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}},ht=e=>e.path.split("/user/")[0],pt=({path:t},n=e.SubscriptionLevels.USER)=>ut(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),ft=({channelId:e,subChannelId:t})=>{const n=Xe();return`${ht(n)}/marker/channel/${e}/message/${t}`},mt=()=>{const e=Xe();return`${ht(e)}/marker/user/${e._id}`},gt=()=>ht(Xe()),yt=()=>{const e=Xe();return`${ht(e)}/smartfeed/${e._id}/channels`},vt=()=>{const e=Xe();return`${ht(e)}/smartfeed/${e._id}/messagefeeds`},bt=()=>{const e=Xe();return`${ht(e)}/smartfeed/${e._id}/messages`},wt=()=>{const e=Xe();return`${ht(e)}/videostreaming`};function Ct(e,t){const{mqtt:n}=Ee();return n?(lt(),n.subscribe(e,t)):()=>null}var It;const St="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:_t={}}=St,kt="production"===(null===(It=_t.env)||void 0===It?void 0:It.NODE_ENV),Ot={EU:"eu",SG:"sg",US:"us"},Tt={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function Et(e,t){return Tt[e].replace("{region}",t)}class At{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 Rt;var Pt,Mt=()=>(Rt||(Rt=new At),Rt);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(Pt||(Pt={}));const jt=new AbortController,Ut=e=>{switch(e){case Pt.UserGlobalBanned:throw new Ie(e,400312,"fatal");case Pt.UserDeleted:throw new Ie(e,400100,"fatal");case Pt.TokenExpired:throw ot("tokenExpired","tokenExpired"),new Ie(e,800403,"fatal");default:throw new Ie("Request Aborted",8e5,"error")}},xt=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=g.default.create({baseURL:e,httpAgent:new y.default(t),httpsAgent:new s.HttpsAgent(t),signal:jt.signal});return n.defaults.withCredentials=!1,n.interceptors.request.use((e=>{if("/api/v5/sessions"===e.url)return e;if(e.metadata){const{tokenExpiry:t,isGlobalBanned:n,isUserDeleted:r}=e.metadata;n&&(jt.abort(),Ut(Pt.UserGlobalBanned)),r&&(jt.abort(),Ut(Pt.UserDeleted)),t&&Date.now()>=Date.parse(t)&&(jt.abort(Pt.UserDeleted),Ut(Pt.TokenExpired))}return e})),n.interceptors.response.use((e=>{var t;const n=new Headers;Object.entries(e.headers).forEach((([e,t])=>{"string"==typeof t&&n.append(e,t)}));const r=(e.config.baseURL||"")+(e.config.url||""),a=null===(t=e.config.method)||void 0===t?void 0:t.toUpperCase(),s={method:a,headers:e.config.headers};return"GET"!==a&&"HEAD"!==a&&(s.body=e.config.data),Mt().setNetworkActivities(new Request(r,s),{data:e.data,status:e.status,statusText:e.statusText,headers:n}),e}),(e=>{var t,n;const{response:r}=e;if(400100===(null==r?void 0:r.data.code)&&ot("tokenTerminated","terminated"),(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new _e(e.code);if("error"===e.status)throw new Se(e.message,e.code,"error")})(null==r?void 0:r.data),jt.signal.aborted)throw e;throw new Error(null!==(n=null==r?void 0:r.data)&&void 0!==n?n:e)})),n.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},n};var Dt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function qt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Nt(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Bt={exports:{}};Bt.exports=function(){function e(t,n,r){function a(o,i){if(!n[o]){if(!t[o]){if(!i&&Nt)return Nt(o);if(s)return s(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[o]={exports:{}};t[o][0].call(l.exports,(function(e){return a(t[o][1][e]||e)}),l,l.exports,e,t,n,r)}return n[o].exports}for(var s=Nt,o=0;o<r.length;o++)a(r[o]);return a}return e}()({1:[function(e,t,n){(function(n,r){(function(){const a=e("events").EventEmitter,s=e("./store"),o=e("./topic-alias-recv"),i=e("./topic-alias-send"),c=e("mqtt-packet"),l=e("./default-message-id-provider"),d=e("readable-stream").Writable,u=e("inherits"),h=e("reinterval"),p=e("rfdc/default"),f=e("./validations"),m=e("xtend"),g=e("debug")("mqttjs:client"),y=n?n.nextTick:function(e){setTimeout(e,0)},v=r.setImmediate||function(e){y(e)},b={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:3e4,clean:!0,resubscribe:!0},w=["ECONNREFUSED","EADDRINUSE","ECONNRESET","ENOTFOUND"],C={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};function I(){return"mqttjs_"+Math.random().toString(16).substr(2,8)}function S(e,t){if(5===e.options.protocolVersion&&"publish"===t.cmd){let n;t.properties&&(n=t.properties.topicAlias);const r=t.topic.toString();if(e.topicAliasSend)if(n){if(0!==r.length&&(g("applyTopicAlias :: register topic: %s - alias: %d",r,n),!e.topicAliasSend.put(r,n)))return g("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}else 0!==r.length&&(e.options.autoAssignTopicAlias?(n=e.topicAliasSend.getAliasByTopic(r),n?(t.topic="",t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",r,n)):(n=e.topicAliasSend.getLruAlias(),e.topicAliasSend.put(r,n),t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto assign topic: %s - alias: %d",r,n))):e.options.autoUseTopicAlias&&(n=e.topicAliasSend.getAliasByTopic(r),n&&(t.topic="",t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto use topic: %s - alias: %d",r,n))));else if(n)return g("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}}function _(e,t){let n;t.properties&&(n=t.properties.topicAlias);let r=t.topic.toString();if(0===r.length){if(void 0===n)return new Error("Unregistered Topic Alias");if(r=e.topicAliasSend.getTopicByAlias(n),void 0===r)return new Error("Unregistered Topic Alias");t.topic=r}n&&delete t.properties.topicAlias}function k(e,t,n){g("sendPacket :: packet: %O",t),g("sendPacket :: emitting `packetsend`"),e.emit("packetsend",t),g("sendPacket :: writing to stream");const r=c.writeToStream(t,e.stream,e.options);g("sendPacket :: writeToStream result %s",r),!r&&n&&n!==A?(g("sendPacket :: handle events on `drain` once through callback."),e.stream.once("drain",n)):n&&(g("sendPacket :: invoking cb"),n())}function O(e){e&&(g("flush: queue exists? %b",!!e),Object.keys(e).forEach((function(t){"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function T(e){e&&(g("flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(e).forEach((function(t){e[t].volatile&&"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function E(e,t,n,r){g("storeAndSend :: store packet with cmd %s to outgoingStore",t.cmd);let a,s=t;if("publish"===s.cmd&&(s=p(t),a=_(e,s),a))return n&&n(a);e.outgoingStore.put(s,(function(a){if(a)return n&&n(a);r(),k(e,t,n)}))}function A(e){g("nop ::",e)}function R(e,t){let n;const r=this;if(!(this instanceof R))return new R(e,t);for(n in this.options=t||{},b)void 0===this.options[n]?this.options[n]=b[n]:this.options[n]=t[n];g("MqttClient :: options.protocol",t.protocol),g("MqttClient :: options.protocolVersion",t.protocolVersion),g("MqttClient :: options.username",t.username),g("MqttClient :: options.keepalive",t.keepalive),g("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),g("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),g("MqttClient :: options.topicAliasMaximum",t.topicAliasMaximum),this.options.clientId="string"==typeof t.clientId?t.clientId:I(),g("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=5===t.protocolVersion&&t.customHandleAcks?t.customHandleAcks:function(){arguments[3](0)},this.streamBuilder=e,this.messageIdProvider=void 0===this.options.messageIdProvider?new l:this.options.messageIdProvider,this.outgoingStore=t.outgoingStore||new s,this.incomingStore=t.incomingStore||new s,this.queueQoSZero=void 0===t.queueQoSZero||t.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.pingTimer=null,this.connected=!1,this.disconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,t.topicAliasMaximum>0&&(t.topicAliasMaximum>65535?g("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new o(t.topicAliasMaximum)),this.on("connect",(function(){const e=this.queue;function t(){const n=e.shift();g("deliver :: entry %o",n);let a=null;if(!n)return void r._resubscribe();a=n.packet,g("deliver :: call _sendPacket for %o",a);let s=!0;a.messageId&&0!==a.messageId&&(r.messageIdProvider.register(a.messageId)||(s=!1)),s?r._sendPacket(a,(function(e){n.cb&&n.cb(e),t()})):(g("messageId: %d has already used. The message is skipped and removed.",a.messageId),t())}g("connect :: sending queued packets"),t()})),this.on("close",(function(){g("close :: connected set to `false`"),this.connected=!1,g("close :: clearing connackTimer"),clearTimeout(this.connackTimer),g("close :: clearing ping timer"),null!==r.pingTimer&&(r.pingTimer.clear(),r.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),g("close :: calling _setupReconnect"),this._setupReconnect()})),a.call(this),g("MqttClient :: setting up stream"),this._setupStream()}u(R,a),R.prototype._setupStream=function(){const e=this,t=new d,n=c.parser(this.options);let r=null;const a=[];function s(){if(a.length)y(o);else{const e=r;r=null,e()}}function o(){g("work :: getting next packet in queue");const t=a.shift();if(t)g("work :: packet pulled from queue"),e._handlePacket(t,s);else{g("work :: no packets in queue");const e=r;r=null,g("work :: done flag is %s",!!e),e&&e()}}function i(t){g("streamErrorHandler :: error",t.message),w.includes(t.code)?(g("streamErrorHandler :: emitting error"),e.emit("error",t)):A(t)}g("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),g("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),n.on("packet",(function(e){g("parser :: on packet push to packets array."),a.push(e)})),t._write=function(e,t,a){r=a,g("writable stream :: parsing buffer"),n.parse(e),o()},g("_setupStream :: pipe stream to writable stream"),this.stream.pipe(t),this.stream.on("error",i),this.stream.on("close",(function(){g("(%s)stream :: on close",e.options.clientId),T(e.outgoing),g("stream: emit close to MqttClient"),e.emit("close")})),g("_setupStream: sending packet `connect`");const l=Object.create(this.options);if(l.cmd="connect",this.topicAliasRecv&&(l.properties||(l.properties={}),this.topicAliasRecv&&(l.properties.topicAliasMaximum=this.topicAliasRecv.max)),k(this,l),n.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return e.end((()=>this.emit("error",new Error("Packet has no Authentication Method")))),this;this.options.properties.authenticationMethod&&this.options.authPacket&&"object"==typeof this.options.authPacket&&k(this,m({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout((function(){g("!!connectTimeout hit!! Calling _cleanUp with force `true`"),e._cleanUp(!0)}),this.options.connectTimeout)},R.prototype._handlePacket=function(e,t){const n=this.options;if(5===n.protocolVersion&&n.properties&&n.properties.maximumPacketSize&&n.properties.maximumPacketSize<e.length)return this.emit("error",new Error("exceeding packets size "+e.cmd)),this.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),this;switch(g("_handlePacket :: emitting packetreceive"),this.emit("packetreceive",e),e.cmd){case"publish":this._handlePublish(e,t);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":this._handleAck(e),t();break;case"pubrel":this._handlePubrel(e,t);break;case"connack":this._handleConnack(e),t();break;case"auth":this._handleAuth(e),t();break;case"pingresp":this._handlePingresp(e),t();break;case"disconnect":this._handleDisconnect(e),t()}},R.prototype._checkDisconnecting=function(e){return this.disconnecting&&(e&&e!==A?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},R.prototype.publish=function(e,t,n,r){g("publish :: message `%s` to topic `%s`",t,e);const a=this.options;if("function"==typeof n&&(r=n,n=null),n=m({qos:0,retain:!1,dup:!1},n),this._checkDisconnecting(r))return this;const s=this,o=function(){let o=0;if((1===n.qos||2===n.qos)&&(o=s._nextId(),null===o))return g("No messageId left"),!1;const i={cmd:"publish",topic:e,payload:t,qos:n.qos,retain:n.retain,messageId:o,dup:n.dup};switch(5===a.protocolVersion&&(i.properties=n.properties),g("publish :: qos",n.qos),n.qos){case 1:case 2:s.outgoing[i.messageId]={volatile:!1,cb:r||A},g("MqttClient:publish: packet cmd: %s",i.cmd),s._sendPacket(i,void 0,n.cbStorePut);break;default:g("MqttClient:publish: packet cmd: %s",i.cmd),s._sendPacket(i,r,n.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,cbStorePut:n.cbStorePut,callback:r}),this},R.prototype.subscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];const n=[];let r=t.shift();const a=r.resubscribe;let s=t.pop()||A,o=t.pop();const i=this.options.protocolVersion;delete r.resubscribe,"string"==typeof r&&(r=[r]),"function"!=typeof s&&(o=s,s=A);const c=f.validateTopics(r);if(null!==c)return v(s,new Error("Invalid topic "+c)),this;if(this._checkDisconnecting(s))return g("subscribe: discconecting true"),this;const l={qos:0};if(5===i&&(l.nl=!1,l.rap=!1,l.rh=0),o=m(l,o),Array.isArray(r)?r.forEach((function(t){if(g("subscribe: array topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<o.qos||a){const e={topic:t,qos:o.qos};5===i&&(e.nl=o.nl,e.rap=o.rap,e.rh=o.rh,e.properties=o.properties),g("subscribe: pushing topic `%s` and qos `%s` to subs list",e.topic,e.qos),n.push(e)}})):Object.keys(r).forEach((function(t){if(g("subscribe: object topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<r[t].qos||a){const e={topic:t,qos:r[t].qos};5===i&&(e.nl=r[t].nl,e.rap=r[t].rap,e.rh=r[t].rh,e.properties=o.properties),g("subscribe: pushing `%s` to subs list",e),n.push(e)}})),!n.length)return s(null,[]),this;const d=function(){const t=e._nextId();if(null===t)return g("No messageId left"),!1;const r={cmd:"subscribe",subscriptions:n,qos:1,retain:!1,dup:!1,messageId:t};if(o.properties&&(r.properties=o.properties),e.options.resubscribe){g("subscribe :: resubscribe true");const t=[];n.forEach((function(n){if(e.options.reconnectPeriod>0){const r={qos:n.qos};5===i&&(r.nl=n.nl||!1,r.rap=n.rap||!1,r.rh=n.rh||0,r.properties=n.properties),e._resubscribeTopics[n.topic]=r,t.push(n.topic)}})),e.messageIdToTopic[r.messageId]=t}return e.outgoing[r.messageId]={volatile:!0,cb:function(e,t){if(!e){const e=t.granted;for(let t=0;t<e.length;t+=1)n[t].qos=e[t]}s(e,n)}},g("subscribe :: call _sendPacket"),e._sendPacket(r),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!d())&&this._storeProcessingQueue.push({invoke:d,callback:s}),this},R.prototype.unsubscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];let n=t.shift(),r=t.pop()||A,a=t.pop();"string"==typeof n&&(n=[n]),"function"!=typeof r&&(a=r,r=A);const s=f.validateTopics(n);if(null!==s)return v(r,new Error("Invalid topic "+s)),this;if(e._checkDisconnecting(r))return this;const o=function(){const t=e._nextId();if(null===t)return g("No messageId left"),!1;const s={cmd:"unsubscribe",qos:1,messageId:t};return"string"==typeof n?s.unsubscriptions=[n]:Array.isArray(n)&&(s.unsubscriptions=n),e.options.resubscribe&&s.unsubscriptions.forEach((function(t){delete e._resubscribeTopics[t]})),"object"==typeof a&&a.properties&&(s.properties=a.properties),e.outgoing[s.messageId]={volatile:!0,cb:r},g("unsubscribe: call _sendPacket"),e._sendPacket(s),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,callback:r}),this},R.prototype.end=function(e,t,n){const r=this;function a(){g("end :: closeStores: closing incoming and outgoing stores"),r.disconnected=!0,r.incomingStore.close((function(e){r.outgoingStore.close((function(t){if(g("end :: closeStores: emitting end"),r.emit("end"),n){const r=e||t;g("end :: closeStores: invoking callback with args"),n(r)}}))})),r._deferredReconnect&&r._deferredReconnect()}function s(){g("end :: (%s) :: finish :: calling _cleanUp with force %s",r.options.clientId,e),r._cleanUp(e,(()=>{g("end :: finish :: calling process.nextTick on closeStores"),y(a.bind(r))}),t)}return g("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(n=t||A,t=e,e=!1,"object"!=typeof t&&(n=t,t=null,"function"!=typeof n&&(n=A))),"object"!=typeof t&&(n=t,t=null),g("end :: cb? %s",!!n),n=n||A,this.disconnecting?(n(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(g("end :: (%s) :: calling finish in 10ms once outgoing is empty",r.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,s,10))):(g("end :: (%s) :: immediately calling finish",r.options.clientId),s()),this)},R.prototype.removeOutgoingMessage=function(e){const t=this.outgoing[e]?this.outgoing[e].cb:null;return delete this.outgoing[e],this.outgoingStore.del({messageId:e},(function(){t(new Error("Message removed"))})),this},R.prototype.reconnect=function(e){g("client reconnect");const t=this,n=function(){e?(t.options.incomingStore=e.incomingStore,t.options.outgoingStore=e.outgoingStore):(t.options.incomingStore=null,t.options.outgoingStore=null),t.incomingStore=t.options.incomingStore||new s,t.outgoingStore=t.options.outgoingStore||new s,t.disconnecting=!1,t.disconnected=!1,t._deferredReconnect=null,t._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=n:n(),this},R.prototype._reconnect=function(){g("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end((()=>{this._setupStream()})),g("client already connected. disconnecting first.")):(g("_reconnect: calling _setupStream"),this._setupStream())},R.prototype._setupReconnect=function(){const e=this;!e.disconnecting&&!e.reconnectTimer&&e.options.reconnectPeriod>0?(this.reconnecting||(g("_setupReconnect :: emit `offline` state"),this.emit("offline"),g("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),g("_setupReconnect :: setting reconnectTimer for %d ms",e.options.reconnectPeriod),e.reconnectTimer=setInterval((function(){g("reconnectTimer :: reconnect triggered!"),e._reconnect()}),e.options.reconnectPeriod)):g("_setupReconnect :: doing nothing...")},R.prototype._clearReconnect=function(){g("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},R.prototype._cleanUp=function(e,t){const n=arguments[2];if(t&&(g("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",t)),g("_cleanUp :: forced? %s",e),e)0===this.options.reconnectPeriod&&this.options.clean&&O(this.outgoing),g("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const e=m({cmd:"disconnect"},n);g("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(e,v.bind(null,this.stream.end.bind(this.stream)))}this.disconnecting||(g("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),null!==this.pingTimer&&(g("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),t&&!this.connected&&(g("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",t),t())},R.prototype._sendPacket=function(e,t,n){g("_sendPacket :: (%s) :: start",this.options.clientId),n=n||A,t=t||A;const r=S(this,e);if(r)t(r);else{if(!this.connected)return"auth"===e.cmd?(this._shiftPingInterval(),void k(this,e,t)):(g("_sendPacket :: client not connected. Storing packet offline."),void this._storePacket(e,t,n));switch(this._shiftPingInterval(),e.cmd){case"publish":break;case"pubrel":return void E(this,e,t,n);default:return void k(this,e,t)}switch(e.qos){case 2:case 1:E(this,e,t,n);break;default:k(this,e,t)}g("_sendPacket :: (%s) :: end",this.options.clientId)}},R.prototype._storePacket=function(e,t,n){g("_storePacket :: packet: %o",e),g("_storePacket :: cb? %s",!!t),n=n||A;let r=e;if("publish"===r.cmd){r=p(e);const n=_(this,r);if(n)return t&&t(n)}0===(r.qos||0)&&this.queueQoSZero||"publish"!==r.cmd?this.queue.push({packet:r,cb:t}):r.qos>0?(t=this.outgoing[r.messageId]?this.outgoing[r.messageId].cb:null,this.outgoingStore.put(r,(function(e){if(e)return t&&t(e);n()}))):t&&t(new Error("No connection to broker"))},R.prototype._setupPingTimer=function(){g("_setupPingTimer :: keepalive %d (seconds)",this.options.keepalive);const e=this;!this.pingTimer&&this.options.keepalive&&(this.pingResp=!0,this.pingTimer=h((function(){e._checkPing()}),1e3*this.options.keepalive))},R.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},R.prototype._checkPing=function(){g("_checkPing :: checking ping..."),this.pingResp?(g("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(g("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},R.prototype._handlePingresp=function(){this.pingResp=!0},R.prototype._handleConnack=function(e){g("_handleConnack");const t=this.options,n=5===t.protocolVersion?e.reasonCode:e.returnCode;if(clearTimeout(this.connackTimer),delete this.topicAliasSend,e.properties){if(e.properties.topicAliasMaximum){if(e.properties.topicAliasMaximum>65535)return void this.emit("error",new Error("topicAliasMaximum from broker is out of range"));e.properties.topicAliasMaximum>0&&(this.topicAliasSend=new i(e.properties.topicAliasMaximum))}e.properties.serverKeepAlive&&t.keepalive&&(t.keepalive=e.properties.serverKeepAlive,this._shiftPingInterval()),e.properties.maximumPacketSize&&(t.properties||(t.properties={}),t.properties.maximumPacketSize=e.properties.maximumPacketSize)}if(0===n)this.reconnecting=!1,this._onConnect(e);else if(n>0){const e=new Error("Connection refused: "+C[n]);e.code=n,this.emit("error",e)}},R.prototype._handleAuth=function(e){const t=this.options.protocolVersion,n=5===t?e.reasonCode:e.returnCode;if(5!==t){const e=new Error("Protocol error: Auth packets are only supported in MQTT 5. Your version:"+t);return e.code=n,void this.emit("error",e)}const r=this;this.handleAuth(e,(function(e,t){if(e)r.emit("error",e);else if(24===n)r.reconnecting=!1,r._sendPacket(t);else{const t=new Error("Connection refused: "+C[n]);e.code=n,r.emit("error",t)}}))},R.prototype.handleAuth=function(e,t){t()},R.prototype._handlePublish=function(e,t){g("_handlePublish: packet %o",e),t=void 0!==t?t:A;let n=e.topic.toString();const r=e.payload,a=e.qos,s=e.messageId,o=this,i=this.options,c=[0,16,128,131,135,144,145,151,153];if(5===this.options.protocolVersion){let t;if(e.properties&&(t=e.properties.topicAlias),void 0!==t)if(0===n.length){if(!(t>0&&t<=65535))return g("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));{const e=this.topicAliasRecv.getTopicByAlias(t);if(!e)return g("_handlePublish :: unregistered topic alias. alias: %d",t),void this.emit("error",new Error("Received unregistered Topic Alias"));n=e,g("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",n,t)}}else{if(!this.topicAliasRecv.put(n,t))return g("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));g("_handlePublish :: registered topic: %s - alias: %d",n,t)}}switch(g("_handlePublish: qos %d",a),a){case 2:i.customHandleAcks(n,r,e,(function(n,r){return n instanceof Error||(r=n,n=null),n?o.emit("error",n):-1===c.indexOf(r)?o.emit("error",new Error("Wrong reason code for pubrec")):void(r?o._sendPacket({cmd:"pubrec",messageId:s,reasonCode:r},t):o.incomingStore.put(e,(function(){o._sendPacket({cmd:"pubrec",messageId:s},t)})))}));break;case 1:i.customHandleAcks(n,r,e,(function(a,i){return a instanceof Error||(i=a,a=null),a?o.emit("error",a):-1===c.indexOf(i)?o.emit("error",new Error("Wrong reason code for puback")):(i||o.emit("message",n,r,e),void o.handleMessage(e,(function(e){if(e)return t&&t(e);o._sendPacket({cmd:"puback",messageId:s,reasonCode:i},t)})))}));break;case 0:this.emit("message",n,r,e),this.handleMessage(e,t);break;default:g("_handlePublish: unknown QoS. Doing nothing.")}},R.prototype.handleMessage=function(e,t){t()},R.prototype._handleAck=function(e){const t=e.messageId,n=e.cmd;let r=null;const a=this.outgoing[t]?this.outgoing[t].cb:null,s=this;let o;if(a){switch(g("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{const n=e.reasonCode;n&&n>0&&16!==n&&(o=new Error("Publish error: "+C[n]),o.code=n,a(o,e)),delete this.outgoing[t],this.outgoingStore.del(e,a),this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue();break}case"pubrec":{r={cmd:"pubrel",qos:2,messageId:t};const n=e.reasonCode;n&&n>0&&16!==n?(o=new Error("Publish error: "+C[n]),o.code=n,a(o,e)):this._sendPacket(r);break}case"suback":delete this.outgoing[t],this.messageIdProvider.deallocate(t);for(let n=0;n<e.granted.length;n++)if(0!=(128&e.granted[n])){const e=this.messageIdToTopic[t];e&&e.forEach((function(e){delete s._resubscribeTopics[e]}))}this._invokeStoreProcessingQueue(),a(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),a(null);break;default:s.emit("error",new Error("unrecognized packet type"))}this.disconnecting&&0===Object.keys(this.outgoing).length&&this.emit("outgoingEmpty")}else g("_handleAck :: Server sent an ack in error. Ignoring.")},R.prototype._handlePubrel=function(e,t){g("handling pubrel packet"),t=void 0!==t?t:A;const n=e.messageId,r=this,a={cmd:"pubcomp",messageId:n};r.incomingStore.get(e,(function(e,n){e?r._sendPacket(a,t):(r.emit("message",n.topic,n.payload,n),r.handleMessage(n,(function(e){if(e)return t(e);r.incomingStore.del(n,A),r._sendPacket(a,t)})))}))},R.prototype._handleDisconnect=function(e){this.emit("disconnect",e)},R.prototype._nextId=function(){return this.messageIdProvider.allocate()},R.prototype.getLastMessageId=function(){return this.messageIdProvider.getLastAllocated()},R.prototype._resubscribe=function(){g("_resubscribe");const e=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||5===this.options.protocolVersion&&!this.connackPacket.sessionPresent)&&e.length>0)if(this.options.resubscribe)if(5===this.options.protocolVersion){g("_resubscribe: protocolVersion 5");for(let t=0;t<e.length;t++){const n={};n[e[t]]=this._resubscribeTopics[e[t]],n.resubscribe=!0,this.subscribe(n,{properties:n[e[t]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1},R.prototype._onConnect=function(e){if(this.disconnected)return void this.emit("connect",e);const t=this;function n(){let r=t.outgoingStore.createStream();function a(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function s(){r.destroy(),r=null,t._flushStoreProcessingQueue(),a()}function o(){if(!r)return;t._storeProcessing=!0;const e=r.read(1);let n;e?t._packetIdsDuringStoreProcessing[e.messageId]?o():t.disconnecting||t.reconnectTimer?r.destroy&&r.destroy():(n=t.outgoing[e.messageId]?t.outgoing[e.messageId].cb:null,t.outgoing[e.messageId]={volatile:!1,cb:function(e,t){n&&n(e,t),o()}},t._packetIdsDuringStoreProcessing[e.messageId]=!0,t.messageIdProvider.register(e.messageId)?t._sendPacket(e):g("messageId: %d has already used.",e.messageId)):r.once("readable",o)}t.once("close",s),r.on("error",(function(e){a(),t._flushStoreProcessingQueue(),t.removeListener("close",s),t.emit("error",e)})),r.on("end",(function(){let r=!0;for(const e in t._packetIdsDuringStoreProcessing)if(!t._packetIdsDuringStoreProcessing[e]){r=!1;break}r?(a(),t.removeListener("close",s),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):n()})),o()}this.connackPacket=e,this.messageIdProvider.clear(),this._setupPingTimer(),this.connected=!0,n()},R.prototype._invokeStoreProcessingQueue=function(){if(this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1},R.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},R.prototype._flushStoreProcessingQueue=function(){for(const e of this._storeProcessingQueue)e.cbStorePut&&e.cbStorePut(new Error("Connection closed")),e.callback&&e.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)},t.exports=R}).call(this)}).call(this,e("_process"),void 0!==Dt?Dt:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-message-id-provider":7,"./store":8,"./topic-alias-recv":9,"./topic-alias-send":10,"./validations":11,_process:50,debug:18,events:22,inherits:24,"mqtt-packet":40,"readable-stream":69,reinterval:70,"rfdc/default":71,xtend:81}],2:[function(e,t,n){const{Buffer:r}=e("buffer"),a=e("readable-stream").Transform,s=e("duplexify");let o,i,c,l=!1;function d(){const e=new a;return e._write=function(e,t,n){o.sendSocketMessage({data:e.buffer,success:function(){n()},fail:function(){n(new Error)}})},e._flush=function(e){o.closeSocket({success:function(){e()}})},e}function u(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function h(e,t){const n="alis"===e.protocol?"wss":"ws";let r=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(r=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function p(){l||(l=!0,o.onSocketOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),o.onSocketMessage((function(e){if("string"==typeof e.data){const t=r.from(e.data,"base64");i.push(t)}else{const t=new FileReader;t.addEventListener("load",(function(){let e=t.result;e=e instanceof ArrayBuffer?r.from(e):r.from(e,"utf8"),i.push(e)})),t.readAsArrayBuffer(e.data)}})),o.onSocketClose((function(){c.end(),c.destroy()})),o.onSocketError((function(e){c.destroy(e)})))}function f(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";u(t);const r=h(t,e);return o=t.my,o.connectSocket({url:r,protocols:n}),i=d(),c=s.obj(),p(),c}t.exports=f},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(e,t,n){const r=e("net"),a=e("debug")("mqttjs:tcp");function s(e,t){t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost";const n=t.port,s=t.hostname;return a("port %d and host %s",n,s),r.createConnection(n,s)}t.exports=s},{debug:18,net:16}],4:[function(e,t,n){const r=e("tls"),a=e("net"),s=e("debug")("mqttjs:tls");function o(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===a.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,s("port %d host %s rejectUnauthorized %b",t.port,t.host,t.rejectUnauthorized);const n=r.connect(t);function o(r){t.rejectUnauthorized&&e.emit("error",r),n.end()}return n.on("secureConnect",(function(){t.rejectUnauthorized&&!n.authorized?n.emit("error",new Error("TLS not authorized")):n.removeListener("error",o)})),n.on("error",o),n}t.exports=o},{debug:18,net:16,tls:16}],5:[function(e,t,n){(function(n){(function(){const{Buffer:r}=e("buffer"),a=e("ws"),s=e("debug")("mqttjs:ws"),o=e("duplexify"),i=e("readable-stream").Transform,c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],l=void 0!==n&&"browser"===n.title||"function"==typeof __webpack_require__;function d(e,t){let n=e.protocol+"://"+e.hostname+":"+e.port+e.path;return"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}function u(e){const t=e;return e.hostname||(t.hostname="localhost"),e.port||("wss"===e.protocol?t.port=443:t.port=80),e.path||(t.path="/"),e.wsOptions||(t.wsOptions={}),l||"wss"!==e.protocol||c.forEach((function(n){Object.prototype.hasOwnProperty.call(e,n)&&!Object.prototype.hasOwnProperty.call(e.wsOptions,n)&&(t.wsOptions[n]=e[n])})),t}function h(e){const t=u(e);if(t.hostname||(t.hostname=t.host),!t.hostname){if("undefined"==typeof document)throw new Error("Could not determine host. Specify host manually.");const e=new URL(document.URL);t.hostname=e.hostname,t.port||(t.port=e.port)}return void 0===t.objectMode&&(t.objectMode=!(!0===t.binary||void 0===t.binary)),t}function p(e,t,n){s("createWebSocket"),s("protocol: "+n.protocolId+" "+n.protocolVersion);const r="MQIsdp"===n.protocolId&&3===n.protocolVersion?"mqttv3.1":"mqtt";return s("creating new Websocket for url: "+t+" and protocol: "+r),new a(t,[r],n.wsOptions)}function f(e,t){const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",r=d(t,e),a=new WebSocket(r,[n]);return a.binaryType="arraybuffer",a}function m(e,t){s("streamBuilder");const n=u(t),r=d(n,e),o=p(e,r,n),i=a.createWebSocketStream(o,n.wsOptions);return i.url=r,o.on("close",(()=>{i.destroy()})),i}function g(e,t){let n;s("browserStreamBuilder");const a=h(t).browserBufferSize||524288,c=t.browserBufferTimeout||1e3,l=!t.objectMode,d=f(e,t),u=m(t,C,I);t.objectMode||(u._writev=w),u.on("close",(()=>{d.close()}));const p=void 0!==d.add