UNPKG

@amityco/ts-sdk-react-native

Version:

Amity Social Cloud Typescript SDK

1 lines 535 kB
var Amity=function(e,t,n,r,s,o,a,i,c,l,d,u){"use strict";function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p=h(n),f=h(r),m=h(s),g=h(o),y=h(a),v=h(i),b=h(c),w=h(d),C=h(u);const I=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video"}),S=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),_=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),k=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var O;e.FileAccessTypeEnum=void 0,(O=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",O.NETWORK="network";const T=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),E=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}}),A="ONLY_ADMIN_CAN_POST",M=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"}),R=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),P=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll"});const U=function(){try{return"v7.2.0-umd"}catch(e){return"__dev__"}}(),j=5,x="cache_then_server",D="For using Live Collection feature you need to enable Cache!",N="Observing unsynced object is not supported by Live Object.",B=-5,q=1e3,F=6e5,L="dead",K=6e4,$=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})),z=e=>JSON.parse(e),Q=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>Q(e[n],t[n])))),V=e=>[400400,400300].includes(e),H=e=>["skip"].some((t=>t in e)),W=e=>["after","before","first","last","limit"].some((t=>t in e)),J=e=>"limit"in e,G=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),Y=(e,n)=>{var r;if(!e||!Object.keys(e).length)return;let s={};return"skiplimit"===n?s={skip:null!==(r=e.after)&&void 0!==r?r:0,limit:e.limit}:"afterbefore"===n&&W(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},Z=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(H(n))return{after:n.skip,limit:n.limit};if(W(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},X=e=>"locally"in e,ee=e=>"optimistically"in e,te=e=>X(e)||ee(e),ne=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),re=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},se=(e,...t)=>({func:e,args:t}),oe=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<K?K:t},ae=({func:e,args:t},n,r=oe("cache_then_server"))=>{let s;const{lifeSpan:o}=oe("cache_then_server",r.lifeSpan);if(te(e)){try{s=ee(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(ie(void 0,{origin:"local",loading:!1,error:e}))}const r=ne(s)&&re(s,o);if(null==n||n(ie(s,{origin:"local",loading:!(X(e)&&r)})),r)return}else null==n||n(ie(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(ie(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(ie(void 0,{origin:"server",loading:!1,error:e}))}))};function ie(e,t){return G(e)||ne(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}const ce={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},le=e=>ce[e],de={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",videoStreamModerations:"streamModeration",follows:"follow",followCounts:"followCount",feeds:"feed",ads:"ad",advertisers:"advertiser",pinTargets:"pinTarget",pins:"pin"};function ue(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}class he 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,he)}}class pe extends he{constructor(e,t,n){super(e,t,n)}}class fe extends he{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class me extends he{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class ge extends he{constructor(e){super(e,800110,"error")}}let ye=null;const ve=()=>{if(!ye)throw new he("There is no active client",8e5,"fatal");return ye},be=e=>{ye=e},we=e=>{const{log:t,cache:n}=ve();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=z(t);return Q(e,n)})).map((e=>n.data[e]))},Ce=e=>{const{log:t,cache:n}=ve();if(!n)return;t("cache/api/pullFromCache",e);const r=$(e);return n.data[r]?n.data[r]:void 0},Ie=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:s}=ve();if(!s)return!1;r("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=$(e);return s.data[o]=Object.assign({key:e,data:t},n),!0},Se=(e,t,n)=>{const{log:r,cache:s}=ve();if(!s)return!1;r("cache/api/mergeInCache",{key:e,mutation:t});const o=Ce(e);if(!o)return!1;const a="function"==typeof t?t(o.data):Object.assign(Object.assign({},o.data),t);return i=o.data,!("updatedAt"in(c=a)&&"updatedAt"in c&&new Date(c.updatedAt)<new Date(i.updatedAt))&&(Ie(e,a,n),!0);var i,c},_e=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:s}=ve();if(!s)return!1;r("cache/api/upsertInCache",{key:e,data:t,options:n});return Ce(e)?Se(e,t,n):Ie(e,t,n)},ke=(e,t=!1)=>{const{log:n,cache:r}=ve();if(!r)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(r.data).map((e=>z(e))).filter((t=>Q(e,t))).map((e=>ke(e,!0))).every((e=>e));const s=$(e);return s in r.data&&(delete r.data[s],!0)},Oe=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,Te=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,Ee=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,Ae=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;if("community"===e.type)return!0;const s=le("channelUsers")({channelId:e.channelPublicId,userId:n}),o=null===(r=Ce(["channelUsers","get",s]))||void 0===r?void 0:r.data;return"member"===t?o&&"none"!==o.membership:!o||"none"===o.membership})),Me=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var r;const s=null===(r=Ce(["feed","get",le("feed")({targetId:e,feedId:n})]))||void 0===r?void 0:r.data;return s&&s.feedType===t})),Re=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;const s=le("communityUsers")({communityId:e.communityId,userId:n}),o=null===(r=Ce(["communityUsers","get",s]))||void 0===r?void 0:r.data;return"member"===t?o&&"member"===o.communityMembership:!o||"none"!==o.communityMembership})),Pe=(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 s=null===(r=Ce(["post","get",n.children[0]]))||void 0===r?void 0:r.data;return(null==t?void 0:t.includes(null==s?void 0:s.dataType))?e:[...e,n]}return e}),[]),Ue=(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))}))},je=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,xe=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,De=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),Ne=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),Be=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),qe=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Fe=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),Le=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf();let Ke=null;const $e=()=>{if(!Ke)throw new he("Connect client first",8e5,"fatal");return Ke},ze=e=>{Ke={_id:e._id,userId:e.userId,path:e.path}};let Qe,Ve=[];const He=e=>{clearTimeout(Qe),Ve.push(e),Qe=setTimeout((()=>{Ve.forEach((e=>e())),Ve=[]}),0)},We=["disconnected","error","connect_error","reconnect_error","reconnect_failed","sessionStateChange","tokenExpired"],Je=["connect","message","disconnect","error","close","end","reconnect","video-streaming.didStart","video-streaming.didRecord","video-streaming.didStop","video-streaming.didFlag","video-streaming.didTerminate"],Ge=(e,t,n,r)=>{const{log:s,emitter:o}=e,a=Date.now();s(`${t}(tmpid: ${a}) > listen`);const i=(...e)=>{s(`${t}(tmpid: ${a}) > trigger`,e);try{r(...e)}catch(e){s(`${t}(tmpid: ${a}) > error`,e)}};return o.on(n,i),()=>{s(`${t}(tmpid: ${a}) > dispose`),o.off(n,i)}},Ye=(e,t)=>{const{emitter:n}=ve();He((()=>{n.emit(e,t)}))};let Ze,Xe;async function et(){var e;const{mqtt:t,emitter:n,token:r}=ve();if(!t)return;const s=null!==(e=null==r?void 0:r.accessToken)&&void 0!==e?e:"",o=$e();Ze===s&&Xe===o._id||(Ze=s,Xe=o._id,await t.connect({accessToken:Ze,userId:Xe}),((e,t)=>{Je.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 tt;e.SubscriptionLevels=void 0,(tt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",tt.POST="post",tt.COMMENT="comment",tt.POST_AND_COMMENT="post_and_comment",tt.USER="user";const nt=(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}},rt=e=>e.path.split("/user/")[0],st=({path:t},n=e.SubscriptionLevels.USER)=>nt(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),ot=({channelId:e,subChannelId:t})=>{const n=$e();return`${rt(n)}/marker/channel/${e}/message/${t}`},at=()=>{const e=$e();return`${rt(e)}/marker/user/${e._id}`},it=()=>rt($e()),ct=()=>{const e=$e();return`${rt(e)}/smartfeed/${e._id}/channels`},lt=()=>{const e=$e();return`${rt(e)}/smartfeed/${e._id}/messagefeeds`},dt=()=>{const e=$e();return`${rt(e)}/smartfeed/${e._id}/messages`};function ut(e,t){const{mqtt:n}=ve();return n?(et(),n.subscribe(e,t)):()=>null}const ht=()=>{const e=$e();return`${rt(e)}/videostreaming`};var pt;const ft="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:mt={}}=ft,gt="production"===(null===(pt=mt.env)||void 0===pt?void 0:pt.NODE_ENV),yt={EU:"eu",SG:"sg",US:"us"},vt={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function bt(e,t){return vt[e].replace("{region}",t)}class wt{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 Ct;var It,St=()=>(Ct||(Ct=new wt),Ct);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(It||(It={}));const _t=new AbortController,kt=e=>{switch(e){case It.UserGlobalBanned:throw new he(e,400312,"fatal");case It.UserDeleted:throw new he(e,400100,"fatal");case It.TokenExpired:throw Ye("tokenExpired","tokenExpired"),new he(e,800403,"fatal");default:throw new he("Request Aborted",8e5,"error")}},Ot=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=m.default.create({baseURL:e,httpAgent:new g.default(t),httpsAgent:new o.HttpsAgent(t),signal:_t.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&&(_t.abort(),kt(It.UserGlobalBanned)),r&&(_t.abort(),kt(It.UserDeleted)),t&&Date.now()>=Date.parse(t)&&(_t.abort(It.UserDeleted),kt(It.TokenExpired))}return e})),n.interceptors.response.use((e=>{const t=new Headers;return Object.entries(e.headers).forEach((([e,n])=>{"string"==typeof n&&t.append(e,n)})),St().setNetworkActivities(new Request(e.request.url,{method:e.request.method,headers:e.request.headers,body:e.request.data}),{data:e.data,status:e.status,statusText:e.statusText,headers:t}),e}),(e=>{var t,n;const{response:r}=e;if(400100===(null==r?void 0:r.data.code)&&Ye("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 fe(e.code);if("error"===e.status)throw new pe(e.message,e.code,"error")})(null==r?void 0:r.data),_t.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 Tt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Et(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function At(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 Mt={exports:{}};Mt.exports=function(){function e(t,n,r){function s(a,i){if(!n[a]){if(!t[a]){if(!i&&At)return At(a);if(o)return o(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[a]={exports:{}};t[a][0].call(l.exports,(function(e){return s(t[a][1][e]||e)}),l,l.exports,e,t,n,r)}return n[a].exports}for(var o=At,a=0;a<r.length;a++)s(r[a]);return s}return e}()({1:[function(e,t,n){(function(n,r){(function(){const s=e("events").EventEmitter,o=e("./store"),a=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 s,o=t;if("publish"===o.cmd&&(o=p(t),s=_(e,o),s))return n&&n(s);e.outgoingStore.put(o,(function(s){if(s)return n&&n(s);r(),k(e,t,n)}))}function A(e){g("nop ::",e)}function M(e,t){let n;const r=this;if(!(this instanceof M))return new M(e,t);for(n in this.options=t||{},b)void 0===this.options[n]?this.options[n]=b[n]:this.options[n]=t[n];g("MqttClient :: options.protocol",t.protocol),g("MqttClient :: options.protocolVersion",t.protocolVersion),g("MqttClient :: options.username",t.username),g("MqttClient :: options.keepalive",t.keepalive),g("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),g("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),g("MqttClient :: options.topicAliasMaximum",t.topicAliasMaximum),this.options.clientId="string"==typeof t.clientId?t.clientId:I(),g("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=5===t.protocolVersion&&t.customHandleAcks?t.customHandleAcks:function(){arguments[3](0)},this.streamBuilder=e,this.messageIdProvider=void 0===this.options.messageIdProvider?new l:this.options.messageIdProvider,this.outgoingStore=t.outgoingStore||new o,this.incomingStore=t.incomingStore||new o,this.queueQoSZero=void 0===t.queueQoSZero||t.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.pingTimer=null,this.connected=!1,this.disconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,t.topicAliasMaximum>0&&(t.topicAliasMaximum>65535?g("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new a(t.topicAliasMaximum)),this.on("connect",(function(){const e=this.queue;function t(){const n=e.shift();g("deliver :: entry %o",n);let s=null;if(!n)return void r._resubscribe();s=n.packet,g("deliver :: call _sendPacket for %o",s);let o=!0;s.messageId&&0!==s.messageId&&(r.messageIdProvider.register(s.messageId)||(o=!1)),o?r._sendPacket(s,(function(e){n.cb&&n.cb(e),t()})):(g("messageId: %d has already used. The message is skipped and removed.",s.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()})),s.call(this),g("MqttClient :: setting up stream"),this._setupStream()}u(M,s),M.prototype._setupStream=function(){const e=this,t=new d,n=c.parser(this.options);let r=null;const s=[];function o(){if(s.length)y(a);else{const e=r;r=null,e()}}function a(){g("work :: getting next packet in queue");const t=s.shift();if(t)g("work :: packet pulled from queue"),e._handlePacket(t,o);else{g("work :: no packets in queue");const e=r;r=null,g("work :: done flag is %s",!!e),e&&e()}}function i(t){g("streamErrorHandler :: error",t.message),w.includes(t.code)?(g("streamErrorHandler :: emitting error"),e.emit("error",t)):A(t)}g("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),g("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),n.on("packet",(function(e){g("parser :: on packet push to packets array."),s.push(e)})),t._write=function(e,t,s){r=s,g("writable stream :: parsing buffer"),n.parse(e),a()},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)},M.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()}},M.prototype._checkDisconnecting=function(e){return this.disconnecting&&(e&&e!==A?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},M.prototype.publish=function(e,t,n,r){g("publish :: message `%s` to topic `%s`",t,e);const s=this.options;if("function"==typeof n&&(r=n,n=null),n=m({qos:0,retain:!1,dup:!1},n),this._checkDisconnecting(r))return this;const o=this,a=function(){let a=0;if((1===n.qos||2===n.qos)&&(a=o._nextId(),null===a))return g("No messageId left"),!1;const i={cmd:"publish",topic:e,payload:t,qos:n.qos,retain:n.retain,messageId:a,dup:n.dup};switch(5===s.protocolVersion&&(i.properties=n.properties),g("publish :: qos",n.qos),n.qos){case 1:case 2:o.outgoing[i.messageId]={volatile:!1,cb:r||A},g("MqttClient:publish: packet cmd: %s",i.cmd),o._sendPacket(i,void 0,n.cbStorePut);break;default:g("MqttClient:publish: packet cmd: %s",i.cmd),o._sendPacket(i,r,n.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!a())&&this._storeProcessingQueue.push({invoke:a,cbStorePut:n.cbStorePut,callback:r}),this},M.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 s=r.resubscribe;let o=t.pop()||A,a=t.pop();const i=this.options.protocolVersion;delete r.resubscribe,"string"==typeof r&&(r=[r]),"function"!=typeof o&&(a=o,o=A);const c=f.validateTopics(r);if(null!==c)return v(o,new Error("Invalid topic "+c)),this;if(this._checkDisconnecting(o))return g("subscribe: discconecting true"),this;const l={qos:0};if(5===i&&(l.nl=!1,l.rap=!1,l.rh=0),a=m(l,a),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<a.qos||s){const e={topic:t,qos:a.qos};5===i&&(e.nl=a.nl,e.rap=a.rap,e.rh=a.rh,e.properties=a.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||s){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=a.properties),g("subscribe: pushing `%s` to subs list",e),n.push(e)}})),!n.length)return o(null,[]),this;const d=function(){const t=e._nextId();if(null===t)return g("No messageId left"),!1;const r={cmd:"subscribe",subscriptions:n,qos:1,retain:!1,dup:!1,messageId:t};if(a.properties&&(r.properties=a.properties),e.options.resubscribe){g("subscribe :: resubscribe true");const t=[];n.forEach((function(n){if(e.options.reconnectPeriod>0){const r={qos:n.qos};5===i&&(r.nl=n.nl||!1,r.rap=n.rap||!1,r.rh=n.rh||0,r.properties=n.properties),e._resubscribeTopics[n.topic]=r,t.push(n.topic)}})),e.messageIdToTopic[r.messageId]=t}return e.outgoing[r.messageId]={volatile:!0,cb:function(e,t){if(!e){const e=t.granted;for(let t=0;t<e.length;t+=1)n[t].qos=e[t]}o(e,n)}},g("subscribe :: call _sendPacket"),e._sendPacket(r),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!d())&&this._storeProcessingQueue.push({invoke:d,callback:o}),this},M.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,s=t.pop();"string"==typeof n&&(n=[n]),"function"!=typeof r&&(s=r,r=A);const o=f.validateTopics(n);if(null!==o)return v(r,new Error("Invalid topic "+o)),this;if(e._checkDisconnecting(r))return this;const a=function(){const t=e._nextId();if(null===t)return g("No messageId left"),!1;const o={cmd:"unsubscribe",qos:1,messageId:t};return"string"==typeof n?o.unsubscriptions=[n]:Array.isArray(n)&&(o.unsubscriptions=n),e.options.resubscribe&&o.unsubscriptions.forEach((function(t){delete e._resubscribeTopics[t]})),"object"==typeof s&&s.properties&&(o.properties=s.properties),e.outgoing[o.messageId]={volatile:!0,cb:r},g("unsubscribe: call _sendPacket"),e._sendPacket(o),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!a())&&this._storeProcessingQueue.push({invoke:a,callback:r}),this},M.prototype.end=function(e,t,n){const r=this;function s(){g("end :: closeStores: closing incoming and outgoing stores"),r.disconnected=!0,r.incomingStore.close((function(e){r.outgoingStore.close((function(t){if(g("end :: closeStores: emitting end"),r.emit("end"),n){const r=e||t;g("end :: closeStores: invoking callback with args"),n(r)}}))})),r._deferredReconnect&&r._deferredReconnect()}function o(){g("end :: (%s) :: finish :: calling _cleanUp with force %s",r.options.clientId,e),r._cleanUp(e,(()=>{g("end :: finish :: calling process.nextTick on closeStores"),y(s.bind(r))}),t)}return g("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(n=t||A,t=e,e=!1,"object"!=typeof t&&(n=t,t=null,"function"!=typeof n&&(n=A))),"object"!=typeof t&&(n=t,t=null),g("end :: cb? %s",!!n),n=n||A,this.disconnecting?(n(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(g("end :: (%s) :: calling finish in 10ms once outgoing is empty",r.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,o,10))):(g("end :: (%s) :: immediately calling finish",r.options.clientId),o()),this)},M.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},M.prototype.reconnect=function(e){g("client reconnect");const t=this,n=function(){e?(t.options.incomingStore=e.incomingStore,t.options.outgoingStore=e.outgoingStore):(t.options.incomingStore=null,t.options.outgoingStore=null),t.incomingStore=t.options.incomingStore||new o,t.outgoingStore=t.options.outgoingStore||new o,t.disconnecting=!1,t.disconnected=!1,t._deferredReconnect=null,t._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=n:n(),this},M.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())},M.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...")},M.prototype._clearReconnect=function(){g("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},M.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())},M.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)}},M.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"))},M.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))},M.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},M.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))},M.prototype._handlePingresp=function(){this.pingResp=!0},M.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)}},M.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)}}))},M.prototype.handleAuth=function(e,t){t()},M.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,s=e.qos,o=e.messageId,a=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",s),s){case 2:i.customHandleAcks(n,r,e,(function(n,r){return n instanceof Error||(r=n,n=null),n?a.emit("error",n):-1===c.indexOf(r)?a.emit("error",new Error("Wrong reason code for pubrec")):void(r?a._sendPacket({cmd:"pubrec",messageId:o,reasonCode:r},t):a.incomingStore.put(e,(function(){a._sendPacket({cmd:"pubrec",messageId:o},t)})))}));break;case 1:i.customHandleAcks(n,r,e,(function(s,i){return s instanceof Error||(i=s,s=null),s?a.emit("error",s):-1===c.indexOf(i)?a.emit("error",new Error("Wrong reason code for puback")):(i||a.emit("message",n,r,e),void a.handleMessage(e,(function(e){if(e)return t&&t(e);a._sendPacket({cmd:"puback",messageId:o,reasonCode:i},t)})))}));break;case 0:this.emit("message",n,r,e),this.handleMessage(e,t);break;default:g("_handlePublish: unknown QoS. Doing nothing.")}},M.prototype.handleMessage=function(e,t){t()},M.prototype._handleAck=function(e){const t=e.messageId,n=e.cmd;let r=null;const s=this.outgoing[t]?this.outgoing[t].cb:null,o=this;let a;if(s){switch(g("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{const n=e.reasonCode;n&&n>0&&16!==n&&(a=new Error("Publish error: "+C[n]),a.code=n,s(a,e)),delete this.outgoing[t],this.outgoingStore.del(e,s),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?(a=new Error("Publish error: "+C[n]),a.code=n,s(a,e)):this._sendPacket(r);break}case"suback":delete this.outgoing[t],this.messageIdProvider.deallocate(t);for(let n=0;n<e.granted.length;n++)if(0!=(128&e.granted[n])){const e=this.messageIdToTopic[t];e&&e.forEach((function(e){delete o._resubscribeTopics[e]}))}this._invokeStoreProcessingQueue(),s(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),s(null);break;default:o.emit("error",new Error("unrecognized packet type"))}this.disconnecting&&0===Object.keys(this.outgoing).length&&this.emit("outgoingEmpty")}else g("_handleAck :: Server sent an ack in error. Ignoring.")},M.prototype._handlePubrel=function(e,t){g("handling pubrel packet"),t=void 0!==t?t:A;const n=e.messageId,r=this,s={cmd:"pubcomp",messageId:n};r.incomingStore.get(e,(function(e,n){e?r._sendPacket(s,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(s,t)})))}))},M.prototype._handleDisconnect=function(e){this.emit("disconnect",e)},M.prototype._nextId=function(){return this.messageIdProvider.allocate()},M.prototype.getLastMessageId=function(){return this.messageIdProvider.getLastAllocated()},M.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},M.prototype._onConnect=function(e){if(this.disconnected)return void this.emit("connect",e);const t=this;function n(){let r=t.outgoingStore.createStream();function s(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function o(){r.destroy(),r=null,t._flushStoreProcessingQueue(),s()}function a(){if(!r)return;t._storeProcessing=!0;const e=r.read(1);let n;e?t._packetIdsDuringStoreProcessing[e.messageId]?a():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),a()}},t._packetIdsDuringStoreProcessing[e.messageId]=!0,t.messageIdProvider.register(e.messageId)?t._sendPacket(e):g("messageId: %d has already used.",e.messageId)):r.once("readable",a)}t.once("close",o),r.on("error",(function(e){s(),t._flushStoreProcessingQueue(),t.removeListener("close",o),t.emit("error",e)})),r.on("end",(function(){let r=!0;for(const e in t._packetIdsDuringStoreProcessing)if(!t._packetIdsDuringStoreProcessing[e]){r=!1;break}r?(s(),t.removeListener("close",o),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):n()})),a()}this.connackPacket=e,this.messageIdProvider.clear(),this._setupPingTimer(),this.connected=!0,n()},M.prototype._invokeStoreProcessingQueue=function(){if(this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1},M.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},M.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=M}).call(this)}).call(this,e("_process"),void 0!==Tt?Tt:"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"),s=e("readable-stream").Transform,o=e("duplexify");let a,i,c,l=!1;function d(){const e=new s;return e._write=function(e,t,n){a.sendSocketMessage({data:e.buffer,success:function(){n()},fail:function(){n(new Error)}})},e._flush=function(e){a.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,a.onSocketOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),a.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)}})),a.onSocketClose((function(){c.end(),c.destroy()})),a.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 a=t.my,a.connectSocket({url:r,protocols:n}),i=d(),c=o.obj(),p(),c}t.exports=f},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(e,t,n){const r=e("net"),s=e("debug")("mqttjs:tcp");function o(e,t){t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost";const n=t.port,o=t.hostname;return s("port %d and host %s",n,o),r.createConnection(n,o)}t.exports=o},{debug:18,net:16}],4:[function(e,t,n){const r=e("tls"),s=e("net"),o=e("debug")("mqttjs:tls");function a(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===s.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,o("port %d host %s rejectUnauthorized %b",t.port,t.host,t.rejectUnauthorized);const n=r.connect(t);function a(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",a)})),n.on("error",a),n}t.exports=a},{debug:18,net:16,tls:16}],5:[function(e,t,n){(function(n){(function(){const{Buffer:r}=e("buffer"),s=e("ws"),o=e("debug")("mqttjs:ws"),a=e("duplexify"),i=e("readable-stream").Transform,c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],l=void 0!==n&&"browser"===n.title||"function"==typeof __webpack_require__;function d(e,t){let n=e.protocol+"://"+e.hostname+":"+e.port+e.path;return"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}function u(e){const t=e;return e.hostname||(t.hostname="localhost"),e.port||("wss"===e.protocol?t.port=443:t.port=80),e.path||(t.path="/"),e.wsOptions||(t.wsOptions={}),l||"wss"!==e.protocol||c.forEach((function(n){Object.prototype.hasOwnProperty.call(e,n)&&!Object.prototype.hasOwnProperty.call(e.wsOptions,n)&&(t.wsOptions[n]=e[n])})),t}function h(e){const t=u(e);if(t.hostname||(t.hostname=t.host),!t.hostname){if("undefined"==typeof document)throw new Error("Could not determine host. Specify host manually.");const e=new URL(document.URL);t.hostname=e.hostname,t.port||(t.port=e.port)}return void 0===t.objectMode&&(t.objectMode=!(!0===t.binary||void 0===t.binary)),t}function p(e,t,n){o("createWebSocket"),o("protocol: "+n.protocolId+" "+n.protocolVersion);const r="MQIsdp"===n.protocolId&&3===n.protocolVersion?"mqttv3.1":"mqtt";return o("creating new Websocket for url: "+t+" and protocol: "+r),new s(t,[r],n.wsOptions)}function f(e,t){const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",r=d(t,e),s=new WebSocket(r,[n]);return s.binaryType="arraybuffer",s}function m(e,t){o("streamBuilder");const n=u(t),r=d(n,e),a=p(e,r,n),i=s.createWebSocketStream(a,n.wsOptions);return i.url=r,a.on("close",(()=>{i.destroy()})),i}function g(e,t){let n;o("browserStreamBuilder");const s=h(t).browserBufferSize||524288,c=t.browserBufferTimeout||1e3,l=!t.objectMode,d=f(e,t),u=m(t,C,I);t.objectMode||(u._writev=w),u.on("close",(()=>{d.close()}));const p=void 0!==d.addEventListener;function m(e,t,n){const r=new i({objectModeMode:e.objectMode});return r._write=t,r._flush=n,r}function g(){n.setReadable(u),n.setWritable(u),n.emit("connect")}function y(){n.end(),n.destroy()}function v(e){n.destroy(e)}function b(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),u.push(t)}function w(e,t){const n=new Array(e.length);for(let t=0;t<e.length;t++)"string"==typeof e[t].chunk?n[t]=r.from(e[t],"utf8"):n[t]=e[t].chunk;this._write(r.concat(n),"binary",t)}function C(e,t,n){d.bufferedAmount>s&&setTimeout(C,c,e,t,n),l&&"string"==typeof e&&(e=r.from(e,"utf8"));try{d.send(e)}catch(e){return n(e)}n()}function I(e){d.close(),e()}return d.readyState===d.OPEN?n=u:(n=n=a(void 0,void 0,t),t.objectMode||(n._writev=w),p?d.addEventListener("open",g):d.onopen=g),n.socket=d,p?(d.addEventListener("close",y),d.addEventListener("error",v),d.addEventListener("message",b)):(d.onclose=y,d.onerror=v,d.onmessage=b),n}t.exports=l?g:m}).call(this)}).call(this,e("_process"))},{_process:50,buffer:17,debug:18,duplexify:20,"readable-stream":69,ws:80}],6:[function(e,t,n){const{Buffer:r}=e("buffer"),s=e("readable-stream").Transform,o=e("duplexify");let a,i,c;function l(){const e=new s;return e._write=function(e,t,n){a.send({data:e.buffer,success:function(){n()},fail:function(e){n(new Error(e))}})},e._flush=function(e){a.close({success:function(){e()}})},e}function d(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function u(e,t){const n="wxs"===e.protocol?"wss":"ws";let r=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(r=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function h(){a.onOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),a.onMessage((function(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),i.push(t)})),a.onClose((function(){c.end(),c.destroy()})),a.onError((function(e){c.destroy(new Error(e.errMsg))}))}function p(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";d(t);const r=u(t,e);a=wx.connectSocket({url:r,protocols:[n]}),i=l(),c=o.obj(),c._destroy=function(e,t){a.close({success:funct