diff --git a/css/base.css b/css/base.css index 0463dc1b..9e0c0858 100644 --- a/css/base.css +++ b/css/base.css @@ -3043,17 +3043,20 @@ ul.tabbar li.active > a { padding: 0.15rem 0.5rem 0.25rem 0.5rem; background-color: #fafafa; background-position: center; - line-height: 1.5em; font-weight: lighter; border-radius: 0 0.25rem 0.25rem 0; color: #666; height: 100%; - width: 100%; - min-width: 24rem; + width: 24rem; + min-width: 0; cursor: pointer; transition: background 0.4s; +} + +.pinned > p { overflow-x: hidden; text-overflow: ellipsis; + white-space: nowrap; } .pinned:hover { @@ -3194,7 +3197,7 @@ ul.phone-country-selector span.country { } .pinned { - min-width: 12rem; + width: 16rem; } } @@ -3236,6 +3239,6 @@ ul.phone-country-selector span.country { } .pinned { - min-width: unset; + width: unset; } } diff --git a/css/base.min.css b/css/base.min.css index bccb0131..1f74322e 100644 --- a/css/base.min.css +++ b/css/base.min.css @@ -1 +1 @@ -*{box-sizing:border-box;font-family:Roboto,Arial,sans-serif;margin:0;padding:0;scrollbar-color:#0000004d #ffffff1a;scrollbar-width:thin;text-rendering:optimizeLegibility}body,html{background-color:silver;box-shadow:inset 0 10rem #3949ab;color:#666;font-size:10pt;height:100%;overflow:hidden;width:100%}tt{font-family:Roboto Mono,Courier,monospace}a{color:#2196f3;text-decoration:none}a:focus,a:hover{color:#0a6ebd;text-decoration:underline}a.danger{color:#d32f2f}a.danger:focus,a.danger:hover{color:#f44336}a.gray:focus,a.gray:hover{color:#999}form{line-height:1.5;padding:.5rem .75rem}form,label{font-size:1.1rem}label{margin-right:auto}label.small{color:#1e88e5;font-size:.95rem}label.large{color:#1e88e5;font-size:1.1rem}img.avatar{border-radius:50%;height:100%;width:100%}button{border:1px solid #0000;border-radius:4px;box-shadow:0 1px 3px 0 #00000040;cursor:pointer;display:inline-block;font-family:inherit;font-size:1.05rem;font-weight:400;height:2.2rem;line-height:2.2rem;margin:0 .35rem;min-width:5rem;padding-left:1.2rem;padding-right:1.2rem;text-align:center;text-transform:uppercase;touch-action:manipulation;vertical-align:middle;white-space:nowrap}button[disabled],html input[disabled]{box-shadow:none;cursor:default;filter:grayscale(50%);opacity:.65}button.round{border-radius:50%;box-shadow:0 2px .5rem 0 #00000040;height:3rem;line-height:3.5rem;margin:0;outline:none;padding:0;width:3rem;z-index:2}button.round.small{box-shadow:0 2px .35rem 0 #00000040;height:2rem;line-height:2rem;width:2rem}button:active:not([disabled]),button:hover:not([disabled]){color:#fff}button:active{box-shadow:inset 0 3px .5rem rgba(0,0,0,.125)}button:active.round.small{box-shadow:inset 0 2px .35rem rgba(0,0,0,.125)}button.primary{background-color:#1e88e5;color:#fff}button.primary:active:not([disabled]),button.primary:hover:not([disabled]){background-color:#2962ff}button.secondary{background-color:#fff;color:#2196f3}button.secondary:active:not([disabled]),button.secondary:hover:not([disabled]){background-color:#e3f2fd}button.outline{background-color:initial;border:1px solid silver;box-shadow:none;color:#2196f3}button.outline:active:not([disabled]),button.outline:hover:not([disabled]){background-color:#e8eaf6}button.danger{background-color:#ec6560;color:#fff}button.danger:active:not([disabled]),button.danger:hover:not([disabled]){background-color:#f77}button.positive{background-color:#71c46f;color:#fff}button.positive:active:not([disabled]),button.positive:hover:not([disabled]){background-color:#7fed7f}input,textarea{background:#0000;border:none;color:#666;font-family:inherit;font-size:1.1rem;margin:.25rem 0;outline:none;padding:0 .125rem}input[type=email],input[type=password],input[type=search],input[type=tel],input[type=text],textarea{border-bottom:1px solid #ccc;box-shadow:0 1px 0 #0000001a;height:2.5rem;transition:all .1s ease-in-out,height 0s}input[type=email],input[type=password],input[type=tel],input[type=text],textarea{width:100%}input[type=email]:focus,input[type=password]:focus,input[type=search]:focus,input[type=tel]:focus,input[type=text]:focus,textarea:focus{border-bottom:1px solid #2196f3;box-shadow:0 1px 0 #2196f340}input[type=email].invalid,input[type=password].invalid,input[type=search].invalid,input[type=tel].invalid,input[type=text].invalid,textarea.invalid{border-bottom:1px solid #e57373;box-shadow:0 1px 0 #e5737340}input[type=email]::placeholder,input[type=password]::placeholder,input[type=search]::placeholder,input[type=tel]::placeholder,input[type=text]::placeholder,textarea::placeholder{color:#bbb;font-weight:lighter}input[type=password].with-visibility,input[type=text].with-visibility{margin-right:-2rem;padding-right:2rem}textarea{padding-top:.45rem;resize:none}textarea.inplace-edit{font-size:unset;height:unset}::-webkit-scrollbar{width:.6rem}::-webkit-scrollbar-track{background-color:#ffffff1a;-webkit-box-shadow:inset 0 0 6px #0003;box-shadow:inset 0 0 6px #0003}::-webkit-scrollbar-thumb{background-color:#0000004d}ul.menu{background-color:#fff;border-radius:.2rem;box-shadow:0 1px 6px #00000073;list-style:none;padding-bottom:.35rem;padding-top:.35rem;position:absolute;width:12rem;z-index:4}ul.menu>li{cursor:pointer;padding:.75rem .75rem .75rem 1.25rem}ul.menu>li:hover{background-color:#f5f5f5}ul.menu>li.separator{height:1px;margin:2px;padding:0}ul.menu>li.separator,ul.menu>li.separator:hover{background-color:#ccc}.menuTrigger{background-color:inherit;border-radius:.7rem;height:1.4rem;line-height:1.4rem;opacity:0;position:absolute;right:.25rem;text-align:center;width:1.4rem}.menuTrigger a{color:#757575}li .menuTrigger{top:.25rem}li:hover .menuTrigger{opacity:.9}li:hover .menuTrigger a{color:#757575}div.alert-container{align-items:center;background:#f0f0f0d9;display:flex;height:100%;justify-content:center;overflow:hidden;padding:1rem;position:absolute;width:100%;z-index:3}div.alert{background-color:#fff;border-radius:.3rem;box-shadow:.15rem .15rem 1.5rem #00000073;height:min-content;margin:auto 2rem;max-height:40rem;max-width:24rem;min-width:16rem;overflow:hidden;padding:1rem;position:relative;width:fit-content}div.alert-container .title{color:#2196f3;font-size:1.2rem;font-weight:500;padding:0 0 .35rem;position:relative;width:100%}div.alert-container .title.with-control{align-items:center;display:flex;flex:none;justify-content:space-between;padding:.5rem .5rem 0;position:relative}div.alert-container .content{padding:.5rem 0;position:relative}div.trusted-badge{margin:.25rem 0}.blue{color:#2196f3!important}.lt-blue{color:#64b5f6!important}.verified-color{color:#03a9f4!important}.staff-color{color:#689f38!important}.danger-color{color:#ffc107!important}.green{color:#388e3c}.white{color:#fff!important}.red{color:#d32f2f!important}.badge-inv{color:#fffd!important}.gray{color:#757575!important}.light-gray{color:#bbb!important}.large{font-size:120%}.small{font-size:90%}.float-right{position:absolute;right:.5rem}.hr{background-color:#f0f0f0;box-shadow:inset 0 .25rem .25rem -.25rem #00000026,inset 0 -.25rem .25rem -.25rem #00000026;display:block;height:.45rem;min-height:.3rem;width:100%}.hr.thin{height:.015rem}.ellipsized{overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.flat-button{align-items:center;background-color:#fff;display:flex;font-weight:400;height:2em;line-height:2em;margin:.15rem .35rem;text-align:center;text-transform:uppercase;touch-action:manipulation;vertical-align:middle;white-space:nowrap;z-index:1}.flat-button:focus,.flat-button:hover{text-decoration:none}.flat-button.faux{background-color:#eee;border:1px solid #999;border-radius:3px;display:inline-block;height:1.4em;line-height:1.4em;margin:.15rem;padding:0 .35rem;text-transform:none}.action-button{background-color:#fafafa;border-radius:50%;bottom:1rem;box-shadow:0 2px .5rem 0 #00000040;color:#999;display:block;font-size:1.8rem;height:3.25rem;margin:0;min-height:unset;min-width:unset;outline:none;padding:0;position:absolute;right:1rem;transition:all .15s;width:3.25rem;z-index:2}.action-button:focus,.action-button:hover{background-color:#f0f0f0;color:#888}.action-button:active{background-color:#eee;color:#777}.action-button.hidden{bottom:2.625rem;font-size:1px;height:1px;line-height:1px;opacity:0;right:2.625rem;width:1px}.group-focus{outline:none}#mountPoint{height:100%;padding-bottom:1rem;padding-top:1rem}#noscript-message{background-color:#fff;border-radius:.25rem;box-shadow:1px 2px .3rem gray;display:flex;flex-direction:column;margin-left:auto;margin-right:auto;margin-top:5rem;max-width:30rem;overflow:hidden;position:relative}#noscript-title{background-color:#2196f3;color:#bbdefb;font-size:120%;font-weight:bolder;padding:1rem}#noscript-content{padding:1rem}#app-container{background-color:#fff;border-radius:.25rem;box-shadow:1px 2px .3rem gray;display:flex;height:100%;margin-left:auto;margin-right:auto;max-width:84rem;overflow:hidden;position:relative}#sidepanel{flex-grow:0;flex-shrink:0.3;min-width:18rem;width:24rem}#sidepanel,#topic-view{display:flex;flex-direction:column;height:100%;position:relative}#topic-view{overflow-x:hidden;width:100%}#info-view{display:flex;flex-direction:column;flex-grow:0;flex-shrink:0.3;height:100%;min-width:18rem;width:24rem}.center-medium-text{align-items:center;display:flex;font-size:1.4rem;height:100%;justify-content:center;text-align:center;width:100%}.nodisplay{display:none!important}.quoted{margin-left:1rem}.space-right{margin-right:.25rem}.rounded-container{background-color:#fafafa;border-radius:.1rem;margin:.25rem;padding:.25rem;position:relative}.in-place-edit{border-bottom:1px dashed #ddd;cursor:pointer;display:inline-block;font-family:inherit;font-size:1rem;margin:.25rem .125rem 0;vertical-align:initial;width:100%}.in-place-edit.short{font-size:1.1rem;height:2.5rem;line-height:2.25}.in-place-edit.disabled{border-bottom:none;color:#888;cursor:default}.in-place-edit.placeholder{color:#bbb}.in-place-edit span{display:inline-block}.in-place-edit.short span{display:block;overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}table.permission-editor{width:100%}table.permission-editor td{font-size:1.1rem;margin:.35rem 0;vertical-align:middle}table.permission-editor td.checkbox{color:#999;text-align:center}.permission-editor .material-icons{font-size:1.3rem;line-height:1.3rem}.material-icons.clickable{border-bottom:none;cursor:pointer}.clickable{border-bottom:1px dashed #ddd}.clean-clickable,.clickable,.image-clickable{cursor:pointer}.panel-title{font-size:1.4rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.panel-title.deleted{text-decoration:line-through}.caption-panel{box-shadow:0 1px 2px gray;flex:none;height:4rem;overflow-x:hidden;white-space:nowrap;z-index:1}.caption-panel,.dialog-buttons{align-items:center;display:flex;padding:.5rem}.dialog-buttons{justify-content:flex-end}.dialog-buttons button{margin:0 .5rem}.avatar-box{flex-grow:0;flex-shrink:0;position:relative}.bot-form{display:flex;flex-direction:column;line-height:2rem;min-width:8rem;overflow:hidden}.bot-form div{min-height:2rem;vertical-align:middle}.bot-form button{background-color:#eef;color:#2196f3;display:inline-block;font-size:inherit;height:2rem;line-height:2rem;margin:.15rem;text-transform:none}.bot-form>div>button{width:auto}.bot-form button:active,.bot-form button:focus,.bot-form button:hover{background-color:#e3f2fd;outline:0}#side-caption-panel{background-color:#2196f3;color:#bbdefb}#side-caption-panel a{color:#bbdefb;line-height:1;padding-left:.5rem}#side-caption-panel :hover{color:#fff}#sidepanel-title{margin-left:.5rem;margin-right:auto}#self-avatar{border-radius:50%;flex:none;height:3rem;min-width:3rem;width:3rem}#self-avatar.avatar-box{font-size:1.8rem}#settings-form ul{list-style:none}#settings-form li{vertical-align:middle}#settings-form label{display:inline-block;padding-left:.5rem}input#host-name{width:100%}input.search{text-indent:1.4rem}i.search{left:.6rem;position:absolute}.info-box{display:none;overflow:hidden;padding:1rem 1.5rem .75rem .5rem;position:relative}.info-box>span{line-height:1.35rem}.info-box .cancel{position:absolute;right:.25rem;top:.5rem}.info-box.error{background-color:#ffcdd2;border-bottom:1px solid #ffbfc8;color:#b71c1c;display:flex}.info-box.warning{background-color:#fff9c4;border-bottom:1px solid #fff59d;color:#6d4c41;display:flex}.info-box.info{background-color:#e1f5fe;border-bottom:1px solid #b3e5fc;color:#0288d1;display:flex}.info-box .cancel .material-icons{color:#757575;font-size:1rem}.info-box.error .cancel .material-icons{color:#b71c1c}.info-box .icon{display:block;margin-right:.5rem}.info-box .icon .material-icons{font-size:1.5rem}.info-box.warning .icon .material-icons{color:#fbc02d}.info-box.error .icon .material-icons{color:#ef5350}.info-box.info .icon .material-icons{color:#0288d1}.flex-column{display:flex;flex-direction:column;height:100%;overflow-x:hidden}.flex-column.narrow{height:auto}.scrollable-panel{height:100%;margin-bottom:auto;margin-top:.25rem;overflow-x:hidden;overflow-y:auto;scroll-behavior:smooth}.contact-box{list-style:none;overflow-x:hidden}.contact-box>li{background:linear-gradient(90deg,#0000 3.5rem,#eee 1px,#eee) 0 100% /100% 1px no-repeat,#fff;cursor:pointer;display:flex;flex-grow:0;flex-shrink:0;min-height:3.75rem;overflow-x:hidden;padding:.35rem .25rem .5rem .35rem;position:relative}.contact-box.small>li{min-height:2.5rem;padding:.25rem .25rem .35rem .35rem}.contact-box>li:last-child{background:#fff}.contact-box>li:hover{background-color:#eceff1}.contact-box>li.selected{background-color:#cfd8dc}.contact-box>li.action{border-bottom:none;min-height:2.5rem}.contact-box .text-box{overflow-x:hidden}.contact-box .contact-title{font-size:1.05rem;overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.contact-box .contact-title.deleted{opacity:.66;text-decoration:line-through;text-decoration-thickness:.5px}.contact-box .contact-comment{font-weight:lighter}.contact-box .contact-comment,.contact-box .contact-comment>span{overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.contact-box .contact-comment b{font-weight:bolder}.contact-box .contact-comment .material-icons{color:#777;margin-bottom:.2rem}.contact-box .avatar-box{font-size:1.8rem;height:3rem;margin-right:.35rem;min-height:3rem;min-width:3rem;overflow:hidden;padding:0;position:relative;width:3rem}.contact-box .avatar{border-radius:50%;height:3rem;width:3rem}.contact-box.small .avatar-box{font-size:1.2rem;height:2rem;min-height:2rem;min-width:2rem;width:2rem}.contact-box.small .avatar{height:2rem;width:2rem}.avatar.deleted{filter:grayscale(1);opacity:.75}.contact-box .avatar-box>.material-icons{display:flex;flex-direction:column;font-size:2.4rem;justify-content:space-around;line-height:3rem}.contact-box.small .avatar-box>.material-icons{font-size:1.6rem;line-height:2rem}.contact-box .text-box{display:flex;flex-direction:column;justify-content:space-around}.contact-box .text-box>div{align-items:center;display:flex;flex-direction:row}.contact-box .action-text{cursor:pointer;font-size:.95rem;line-height:2.5rem;margin:0 auto;text-align:center}img.channel{height:1.25rem;margin-left:.3rem;vertical-align:middle;width:1.25rem}.large img.channel{height:1.45rem;margin-bottom:.15rem;margin-left:.5rem;width:1.45rem}.avatar-box .online,.offline{border-radius:50%;bottom:.1rem;flex-shrink:0;height:.75rem;min-height:.75rem;min-width:.75rem;position:absolute;right:0;width:.75rem}.avatar-box .online{background-color:#4caf50}.avatar-box .offline{background-color:silver}.online.typing{animation:typing .5s infinite}@keyframes typing{0%,to{transform:translateX(0)}50%{transform:translateX(-.3rem)}}.contact-box .checkmark.material-icons{border:0 solid #0000;color:#0097a7;overflow:visible;padding-left:.5px}.contact-box .checkmark.material-icons,.contact-box .deleted.material-icons{background-color:#fff;bottom:0;font-size:1.5rem;height:1.5rem;position:absolute;right:0;width:1.5rem}.contact-box .deleted.material-icons{color:#999}#add-topic{bottom:1rem;position:absolute;right:1rem}.panel-form{display:flex;flex-direction:column;padding:0;position:relative}.panel-form-row{align-items:center;flex-shrink:0}.panel-form-column,.panel-form-row{display:flex;flex-grow:0;line-height:1.5;padding:.5rem .75rem;position:relative}.panel-form-column{flex-direction:column;overflow-x:hidden}.panel-form-column>.panel-form-column,.panel-form-row>.panel-form-column{flex-grow:1;padding:0!important}.panel-form-column>.panel-form-row,.panel-form-row>.panel-form-row{padding:0!important}.panel-form-column>.group{margin-bottom:.25rem;margin-top:.25rem}.avatar-upload{display:flex;flex-direction:column;flex-shrink:0;font-size:4.5rem;height:10.5rem;padding:0;position:relative;width:10rem}.avatar-upload.read-only{height:auto}.avatar-upload .clear-avatar{background-image:radial-gradient(#fff 40%,#0000 75%);font-size:1rem;opacity:0;position:absolute;right:0;top:0}.avatar-upload:hover .clear-avatar{opacity:1}.avatar-upload .avatar-box{height:10rem;position:relative;width:10rem}.avatar-upload .avatar-box>.material-icons{font-size:4rem;line-height:10rem;position:relative;vertical-align:middle}.avatar-upload:after{clear:both;content:".";display:block;height:0;visibility:hidden}.avatar-upload .blank{border:1px dashed #999;color:#999;flex-shrink:0;font-size:1rem;line-height:10rem;text-align:center;vertical-align:middle}.avatar-upload .blank,.avatar-upload img.preview{border-radius:50%;height:10rem;overflow:hidden;width:10rem}.avatar-upload img.preview:before{background:50% no-repeat url(../img/broken_image.png);border-radius:50%;color:#666;content:" ";display:flex;font-size:.9rem;font-weight:lighter;height:10rem;justify-content:center;left:0;position:absolute;top:0;width:10rem}.avatar-upload .inputfile.hidden{height:.1px;opacity:0;overflow:hidden;position:absolute;width:.1px}.avatar-upload .inputfile+label.round{align-items:center;background-color:#fafafa;border-radius:50%;bottom:0;box-shadow:0 1px 4px #0006;cursor:pointer;display:flex;height:3rem;justify-content:center;line-height:3rem;position:absolute;right:0;width:3rem;z-index:1}.avatar-upload .inputfile:focus+label.round{outline:none}.avatar-upload .inputfile+label:hover,.avatar-upload .inputfile:focus+label{background-color:#e3f2fd;color:#42a5f5}#topic-caption-panel{background-color:#b0bec5}#topic-caption-panel a{color:#757575;text-decoration:none}#topic-caption-panel :hover{color:#000}#topic-caption-panel .avatar-box{font-size:1.8rem;height:3rem;margin-right:.35rem;min-width:3rem;position:relative;width:3rem}#topic-caption-panel .avatar-box>.material-icons{font-size:2.4rem;line-height:3rem}#topic-title-group{overflow-x:hidden}#hide-message-view{display:block;margin-right:.35rem}#topic-users{margin-left:auto;margin-right:1rem;width:min-content}#topic-users .avatar-box{display:inline-block;font-size:1rem;height:1.8rem;margin-right:.2rem;min-height:1.8rem;min-width:1.8rem;width:1.8rem}#topic-users .avatar-box>.material-icons{font-size:1.4rem;line-height:1.8rem}#topic-users>span{line-height:2rem;vertical-align:top}#messages-panel{background-color:#eceff1;background-image:url(../img/bg_messages.png);height:100%;overflow-y:scroll;padding:.75rem;position:relative}#messages-container{height:100%;overflow-y:hidden;position:relative}#write-only-background{background-image:repeating-linear-gradient(45deg,#ffffff80,#ffffff80 .5rem,#fffc 0,#fffc 1rem);height:100%;left:0;position:absolute;top:0;width:100%}#write-only-note{height:auto;top:50%;transform:translate(-50%,-50%);width:auto}#peer-messaging-disabled-note,#write-only-note{background-color:#fff;border-radius:.5rem;box-shadow:0 1px .5px #0000001f;color:#666;left:50%;line-height:2rem;padding:.75rem 1.25rem;position:absolute;text-align:center}#peer-messaging-disabled-note{bottom:4.3rem;transform:translate(-50%);width:fit-content}#send-message-panel{align-items:center;background-color:#eceff1;display:flex;flex:none;min-height:4rem;padding:.4rem .4rem .4rem .6rem;z-index:2}#send-message-panel #writing-disabled{font-size:1.2rem;text-align:center;width:100%}#send-message-wrapper{background-color:#eceff1;box-shadow:0 -2px 3px -1px #0000001a;z-index:2}#sendMessage{overflow:hidden;overflow-wrap:break-word}#send-message-panel .material-icons{font-size:1.6rem;min-width:2rem}#send-message-panel .material-icons.secondary,.material-icons.disabled{color:#999!important}#send-message-panel .material-icons.secondary:hover{color:#2196f3!important}#send-message-input{max-height:6rem;min-height:2.5rem;overflow:hidden auto}.accept-invite-panel{background-color:#eceff1;box-shadow:0 -2px 3px -1px #0000001a;width:100%;z-index:1}.accept-invite-panel .title{font-size:1.2rem;padding:.75rem}.accept-invite-panel .footer{background-color:#fafafa;padding-bottom:.35rem;text-align:center;white-space:nowrap}.accept-invite-panel button{border:1px solid #0000;box-shadow:0 1px 2px 0 #00000040;font-size:1rem;height:2em;line-height:2em;margin:.25rem}#dummy-view{align-items:center;background-color:#e0f7fa;display:flex;height:100%;justify-content:center;width:100%}#dummy-view a{display:block;text-align:center;text-decoration:none}#image-preview{background-color:#ffffffe6;display:flex;flex-direction:column;height:100%;left:0;position:absolute;top:0;width:100%;z-index:2}#image-preview-caption-panel{background-color:#eceff1;box-shadow:0 1px 2px silver;display:flex;height:4.6rem;justify-content:space-between;line-height:2.5rem;padding:1rem .75rem 0;z-index:3}#image-preview-caption-panel a{color:#757575;text-decoration:none}#image-preview-caption-panel a:hover{color:#000}#image-preview-container{align-items:center;display:flex;height:100%;justify-content:space-around;overflow:hidden;width:100%}#image-preview-footer{background-color:#eceff1;box-shadow:0 -2px 3px -1px #0000001a;display:flex;height:3.2rem;justify-content:space-around;line-height:1.5rem;z-index:1}#image-preview-container .material-icons{font-size:6rem}#video-container{background-color:#ffffffe6;flex-direction:column;height:100%;justify-content:space-between;left:0;top:0}#video-container,.controls{display:flex;position:absolute;width:100%}.controls{align-items:center;bottom:2.5rem;column-gap:1rem;justify-content:center;z-index:1}.incoming-call .controls{bottom:1rem}.controls button{border-radius:50%;box-shadow:0 3px 6px 0 #00000040;height:4rem;min-width:auto;width:4rem}#video-container-panel{height:100%;position:relative;width:100%}.call-party{background-color:#eee;border:2px solid #ccc;border-radius:.5rem;overflow:hidden}.call-party:hover{border:2px solid #2196f3}.call-party.peer{bottom:1rem;left:1rem;position:absolute;right:1rem;top:1rem;z-index:1}.call-party.self{bottom:.5rem;height:10rem;position:absolute;right:.5rem;width:10rem;z-index:2}.call-party.self[disabled]{display:none}video{height:100%;object-fit:contain;width:100%}.call-party.self video{transform:scaleX(-1)}.call-party[disabled] video{display:none}.caller-card{align-items:center;display:flex;flex-direction:column;height:100%;justify-content:center;left:0;position:absolute;top:0;width:100%}.caller-card .avatar-box{font-size:6rem;height:10rem;width:10rem}.caller-card.pulse .lettertile,.caller-card.pulse img.avatar{animation:active-call 1.5s linear infinite}.caller-card .avatar-box .material-icons{font-size:6rem;line-height:1.6}.call-party .caller-name{background-color:#ffffffb3;border-radius:.35rem;padding:.15rem .5rem;text-shadow:0 0 1px #fff;z-index:1}.call-party.self .caller-name.inactive{bottom:.25rem;position:absolute;right:.25rem}.caller-card .caller-name{font-size:larger;margin-top:.5rem}.caller-card .trusted-badge{display:inline-block}.call-party.peer .caller-name.inactive{bottom:.5rem;font-size:larger;left:1rem;margin:0 auto;position:absolute}.incoming-call{background-color:#fff;border-radius:.3rem;box-shadow:.15rem .15rem 1.5rem #00000073;margin:auto 2rem;max-width:24rem;min-width:16rem;position:relative;width:fit-content}.incoming-call .caller-card{align-items:center;display:flex;flex-direction:column;height:100%;justify-content:center;left:auto;padding:4rem 3.5rem 5.5rem;position:relative;top:auto;width:100%}.incoming-call .caller-name{background-color:#ffffffb3;border-radius:.35rem;padding:.15rem .5rem;text-shadow:0 0 1px #fff;z-index:1}.call-message{display:flex;flex-direction:row}.call-message .duration{font-weight:lighter}@keyframes active-call{0%{box-shadow:0 0 0 .1rem #2196f34d,0 0 0 .3rem #2196f34d,0 0 0 .5rem #2196f34d}to{box-shadow:0 0 0 .4rem #2196f34d,0 0 0 2rem #2196f300,0 0 0 3rem #2196f300}}.chat-box{list-style:none;margin:0 .5rem;padding:0 0 3.5rem;scroll-behavior:smooth}.chat-box.group{margin-left:-.4rem}.chat-box li{align-items:flex-end;display:flex;margin:0;padding:0}.chat-box .right{justify-content:flex-end}.bubble{border-radius:.5rem;color:#212121;display:flex;filter:drop-shadow(.5px .5px .7px rgb(0,0,0,.3));height:auto;margin:0;max-width:36rem;min-width:9rem;padding:.75rem .5rem;position:relative;text-align:left;transition:background-color .5s ease-out;transition-delay:.3s}.chat-box li.single{margin-bottom:.75rem;margin-top:.25rem}.chat-box li.first{margin-bottom:.15rem;margin-top:.25rem}.chat-box li.middle{margin-bottom:.15rem;margin-top:.15rem}.chat-box li.last{margin-bottom:.75rem;margin-top:.15rem}.left .bubble{background-color:#c5e1a5;margin-right:.5rem}.left.flash .bubble{background-color:#94a97c}.left .bubble.tip{border-bottom-left-radius:0}.right .bubble{background-color:#fafafa;margin-left:1.75rem}.right.flash .bubble{background-color:#ccc}.right .bubble.tip{border-bottom-right-radius:0}.chat-box .meta{justify-content:center;margin-bottom:.5rem;margin-top:.5rem}.chat-box .meta .bubble{color:#666;min-width:unset}.meta .bubble.deleted{background-color:#e3f2fd;padding:.75rem .75rem .5rem}.meta .bubble.date{background-color:#fffc;font-size:smaller;padding:.5rem;text-transform:uppercase}.left .bubble.tip:before{background-color:#c5e1a5;border-bottom-left-radius:.3rem;bottom:0;clip-path:polygon(100% 0,0 110%,100% 110%);-webkit-clip-path:polygon(100% 0,0 110%,100% 110%);content:"";height:.85rem;left:-.8rem;position:absolute;transition:background-color .5s ease-out;transition-delay:.3s;width:.85rem}.left.flash .bubble.tip:before{background-color:#94a97c}.right .bubble.tip:before{background-color:#fafafa;border-bottom-right-radius:.3rem;bottom:0;clip-path:polygon(0 0,100% 110%,0 110%);-webkit-clip-path:polygon(0 0,100% 110%,0 110%);content:"";height:.85rem;left:99.8%;position:absolute;transition:background-color .5s ease-out;transition-delay:.3s;width:.85rem}.right.flash .bubble.tip:before{background-color:#ccc}.chat-box .avatar-box{font-size:.8rem;height:1.4rem;margin-bottom:.8rem;margin-right:.8rem;min-height:1.4rem;min-width:1.4rem;position:relative;width:1.4rem}.bubble div.content-meta{width:100%}.bubble div.message-content{margin:0;max-width:36rem;overflow-wrap:anywhere;padding:0 .75rem;position:relative;width:100%}.bubble div.message-content:after{clear:both;content:".";display:block;height:0;visibility:hidden}.chat-box .timestamp-padding{display:inline-block;height:0;width:4rem}.chat-box .timestamp{float:right;position:relative;top:.35rem;user-select:none;white-space:nowrap}.chat-box .author,.chat-box .timestamp{color:#777;font-size:80%}.image-preview,.inline-image{border-radius:.1rem;overflow:hidden;position:relative}.inline-image{max-height:24rem;max-width:36rem}.inline-image>.rounded-container{border-left:.25rem solid #0000;border-right:.25rem solid #0000;bottom:2rem;margin:.25rem auto;position:relative}img.image-preview:before,img.inline-image:before{background:50% no-repeat #ccc url(../img/broken_image.png);color:#666;display:flex;font-size:.9rem;font-weight:lighter;height:100%;justify-content:center;left:0;position:absolute;top:0;width:100%}img.inline-image:before{background-size:3rem 3rem;content:attr(alt)}img.image-preview:before{background-size:10rem 10rem;content:" "}.inline-image.video>img.inline-image:before,img.image-preview.video:before{background:50% no-repeat #ccc url(../img/broken_video.png)}.inline-image.video>img.inline-image:before{background-size:3rem 3rem}.inline-video{align-items:center;display:flex;justify-content:center;position:relative}.inline-video>img.inline-image:before{background:#ccc}.inline-video .duration{background-color:#ffffff80;border-radius:.3rem;bottom:.25rem;color:#333;font-size:80%;left:.25rem;padding:.25rem .5rem;position:absolute}.inline-video .play-control{align-items:center;background-color:#0006;border-radius:50%;cursor:pointer;display:flex;height:4rem;justify-content:center;pointer-events:none;position:absolute;width:4rem}.attachment{display:flex}.attachment:last-of-type{margin-bottom:-.45rem}#info-caption-panel{background-color:#b0bec5}#info-caption-panel a{color:#757575;line-height:1;text-decoration:none}#info-caption-panel :hover{color:#000}#info-title{margin-right:auto}#group-manager{display:flex;flex-direction:column;height:100%;overflow-y:hidden;position:relative}#group-manager-buttons{background-color:#eceff1;border-left:1px solid #ccc;box-shadow:0 -1px #0000001a;display:flex;height:4rem;justify-content:space-around;padding:.4rem;z-index:2}ul.tabbar{background:#eee;display:flex;flex-grow:0;flex-shrink:0;list-style:none;margin:0;overflow:hidden;padding:0 0 0 1rem;width:100%}ul.tabbar>li{box-shadow:inset 0 -2px 2.5px -1px #00000040;height:2.4rem;position:relative}ul.tabbar li.active{background:#fff}ul.tabbar li:after{background:#ccc;bottom:0;content:"";height:.1rem;left:0;position:absolute;width:100%}ul.tabbar li.active:after{animation:tabbar-border-expand .2s cubic-bezier(.4,0,.4,1) 0s alternate forwards;background:#2196f3;bottom:0;content:"";height:.15rem;left:0;position:absolute}@keyframes tabbar-border-expand{0%{opacity:0;width:0}to{opacity:1;width:100%}}ul.tabbar>li>a{color:#2196f399;font-size:1.3rem;font-variant:small-caps;font-weight:400;line-height:2.4rem;overflow:hidden;padding-left:1rem;padding-right:1rem;position:relative;text-align:center;text-decoration:none}ul.tabbar li.active>a{color:#2196f3}.unread{background-color:#0097a7;border-radius:50%;color:#fff;display:inline-block;font-size:.75rem;font-weight:bolder;height:1.35rem;line-height:1.45rem;margin-left:.5rem;text-align:center;vertical-align:middle;width:1.35rem}.material-icons.as-badge{color:#aaa;font-size:1.15rem;padding-left:.2rem}.badge{align-self:flex-start;background-color:#e8e8e8;border:1px solid silver;border-radius:.2rem;color:#666;display:inline-block;font-family:Roboto Mono,Courier,monospace,sans-serif;font-size:.8rem;margin:.05rem .1rem;padding:.05rem .25rem}.badge.green{background-color:#efe;border-color:#aca;color:#383}.badge.yellow{background-color:#ffe;border-color:#cc9;color:#660}.badge.blue{background-color:#eef;border-color:#aad;color:#339}.badge.red{background-color:#fee;border-color:#c99;color:#933}.badge.magenta{background-color:#fef;border-color:#c9c;color:#939}.lettertile{border-radius:50%;padding-bottom:100%;user-select:none;width:100%}.lettertile>div{align-items:center;border-radius:50%;bottom:0;color:#fafafacc;display:flex;flex-grow:0;flex-shrink:0;justify-content:center;left:0;line-height:1;padding-top:.1em;position:absolute;right:0;text-align:center;text-transform:uppercase;top:0}.lettertile:hover{color:#fff}.lettertile.disabled{opacity:.5}.lt-bg-0{background-color:#ef9a9a}.lt-bg-1{background-color:#90caf9}.lt-bg-2{background-color:#b0bec5}.lt-bg-3{background-color:#b39ddb}.lt-bg-4{background-color:#ffab91}.lt-bg-5{background-color:#a5d6a7}.lt-bg-6{background-color:#eee}.lt-bg-7{background-color:#e6ee9c}.lt-bg-8{background-color:#c5e1a5}.lt-bg-9{background-color:#f0e57d}.lt-bg-10{background-color:#f48fb1}.lt-bg-11{background-color:#9fa8da}.lt-bg-12{background-color:#ffe082}.lt-bg-13{background-color:#bcaaa4}.lt-bg-14{background-color:#80deea}.lt-bg-15{background-color:#ce93d8}.dk-bg-0{background-color:#c62828}.dk-bg-1{background-color:#ad1457}.dk-bg-2{background-color:#6a1b9a}.dk-bg-3{background-color:#4527a0}.dk-bg-4{background-color:#283593}.dk-bg-5{background-color:#1565c0}.dk-bg-6{background-color:#0277bd}.dk-bg-7{background-color:#00838f}.dk-bg-8{background-color:#00695c}.dk-bg-9{background-color:#2e7d32}.dk-bg-10{background-color:#558b2f}.dk-bg-11{background-color:#9e9d24}.dk-bg-12{background-color:#f9a825}.dk-bg-13{background-color:#ff8f00}.dk-bg-14{background-color:#ef6c00}.dk-bg-15{background-color:#d84315}.lt-fg-0{color:#ef9a9a!important}.lt-fg-1{color:#90caf9!important}.lt-fg-2{color:#b0bec5!important}.lt-fg-3{color:#b39ddb!important}.lt-fg-4{color:#ffab91!important}.lt-fg-5{color:#a5d6a7!important}.lt-fg-6{color:#eee!important}.lt-fg-7{color:#e6ee9c!important}.lt-fg-8{color:#c5e1a5!important}.lt-fg-9{color:#f0e57d!important}.lt-fg-10{color:#f48fb1!important}.lt-fg-11{color:#9fa8da!important}.lt-fg-12{color:#ffe082!important}.lt-fg-13{color:#bcaaa4!important}.lt-fg-14{color:#80deea!important}.lt-fg-15{color:#ce93d8!important}.dk-fg-0{color:#c62828!important}.dk-fg-1{color:#ad1457!important}.dk-fg-2{color:#6a1b9a!important}.dk-fg-3{color:#4527a0!important}.dk-fg-4{color:#283593!important}.dk-fg-5{color:#1565c0!important}.dk-fg-6{color:#0277bd!important}.dk-fg-7{color:#00838f!important}.dk-fg-8{color:#00695c!important}.dk-fg-9{color:#2e7d32!important}.dk-fg-10{color:#558b2f!important}.dk-fg-11{color:#9e9d24!important}.dk-fg-12{color:#f9a825!important}.dk-fg-13{color:#ff8f00!important}.dk-fg-14{color:#ef6c00!important}.dk-fg-15{color:#d84315!important}.material-icons{font-size:1.4rem;line-height:1;text-align:center;vertical-align:middle}.material-icons.small{font-size:1rem}.material-icons.medium{font-size:1.2rem}.material-icons.big{font-size:2.2rem}.material-icons.bigger{font-size:3rem}.material-icons.huge{font-size:4rem}.composed-material{display:inline-block;position:relative}.composed-material i:nth-child(2){font-size:85%;font-weight:700;left:39%;position:absolute;top:7%}#self-avatar .material-icons{font-size:2.4rem;line-height:3rem}.avatar-box .material-icons{border-radius:50%;color:#fafafacc;height:inherit;width:inherit}.chip-input{align-items:center;background:#0000;border-bottom:1px solid #ccc;box-shadow:0 1px 0 #0000001a;color:#666;cursor:text;display:flex;flex-grow:1;flex-wrap:wrap;font-size:1.1rem;font-weight:400;justify-content:flex-start;margin:.25rem 0;max-height:10rem;min-height:4rem;outline:none;overflow-y:scroll;text-align:center;transition:all .1s ease-in-out}.chip-input.focused{border-bottom:1px solid #2196f3;box-shadow:0 1px 0 #2196f340}.chip-input>input[type=text]{border:none;box-shadow:none;display:inline-block;flex:1 0 auto;min-width:4rem;width:auto}.chip,.chip-input>input[type=text]{height:1.8rem;line-height:1.8;margin:.125rem}.chip{align-items:center;background-color:#eee;border-radius:.9rem;display:flex;flex:0 0 auto;font-size:90%;max-width:12rem;overflow:hidden}.chip,.chip>span{text-overflow:ellipsis;white-space:nowrap}.chip>span{overflow-x:hidden}.chip.invalid{background-color:#fee;color:#c66}.chip>a{background-color:#aaa;border-radius:50%;color:#eee;display:inline-block;height:1.175rem;line-height:1.15;margin:.3rem;min-width:1.175rem;text-decoration:none;width:1.175rem}.chip>a:focus,.chip>a:hover{background-color:#bbb;color:#fff;text-decoration:none}.chip .avatar-box{font-size:1rem;height:1.8rem;margin-right:.2rem;min-height:1.8rem;min-width:1.8rem;position:relative;width:1.8rem}.chip .avatar-box .material-icons{font-size:1.4rem;line-height:1.8rem}.chip .spacer{display:inline-block;height:1.175rem;margin:.3rem;width:.25rem}.load-spinner-box{--size-small:2.5rem;--size-large:4rem;background-color:#fff;border-radius:50%;box-shadow:.1rem .1rem .15rem 1px #00000040;height:var(--size-small);left:0;margin-left:auto;margin-right:auto;padding:.25rem;position:absolute;right:0;top:5rem;width:var(--size-small);z-index:2}.load-spinner-box.large{height:var(--size-large);width:var(--size-large)}.load-spinner-box.clear{background-color:#fff8;-x-box-shadow:none;box-shadow:.1rem .1rem .15rem 1px #0000001f}.load-spinner-box.centered{top:calc(var(--size-small)/2 - .25rem)}.load-spinner-box.large.centered{top:calc(var(--size-large)/2 - .25rem)}.loader-spinner{animation:spin 1.5s linear infinite;border:.35rem solid #f3f3f3;border-radius:50%;border-top-color:#1e88e5;height:2rem;width:2rem}.load-spinner-box.large .loader-spinner{height:3.5rem;width:3.5rem}@keyframes spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.uploader{display:flex}.uploader>div{background-color:#cfd8dc;border-radius:.1rem;height:.6rem;line-height:0;margin:.35rem;padding:.15rem;position:relative;width:6rem}.uploader>div>span{background-color:#1e88e5;border-radius:.08rem;display:inline-block;height:.3rem}.highlight{color:teal;font-weight:bolder}.highlight .preview{color:#5f9ea0;font-weight:inherit}.cropper{align-self:center;height:21rem;margin:1rem auto auto;transform:translateZ(0)}.cropper,.cropper .bounding-box{border-radius:.25rem;position:relative;width:18rem}.cropper .bounding-box{background-color:#999;border:2px solid #1e88e5;box-shadow:1px 1px 3px grey;height:18rem;overflow:hidden;z-index:1}.cropper .preview{max-height:none;max-width:none;position:absolute;z-index:-1}.cropper .cutout{border:1px dashed #999;bottom:0;box-shadow:0 0 150rem 150rem #e6f6ffa8;height:17rem;left:0;margin:auto;position:absolute;right:0;top:0;width:17rem;z-index:0}.cropper .cutout.circle{border-radius:50%}.cropper .overlay{cursor:move;position:absolute;touch-action:none;z-index:1}.cropper .zoom-wrapper{height:2rem;margin:1rem auto;text-align:center;width:80%}.cropper .zoom{box-shadow:none;pointer-events:none;z-index:2}.cropper .zoom:focus{outline:none}.reply-quote{border-left:.25rem solid #039be5;border-radius:.25rem;color:#666;cursor:pointer;font-weight:lighter;line-height:1.5em;padding:.15rem .5rem .25rem;position:relative}.chat-box .bubble .reply-quote{margin:.15rem -.75rem .3rem}.chat-box .bubble .reply-quote:first-child{margin-top:-.25rem}.chat-box .left .reply-quote{background-color:#fff6}.chat-box .right .reply-quote{background-color:#8080801f}.reply-quote .inline-image{margin-bottom:.1rem;vertical-align:middle}.reply-quote img.inline-image:before{content:""}#reply-quote-preview{align-items:center;display:flex}#reply-quote-preview .reply-quote{background-color:#fafafa;cursor:auto;margin:.35rem .5rem 0 0;width:100%}#reply-quote-preview .cancel{min-width:2.4rem;text-align:center}#reply-quote-preview .inline-image{background-color:#ccc}#reply-quote-preview img.inline-image:before{content:""}#send-message-panel #reply-quote-preview{width:100%}#send-message-panel #reply-quote-preview .reply-quote{margin-bottom:.35rem}.forwarding-quote{font-size:200%;line-height:200%}.mention{font-weight:500}.forward-dialog{background-color:#fff;border-radius:.3rem;box-shadow:.15rem .15rem 1.5rem #00000073;height:80%;margin:auto 1rem;overflow:hidden;padding:.5rem;position:relative;width:24rem}.forward-dialog .scrollable-panel{height:80%}.audio{align-items:center;background-color:#eee;border-radius:1.5rem;display:flex;flex:none;height:3rem;margin-left:auto}.audio canvas{height:2.6rem;margin-right:2rem;width:14rem}.audio canvas.playback{margin-right:0}.audio .duration{font-size:large}.audio-player{align-items:center;display:flex}.audio-player .material-icons.large{color:#667575cc;font-size:2.4rem}.audio-player .material-icons.disabled{color:#999c;cursor:default}.audio-player .playback{height:2.6rem;width:14rem}.audio-player canvas.playback{display:block}.audio-player div.playback{align-items:center;color:#757575cc;display:flex;font-size:small;justify-content:center}.audio-player .timer{color:#666c;font-size:smaller}#pinned-wrapper{margin-right:1rem}#pinned-wrapper,.pinned{align-items:center;display:flex;height:100%;position:relative}.pinned{background-color:#fafafa;background-position:50%;border-radius:0 .25rem .25rem 0;color:#666;cursor:pointer;font-weight:lighter;line-height:1.5em;min-width:24rem;overflow-x:hidden;padding:.15rem .5rem .25rem;text-overflow:ellipsis;transition:background .4s;width:100%}.pinned:hover{background-color:#fafdff}.pinned:active{background-color:#d8e8ff;transition:background 0s}.pinned-scroll{align-items:center;background-color:#eeee;border-radius:.25rem 0 0 .25rem;display:flex;flex-direction:column;height:100%;justify-content:space-evenly;margin-left:.35rem;padding:.1rem;position:relative}.pinned-scroll .dot{background-color:#999;border-radius:50%;height:.3rem;width:.3rem}.pinned-scroll .adot{background-color:#039be5;border-radius:50%;height:.45rem;width:.45rem}#pinned-wrapper .menuTrigger.upper{top:.25rem}#pinned-wrapper .menuTrigger.lower{bottom:.25rem}#pinned-wrapper:hover .menuTrigger{opacity:.9}#pinned-wrapper:hover .menuTrigger a{color:#757575}.drag-n-drop{align-items:center;background-color:#fffffff2;border:.15rem dashed grey;border-radius:1rem;bottom:1.5rem;color:grey;display:flex;font-size:2rem;justify-content:center;left:1.5rem;outline:.5rem solid #fffffff2;position:absolute;right:1.5rem;top:1.5rem;z-index:3}.country-flag{display:inline-block;font-size:larger}.dial-code{cursor:pointer;display:inline-block;margin-bottom:.15rem;vertical-align:middle;white-space:nowrap}ul.phone-country-selector{list-style:none;overflow-x:hidden}ul.phone-country-selector>li{cursor:pointer;font-weight:lighter;padding:.25rem .5rem .15rem;position:relative;width:100%}ul.phone-country-selector>li:hover{background-color:#eceff1}ul.phone-country-selector>li.selected{background-color:#cfd8dc}ul.phone-country-selector .dial-code{color:#1e88e5;font-weight:400;position:absolute;right:.5rem}ul.phone-country-selector span{display:inline-block}ul.phone-country-selector span.country{overflow-x:hidden;text-overflow:ellipsis}@media (min-width:1440px){#app-container{max-width:114rem}}@media (max-width:960px){#mountPoint{padding:0}.pinned{min-width:12rem}}@media (max-width:640px){#app-container{border-radius:0;box-shadow:none;width:100%}#info-view,#sidepanel{width:100%}.forward-dialog{border-radius:.3rem .3rem 0 0;margin:auto 0 0;width:100%}.menuTrigger{opacity:.3}#send-message-input{transition-property:-tinode-mobile}#pinned-wrapper{height:3.5rem;margin:.25rem}.pinned{min-width:unset}} \ No newline at end of file +*{box-sizing:border-box;font-family:Roboto,Arial,sans-serif;margin:0;padding:0;scrollbar-color:#0000004d #ffffff1a;scrollbar-width:thin;text-rendering:optimizeLegibility}body,html{background-color:silver;box-shadow:inset 0 10rem #3949ab;color:#666;font-size:10pt;height:100%;overflow:hidden;width:100%}tt{font-family:Roboto Mono,Courier,monospace}a{color:#2196f3;text-decoration:none}a:focus,a:hover{color:#0a6ebd;text-decoration:underline}a.danger{color:#d32f2f}a.danger:focus,a.danger:hover{color:#f44336}a.gray:focus,a.gray:hover{color:#999}form{line-height:1.5;padding:.5rem .75rem}form,label{font-size:1.1rem}label{margin-right:auto}label.small{color:#1e88e5;font-size:.95rem}label.large{color:#1e88e5;font-size:1.1rem}img.avatar{border-radius:50%;height:100%;width:100%}button{border:1px solid #0000;border-radius:4px;box-shadow:0 1px 3px 0 #00000040;cursor:pointer;display:inline-block;font-family:inherit;font-size:1.05rem;font-weight:400;height:2.2rem;line-height:2.2rem;margin:0 .35rem;min-width:5rem;padding-left:1.2rem;padding-right:1.2rem;text-align:center;text-transform:uppercase;touch-action:manipulation;vertical-align:middle;white-space:nowrap}button[disabled],html input[disabled]{box-shadow:none;cursor:default;filter:grayscale(50%);opacity:.65}button.round{border-radius:50%;box-shadow:0 2px .5rem 0 #00000040;height:3rem;line-height:3.5rem;margin:0;outline:none;padding:0;width:3rem;z-index:2}button.round.small{box-shadow:0 2px .35rem 0 #00000040;height:2rem;line-height:2rem;width:2rem}button:active:not([disabled]),button:hover:not([disabled]){color:#fff}button:active{box-shadow:inset 0 3px .5rem rgba(0,0,0,.125)}button:active.round.small{box-shadow:inset 0 2px .35rem rgba(0,0,0,.125)}button.primary{background-color:#1e88e5;color:#fff}button.primary:active:not([disabled]),button.primary:hover:not([disabled]){background-color:#2962ff}button.secondary{background-color:#fff;color:#2196f3}button.secondary:active:not([disabled]),button.secondary:hover:not([disabled]){background-color:#e3f2fd}button.outline{background-color:initial;border:1px solid silver;box-shadow:none;color:#2196f3}button.outline:active:not([disabled]),button.outline:hover:not([disabled]){background-color:#e8eaf6}button.danger{background-color:#ec6560;color:#fff}button.danger:active:not([disabled]),button.danger:hover:not([disabled]){background-color:#f77}button.positive{background-color:#71c46f;color:#fff}button.positive:active:not([disabled]),button.positive:hover:not([disabled]){background-color:#7fed7f}input,textarea{background:#0000;border:none;color:#666;font-family:inherit;font-size:1.1rem;margin:.25rem 0;outline:none;padding:0 .125rem}input[type=email],input[type=password],input[type=search],input[type=tel],input[type=text],textarea{border-bottom:1px solid #ccc;box-shadow:0 1px 0 #0000001a;height:2.5rem;transition:all .1s ease-in-out,height 0s}input[type=email],input[type=password],input[type=tel],input[type=text],textarea{width:100%}input[type=email]:focus,input[type=password]:focus,input[type=search]:focus,input[type=tel]:focus,input[type=text]:focus,textarea:focus{border-bottom:1px solid #2196f3;box-shadow:0 1px 0 #2196f340}input[type=email].invalid,input[type=password].invalid,input[type=search].invalid,input[type=tel].invalid,input[type=text].invalid,textarea.invalid{border-bottom:1px solid #e57373;box-shadow:0 1px 0 #e5737340}input[type=email]::placeholder,input[type=password]::placeholder,input[type=search]::placeholder,input[type=tel]::placeholder,input[type=text]::placeholder,textarea::placeholder{color:#bbb;font-weight:lighter}input[type=password].with-visibility,input[type=text].with-visibility{margin-right:-2rem;padding-right:2rem}textarea{padding-top:.45rem;resize:none}textarea.inplace-edit{font-size:unset;height:unset}::-webkit-scrollbar{width:.6rem}::-webkit-scrollbar-track{background-color:#ffffff1a;-webkit-box-shadow:inset 0 0 6px #0003;box-shadow:inset 0 0 6px #0003}::-webkit-scrollbar-thumb{background-color:#0000004d}ul.menu{background-color:#fff;border-radius:.2rem;box-shadow:0 1px 6px #00000073;list-style:none;padding-bottom:.35rem;padding-top:.35rem;position:absolute;width:12rem;z-index:4}ul.menu>li{cursor:pointer;padding:.75rem .75rem .75rem 1.25rem}ul.menu>li:hover{background-color:#f5f5f5}ul.menu>li.separator{height:1px;margin:2px;padding:0}ul.menu>li.separator,ul.menu>li.separator:hover{background-color:#ccc}.menuTrigger{background-color:inherit;border-radius:.7rem;height:1.4rem;line-height:1.4rem;opacity:0;position:absolute;right:.25rem;text-align:center;width:1.4rem}.menuTrigger a{color:#757575}li .menuTrigger{top:.25rem}li:hover .menuTrigger{opacity:.9}li:hover .menuTrigger a{color:#757575}div.alert-container{align-items:center;background:#f0f0f0d9;display:flex;height:100%;justify-content:center;overflow:hidden;padding:1rem;position:absolute;width:100%;z-index:3}div.alert{background-color:#fff;border-radius:.3rem;box-shadow:.15rem .15rem 1.5rem #00000073;height:min-content;margin:auto 2rem;max-height:40rem;max-width:24rem;min-width:16rem;overflow:hidden;padding:1rem;position:relative;width:fit-content}div.alert-container .title{color:#2196f3;font-size:1.2rem;font-weight:500;padding:0 0 .35rem;position:relative;width:100%}div.alert-container .title.with-control{align-items:center;display:flex;flex:none;justify-content:space-between;padding:.5rem .5rem 0;position:relative}div.alert-container .content{padding:.5rem 0;position:relative}div.trusted-badge{margin:.25rem 0}.blue{color:#2196f3!important}.lt-blue{color:#64b5f6!important}.verified-color{color:#03a9f4!important}.staff-color{color:#689f38!important}.danger-color{color:#ffc107!important}.green{color:#388e3c}.white{color:#fff!important}.red{color:#d32f2f!important}.badge-inv{color:#fffd!important}.gray{color:#757575!important}.light-gray{color:#bbb!important}.large{font-size:120%}.small{font-size:90%}.float-right{position:absolute;right:.5rem}.hr{background-color:#f0f0f0;box-shadow:inset 0 .25rem .25rem -.25rem #00000026,inset 0 -.25rem .25rem -.25rem #00000026;display:block;height:.45rem;min-height:.3rem;width:100%}.hr.thin{height:.015rem}.ellipsized{overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.flat-button{align-items:center;background-color:#fff;display:flex;font-weight:400;height:2em;line-height:2em;margin:.15rem .35rem;text-align:center;text-transform:uppercase;touch-action:manipulation;vertical-align:middle;white-space:nowrap;z-index:1}.flat-button:focus,.flat-button:hover{text-decoration:none}.flat-button.faux{background-color:#eee;border:1px solid #999;border-radius:3px;display:inline-block;height:1.4em;line-height:1.4em;margin:.15rem;padding:0 .35rem;text-transform:none}.action-button{background-color:#fafafa;border-radius:50%;bottom:1rem;box-shadow:0 2px .5rem 0 #00000040;color:#999;display:block;font-size:1.8rem;height:3.25rem;margin:0;min-height:unset;min-width:unset;outline:none;padding:0;position:absolute;right:1rem;transition:all .15s;width:3.25rem;z-index:2}.action-button:focus,.action-button:hover{background-color:#f0f0f0;color:#888}.action-button:active{background-color:#eee;color:#777}.action-button.hidden{bottom:2.625rem;font-size:1px;height:1px;line-height:1px;opacity:0;right:2.625rem;width:1px}.group-focus{outline:none}#mountPoint{height:100%;padding-bottom:1rem;padding-top:1rem}#noscript-message{background-color:#fff;border-radius:.25rem;box-shadow:1px 2px .3rem gray;display:flex;flex-direction:column;margin-left:auto;margin-right:auto;margin-top:5rem;max-width:30rem;overflow:hidden;position:relative}#noscript-title{background-color:#2196f3;color:#bbdefb;font-size:120%;font-weight:bolder;padding:1rem}#noscript-content{padding:1rem}#app-container{background-color:#fff;border-radius:.25rem;box-shadow:1px 2px .3rem gray;display:flex;height:100%;margin-left:auto;margin-right:auto;max-width:84rem;overflow:hidden;position:relative}#sidepanel{flex-grow:0;flex-shrink:0.3;min-width:18rem;width:24rem}#sidepanel,#topic-view{display:flex;flex-direction:column;height:100%;position:relative}#topic-view{overflow-x:hidden;width:100%}#info-view{display:flex;flex-direction:column;flex-grow:0;flex-shrink:0.3;height:100%;min-width:18rem;width:24rem}.center-medium-text{align-items:center;display:flex;font-size:1.4rem;height:100%;justify-content:center;text-align:center;width:100%}.nodisplay{display:none!important}.quoted{margin-left:1rem}.space-right{margin-right:.25rem}.rounded-container{background-color:#fafafa;border-radius:.1rem;margin:.25rem;padding:.25rem;position:relative}.in-place-edit{border-bottom:1px dashed #ddd;cursor:pointer;display:inline-block;font-family:inherit;font-size:1rem;margin:.25rem .125rem 0;vertical-align:initial;width:100%}.in-place-edit.short{font-size:1.1rem;height:2.5rem;line-height:2.25}.in-place-edit.disabled{border-bottom:none;color:#888;cursor:default}.in-place-edit.placeholder{color:#bbb}.in-place-edit span{display:inline-block}.in-place-edit.short span{display:block;overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}table.permission-editor{width:100%}table.permission-editor td{font-size:1.1rem;margin:.35rem 0;vertical-align:middle}table.permission-editor td.checkbox{color:#999;text-align:center}.permission-editor .material-icons{font-size:1.3rem;line-height:1.3rem}.material-icons.clickable{border-bottom:none;cursor:pointer}.clickable{border-bottom:1px dashed #ddd}.clean-clickable,.clickable,.image-clickable{cursor:pointer}.panel-title{font-size:1.4rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.panel-title.deleted{text-decoration:line-through}.caption-panel{box-shadow:0 1px 2px gray;flex:none;height:4rem;overflow-x:hidden;white-space:nowrap;z-index:1}.caption-panel,.dialog-buttons{align-items:center;display:flex;padding:.5rem}.dialog-buttons{justify-content:flex-end}.dialog-buttons button{margin:0 .5rem}.avatar-box{flex-grow:0;flex-shrink:0;position:relative}.bot-form{display:flex;flex-direction:column;line-height:2rem;min-width:8rem;overflow:hidden}.bot-form div{min-height:2rem;vertical-align:middle}.bot-form button{background-color:#eef;color:#2196f3;display:inline-block;font-size:inherit;height:2rem;line-height:2rem;margin:.15rem;text-transform:none}.bot-form>div>button{width:auto}.bot-form button:active,.bot-form button:focus,.bot-form button:hover{background-color:#e3f2fd;outline:0}#side-caption-panel{background-color:#2196f3;color:#bbdefb}#side-caption-panel a{color:#bbdefb;line-height:1;padding-left:.5rem}#side-caption-panel :hover{color:#fff}#sidepanel-title{margin-left:.5rem;margin-right:auto}#self-avatar{border-radius:50%;flex:none;height:3rem;min-width:3rem;width:3rem}#self-avatar.avatar-box{font-size:1.8rem}#settings-form ul{list-style:none}#settings-form li{vertical-align:middle}#settings-form label{display:inline-block;padding-left:.5rem}input#host-name{width:100%}input.search{text-indent:1.4rem}i.search{left:.6rem;position:absolute}.info-box{display:none;overflow:hidden;padding:1rem 1.5rem .75rem .5rem;position:relative}.info-box>span{line-height:1.35rem}.info-box .cancel{position:absolute;right:.25rem;top:.5rem}.info-box.error{background-color:#ffcdd2;border-bottom:1px solid #ffbfc8;color:#b71c1c;display:flex}.info-box.warning{background-color:#fff9c4;border-bottom:1px solid #fff59d;color:#6d4c41;display:flex}.info-box.info{background-color:#e1f5fe;border-bottom:1px solid #b3e5fc;color:#0288d1;display:flex}.info-box .cancel .material-icons{color:#757575;font-size:1rem}.info-box.error .cancel .material-icons{color:#b71c1c}.info-box .icon{display:block;margin-right:.5rem}.info-box .icon .material-icons{font-size:1.5rem}.info-box.warning .icon .material-icons{color:#fbc02d}.info-box.error .icon .material-icons{color:#ef5350}.info-box.info .icon .material-icons{color:#0288d1}.flex-column{display:flex;flex-direction:column;height:100%;overflow-x:hidden}.flex-column.narrow{height:auto}.scrollable-panel{height:100%;margin-bottom:auto;margin-top:.25rem;overflow-x:hidden;overflow-y:auto;scroll-behavior:smooth}.contact-box{list-style:none;overflow-x:hidden}.contact-box>li{background:linear-gradient(90deg,#0000 3.5rem,#eee 1px,#eee) 0 100% /100% 1px no-repeat,#fff;cursor:pointer;display:flex;flex-grow:0;flex-shrink:0;min-height:3.75rem;overflow-x:hidden;padding:.35rem .25rem .5rem .35rem;position:relative}.contact-box.small>li{min-height:2.5rem;padding:.25rem .25rem .35rem .35rem}.contact-box>li:last-child{background:#fff}.contact-box>li:hover{background-color:#eceff1}.contact-box>li.selected{background-color:#cfd8dc}.contact-box>li.action{border-bottom:none;min-height:2.5rem}.contact-box .text-box{overflow-x:hidden}.contact-box .contact-title{font-size:1.05rem;overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.contact-box .contact-title.deleted{opacity:.66;text-decoration:line-through;text-decoration-thickness:.5px}.contact-box .contact-comment{font-weight:lighter}.contact-box .contact-comment,.contact-box .contact-comment>span{overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.contact-box .contact-comment b{font-weight:bolder}.contact-box .contact-comment .material-icons{color:#777;margin-bottom:.2rem}.contact-box .avatar-box{font-size:1.8rem;height:3rem;margin-right:.35rem;min-height:3rem;min-width:3rem;overflow:hidden;padding:0;position:relative;width:3rem}.contact-box .avatar{border-radius:50%;height:3rem;width:3rem}.contact-box.small .avatar-box{font-size:1.2rem;height:2rem;min-height:2rem;min-width:2rem;width:2rem}.contact-box.small .avatar{height:2rem;width:2rem}.avatar.deleted{filter:grayscale(1);opacity:.75}.contact-box .avatar-box>.material-icons{display:flex;flex-direction:column;font-size:2.4rem;justify-content:space-around;line-height:3rem}.contact-box.small .avatar-box>.material-icons{font-size:1.6rem;line-height:2rem}.contact-box .text-box{display:flex;flex-direction:column;justify-content:space-around}.contact-box .text-box>div{align-items:center;display:flex;flex-direction:row}.contact-box .action-text{cursor:pointer;font-size:.95rem;line-height:2.5rem;margin:0 auto;text-align:center}img.channel{height:1.25rem;margin-left:.3rem;vertical-align:middle;width:1.25rem}.large img.channel{height:1.45rem;margin-bottom:.15rem;margin-left:.5rem;width:1.45rem}.avatar-box .online,.offline{border-radius:50%;bottom:.1rem;flex-shrink:0;height:.75rem;min-height:.75rem;min-width:.75rem;position:absolute;right:0;width:.75rem}.avatar-box .online{background-color:#4caf50}.avatar-box .offline{background-color:silver}.online.typing{animation:typing .5s infinite}@keyframes typing{0%,to{transform:translateX(0)}50%{transform:translateX(-.3rem)}}.contact-box .checkmark.material-icons{border:0 solid #0000;color:#0097a7;overflow:visible;padding-left:.5px}.contact-box .checkmark.material-icons,.contact-box .deleted.material-icons{background-color:#fff;bottom:0;font-size:1.5rem;height:1.5rem;position:absolute;right:0;width:1.5rem}.contact-box .deleted.material-icons{color:#999}#add-topic{bottom:1rem;position:absolute;right:1rem}.panel-form{display:flex;flex-direction:column;padding:0;position:relative}.panel-form-row{align-items:center;flex-shrink:0}.panel-form-column,.panel-form-row{display:flex;flex-grow:0;line-height:1.5;padding:.5rem .75rem;position:relative}.panel-form-column{flex-direction:column;overflow-x:hidden}.panel-form-column>.panel-form-column,.panel-form-row>.panel-form-column{flex-grow:1;padding:0!important}.panel-form-column>.panel-form-row,.panel-form-row>.panel-form-row{padding:0!important}.panel-form-column>.group{margin-bottom:.25rem;margin-top:.25rem}.avatar-upload{display:flex;flex-direction:column;flex-shrink:0;font-size:4.5rem;height:10.5rem;padding:0;position:relative;width:10rem}.avatar-upload.read-only{height:auto}.avatar-upload .clear-avatar{background-image:radial-gradient(#fff 40%,#0000 75%);font-size:1rem;opacity:0;position:absolute;right:0;top:0}.avatar-upload:hover .clear-avatar{opacity:1}.avatar-upload .avatar-box{height:10rem;position:relative;width:10rem}.avatar-upload .avatar-box>.material-icons{font-size:4rem;line-height:10rem;position:relative;vertical-align:middle}.avatar-upload:after{clear:both;content:".";display:block;height:0;visibility:hidden}.avatar-upload .blank{border:1px dashed #999;color:#999;flex-shrink:0;font-size:1rem;line-height:10rem;text-align:center;vertical-align:middle}.avatar-upload .blank,.avatar-upload img.preview{border-radius:50%;height:10rem;overflow:hidden;width:10rem}.avatar-upload img.preview:before{background:50% no-repeat url(../img/broken_image.png);border-radius:50%;color:#666;content:" ";display:flex;font-size:.9rem;font-weight:lighter;height:10rem;justify-content:center;left:0;position:absolute;top:0;width:10rem}.avatar-upload .inputfile.hidden{height:.1px;opacity:0;overflow:hidden;position:absolute;width:.1px}.avatar-upload .inputfile+label.round{align-items:center;background-color:#fafafa;border-radius:50%;bottom:0;box-shadow:0 1px 4px #0006;cursor:pointer;display:flex;height:3rem;justify-content:center;line-height:3rem;position:absolute;right:0;width:3rem;z-index:1}.avatar-upload .inputfile:focus+label.round{outline:none}.avatar-upload .inputfile+label:hover,.avatar-upload .inputfile:focus+label{background-color:#e3f2fd;color:#42a5f5}#topic-caption-panel{background-color:#b0bec5}#topic-caption-panel a{color:#757575;text-decoration:none}#topic-caption-panel :hover{color:#000}#topic-caption-panel .avatar-box{font-size:1.8rem;height:3rem;margin-right:.35rem;min-width:3rem;position:relative;width:3rem}#topic-caption-panel .avatar-box>.material-icons{font-size:2.4rem;line-height:3rem}#topic-title-group{overflow-x:hidden}#hide-message-view{display:block;margin-right:.35rem}#topic-users{margin-left:auto;margin-right:1rem;width:min-content}#topic-users .avatar-box{display:inline-block;font-size:1rem;height:1.8rem;margin-right:.2rem;min-height:1.8rem;min-width:1.8rem;width:1.8rem}#topic-users .avatar-box>.material-icons{font-size:1.4rem;line-height:1.8rem}#topic-users>span{line-height:2rem;vertical-align:top}#messages-panel{background-color:#eceff1;background-image:url(../img/bg_messages.png);height:100%;overflow-y:scroll;padding:.75rem;position:relative}#messages-container{height:100%;overflow-y:hidden;position:relative}#write-only-background{background-image:repeating-linear-gradient(45deg,#ffffff80,#ffffff80 .5rem,#fffc 0,#fffc 1rem);height:100%;left:0;position:absolute;top:0;width:100%}#write-only-note{height:auto;top:50%;transform:translate(-50%,-50%);width:auto}#peer-messaging-disabled-note,#write-only-note{background-color:#fff;border-radius:.5rem;box-shadow:0 1px .5px #0000001f;color:#666;left:50%;line-height:2rem;padding:.75rem 1.25rem;position:absolute;text-align:center}#peer-messaging-disabled-note{bottom:4.3rem;transform:translate(-50%);width:fit-content}#send-message-panel{align-items:center;background-color:#eceff1;display:flex;flex:none;min-height:4rem;padding:.4rem .4rem .4rem .6rem;z-index:2}#send-message-panel #writing-disabled{font-size:1.2rem;text-align:center;width:100%}#send-message-wrapper{background-color:#eceff1;box-shadow:0 -2px 3px -1px #0000001a;z-index:2}#sendMessage{overflow:hidden;overflow-wrap:break-word}#send-message-panel .material-icons{font-size:1.6rem;min-width:2rem}#send-message-panel .material-icons.secondary,.material-icons.disabled{color:#999!important}#send-message-panel .material-icons.secondary:hover{color:#2196f3!important}#send-message-input{max-height:6rem;min-height:2.5rem;overflow:hidden auto}.accept-invite-panel{background-color:#eceff1;box-shadow:0 -2px 3px -1px #0000001a;width:100%;z-index:1}.accept-invite-panel .title{font-size:1.2rem;padding:.75rem}.accept-invite-panel .footer{background-color:#fafafa;padding-bottom:.35rem;text-align:center;white-space:nowrap}.accept-invite-panel button{border:1px solid #0000;box-shadow:0 1px 2px 0 #00000040;font-size:1rem;height:2em;line-height:2em;margin:.25rem}#dummy-view{align-items:center;background-color:#e0f7fa;display:flex;height:100%;justify-content:center;width:100%}#dummy-view a{display:block;text-align:center;text-decoration:none}#image-preview{background-color:#ffffffe6;display:flex;flex-direction:column;height:100%;left:0;position:absolute;top:0;width:100%;z-index:2}#image-preview-caption-panel{background-color:#eceff1;box-shadow:0 1px 2px silver;display:flex;height:4.6rem;justify-content:space-between;line-height:2.5rem;padding:1rem .75rem 0;z-index:3}#image-preview-caption-panel a{color:#757575;text-decoration:none}#image-preview-caption-panel a:hover{color:#000}#image-preview-container{align-items:center;display:flex;height:100%;justify-content:space-around;overflow:hidden;width:100%}#image-preview-footer{background-color:#eceff1;box-shadow:0 -2px 3px -1px #0000001a;display:flex;height:3.2rem;justify-content:space-around;line-height:1.5rem;z-index:1}#image-preview-container .material-icons{font-size:6rem}#video-container{background-color:#ffffffe6;flex-direction:column;height:100%;justify-content:space-between;left:0;top:0}#video-container,.controls{display:flex;position:absolute;width:100%}.controls{align-items:center;bottom:2.5rem;column-gap:1rem;justify-content:center;z-index:1}.incoming-call .controls{bottom:1rem}.controls button{border-radius:50%;box-shadow:0 3px 6px 0 #00000040;height:4rem;min-width:auto;width:4rem}#video-container-panel{height:100%;position:relative;width:100%}.call-party{background-color:#eee;border:2px solid #ccc;border-radius:.5rem;overflow:hidden}.call-party:hover{border:2px solid #2196f3}.call-party.peer{bottom:1rem;left:1rem;position:absolute;right:1rem;top:1rem;z-index:1}.call-party.self{bottom:.5rem;height:10rem;position:absolute;right:.5rem;width:10rem;z-index:2}.call-party.self[disabled]{display:none}video{height:100%;object-fit:contain;width:100%}.call-party.self video{transform:scaleX(-1)}.call-party[disabled] video{display:none}.caller-card{align-items:center;display:flex;flex-direction:column;height:100%;justify-content:center;left:0;position:absolute;top:0;width:100%}.caller-card .avatar-box{font-size:6rem;height:10rem;width:10rem}.caller-card.pulse .lettertile,.caller-card.pulse img.avatar{animation:active-call 1.5s linear infinite}.caller-card .avatar-box .material-icons{font-size:6rem;line-height:1.6}.call-party .caller-name{background-color:#ffffffb3;border-radius:.35rem;padding:.15rem .5rem;text-shadow:0 0 1px #fff;z-index:1}.call-party.self .caller-name.inactive{bottom:.25rem;position:absolute;right:.25rem}.caller-card .caller-name{font-size:larger;margin-top:.5rem}.caller-card .trusted-badge{display:inline-block}.call-party.peer .caller-name.inactive{bottom:.5rem;font-size:larger;left:1rem;margin:0 auto;position:absolute}.incoming-call{background-color:#fff;border-radius:.3rem;box-shadow:.15rem .15rem 1.5rem #00000073;margin:auto 2rem;max-width:24rem;min-width:16rem;position:relative;width:fit-content}.incoming-call .caller-card{align-items:center;display:flex;flex-direction:column;height:100%;justify-content:center;left:auto;padding:4rem 3.5rem 5.5rem;position:relative;top:auto;width:100%}.incoming-call .caller-name{background-color:#ffffffb3;border-radius:.35rem;padding:.15rem .5rem;text-shadow:0 0 1px #fff;z-index:1}.call-message{display:flex;flex-direction:row}.call-message .duration{font-weight:lighter}@keyframes active-call{0%{box-shadow:0 0 0 .1rem #2196f34d,0 0 0 .3rem #2196f34d,0 0 0 .5rem #2196f34d}to{box-shadow:0 0 0 .4rem #2196f34d,0 0 0 2rem #2196f300,0 0 0 3rem #2196f300}}.chat-box{list-style:none;margin:0 .5rem;padding:0 0 3.5rem;scroll-behavior:smooth}.chat-box.group{margin-left:-.4rem}.chat-box li{align-items:flex-end;display:flex;margin:0;padding:0}.chat-box .right{justify-content:flex-end}.bubble{border-radius:.5rem;color:#212121;display:flex;filter:drop-shadow(.5px .5px .7px rgb(0,0,0,.3));height:auto;margin:0;max-width:36rem;min-width:9rem;padding:.75rem .5rem;position:relative;text-align:left;transition:background-color .5s ease-out;transition-delay:.3s}.chat-box li.single{margin-bottom:.75rem;margin-top:.25rem}.chat-box li.first{margin-bottom:.15rem;margin-top:.25rem}.chat-box li.middle{margin-bottom:.15rem;margin-top:.15rem}.chat-box li.last{margin-bottom:.75rem;margin-top:.15rem}.left .bubble{background-color:#c5e1a5;margin-right:.5rem}.left.flash .bubble{background-color:#94a97c}.left .bubble.tip{border-bottom-left-radius:0}.right .bubble{background-color:#fafafa;margin-left:1.75rem}.right.flash .bubble{background-color:#ccc}.right .bubble.tip{border-bottom-right-radius:0}.chat-box .meta{justify-content:center;margin-bottom:.5rem;margin-top:.5rem}.chat-box .meta .bubble{color:#666;min-width:unset}.meta .bubble.deleted{background-color:#e3f2fd;padding:.75rem .75rem .5rem}.meta .bubble.date{background-color:#fffc;font-size:smaller;padding:.5rem;text-transform:uppercase}.left .bubble.tip:before{background-color:#c5e1a5;border-bottom-left-radius:.3rem;bottom:0;clip-path:polygon(100% 0,0 110%,100% 110%);-webkit-clip-path:polygon(100% 0,0 110%,100% 110%);content:"";height:.85rem;left:-.8rem;position:absolute;transition:background-color .5s ease-out;transition-delay:.3s;width:.85rem}.left.flash .bubble.tip:before{background-color:#94a97c}.right .bubble.tip:before{background-color:#fafafa;border-bottom-right-radius:.3rem;bottom:0;clip-path:polygon(0 0,100% 110%,0 110%);-webkit-clip-path:polygon(0 0,100% 110%,0 110%);content:"";height:.85rem;left:99.8%;position:absolute;transition:background-color .5s ease-out;transition-delay:.3s;width:.85rem}.right.flash .bubble.tip:before{background-color:#ccc}.chat-box .avatar-box{font-size:.8rem;height:1.4rem;margin-bottom:.8rem;margin-right:.8rem;min-height:1.4rem;min-width:1.4rem;position:relative;width:1.4rem}.bubble div.content-meta{width:100%}.bubble div.message-content{margin:0;max-width:36rem;overflow-wrap:anywhere;padding:0 .75rem;position:relative;width:100%}.bubble div.message-content:after{clear:both;content:".";display:block;height:0;visibility:hidden}.chat-box .timestamp-padding{display:inline-block;height:0;width:4rem}.chat-box .timestamp{float:right;position:relative;top:.35rem;user-select:none;white-space:nowrap}.chat-box .author,.chat-box .timestamp{color:#777;font-size:80%}.image-preview,.inline-image{border-radius:.1rem;overflow:hidden;position:relative}.inline-image{max-height:24rem;max-width:36rem}.inline-image>.rounded-container{border-left:.25rem solid #0000;border-right:.25rem solid #0000;bottom:2rem;margin:.25rem auto;position:relative}img.image-preview:before,img.inline-image:before{background:50% no-repeat #ccc url(../img/broken_image.png);color:#666;display:flex;font-size:.9rem;font-weight:lighter;height:100%;justify-content:center;left:0;position:absolute;top:0;width:100%}img.inline-image:before{background-size:3rem 3rem;content:attr(alt)}img.image-preview:before{background-size:10rem 10rem;content:" "}.inline-image.video>img.inline-image:before,img.image-preview.video:before{background:50% no-repeat #ccc url(../img/broken_video.png)}.inline-image.video>img.inline-image:before{background-size:3rem 3rem}.inline-video{align-items:center;display:flex;justify-content:center;position:relative}.inline-video>img.inline-image:before{background:#ccc}.inline-video .duration{background-color:#ffffff80;border-radius:.3rem;bottom:.25rem;color:#333;font-size:80%;left:.25rem;padding:.25rem .5rem;position:absolute}.inline-video .play-control{align-items:center;background-color:#0006;border-radius:50%;cursor:pointer;display:flex;height:4rem;justify-content:center;pointer-events:none;position:absolute;width:4rem}.attachment{display:flex}.attachment:last-of-type{margin-bottom:-.45rem}#info-caption-panel{background-color:#b0bec5}#info-caption-panel a{color:#757575;line-height:1;text-decoration:none}#info-caption-panel :hover{color:#000}#info-title{margin-right:auto}#group-manager{display:flex;flex-direction:column;height:100%;overflow-y:hidden;position:relative}#group-manager-buttons{background-color:#eceff1;border-left:1px solid #ccc;box-shadow:0 -1px #0000001a;display:flex;height:4rem;justify-content:space-around;padding:.4rem;z-index:2}ul.tabbar{background:#eee;display:flex;flex-grow:0;flex-shrink:0;list-style:none;margin:0;overflow:hidden;padding:0 0 0 1rem;width:100%}ul.tabbar>li{box-shadow:inset 0 -2px 2.5px -1px #00000040;height:2.4rem;position:relative}ul.tabbar li.active{background:#fff}ul.tabbar li:after{background:#ccc;bottom:0;content:"";height:.1rem;left:0;position:absolute;width:100%}ul.tabbar li.active:after{animation:tabbar-border-expand .2s cubic-bezier(.4,0,.4,1) 0s alternate forwards;background:#2196f3;bottom:0;content:"";height:.15rem;left:0;position:absolute}@keyframes tabbar-border-expand{0%{opacity:0;width:0}to{opacity:1;width:100%}}ul.tabbar>li>a{color:#2196f399;font-size:1.3rem;font-variant:small-caps;font-weight:400;line-height:2.4rem;overflow:hidden;padding-left:1rem;padding-right:1rem;position:relative;text-align:center;text-decoration:none}ul.tabbar li.active>a{color:#2196f3}.unread{background-color:#0097a7;border-radius:50%;color:#fff;display:inline-block;font-size:.75rem;font-weight:bolder;height:1.35rem;line-height:1.45rem;margin-left:.5rem;text-align:center;vertical-align:middle;width:1.35rem}.material-icons.as-badge{color:#aaa;font-size:1.15rem;padding-left:.2rem}.badge{align-self:flex-start;background-color:#e8e8e8;border:1px solid silver;border-radius:.2rem;color:#666;display:inline-block;font-family:Roboto Mono,Courier,monospace,sans-serif;font-size:.8rem;margin:.05rem .1rem;padding:.05rem .25rem}.badge.green{background-color:#efe;border-color:#aca;color:#383}.badge.yellow{background-color:#ffe;border-color:#cc9;color:#660}.badge.blue{background-color:#eef;border-color:#aad;color:#339}.badge.red{background-color:#fee;border-color:#c99;color:#933}.badge.magenta{background-color:#fef;border-color:#c9c;color:#939}.lettertile{border-radius:50%;padding-bottom:100%;user-select:none;width:100%}.lettertile>div{align-items:center;border-radius:50%;bottom:0;color:#fafafacc;display:flex;flex-grow:0;flex-shrink:0;justify-content:center;left:0;line-height:1;padding-top:.1em;position:absolute;right:0;text-align:center;text-transform:uppercase;top:0}.lettertile:hover{color:#fff}.lettertile.disabled{opacity:.5}.lt-bg-0{background-color:#ef9a9a}.lt-bg-1{background-color:#90caf9}.lt-bg-2{background-color:#b0bec5}.lt-bg-3{background-color:#b39ddb}.lt-bg-4{background-color:#ffab91}.lt-bg-5{background-color:#a5d6a7}.lt-bg-6{background-color:#eee}.lt-bg-7{background-color:#e6ee9c}.lt-bg-8{background-color:#c5e1a5}.lt-bg-9{background-color:#f0e57d}.lt-bg-10{background-color:#f48fb1}.lt-bg-11{background-color:#9fa8da}.lt-bg-12{background-color:#ffe082}.lt-bg-13{background-color:#bcaaa4}.lt-bg-14{background-color:#80deea}.lt-bg-15{background-color:#ce93d8}.dk-bg-0{background-color:#c62828}.dk-bg-1{background-color:#ad1457}.dk-bg-2{background-color:#6a1b9a}.dk-bg-3{background-color:#4527a0}.dk-bg-4{background-color:#283593}.dk-bg-5{background-color:#1565c0}.dk-bg-6{background-color:#0277bd}.dk-bg-7{background-color:#00838f}.dk-bg-8{background-color:#00695c}.dk-bg-9{background-color:#2e7d32}.dk-bg-10{background-color:#558b2f}.dk-bg-11{background-color:#9e9d24}.dk-bg-12{background-color:#f9a825}.dk-bg-13{background-color:#ff8f00}.dk-bg-14{background-color:#ef6c00}.dk-bg-15{background-color:#d84315}.lt-fg-0{color:#ef9a9a!important}.lt-fg-1{color:#90caf9!important}.lt-fg-2{color:#b0bec5!important}.lt-fg-3{color:#b39ddb!important}.lt-fg-4{color:#ffab91!important}.lt-fg-5{color:#a5d6a7!important}.lt-fg-6{color:#eee!important}.lt-fg-7{color:#e6ee9c!important}.lt-fg-8{color:#c5e1a5!important}.lt-fg-9{color:#f0e57d!important}.lt-fg-10{color:#f48fb1!important}.lt-fg-11{color:#9fa8da!important}.lt-fg-12{color:#ffe082!important}.lt-fg-13{color:#bcaaa4!important}.lt-fg-14{color:#80deea!important}.lt-fg-15{color:#ce93d8!important}.dk-fg-0{color:#c62828!important}.dk-fg-1{color:#ad1457!important}.dk-fg-2{color:#6a1b9a!important}.dk-fg-3{color:#4527a0!important}.dk-fg-4{color:#283593!important}.dk-fg-5{color:#1565c0!important}.dk-fg-6{color:#0277bd!important}.dk-fg-7{color:#00838f!important}.dk-fg-8{color:#00695c!important}.dk-fg-9{color:#2e7d32!important}.dk-fg-10{color:#558b2f!important}.dk-fg-11{color:#9e9d24!important}.dk-fg-12{color:#f9a825!important}.dk-fg-13{color:#ff8f00!important}.dk-fg-14{color:#ef6c00!important}.dk-fg-15{color:#d84315!important}.material-icons{font-size:1.4rem;line-height:1;text-align:center;vertical-align:middle}.material-icons.small{font-size:1rem}.material-icons.medium{font-size:1.2rem}.material-icons.big{font-size:2.2rem}.material-icons.bigger{font-size:3rem}.material-icons.huge{font-size:4rem}.composed-material{display:inline-block;position:relative}.composed-material i:nth-child(2){font-size:85%;font-weight:700;left:39%;position:absolute;top:7%}#self-avatar .material-icons{font-size:2.4rem;line-height:3rem}.avatar-box .material-icons{border-radius:50%;color:#fafafacc;height:inherit;width:inherit}.chip-input{align-items:center;background:#0000;border-bottom:1px solid #ccc;box-shadow:0 1px 0 #0000001a;color:#666;cursor:text;display:flex;flex-grow:1;flex-wrap:wrap;font-size:1.1rem;font-weight:400;justify-content:flex-start;margin:.25rem 0;max-height:10rem;min-height:4rem;outline:none;overflow-y:scroll;text-align:center;transition:all .1s ease-in-out}.chip-input.focused{border-bottom:1px solid #2196f3;box-shadow:0 1px 0 #2196f340}.chip-input>input[type=text]{border:none;box-shadow:none;display:inline-block;flex:1 0 auto;min-width:4rem;width:auto}.chip,.chip-input>input[type=text]{height:1.8rem;line-height:1.8;margin:.125rem}.chip{align-items:center;background-color:#eee;border-radius:.9rem;display:flex;flex:0 0 auto;font-size:90%;max-width:12rem;overflow:hidden}.chip,.chip>span{text-overflow:ellipsis;white-space:nowrap}.chip>span{overflow-x:hidden}.chip.invalid{background-color:#fee;color:#c66}.chip>a{background-color:#aaa;border-radius:50%;color:#eee;display:inline-block;height:1.175rem;line-height:1.15;margin:.3rem;min-width:1.175rem;text-decoration:none;width:1.175rem}.chip>a:focus,.chip>a:hover{background-color:#bbb;color:#fff;text-decoration:none}.chip .avatar-box{font-size:1rem;height:1.8rem;margin-right:.2rem;min-height:1.8rem;min-width:1.8rem;position:relative;width:1.8rem}.chip .avatar-box .material-icons{font-size:1.4rem;line-height:1.8rem}.chip .spacer{display:inline-block;height:1.175rem;margin:.3rem;width:.25rem}.load-spinner-box{--size-small:2.5rem;--size-large:4rem;background-color:#fff;border-radius:50%;box-shadow:.1rem .1rem .15rem 1px #00000040;height:var(--size-small);left:0;margin-left:auto;margin-right:auto;padding:.25rem;position:absolute;right:0;top:5rem;width:var(--size-small);z-index:2}.load-spinner-box.large{height:var(--size-large);width:var(--size-large)}.load-spinner-box.clear{background-color:#fff8;-x-box-shadow:none;box-shadow:.1rem .1rem .15rem 1px #0000001f}.load-spinner-box.centered{top:calc(var(--size-small)/2 - .25rem)}.load-spinner-box.large.centered{top:calc(var(--size-large)/2 - .25rem)}.loader-spinner{animation:spin 1.5s linear infinite;border:.35rem solid #f3f3f3;border-radius:50%;border-top-color:#1e88e5;height:2rem;width:2rem}.load-spinner-box.large .loader-spinner{height:3.5rem;width:3.5rem}@keyframes spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.uploader{display:flex}.uploader>div{background-color:#cfd8dc;border-radius:.1rem;height:.6rem;line-height:0;margin:.35rem;padding:.15rem;position:relative;width:6rem}.uploader>div>span{background-color:#1e88e5;border-radius:.08rem;display:inline-block;height:.3rem}.highlight{color:teal;font-weight:bolder}.highlight .preview{color:#5f9ea0;font-weight:inherit}.cropper{align-self:center;height:21rem;margin:1rem auto auto;transform:translateZ(0)}.cropper,.cropper .bounding-box{border-radius:.25rem;position:relative;width:18rem}.cropper .bounding-box{background-color:#999;border:2px solid #1e88e5;box-shadow:1px 1px 3px grey;height:18rem;overflow:hidden;z-index:1}.cropper .preview{max-height:none;max-width:none;position:absolute;z-index:-1}.cropper .cutout{border:1px dashed #999;bottom:0;box-shadow:0 0 150rem 150rem #e6f6ffa8;height:17rem;left:0;margin:auto;position:absolute;right:0;top:0;width:17rem;z-index:0}.cropper .cutout.circle{border-radius:50%}.cropper .overlay{cursor:move;position:absolute;touch-action:none;z-index:1}.cropper .zoom-wrapper{height:2rem;margin:1rem auto;text-align:center;width:80%}.cropper .zoom{box-shadow:none;pointer-events:none;z-index:2}.cropper .zoom:focus{outline:none}.reply-quote{border-left:.25rem solid #039be5;border-radius:.25rem;color:#666;cursor:pointer;font-weight:lighter;line-height:1.5em;padding:.15rem .5rem .25rem;position:relative}.chat-box .bubble .reply-quote{margin:.15rem -.75rem .3rem}.chat-box .bubble .reply-quote:first-child{margin-top:-.25rem}.chat-box .left .reply-quote{background-color:#fff6}.chat-box .right .reply-quote{background-color:#8080801f}.reply-quote .inline-image{margin-bottom:.1rem;vertical-align:middle}.reply-quote img.inline-image:before{content:""}#reply-quote-preview{align-items:center;display:flex}#reply-quote-preview .reply-quote{background-color:#fafafa;cursor:auto;margin:.35rem .5rem 0 0;width:100%}#reply-quote-preview .cancel{min-width:2.4rem;text-align:center}#reply-quote-preview .inline-image{background-color:#ccc}#reply-quote-preview img.inline-image:before{content:""}#send-message-panel #reply-quote-preview{width:100%}#send-message-panel #reply-quote-preview .reply-quote{margin-bottom:.35rem}.forwarding-quote{font-size:200%;line-height:200%}.mention{font-weight:500}.forward-dialog{background-color:#fff;border-radius:.3rem;box-shadow:.15rem .15rem 1.5rem #00000073;height:80%;margin:auto 1rem;overflow:hidden;padding:.5rem;position:relative;width:24rem}.forward-dialog .scrollable-panel{height:80%}.audio{align-items:center;background-color:#eee;border-radius:1.5rem;display:flex;flex:none;height:3rem;margin-left:auto}.audio canvas{height:2.6rem;margin-right:2rem;width:14rem}.audio canvas.playback{margin-right:0}.audio .duration{font-size:large}.audio-player{align-items:center;display:flex}.audio-player .material-icons.large{color:#667575cc;font-size:2.4rem}.audio-player .material-icons.disabled{color:#999c;cursor:default}.audio-player .playback{height:2.6rem;width:14rem}.audio-player canvas.playback{display:block}.audio-player div.playback{align-items:center;color:#757575cc;display:flex;font-size:small;justify-content:center}.audio-player .timer{color:#666c;font-size:smaller}#pinned-wrapper{margin-right:1rem}#pinned-wrapper,.pinned{align-items:center;display:flex;height:100%;position:relative}.pinned{background-color:#fafafa;background-position:50%;border-radius:0 .25rem .25rem 0;color:#666;cursor:pointer;font-weight:lighter;min-width:0;padding:.15rem .5rem .25rem;transition:background .4s;width:24rem}.pinned>p{overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.pinned:hover{background-color:#fafdff}.pinned:active{background-color:#d8e8ff;transition:background 0s}.pinned-scroll{align-items:center;background-color:#eeee;border-radius:.25rem 0 0 .25rem;display:flex;flex-direction:column;height:100%;justify-content:space-evenly;margin-left:.35rem;padding:.1rem;position:relative}.pinned-scroll .dot{background-color:#999;border-radius:50%;height:.3rem;width:.3rem}.pinned-scroll .adot{background-color:#039be5;border-radius:50%;height:.45rem;width:.45rem}#pinned-wrapper .menuTrigger.upper{top:.25rem}#pinned-wrapper .menuTrigger.lower{bottom:.25rem}#pinned-wrapper:hover .menuTrigger{opacity:.9}#pinned-wrapper:hover .menuTrigger a{color:#757575}.drag-n-drop{align-items:center;background-color:#fffffff2;border:.15rem dashed grey;border-radius:1rem;bottom:1.5rem;color:grey;display:flex;font-size:2rem;justify-content:center;left:1.5rem;outline:.5rem solid #fffffff2;position:absolute;right:1.5rem;top:1.5rem;z-index:3}.country-flag{display:inline-block;font-size:larger}.dial-code{cursor:pointer;display:inline-block;margin-bottom:.15rem;vertical-align:middle;white-space:nowrap}ul.phone-country-selector{list-style:none;overflow-x:hidden}ul.phone-country-selector>li{cursor:pointer;font-weight:lighter;padding:.25rem .5rem .15rem;position:relative;width:100%}ul.phone-country-selector>li:hover{background-color:#eceff1}ul.phone-country-selector>li.selected{background-color:#cfd8dc}ul.phone-country-selector .dial-code{color:#1e88e5;font-weight:400;position:absolute;right:.5rem}ul.phone-country-selector span{display:inline-block}ul.phone-country-selector span.country{overflow-x:hidden;text-overflow:ellipsis}@media (min-width:1440px){#app-container{max-width:114rem}}@media (max-width:960px){#mountPoint{padding:0}.pinned{width:16rem}}@media (max-width:640px){#app-container{border-radius:0;box-shadow:none;width:100%}#info-view,#sidepanel{width:100%}.forward-dialog{border-radius:.3rem .3rem 0 0;margin:auto 0 0;width:100%}.menuTrigger{opacity:.3}#send-message-input{transition-property:-tinode-mobile}#pinned-wrapper{height:3.5rem;margin:.25rem}.pinned{width:unset}} \ No newline at end of file diff --git a/src/widgets/pinned-messages.jsx b/src/widgets/pinned-messages.jsx index 0c89be2a..f42be936 100644 --- a/src/widgets/pinned-messages.jsx +++ b/src/widgets/pinned-messages.jsx @@ -72,7 +72,7 @@ class PinnedMessages extends React.PureComponent {
{shown}
Visible for testing\r\n */\r\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\r\n/**\r\n * The percentage of backoff time to randomize by.\r\n * See\r\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\r\n * for context.\r\n *\r\n *
Visible for testing\r\n */\r\nconst RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\r\n // Calculates an exponentially increasing value.\r\n // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n // and count to restore state.\r\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n // A random \"fuzz\" to avoid waves of retries.\r\n // Deviation: randomFactor is required.\r\n const randomWait = Math.round(\r\n // A fraction of the backoff value to add/subtract.\r\n // Deviation: changes multiplication order to improve readability.\r\n RANDOM_FACTOR *\r\n currBaseValue *\r\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n // if we add or subtract.\r\n (Math.random() - 0.5) *\r\n 2);\r\n // Limits backoff to max to avoid effectively permanent backoff.\r\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n if (!Number.isFinite(i)) {\r\n return `${i}`;\r\n }\r\n return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n i = Math.abs(i);\r\n const cent = i % 100;\r\n if (cent >= 10 && cent <= 20) {\r\n return 'th';\r\n }\r\n const dec = i % 10;\r\n if (dec === 1) {\r\n return 'st';\r\n }\r\n if (dec === 2) {\r\n return 'nd';\r\n }\r\n if (dec === 3) {\r\n return 'rd';\r\n }\r\n return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n if (service && service._delegate) {\r\n return service._delegate;\r\n }\r\n else {\r\n return service;\r\n }\r\n}\n\nexport { CONSTANTS, DecodeBase64StringError, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm2017.js.map\n","import { PACKAGE_VERSION } from './version.js';\n\n// Name of this application, used in the User-Agent.\nexport const APP_NAME = 'TinodeWeb/' + (PACKAGE_VERSION || '0.21');\n\n// API key. Use https://github.com/tinode/chat/tree/master/keygen to generate your own\nexport const API_KEY = 'AQEAAAABAAD_rAp4DJh05a1HAwFT3A6K';\n\n// The array of possible hosts to connect to.\nexport const KNOWN_HOSTS = {hosted: 'web.tinode.co', local: 'localhost:6060'};\n\n// Default host name and port to connect to.\nexport const DEFAULT_HOST = KNOWN_HOSTS.hosted;\n\n// Enable console logging.\nexport const LOGGING_ENABLED = true;\n\n// Minimum time between two keypress notifications, milliseconds.\nexport const KEYPRESS_DELAY = 3_000;\n// Delay before sending a read notification, milliseconds.\nexport const READ_DELAY = 1_500;\n\n// The default shortest allowed tag length. Matches the value on the server.\nexport const MIN_TAG_LENGTH = 2;\n// The default greatest allowed tag length. Matches the value on the server.\nexport const MAX_TAG_LENGTH = 96;\n// The default maximum number of tags allowed. Matches the value on the server.\nexport const MAX_TAG_COUNT = 16;\n\n// Access mode for P2P subscriptions initiated by the current user.\nexport const DEFAULT_P2P_ACCESS_MODE = 'JRWPS';\n// Access mode for new group topics created by the current user.\nexport const NEW_GRP_ACCESS_MODE = 'JRWPSAO';\n// Access mode for a channel.\nexport const CHANNEL_ACCESS_MODE = 'JR';\n\n// Access mode for no access.\nexport const NO_ACCESS_MODE = 'N';\n\n// Mediaquery breakpoint between desktop and mobile, in px. Should match the value\n// in @media (max-size: 640px) in base.css\nexport const MEDIA_BREAKPOINT = 640;\n// Size of css 'rem' unit in pixels. Default 1rem = 10pt = 13px.\nexport const REM_SIZE = 13;\n\n// Size of the avatar image: when image dimensions are greater or the image is not square, it's resized to\n// a square of this size or less.\nexport const AVATAR_SIZE = 384;\n\n// Maximum size of an avatar in bytes for sending in-band. Bigger avatars will be sent out of band (as uploads).\nexport const MAX_AVATAR_BYTES = 4096;\n\n// Size of the broken_image shown in MessagesView\nexport const BROKEN_IMAGE_SIZE = 32;\n\n// Size of video preview when dimensions are missing.\nexport const NO_DIMENSIONS_VIDEO = 128;\n\n// Number of chat messages to fetch in one call.\nexport const MESSAGES_PAGE = 24;\n\n// Default maximum in-band (included directly into the message) attachment size which fits into\n// a message of 256K in size. Used when the server-provided value is unavailable. The actual\n// binary size of the attachment should be smaller due to base64 encoding expansion and some overhead,\n// for instance 1024 bytes.\n// Increase this limit to a greater value in production, if desired. Also increase\n// max_message_size in the server config.\nexport const MAX_INBAND_ATTACHMENT_SIZE = 262_144;\n\n// Default absolute maximum attachment size to be used with the server = 8MB.\n// Used when the server-provided value is unavailable. Increase to something like 100MB in production.\nexport const MAX_EXTERN_ATTACHMENT_SIZE = 1 << 23;\n\n// Maximum allowed linear dimension (pixels) of an image sent inline. Larger images will be shrunk\n// to make the larger dimension fit under this size. You may want to adjust it to 1600 or\n// 2400 for production.\nexport const MAX_IMAGE_DIM = 1024;\n\n// Linear dimensions of image preview: shrink image under this size for previews.\nexport const IMAGE_PREVIEW_DIM = 64;\n\n// Linear dimensions of video screencapture: shrink image under this size for previews.\nexport const VIDEO_PREVIEW_DIM = 96;\n\n// Linear dimensions of image thumbnail: shrink image under this size for thumbnails in reply quote previews.\nexport const IMAGE_THUMBNAIL_DIM = 36;\n// Width of video thumbnail: allow it to be wider, but not taller. Use IMAGE_THUMBNAIL_DIM for height.\nexport const VIDEO_THUMBNAIL_WIDTH = 48;\n\n// Maximum number of online users to be shown in a topic title bar. Others will be\n// hidden under \"+X more\"\nexport const MAX_ONLINE_IN_TOPIC = 4;\n\n// Maximum length of user name, topic title, and private comment.\nexport const MAX_TITLE_LENGTH = 60;\n// Maximum length of topic description.\nexport const MAX_TOPIC_DESCRIPTION_LENGTH = 360;\n// Maximum length of user name when displaying a video call.\nexport const MAX_PEER_TITLE_LENGTH = 20;\n\n// Length of message previews in chat list, in characters.\nexport const MESSAGE_PREVIEW_LENGTH = 80;\n\n// Length of a quote in quoted reply (for outgoing messages).\nexport const QUOTED_REPLY_LENGTH = 30;\n// Length of a preview of a forwarded message.\nexport const FORWARDED_PREVIEW_LENGTH = 84;\n// Length of preview for a message being edited.\nexport const EDIT_PREVIEW_LENGTH = 48;\n\n// Minimum duration of an audio recording in milliseconds (2 sec).\nexport const MIN_DURATION = 2_000;\n// Maximum duration of an audio recording in milliseconds (10 min).\nexport const MAX_DURATION = 600_000;\n\n// Link for \"Contact Us\".\nexport const LINK_CONTACT_US = 'mailto:support@tinode.co';\n\n// Link to Privacy Policy.\nexport const LINK_PRIVACY_POLICY = 'https://tinode.co/privacy.html';\n\n// Link to Terms of Service.\nexport const LINK_TERMS_OF_SERVICE = 'https://tinode.co/terms.html';\n\n// When user starts a P2P topic, automatic subscription does not\n// happen until the first message. Setting this option to true enables\n// immediate subscription.\nexport const IMMEDIATE_P2P_SUBSCRIPTION = false;\n","// Video call states.\nexport const CALL_STATE_NONE = 0;\nexport const CALL_STATE_OUTGOING_INITATED = 1;\nexport const CALL_STATE_INCOMING_RECEIVED = 2;\nexport const CALL_STATE_IN_PROGRESS = 3;\n\n// Video call message headers representing call state.\nexport const CALL_HEAD_STARTED = 'started';\n","// File and image helper functions.\n\n// Supported image MIME types and corresponding file extensions.\nexport const SUPPORTED_IMAGE_FORMATS = ['image/jpeg', 'image/gif', 'image/png', 'image/svg', 'image/svg+xml'];\nexport const MIME_EXTENSIONS = ['jpg', 'gif', 'png', 'svg', 'svg'];\n\n// Get an URL from a theCard photo: either create a data: URL or return reference URL.\nexport function makeImageUrl(photo) {\n if (photo && typeof photo == 'object') {\n if (photo.ref) {\n return photo.ref\n }\n if (photo.data && photo.type) {\n const mime = photo.type.startsWith('image/') ? photo.type : ('image/' + photo.type);\n return 'data:' + mime + ';base64,' + photo.data;\n }\n }\n return null;\n}\n\n// Calculate linear dimensions for scaling image down to fit under a certain size.\n// Returns an object which contains destination sizes, source sizes, and offsets\n// into source (when making square images).\nexport function fitImageSize(width, height, maxWidth, maxHeight, forceSquare) {\n // Sanitize input\n width = width | 0;\n height = height | 0;\n maxWidth = maxWidth | 0;\n maxHeight = maxHeight | 0;\n\n if (width <= 0 || height <= 0 || maxWidth <= 0 || maxHeight <= 0) {\n return null;\n }\n\n if (forceSquare) {\n maxWidth = maxHeight = Math.min(maxWidth, maxHeight);\n }\n\n const scale = Math.min(\n Math.min(width, maxWidth) / width,\n Math.min(height, maxHeight) / height\n );\n\n const size = {\n dstWidth: (width * scale) | 0,\n dstHeight: (height * scale) | 0,\n };\n\n if (forceSquare) {\n // Also calculate parameters for making the image square.\n size.dstWidth = size.dstHeight = Math.min(size.dstWidth, size.dstHeight);\n size.srcWidth = size.srcHeight = Math.min(width, height);\n size.xoffset = ((width - size.srcWidth) / 2) | 0;\n size.yoffset = ((height - size.srcWidth) / 2) | 0;\n } else {\n size.xoffset = size.yoffset = 0;\n size.srcWidth = width;\n size.srcHeight = height;\n }\n return size;\n}\n\n// Ensure file's extension matches mime content type\nexport function fileNameForMime(fname, mime) {\n const idx = SUPPORTED_IMAGE_FORMATS.indexOf(mime);\n if (idx < 0 || !fname) {\n // Unknown mime or empty name.\n return fname;\n }\n const ext = MIME_EXTENSIONS[idx];\n\n const at = fname.lastIndexOf('.');\n if (at >= 0) {\n fname = fname.substring(0, at);\n }\n return fname + '.' + ext;\n}\n\n// Scale uploaded image to fit under certain dimensions and byte size, optionally constraining to a square.\n// Returns a promise which is resolven on success or rejected on failure.\nexport function imageScaled(fileOrBlob, maxWidth, maxHeight, maxSize, forceSquare) {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.crossOrigin = 'Anonymous';\n img.onerror = function(err) {\n reject(new Error(\"Image format unrecognized\"));\n }\n img.onload = async function() {\n // Once the image is loaded, the URL is no longer needed.\n URL.revokeObjectURL(img.src);\n\n // Calculate the desired image dimensions.\n const dim = fitImageSize(img.width, img.height, maxWidth, maxHeight, forceSquare);\n if (!dim) {\n reject(new Error(\"Invalid image\"));\n return;\n }\n let canvas = document.createElement('canvas');\n canvas.width = dim.dstWidth;\n canvas.height = dim.dstHeight;\n let ctx = canvas.getContext('2d');\n ctx.imageSmoothingEnabled = true;\n ctx.drawImage(img, dim.xoffset, dim.yoffset, dim.srcWidth, dim.srcHeight,\n 0, 0, dim.dstWidth, dim.dstHeight);\n\n const mime = SUPPORTED_IMAGE_FORMATS.includes(fileOrBlob.type) ? fileOrBlob.type : 'image/jpeg';\n // Generate blob to check size of the image.\n let blob = await new Promise(resolve => canvas.toBlob(resolve, mime));\n if (!blob) {\n reject(new Error(\"Unsupported image format\"));\n return;\n }\n // Ensure the image is not too large. Shrink the image keeping the aspect ratio.\n // Do nothing if maxsize is <= 0.\n while (maxSize > 0 && blob.length > maxSize) {\n dim.dstWidth = (dim.dstWidth * 0.70710678118) | 0;\n dim.dstHeight = (dim.dstHeight * 0.70710678118) | 0;\n canvas.width = dim.dstWidth;\n canvas.height = dim.dstHeight;\n ctx = canvas.getContext('2d');\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.drawImage(img, dim.xoffset, dim.yoffset, dim.srcWidth, dim.srcHeight,\n 0, 0, dim.dstWidth, dim.dstHeight);\n blob = await new Promise(resolve => canvas.toBlob(resolve, mime));\n }\n\n canvas = null;\n resolve({mime: mime, blob: blob, width: dim.dstWidth, height: dim.dstHeight, name: fileNameForMime(fileOrBlob.name, mime)});\n };\n img.src = URL.createObjectURL(fileOrBlob);\n });\n}\n\n// Scale and crop image according to specified dimensions.\n// The coordinates are in unscaled image pixels, i.e. cut the rectangle first then scale it.\n// returns a promise.\nexport function imageCrop(mime, objURL, left, top, width, height, scale) {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.crossOrigin = 'Anonymous';\n img.onerror = _ => {\n reject(new Error(\"Image format unrecognized\"));\n };\n img.onload = _ => {\n // Once the image is loaded, the URL is no longer needed.\n URL.revokeObjectURL(img.src);\n\n let canvas = document.createElement('canvas');\n canvas.width = width * scale;\n canvas.height = height * scale;\n let ctx = canvas.getContext('2d');\n ctx.imageSmoothingEnabled = true;\n ctx.drawImage(img, left, top, width, height, 0, 0, canvas.width, canvas.height);\n\n mime = SUPPORTED_IMAGE_FORMATS.includes(mime) ? mime : 'image/jpeg';\n // Generate blob to check size of the image.\n canvas.toBlob((blob) => {\n // Allow GC.\n canvas = null;\n if (blob) {\n resolve({mime: mime, blob: blob, width: width, height: height});\n } else {\n reject(new Error(\"Unsupported image format\"));\n }\n }, mime);\n };\n img.src = objURL;\n });\n}\n\n// Convert file to base64 string.\nexport function fileToBase64(file) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = _ => {\n reject(reader.error);\n };\n reader.onload = _ => {\n resolve({mime: file.type, bits: reader.result.split(',')[1], name: file.name});\n };\n reader.readAsDataURL(file);\n });\n}\n\n// Convert Blob to base64 string. Returns a promise resolved with the base64 string and mime.\nexport function blobToBase64(blob) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = _ => {\n reject(reader.error);\n };\n reader.onload = _ => {\n resolve({mime: blob.type, bits: reader.result.split(',')[1]});\n };\n reader.readAsDataURL(blob);\n });\n}\n\n// File pasted from the clipboard. It's either an inline image or a file attachment.\nexport function filePasted(event, onImageSuccess, onAttachmentSuccess, onError) {\n const items = (event.clipboardData || event.originalEvent.clipboardData || {}).items;\n if (!items || !items.length) {\n return false;\n }\n\n for (let i in items) {\n const item = items[i];\n if (item.kind === 'file') {\n const file = item.getAsFile();\n if (!file) {\n console.error(\"Failed to get file object from pasted file item\", item.kind, item.type);\n onError(\"Failed to get file object from pasted file item\");\n continue;\n }\n if (file.type && file.type.split('/')[0] == 'image') {\n onImageSuccess(file);\n } else {\n onAttachmentSuccess(file);\n }\n // Indicate that the pasted data contains a file.\n return true;\n }\n }\n // No file found.\n return false;\n}\n\n// Get mime type from data URL header.\nexport function getMimeType(header) {\n const mime = /^data:(image\\/[-+a-z0-9.]+);base64/.exec(header);\n return (mime && mime.length > 1) ? mime[1] : null;\n}\n\n// Given length of a binary object in bytes, calculate the length after\n// base64 encoding.\nexport function base64EncodedLen(n) {\n return Math.floor((n + 2) / 3) * 4;\n}\n\n// Given length of a base64-encoded object, calculate decoded size of the\n// pbject in bytes.\nexport function base64DecodedLen(n) {\n return Math.floor(n / 4) * 3;\n}\n\n// Re-encode string to standard base64 encoding with padding.\n// The string may be base64-URL encoded without the padding.\nexport function base64ReEncode(str) {\n if (str) {\n str = str.replace(/-/g, '+').replace(/_/g, '/');\n try {\n str = btoa(atob(str));\n } catch(err) {\n console.error(\"Failed to base64 re-encode string.\", err);\n str = null;\n }\n }\n return str;\n}\n\n// Convert a base64 encoded string with the provided mime type into a Blob.\nexport function base64ToBlob(str, mime) {\n if (!str) {\n return null;\n }\n\n try {\n // Make blob.\n const bin = atob(str);\n const length = bin.length;\n const buf = new ArrayBuffer(length);\n const arr = new Uint8Array(buf);\n for (let i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n\n return new Blob([buf], { type: mime });\n } catch(err) {\n console.error(\"Failed to convert base64 to blob: \", err);\n }\n\n return null;\n}\n\nexport function intArrayToBase64(arr) {\n if (!Array.isArray(arr)) {\n return null;\n }\n try {\n let bin = '';\n new Uint8Array(arr).forEach(b => bin += String.fromCharCode(b));\n return window.btoa(bin);\n } catch (err) {}\n return null;\n}\n\nexport function base64ToIntArray(b64) {\n const arr = [];\n try {\n const bin = window.atob(b64);\n [...bin].forEach(c => {\n arr.push(c.charCodeAt(0));\n });\n return arr;\n } catch (err) {}\n return null;\n}\n","import React from 'react';\nimport { defineMessages } from 'react-intl';\n\nimport { Drafty } from 'tinode-sdk';\n\nimport AudioPlayer from '../widgets/audio-player.jsx'\nimport CallMessage from '../widgets/call-message.jsx'\nimport CallStatus from '../widgets/call-status.jsx';\nimport InlineVideo from '../widgets/inline-video.jsx';\nimport LazyImage from '../widgets/lazy-image.jsx'\nimport UploadingImage from '../widgets/uploading-image.jsx'\n\nimport { BROKEN_IMAGE_SIZE, IMAGE_THUMBNAIL_DIM, NO_DIMENSIONS_VIDEO, REM_SIZE, VIDEO_THUMBNAIL_WIDTH } from '../config.js';\nimport { base64ToBlob, blobToBase64, fitImageSize, imageScaled } from './blob-helpers.js';\nimport { idToColorClass, secondsToTime, shortenFileName } from './strformat.js';\nimport { cancelablePromise, sanitizeUrlForMime } from './utils.js';\n\nconst messages = defineMessages({\n drafty_form: {\n id: 'drafty_form',\n defaultMessage: 'Form: ',\n description: 'Comment for form in Drafty'\n },\n drafty_attachment: {\n id: 'drafty_attachment',\n defaultMessage: 'Attachment',\n description: 'Comment for attachment in Drafty'\n },\n drafty_image: {\n id: 'drafty_image',\n defaultMessage: 'Picture',\n description: 'Comment for embedded images in Drafty'\n },\n drafty_video: {\n id: 'drafty_video',\n defaultMessage: 'Video recording',\n description: 'Comment for videos embedded in Drafty'\n },\n drafty_unknown: {\n id: 'drafty_unknown',\n defaultMessage: 'Unsupported',\n description: 'Unsupported entity in drafty'\n }\n});\n\n// The main Drafty formatter: converts Drafty elements into React classes. 'this' is set by the caller.\n// 'this' must contain:\n// viewportWidth:\n// authorizeURL:\n// onImagePreview:\n// onVideoPreview:\n// onFormButtonClick:\n// onQuoteClick:\nexport function fullFormatter(style, data, values, key, stack) {\n if (stack.includes('QQ')) {\n return quoteFormatter.call(this, style, data, values, key);\n }\n\n if (!style) {\n // Unformatted.\n return values;\n }\n\n let el = Drafty.tagName(style);\n let attr = Drafty.attrValue(style, data) || {};\n attr.key = key;\n switch (style) {\n case 'AU':\n // Show audio player.\n if (attr.src) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'audio'));\n attr.duration = data.duration > 0 ? (data.duration | 0) : undefined;\n attr.preview = data.preview;\n attr.loading = 'lazy';\n }\n el = AudioPlayer;\n // Audio element cannot have content.\n values = null;\n break;\n case 'BR':\n values = null;\n break;\n case 'EX':\n // Ignore.\n break;\n case 'HL':\n // Highlighted text. Assign class name.\n attr.className = 'highlight';\n break;\n case 'HD':\n el = null;\n values = null;\n break;\n case 'IM':\n // Additional processing for images\n el = handleImageData.call(this, el, data, attr);\n // Image element cannot have content.\n values = null;\n break;\n case 'BN':\n // Button\n attr.onClick = this.onFormButtonClick;\n let inner = React.Children.map(values, (child) => {\n return typeof child == 'string' ? child : undefined;\n });\n if (!inner || inner.length == 0) {\n inner = [attr.name]\n }\n // Get text which will be sent back when the button is clicked.\n attr['data-title'] = inner.join('');\n break;\n case 'MN':\n // Mention\n attr.className = 'mention'\n if (data) {\n attr.className += ' ' + idToColorClass(data.val, false, true);\n }\n break;\n case 'FM':\n // Form\n attr.className = 'bot-form';\n break;\n case 'RW':\n // Form element formatting is dependent on element content.\n break;\n case 'QQ':\n // Quote/citation.\n attr.className = 'reply-quote'\n attr.onClick = this.onQuoteClick;\n break;\n case 'VC':\n el = CallMessage;\n // Video call messages do not have content.\n values = null;\n if (data) {\n attr.callState = data.state;\n attr.incoming = data.incoming;\n attr.duration = data.duration;\n }\n break;\n case 'VD':\n // Additional processing for videos.\n el = handleVideoData.call(this, el, data, attr);\n // Video element cannot have content.\n values = null;\n break;\n default:\n if (!el) {\n // Unknown element.\n el = React.Fragment;\n attr = {key: key};\n // Generate comment for unknown element.\n let body = values;\n if (!Array.isArray(values) || !values.join('').trim()) {\n body = [{this.formatMessage(messages.drafty_unknown)}];\n }\n values = [extension, ' '].concat(body);\n }\n break;\n }\n if (!el) {\n return values;\n }\n return React.createElement(el, attr, values);\n}\n\n// Additional processing of image data.\nfunction handleImageData(el, data, attr) {\n if (!data) {\n attr.src = 'img/broken_image.png';\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n };\n return el;\n }\n\n attr.className = 'inline-image';\n const dim = fitImageSize(data.width, data.height,\n this.viewportWidth > 0 ? Math.min(this.viewportWidth - REM_SIZE * 6.5, REM_SIZE * 34.5) :\n REM_SIZE * 34.5, REM_SIZE * 24, false) ||\n {dstWidth: BROKEN_IMAGE_SIZE, dstHeight: BROKEN_IMAGE_SIZE};\n attr.style = {\n width: dim.dstWidth + 'px',\n height: dim.dstHeight + 'px',\n // Looks like a Chrome bug: broken image does not respect 'width' and 'height'.\n minWidth: dim.dstWidth + 'px',\n minHeight: dim.dstHeight + 'px'\n };\n if (!Drafty.isProcessing(data)) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'image'));\n attr.alt = data.name;\n if (attr.src) {\n if (Math.max(data.width || 0, data.height || 0) > IMAGE_THUMBNAIL_DIM) {\n // Allow previews for large enough images.\n attr.onClick = this.onImagePreview;\n attr.className += ' image-clickable';\n }\n attr.loading = 'lazy';\n } else {\n attr.src = null;\n }\n } else {\n // Use custom element instead of Visible for testing\r\n */\r\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\r\n/**\r\n * The percentage of backoff time to randomize by.\r\n * See\r\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\r\n * for context.\r\n *\r\n * Visible for testing\r\n */\r\nconst RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\r\n // Calculates an exponentially increasing value.\r\n // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n // and count to restore state.\r\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n // A random \"fuzz\" to avoid waves of retries.\r\n // Deviation: randomFactor is required.\r\n const randomWait = Math.round(\r\n // A fraction of the backoff value to add/subtract.\r\n // Deviation: changes multiplication order to improve readability.\r\n RANDOM_FACTOR *\r\n currBaseValue *\r\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n // if we add or subtract.\r\n (Math.random() - 0.5) *\r\n 2);\r\n // Limits backoff to max to avoid effectively permanent backoff.\r\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n if (!Number.isFinite(i)) {\r\n return `${i}`;\r\n }\r\n return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n i = Math.abs(i);\r\n const cent = i % 100;\r\n if (cent >= 10 && cent <= 20) {\r\n return 'th';\r\n }\r\n const dec = i % 10;\r\n if (dec === 1) {\r\n return 'st';\r\n }\r\n if (dec === 2) {\r\n return 'nd';\r\n }\r\n if (dec === 3) {\r\n return 'rd';\r\n }\r\n return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n if (service && service._delegate) {\r\n return service._delegate;\r\n }\r\n else {\r\n return service;\r\n }\r\n}\n\nexport { CONSTANTS, DecodeBase64StringError, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm2017.js.map\n","import { PACKAGE_VERSION } from './version.js';\n\n// Name of this application, used in the User-Agent.\nexport const APP_NAME = 'TinodeWeb/' + (PACKAGE_VERSION || '0.21');\n\n// API key. Use https://github.com/tinode/chat/tree/master/keygen to generate your own\nexport const API_KEY = 'AQEAAAABAAD_rAp4DJh05a1HAwFT3A6K';\n\n// The array of possible hosts to connect to.\nexport const KNOWN_HOSTS = {hosted: 'web.tinode.co', local: 'localhost:6060'};\n\n// Default host name and port to connect to.\nexport const DEFAULT_HOST = KNOWN_HOSTS.hosted;\n\n// Enable console logging.\nexport const LOGGING_ENABLED = true;\n\n// Minimum time between two keypress notifications, milliseconds.\nexport const KEYPRESS_DELAY = 3_000;\n// Delay before sending a read notification, milliseconds.\nexport const READ_DELAY = 1_500;\n\n// The default shortest allowed tag length. Matches the value on the server.\nexport const MIN_TAG_LENGTH = 2;\n// The default greatest allowed tag length. Matches the value on the server.\nexport const MAX_TAG_LENGTH = 96;\n// The default maximum number of tags allowed. Matches the value on the server.\nexport const MAX_TAG_COUNT = 16;\n\n// Access mode for P2P subscriptions initiated by the current user.\nexport const DEFAULT_P2P_ACCESS_MODE = 'JRWPS';\n// Access mode for new group topics created by the current user.\nexport const NEW_GRP_ACCESS_MODE = 'JRWPSAO';\n// Access mode for a channel.\nexport const CHANNEL_ACCESS_MODE = 'JR';\n\n// Access mode for no access.\nexport const NO_ACCESS_MODE = 'N';\n\n// Mediaquery breakpoint between desktop and mobile, in px. Should match the value\n// in @media (max-size: 640px) in base.css\nexport const MEDIA_BREAKPOINT = 640;\n// Size of css 'rem' unit in pixels. Default 1rem = 10pt = 13px.\nexport const REM_SIZE = 13;\n\n// Size of the avatar image: when image dimensions are greater or the image is not square, it's resized to\n// a square of this size or less.\nexport const AVATAR_SIZE = 384;\n\n// Maximum size of an avatar in bytes for sending in-band. Bigger avatars will be sent out of band (as uploads).\nexport const MAX_AVATAR_BYTES = 4096;\n\n// Size of the broken_image shown in MessagesView\nexport const BROKEN_IMAGE_SIZE = 32;\n\n// Size of video preview when dimensions are missing.\nexport const NO_DIMENSIONS_VIDEO = 128;\n\n// Number of chat messages to fetch in one call.\nexport const MESSAGES_PAGE = 24;\n\n// Default maximum in-band (included directly into the message) attachment size which fits into\n// a message of 256K in size. Used when the server-provided value is unavailable. The actual\n// binary size of the attachment should be smaller due to base64 encoding expansion and some overhead,\n// for instance 1024 bytes.\n// Increase this limit to a greater value in production, if desired. Also increase\n// max_message_size in the server config.\nexport const MAX_INBAND_ATTACHMENT_SIZE = 262_144;\n\n// Default absolute maximum attachment size to be used with the server = 8MB.\n// Used when the server-provided value is unavailable. Increase to something like 100MB in production.\nexport const MAX_EXTERN_ATTACHMENT_SIZE = 1 << 23;\n\n// Maximum allowed linear dimension (pixels) of an image sent inline. Larger images will be shrunk\n// to make the larger dimension fit under this size. You may want to adjust it to 1600 or\n// 2400 for production.\nexport const MAX_IMAGE_DIM = 1024;\n\n// Linear dimensions of image preview: shrink image under this size for previews.\nexport const IMAGE_PREVIEW_DIM = 64;\n\n// Linear dimensions of video screencapture: shrink image under this size for previews.\nexport const VIDEO_PREVIEW_DIM = 96;\n\n// Linear dimensions of image thumbnail: shrink image under this size for thumbnails in reply quote previews.\nexport const IMAGE_THUMBNAIL_DIM = 36;\n// Width of video thumbnail: allow it to be wider, but not taller. Use IMAGE_THUMBNAIL_DIM for height.\nexport const VIDEO_THUMBNAIL_WIDTH = 48;\n\n// Maximum number of online users to be shown in a topic title bar. Others will be\n// hidden under \"+X more\"\nexport const MAX_ONLINE_IN_TOPIC = 4;\n\n// Maximum length of user name, topic title, and private comment.\nexport const MAX_TITLE_LENGTH = 60;\n// Maximum length of topic description.\nexport const MAX_TOPIC_DESCRIPTION_LENGTH = 360;\n// Maximum length of user name when displaying a video call.\nexport const MAX_PEER_TITLE_LENGTH = 20;\n\n// Length of message previews in chat list, in characters.\nexport const MESSAGE_PREVIEW_LENGTH = 80;\n\n// Length of a quote in quoted reply (for outgoing messages).\nexport const QUOTED_REPLY_LENGTH = 30;\n// Length of a preview of a forwarded message.\nexport const FORWARDED_PREVIEW_LENGTH = 84;\n// Length of preview for a message being edited.\nexport const EDIT_PREVIEW_LENGTH = 48;\n\n// Minimum duration of an audio recording in milliseconds (2 sec).\nexport const MIN_DURATION = 2_000;\n// Maximum duration of an audio recording in milliseconds (10 min).\nexport const MAX_DURATION = 600_000;\n\n// Link for \"Contact Us\".\nexport const LINK_CONTACT_US = 'mailto:support@tinode.co';\n\n// Link to Privacy Policy.\nexport const LINK_PRIVACY_POLICY = 'https://tinode.co/privacy.html';\n\n// Link to Terms of Service.\nexport const LINK_TERMS_OF_SERVICE = 'https://tinode.co/terms.html';\n\n// When user starts a P2P topic, automatic subscription does not\n// happen until the first message. Setting this option to true enables\n// immediate subscription.\nexport const IMMEDIATE_P2P_SUBSCRIPTION = false;\n","// Video call states.\nexport const CALL_STATE_NONE = 0;\nexport const CALL_STATE_OUTGOING_INITATED = 1;\nexport const CALL_STATE_INCOMING_RECEIVED = 2;\nexport const CALL_STATE_IN_PROGRESS = 3;\n\n// Video call message headers representing call state.\nexport const CALL_HEAD_STARTED = 'started';\n","// File and image helper functions.\n\n// Supported image MIME types and corresponding file extensions.\nexport const SUPPORTED_IMAGE_FORMATS = ['image/jpeg', 'image/gif', 'image/png', 'image/svg', 'image/svg+xml'];\nexport const MIME_EXTENSIONS = ['jpg', 'gif', 'png', 'svg', 'svg'];\n\n// Get an URL from a theCard photo: either create a data: URL or return reference URL.\nexport function makeImageUrl(photo) {\n if (photo && typeof photo == 'object') {\n if (photo.ref) {\n return photo.ref\n }\n if (photo.data && photo.type) {\n const mime = photo.type.startsWith('image/') ? photo.type : ('image/' + photo.type);\n return 'data:' + mime + ';base64,' + photo.data;\n }\n }\n return null;\n}\n\n// Calculate linear dimensions for scaling image down to fit under a certain size.\n// Returns an object which contains destination sizes, source sizes, and offsets\n// into source (when making square images).\nexport function fitImageSize(width, height, maxWidth, maxHeight, forceSquare) {\n // Sanitize input\n width = width | 0;\n height = height | 0;\n maxWidth = maxWidth | 0;\n maxHeight = maxHeight | 0;\n\n if (width <= 0 || height <= 0 || maxWidth <= 0 || maxHeight <= 0) {\n return null;\n }\n\n if (forceSquare) {\n maxWidth = maxHeight = Math.min(maxWidth, maxHeight);\n }\n\n const scale = Math.min(\n Math.min(width, maxWidth) / width,\n Math.min(height, maxHeight) / height\n );\n\n const size = {\n dstWidth: (width * scale) | 0,\n dstHeight: (height * scale) | 0,\n };\n\n if (forceSquare) {\n // Also calculate parameters for making the image square.\n size.dstWidth = size.dstHeight = Math.min(size.dstWidth, size.dstHeight);\n size.srcWidth = size.srcHeight = Math.min(width, height);\n size.xoffset = ((width - size.srcWidth) / 2) | 0;\n size.yoffset = ((height - size.srcWidth) / 2) | 0;\n } else {\n size.xoffset = size.yoffset = 0;\n size.srcWidth = width;\n size.srcHeight = height;\n }\n return size;\n}\n\n// Ensure file's extension matches mime content type\nexport function fileNameForMime(fname, mime) {\n const idx = SUPPORTED_IMAGE_FORMATS.indexOf(mime);\n if (idx < 0 || !fname) {\n // Unknown mime or empty name.\n return fname;\n }\n const ext = MIME_EXTENSIONS[idx];\n\n const at = fname.lastIndexOf('.');\n if (at >= 0) {\n fname = fname.substring(0, at);\n }\n return fname + '.' + ext;\n}\n\n// Scale uploaded image to fit under certain dimensions and byte size, optionally constraining to a square.\n// Returns a promise which is resolven on success or rejected on failure.\nexport function imageScaled(fileOrBlob, maxWidth, maxHeight, maxSize, forceSquare) {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.crossOrigin = 'Anonymous';\n img.onerror = function(err) {\n reject(new Error(\"Image format unrecognized\"));\n }\n img.onload = async function() {\n // Once the image is loaded, the URL is no longer needed.\n URL.revokeObjectURL(img.src);\n\n // Calculate the desired image dimensions.\n const dim = fitImageSize(img.width, img.height, maxWidth, maxHeight, forceSquare);\n if (!dim) {\n reject(new Error(\"Invalid image\"));\n return;\n }\n let canvas = document.createElement('canvas');\n canvas.width = dim.dstWidth;\n canvas.height = dim.dstHeight;\n let ctx = canvas.getContext('2d');\n ctx.imageSmoothingEnabled = true;\n ctx.drawImage(img, dim.xoffset, dim.yoffset, dim.srcWidth, dim.srcHeight,\n 0, 0, dim.dstWidth, dim.dstHeight);\n\n const mime = SUPPORTED_IMAGE_FORMATS.includes(fileOrBlob.type) ? fileOrBlob.type : 'image/jpeg';\n // Generate blob to check size of the image.\n let blob = await new Promise(resolve => canvas.toBlob(resolve, mime));\n if (!blob) {\n reject(new Error(\"Unsupported image format\"));\n return;\n }\n // Ensure the image is not too large. Shrink the image keeping the aspect ratio.\n // Do nothing if maxsize is <= 0.\n while (maxSize > 0 && blob.length > maxSize) {\n dim.dstWidth = (dim.dstWidth * 0.70710678118) | 0;\n dim.dstHeight = (dim.dstHeight * 0.70710678118) | 0;\n canvas.width = dim.dstWidth;\n canvas.height = dim.dstHeight;\n ctx = canvas.getContext('2d');\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.drawImage(img, dim.xoffset, dim.yoffset, dim.srcWidth, dim.srcHeight,\n 0, 0, dim.dstWidth, dim.dstHeight);\n blob = await new Promise(resolve => canvas.toBlob(resolve, mime));\n }\n\n canvas = null;\n resolve({mime: mime, blob: blob, width: dim.dstWidth, height: dim.dstHeight, name: fileNameForMime(fileOrBlob.name, mime)});\n };\n img.src = URL.createObjectURL(fileOrBlob);\n });\n}\n\n// Scale and crop image according to specified dimensions.\n// The coordinates are in unscaled image pixels, i.e. cut the rectangle first then scale it.\n// returns a promise.\nexport function imageCrop(mime, objURL, left, top, width, height, scale) {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.crossOrigin = 'Anonymous';\n img.onerror = _ => {\n reject(new Error(\"Image format unrecognized\"));\n };\n img.onload = _ => {\n // Once the image is loaded, the URL is no longer needed.\n URL.revokeObjectURL(img.src);\n\n let canvas = document.createElement('canvas');\n canvas.width = width * scale;\n canvas.height = height * scale;\n let ctx = canvas.getContext('2d');\n ctx.imageSmoothingEnabled = true;\n ctx.drawImage(img, left, top, width, height, 0, 0, canvas.width, canvas.height);\n\n mime = SUPPORTED_IMAGE_FORMATS.includes(mime) ? mime : 'image/jpeg';\n // Generate blob to check size of the image.\n canvas.toBlob((blob) => {\n // Allow GC.\n canvas = null;\n if (blob) {\n resolve({mime: mime, blob: blob, width: width, height: height});\n } else {\n reject(new Error(\"Unsupported image format\"));\n }\n }, mime);\n };\n img.src = objURL;\n });\n}\n\n// Convert file to base64 string.\nexport function fileToBase64(file) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = _ => {\n reject(reader.error);\n };\n reader.onload = _ => {\n resolve({mime: file.type, bits: reader.result.split(',')[1], name: file.name});\n };\n reader.readAsDataURL(file);\n });\n}\n\n// Convert Blob to base64 string. Returns a promise resolved with the base64 string and mime.\nexport function blobToBase64(blob) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = _ => {\n reject(reader.error);\n };\n reader.onload = _ => {\n resolve({mime: blob.type, bits: reader.result.split(',')[1]});\n };\n reader.readAsDataURL(blob);\n });\n}\n\n// File pasted from the clipboard. It's either an inline image or a file attachment.\nexport function filePasted(event, onImageSuccess, onAttachmentSuccess, onError) {\n const items = (event.clipboardData || event.originalEvent.clipboardData || {}).items;\n if (!items || !items.length) {\n return false;\n }\n\n for (let i in items) {\n const item = items[i];\n if (item.kind === 'file') {\n const file = item.getAsFile();\n if (!file) {\n console.error(\"Failed to get file object from pasted file item\", item.kind, item.type);\n onError(\"Failed to get file object from pasted file item\");\n continue;\n }\n if (file.type && file.type.split('/')[0] == 'image') {\n onImageSuccess(file);\n } else {\n onAttachmentSuccess(file);\n }\n // Indicate that the pasted data contains a file.\n return true;\n }\n }\n // No file found.\n return false;\n}\n\n// Get mime type from data URL header.\nexport function getMimeType(header) {\n const mime = /^data:(image\\/[-+a-z0-9.]+);base64/.exec(header);\n return (mime && mime.length > 1) ? mime[1] : null;\n}\n\n// Given length of a binary object in bytes, calculate the length after\n// base64 encoding.\nexport function base64EncodedLen(n) {\n return Math.floor((n + 2) / 3) * 4;\n}\n\n// Given length of a base64-encoded object, calculate decoded size of the\n// pbject in bytes.\nexport function base64DecodedLen(n) {\n return Math.floor(n / 4) * 3;\n}\n\n// Re-encode string to standard base64 encoding with padding.\n// The string may be base64-URL encoded without the padding.\nexport function base64ReEncode(str) {\n if (str) {\n str = str.replace(/-/g, '+').replace(/_/g, '/');\n try {\n str = btoa(atob(str));\n } catch(err) {\n console.error(\"Failed to base64 re-encode string.\", err);\n str = null;\n }\n }\n return str;\n}\n\n// Convert a base64 encoded string with the provided mime type into a Blob.\nexport function base64ToBlob(str, mime) {\n if (!str) {\n return null;\n }\n\n try {\n // Make blob.\n const bin = atob(str);\n const length = bin.length;\n const buf = new ArrayBuffer(length);\n const arr = new Uint8Array(buf);\n for (let i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n\n return new Blob([buf], { type: mime });\n } catch(err) {\n console.error(\"Failed to convert base64 to blob: \", err);\n }\n\n return null;\n}\n\nexport function intArrayToBase64(arr) {\n if (!Array.isArray(arr)) {\n return null;\n }\n try {\n let bin = '';\n new Uint8Array(arr).forEach(b => bin += String.fromCharCode(b));\n return window.btoa(bin);\n } catch (err) {}\n return null;\n}\n\nexport function base64ToIntArray(b64) {\n const arr = [];\n try {\n const bin = window.atob(b64);\n [...bin].forEach(c => {\n arr.push(c.charCodeAt(0));\n });\n return arr;\n } catch (err) {}\n return null;\n}\n","import React from 'react';\nimport { defineMessages } from 'react-intl';\n\nimport { Drafty } from 'tinode-sdk';\n\nimport AudioPlayer from '../widgets/audio-player.jsx'\nimport CallMessage from '../widgets/call-message.jsx'\nimport CallStatus from '../widgets/call-status.jsx';\nimport InlineVideo from '../widgets/inline-video.jsx';\nimport LazyImage from '../widgets/lazy-image.jsx'\nimport UploadingImage from '../widgets/uploading-image.jsx'\n\nimport { BROKEN_IMAGE_SIZE, IMAGE_THUMBNAIL_DIM, NO_DIMENSIONS_VIDEO, REM_SIZE, VIDEO_THUMBNAIL_WIDTH } from '../config.js';\nimport { base64ToBlob, blobToBase64, fitImageSize, imageScaled } from './blob-helpers.js';\nimport { idToColorClass, secondsToTime, shortenFileName } from './strformat.js';\nimport { cancelablePromise, sanitizeUrlForMime } from './utils.js';\n\nconst messages = defineMessages({\n drafty_form: {\n id: 'drafty_form',\n defaultMessage: 'Form: ',\n description: 'Comment for form in Drafty'\n },\n drafty_attachment: {\n id: 'drafty_attachment',\n defaultMessage: 'Attachment',\n description: 'Comment for attachment in Drafty'\n },\n drafty_image: {\n id: 'drafty_image',\n defaultMessage: 'Picture',\n description: 'Comment for embedded images in Drafty'\n },\n drafty_video: {\n id: 'drafty_video',\n defaultMessage: 'Video recording',\n description: 'Comment for videos embedded in Drafty'\n },\n drafty_unknown: {\n id: 'drafty_unknown',\n defaultMessage: 'Unsupported',\n description: 'Unsupported entity in drafty'\n }\n});\n\n// The main Drafty formatter: converts Drafty elements into React classes. 'this' is set by the caller.\n// 'this' must contain:\n// viewportWidth:\n// authorizeURL:\n// onImagePreview:\n// onVideoPreview:\n// onFormButtonClick:\n// onQuoteClick:\nexport function fullFormatter(style, data, values, key, stack) {\n if (stack.includes('QQ')) {\n return quoteFormatter.call(this, style, data, values, key);\n }\n\n if (!style) {\n // Unformatted.\n return values;\n }\n\n let el = Drafty.tagName(style);\n let attr = Drafty.attrValue(style, data) || {};\n attr.key = key;\n switch (style) {\n case 'AU':\n // Show audio player.\n if (attr.src) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'audio'));\n attr.duration = data.duration > 0 ? (data.duration | 0) : undefined;\n attr.preview = data.preview;\n attr.loading = 'lazy';\n }\n el = AudioPlayer;\n // Audio element cannot have content.\n values = null;\n break;\n case 'BR':\n values = null;\n break;\n case 'EX':\n // Ignore.\n break;\n case 'HL':\n // Highlighted text. Assign class name.\n attr.className = 'highlight';\n break;\n case 'HD':\n el = null;\n values = null;\n break;\n case 'IM':\n // Additional processing for images\n el = handleImageData.call(this, el, data, attr);\n // Image element cannot have content.\n values = null;\n break;\n case 'BN':\n // Button\n attr.onClick = this.onFormButtonClick;\n let inner = React.Children.map(values, (child) => {\n return typeof child == 'string' ? child : undefined;\n });\n if (!inner || inner.length == 0) {\n inner = [attr.name]\n }\n // Get text which will be sent back when the button is clicked.\n attr['data-title'] = inner.join('');\n break;\n case 'MN':\n // Mention\n attr.className = 'mention'\n if (data) {\n attr.className += ' ' + idToColorClass(data.val, false, true);\n }\n break;\n case 'FM':\n // Form\n attr.className = 'bot-form';\n break;\n case 'RW':\n // Form element formatting is dependent on element content.\n break;\n case 'QQ':\n // Quote/citation.\n attr.className = 'reply-quote'\n attr.onClick = this.onQuoteClick;\n break;\n case 'VC':\n el = CallMessage;\n // Video call messages do not have content.\n values = null;\n if (data) {\n attr.callState = data.state;\n attr.incoming = data.incoming;\n attr.duration = data.duration;\n }\n break;\n case 'VD':\n // Additional processing for videos.\n el = handleVideoData.call(this, el, data, attr);\n // Video element cannot have content.\n values = null;\n break;\n default:\n if (!el) {\n // Unknown element.\n el = React.Fragment;\n attr = {key: key};\n // Generate comment for unknown element.\n let body = values;\n if (!Array.isArray(values) || !values.join('').trim()) {\n body = [{this.formatMessage(messages.drafty_unknown)}];\n }\n values = [extension, ' '].concat(body);\n }\n break;\n }\n if (!el) {\n return values;\n }\n return React.createElement(el, attr, values);\n}\n\n// Additional processing of image data.\nfunction handleImageData(el, data, attr) {\n if (!data) {\n attr.src = 'img/broken_image.png';\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n };\n return el;\n }\n\n attr.className = 'inline-image';\n const dim = fitImageSize(data.width, data.height,\n this.viewportWidth > 0 ? Math.min(this.viewportWidth - REM_SIZE * 6.5, REM_SIZE * 34.5) :\n REM_SIZE * 34.5, REM_SIZE * 24, false) ||\n {dstWidth: BROKEN_IMAGE_SIZE, dstHeight: BROKEN_IMAGE_SIZE};\n attr.style = {\n width: dim.dstWidth + 'px',\n height: dim.dstHeight + 'px',\n // Looks like a Chrome bug: broken image does not respect 'width' and 'height'.\n minWidth: dim.dstWidth + 'px',\n minHeight: dim.dstHeight + 'px'\n };\n if (!Drafty.isProcessing(data)) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'image'));\n attr.alt = data.name;\n if (attr.src) {\n if (Math.max(data.width || 0, data.height || 0) > IMAGE_THUMBNAIL_DIM) {\n // Allow previews for large enough images.\n attr.onClick = this.onImagePreview;\n attr.className += ' image-clickable';\n }\n attr.loading = 'lazy';\n } else {\n attr.src = null;\n }\n } else {\n // Use custom element instead of {shown} Visible for testing\r\n */\r\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\r\n/**\r\n * The percentage of backoff time to randomize by.\r\n * See\r\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\r\n * for context.\r\n *\r\n * Visible for testing\r\n */\r\nconst RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\r\n // Calculates an exponentially increasing value.\r\n // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n // and count to restore state.\r\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n // A random \"fuzz\" to avoid waves of retries.\r\n // Deviation: randomFactor is required.\r\n const randomWait = Math.round(\r\n // A fraction of the backoff value to add/subtract.\r\n // Deviation: changes multiplication order to improve readability.\r\n RANDOM_FACTOR *\r\n currBaseValue *\r\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n // if we add or subtract.\r\n (Math.random() - 0.5) *\r\n 2);\r\n // Limits backoff to max to avoid effectively permanent backoff.\r\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n if (!Number.isFinite(i)) {\r\n return `${i}`;\r\n }\r\n return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n i = Math.abs(i);\r\n const cent = i % 100;\r\n if (cent >= 10 && cent <= 20) {\r\n return 'th';\r\n }\r\n const dec = i % 10;\r\n if (dec === 1) {\r\n return 'st';\r\n }\r\n if (dec === 2) {\r\n return 'nd';\r\n }\r\n if (dec === 3) {\r\n return 'rd';\r\n }\r\n return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n if (service && service._delegate) {\r\n return service._delegate;\r\n }\r\n else {\r\n return service;\r\n }\r\n}\n\nexport { CONSTANTS, DecodeBase64StringError, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm2017.js.map\n","import { Deferred } from '@firebase/util';\n\n/**\r\n * Component for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass Component {\r\n /**\r\n *\r\n * @param name The public service name, e.g. app, auth, firestore, database\r\n * @param instanceFactory Service factory responsible for creating the public interface\r\n * @param type whether the service provided by the component is public or private\r\n */\r\n constructor(name, instanceFactory, type) {\r\n this.name = name;\r\n this.instanceFactory = instanceFactory;\r\n this.type = type;\r\n this.multipleInstances = false;\r\n /**\r\n * Properties to be added to the service namespace\r\n */\r\n this.serviceProps = {};\r\n this.instantiationMode = \"LAZY\" /* InstantiationMode.LAZY */;\r\n this.onInstanceCreated = null;\r\n }\r\n setInstantiationMode(mode) {\r\n this.instantiationMode = mode;\r\n return this;\r\n }\r\n setMultipleInstances(multipleInstances) {\r\n this.multipleInstances = multipleInstances;\r\n return this;\r\n }\r\n setServiceProps(props) {\r\n this.serviceProps = props;\r\n return this;\r\n }\r\n setInstanceCreatedCallback(callback) {\r\n this.onInstanceCreated = callback;\r\n return this;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\r\n * NameServiceMapping[T] is an alias for the type of the instance\r\n */\r\nclass Provider {\r\n constructor(name, container) {\r\n this.name = name;\r\n this.container = container;\r\n this.component = null;\r\n this.instances = new Map();\r\n this.instancesDeferred = new Map();\r\n this.instancesOptions = new Map();\r\n this.onInitCallbacks = new Map();\r\n }\r\n /**\r\n * @param identifier A provider can provide mulitple instances of a service\r\n * if this.component.multipleInstances is true.\r\n */\r\n get(identifier) {\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\r\n const deferred = new Deferred();\r\n this.instancesDeferred.set(normalizedIdentifier, deferred);\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n // initialize the service if it can be auto-initialized\r\n try {\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n if (instance) {\r\n deferred.resolve(instance);\r\n }\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception during get(), it should not cause\r\n // a fatal error. We just return the unresolved promise in this case.\r\n }\r\n }\r\n }\r\n return this.instancesDeferred.get(normalizedIdentifier).promise;\r\n }\r\n getImmediate(options) {\r\n var _a;\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);\r\n const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n try {\r\n return this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n }\r\n catch (e) {\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw e;\r\n }\r\n }\r\n }\r\n else {\r\n // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw Error(`Service ${this.name} is not available`);\r\n }\r\n }\r\n }\r\n getComponent() {\r\n return this.component;\r\n }\r\n setComponent(component) {\r\n if (component.name !== this.name) {\r\n throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);\r\n }\r\n if (this.component) {\r\n throw Error(`Component for ${this.name} has already been provided`);\r\n }\r\n this.component = component;\r\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\r\n if (!this.shouldAutoInitialize()) {\r\n return;\r\n }\r\n // if the service is eager, initialize the default instance\r\n if (isComponentEager(component)) {\r\n try {\r\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\r\n }\r\n catch (e) {\r\n // when the instance factory for an eager Component throws an exception during the eager\r\n // initialization, it should not cause a fatal error.\r\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\r\n // a fatal error in this case?\r\n }\r\n }\r\n // Create service instances for the pending promises and resolve them\r\n // NOTE: if this.multipleInstances is false, only the default instance will be created\r\n // and all promises with resolve with it regardless of the identifier.\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n try {\r\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n instanceDeferred.resolve(instance);\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception, it should not cause\r\n // a fatal error. We just leave the promise unresolved.\r\n }\r\n }\r\n }\r\n clearInstance(identifier = DEFAULT_ENTRY_NAME) {\r\n this.instancesDeferred.delete(identifier);\r\n this.instancesOptions.delete(identifier);\r\n this.instances.delete(identifier);\r\n }\r\n // app.delete() will call this method on every provider to delete the services\r\n // TODO: should we mark the provider as deleted?\r\n async delete() {\r\n const services = Array.from(this.instances.values());\r\n await Promise.all([\r\n ...services\r\n .filter(service => 'INTERNAL' in service) // legacy services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service.INTERNAL.delete()),\r\n ...services\r\n .filter(service => '_delete' in service) // modularized services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service._delete())\r\n ]);\r\n }\r\n isComponentSet() {\r\n return this.component != null;\r\n }\r\n isInitialized(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instances.has(identifier);\r\n }\r\n getOptions(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instancesOptions.get(identifier) || {};\r\n }\r\n initialize(opts = {}) {\r\n const { options = {} } = opts;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);\r\n if (this.isInitialized(normalizedIdentifier)) {\r\n throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);\r\n }\r\n if (!this.isComponentSet()) {\r\n throw Error(`Component ${this.name} has not been registered yet`);\r\n }\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier,\r\n options\r\n });\r\n // resolve any pending promise waiting for the service instance\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\r\n instanceDeferred.resolve(instance);\r\n }\r\n }\r\n return instance;\r\n }\r\n /**\r\n *\r\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\r\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\r\n *\r\n * @param identifier An optional instance identifier\r\n * @returns a function to unregister the callback\r\n */\r\n onInit(callback, identifier) {\r\n var _a;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();\r\n existingCallbacks.add(callback);\r\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\r\n const existingInstance = this.instances.get(normalizedIdentifier);\r\n if (existingInstance) {\r\n callback(existingInstance, normalizedIdentifier);\r\n }\r\n return () => {\r\n existingCallbacks.delete(callback);\r\n };\r\n }\r\n /**\r\n * Invoke onInit callbacks synchronously\r\n * @param instance the service instance`\r\n */\r\n invokeOnInitCallbacks(instance, identifier) {\r\n const callbacks = this.onInitCallbacks.get(identifier);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n try {\r\n callback(instance, identifier);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInit callback\r\n }\r\n }\r\n }\r\n getOrInitializeService({ instanceIdentifier, options = {} }) {\r\n let instance = this.instances.get(instanceIdentifier);\r\n if (!instance && this.component) {\r\n instance = this.component.instanceFactory(this.container, {\r\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\r\n options\r\n });\r\n this.instances.set(instanceIdentifier, instance);\r\n this.instancesOptions.set(instanceIdentifier, options);\r\n /**\r\n * Invoke onInit listeners.\r\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\r\n * while onInit listeners are registered by consumers of the provider.\r\n */\r\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\r\n /**\r\n * Order is important\r\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\r\n * makes `isInitialized()` return true.\r\n */\r\n if (this.component.onInstanceCreated) {\r\n try {\r\n this.component.onInstanceCreated(this.container, instanceIdentifier, instance);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInstanceCreatedCallback\r\n }\r\n }\r\n }\r\n return instance || null;\r\n }\r\n normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) {\r\n if (this.component) {\r\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\r\n }\r\n else {\r\n return identifier; // assume multiple instances are supported before the component is provided.\r\n }\r\n }\r\n shouldAutoInitialize() {\r\n return (!!this.component &&\r\n this.component.instantiationMode !== \"EXPLICIT\" /* InstantiationMode.EXPLICIT */);\r\n }\r\n}\r\n// undefined should be passed to the service factory for the default instance\r\nfunction normalizeIdentifierForFactory(identifier) {\r\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\r\n}\r\nfunction isComponentEager(component) {\r\n return component.instantiationMode === \"EAGER\" /* InstantiationMode.EAGER */;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass ComponentContainer {\r\n constructor(name) {\r\n this.name = name;\r\n this.providers = new Map();\r\n }\r\n /**\r\n *\r\n * @param component Component being added\r\n * @param overwrite When a component with the same name has already been registered,\r\n * if overwrite is true: overwrite the existing component with the new component and create a new\r\n * provider with the new component. It can be useful in tests where you want to use different mocks\r\n * for different tests.\r\n * if overwrite is false: throw an exception\r\n */\r\n addComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n throw new Error(`Component ${component.name} has already been registered with ${this.name}`);\r\n }\r\n provider.setComponent(component);\r\n }\r\n addOrOverwriteComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n // delete the existing provider from the container, so we can register the new component\r\n this.providers.delete(component.name);\r\n }\r\n this.addComponent(component);\r\n }\r\n /**\r\n * getProvider provides a type safe interface where it can only be called with a field name\r\n * present in NameServiceMapping interface.\r\n *\r\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\r\n * themselves.\r\n */\r\n getProvider(name) {\r\n if (this.providers.has(name)) {\r\n return this.providers.get(name);\r\n }\r\n // create a Provider for a service that hasn't registered with Firebase\r\n const provider = new Provider(name, this);\r\n this.providers.set(name, provider);\r\n return provider;\r\n }\r\n getProviders() {\r\n return Array.from(this.providers.values());\r\n }\r\n}\n\nexport { Component, ComponentContainer, Provider };\n//# sourceMappingURL=index.esm2017.js.map\n","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A container for all of the Logger instances\r\n */\r\nconst instances = [];\r\n/**\r\n * The JS SDK supports 5 log levels and also allows a user the ability to\r\n * silence the logs altogether.\r\n *\r\n * The order is a follows:\r\n * DEBUG < VERBOSE < INFO < WARN < ERROR\r\n *\r\n * All of the log types above the current log level will be captured (i.e. if\r\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\r\n * `VERBOSE` logs will not)\r\n */\r\nvar LogLevel;\r\n(function (LogLevel) {\r\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\r\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\r\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\r\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\r\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\r\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\r\n})(LogLevel || (LogLevel = {}));\r\nconst levelStringToEnum = {\r\n 'debug': LogLevel.DEBUG,\r\n 'verbose': LogLevel.VERBOSE,\r\n 'info': LogLevel.INFO,\r\n 'warn': LogLevel.WARN,\r\n 'error': LogLevel.ERROR,\r\n 'silent': LogLevel.SILENT\r\n};\r\n/**\r\n * The default log level\r\n */\r\nconst defaultLogLevel = LogLevel.INFO;\r\n/**\r\n * By default, `console.debug` is not displayed in the developer console (in\r\n * chrome). To avoid forcing users to have to opt-in to these logs twice\r\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\r\n * logs to the `console.log` function.\r\n */\r\nconst ConsoleMethod = {\r\n [LogLevel.DEBUG]: 'log',\r\n [LogLevel.VERBOSE]: 'log',\r\n [LogLevel.INFO]: 'info',\r\n [LogLevel.WARN]: 'warn',\r\n [LogLevel.ERROR]: 'error'\r\n};\r\n/**\r\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\r\n * messages on to their corresponding console counterparts (if the log method\r\n * is supported by the current log level)\r\n */\r\nconst defaultLogHandler = (instance, logType, ...args) => {\r\n if (logType < instance.logLevel) {\r\n return;\r\n }\r\n const now = new Date().toISOString();\r\n const method = ConsoleMethod[logType];\r\n if (method) {\r\n console[method](`[${now}] ${instance.name}:`, ...args);\r\n }\r\n else {\r\n throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);\r\n }\r\n};\r\nclass Logger {\r\n /**\r\n * Gives you an instance of a Logger to capture messages according to\r\n * Firebase's logging scheme.\r\n *\r\n * @param name The name that the logs will be associated with\r\n */\r\n constructor(name) {\r\n this.name = name;\r\n /**\r\n * The log level of the given Logger instance.\r\n */\r\n this._logLevel = defaultLogLevel;\r\n /**\r\n * The main (internal) log handler for the Logger instance.\r\n * Can be set to a new function in internal package code but not by user.\r\n */\r\n this._logHandler = defaultLogHandler;\r\n /**\r\n * The optional, additional, user-defined log handler for the Logger instance.\r\n */\r\n this._userLogHandler = null;\r\n /**\r\n * Capture the current instance for later use\r\n */\r\n instances.push(this);\r\n }\r\n get logLevel() {\r\n return this._logLevel;\r\n }\r\n set logLevel(val) {\r\n if (!(val in LogLevel)) {\r\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\r\n }\r\n this._logLevel = val;\r\n }\r\n // Workaround for setter/getter having to be the same type.\r\n setLogLevel(val) {\r\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\r\n }\r\n get logHandler() {\r\n return this._logHandler;\r\n }\r\n set logHandler(val) {\r\n if (typeof val !== 'function') {\r\n throw new TypeError('Value assigned to `logHandler` must be a function');\r\n }\r\n this._logHandler = val;\r\n }\r\n get userLogHandler() {\r\n return this._userLogHandler;\r\n }\r\n set userLogHandler(val) {\r\n this._userLogHandler = val;\r\n }\r\n /**\r\n * The functions below are all based on the `console` interface\r\n */\r\n debug(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\r\n this._logHandler(this, LogLevel.DEBUG, ...args);\r\n }\r\n log(...args) {\r\n this._userLogHandler &&\r\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\r\n this._logHandler(this, LogLevel.VERBOSE, ...args);\r\n }\r\n info(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\r\n this._logHandler(this, LogLevel.INFO, ...args);\r\n }\r\n warn(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\r\n this._logHandler(this, LogLevel.WARN, ...args);\r\n }\r\n error(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\r\n this._logHandler(this, LogLevel.ERROR, ...args);\r\n }\r\n}\r\nfunction setLogLevel(level) {\r\n instances.forEach(inst => {\r\n inst.setLogLevel(level);\r\n });\r\n}\r\nfunction setUserLogHandler(logCallback, options) {\r\n for (const instance of instances) {\r\n let customLogLevel = null;\r\n if (options && options.level) {\r\n customLogLevel = levelStringToEnum[options.level];\r\n }\r\n if (logCallback === null) {\r\n instance.userLogHandler = null;\r\n }\r\n else {\r\n instance.userLogHandler = (instance, level, ...args) => {\r\n const message = args\r\n .map(arg => {\r\n if (arg == null) {\r\n return null;\r\n }\r\n else if (typeof arg === 'string') {\r\n return arg;\r\n }\r\n else if (typeof arg === 'number' || typeof arg === 'boolean') {\r\n return arg.toString();\r\n }\r\n else if (arg instanceof Error) {\r\n return arg.message;\r\n }\r\n else {\r\n try {\r\n return JSON.stringify(arg);\r\n }\r\n catch (ignored) {\r\n return null;\r\n }\r\n }\r\n })\r\n .filter(arg => arg)\r\n .join(' ');\r\n if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) {\r\n logCallback({\r\n level: LogLevel[level].toLowerCase(),\r\n message,\r\n args,\r\n type: instance.name\r\n });\r\n }\r\n };\r\n }\r\n }\r\n}\n\nexport { LogLevel, Logger, setLogLevel, setUserLogHandler };\n//# sourceMappingURL=index.esm2017.js.map\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","import { Component, ComponentContainer } from '@firebase/component';\nimport { Logger, setUserLogHandler, setLogLevel as setLogLevel$1 } from '@firebase/logger';\nimport { ErrorFactory, getDefaultAppConfig, deepEqual, FirebaseError, base64urlEncodeWithoutPadding, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';\nexport { FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PlatformLoggerServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n }\r\n // In initial implementation, this will be called by installations on\r\n // auth token refresh, and installations will send this string.\r\n getPlatformInfoString() {\r\n const providers = this.container.getProviders();\r\n // Loop through providers and get library/version pairs from any that are\r\n // version components.\r\n return providers\r\n .map(provider => {\r\n if (isVersionServiceProvider(provider)) {\r\n const service = provider.getImmediate();\r\n return `${service.library}/${service.version}`;\r\n }\r\n else {\r\n return null;\r\n }\r\n })\r\n .filter(logString => logString)\r\n .join(' ');\r\n }\r\n}\r\n/**\r\n *\r\n * @param provider check if this provider provides a VersionService\r\n *\r\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\r\n * provides VersionService. The provider is not necessarily a 'app-version'\r\n * provider.\r\n */\r\nfunction isVersionServiceProvider(provider) {\r\n const component = provider.getComponent();\r\n return (component === null || component === void 0 ? void 0 : component.type) === \"VERSION\" /* ComponentType.VERSION */;\r\n}\n\nconst name$o = \"@firebase/app\";\nconst version$1 = \"0.9.7\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logger = new Logger('@firebase/app');\n\nconst name$n = \"@firebase/app-compat\";\n\nconst name$m = \"@firebase/analytics-compat\";\n\nconst name$l = \"@firebase/analytics\";\n\nconst name$k = \"@firebase/app-check-compat\";\n\nconst name$j = \"@firebase/app-check\";\n\nconst name$i = \"@firebase/auth\";\n\nconst name$h = \"@firebase/auth-compat\";\n\nconst name$g = \"@firebase/database\";\n\nconst name$f = \"@firebase/database-compat\";\n\nconst name$e = \"@firebase/functions\";\n\nconst name$d = \"@firebase/functions-compat\";\n\nconst name$c = \"@firebase/installations\";\n\nconst name$b = \"@firebase/installations-compat\";\n\nconst name$a = \"@firebase/messaging\";\n\nconst name$9 = \"@firebase/messaging-compat\";\n\nconst name$8 = \"@firebase/performance\";\n\nconst name$7 = \"@firebase/performance-compat\";\n\nconst name$6 = \"@firebase/remote-config\";\n\nconst name$5 = \"@firebase/remote-config-compat\";\n\nconst name$4 = \"@firebase/storage\";\n\nconst name$3 = \"@firebase/storage-compat\";\n\nconst name$2 = \"@firebase/firestore\";\n\nconst name$1 = \"@firebase/firestore-compat\";\n\nconst name = \"firebase\";\nconst version = \"9.19.1\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The default app name\r\n *\r\n * @internal\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\r\nconst PLATFORM_LOG_STRING = {\r\n [name$o]: 'fire-core',\r\n [name$n]: 'fire-core-compat',\r\n [name$l]: 'fire-analytics',\r\n [name$m]: 'fire-analytics-compat',\r\n [name$j]: 'fire-app-check',\r\n [name$k]: 'fire-app-check-compat',\r\n [name$i]: 'fire-auth',\r\n [name$h]: 'fire-auth-compat',\r\n [name$g]: 'fire-rtdb',\r\n [name$f]: 'fire-rtdb-compat',\r\n [name$e]: 'fire-fn',\r\n [name$d]: 'fire-fn-compat',\r\n [name$c]: 'fire-iid',\r\n [name$b]: 'fire-iid-compat',\r\n [name$a]: 'fire-fcm',\r\n [name$9]: 'fire-fcm-compat',\r\n [name$8]: 'fire-perf',\r\n [name$7]: 'fire-perf-compat',\r\n [name$6]: 'fire-rc',\r\n [name$5]: 'fire-rc-compat',\r\n [name$4]: 'fire-gcs',\r\n [name$3]: 'fire-gcs-compat',\r\n [name$2]: 'fire-fst',\r\n [name$1]: 'fire-fst-compat',\r\n 'fire-js': 'fire-js',\r\n [name]: 'fire-js-all'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @internal\r\n */\r\nconst _apps = new Map();\r\n/**\r\n * Registered components.\r\n *\r\n * @internal\r\n */\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nconst _components = new Map();\r\n/**\r\n * @param component - the component being added to this app's container\r\n *\r\n * @internal\r\n */\r\nfunction _addComponent(app, component) {\r\n try {\r\n app.container.addComponent(component);\r\n }\r\n catch (e) {\r\n logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);\r\n }\r\n}\r\n/**\r\n *\r\n * @internal\r\n */\r\nfunction _addOrOverwriteComponent(app, component) {\r\n app.container.addOrOverwriteComponent(component);\r\n}\r\n/**\r\n *\r\n * @param component - the component to register\r\n * @returns whether or not the component is registered successfully\r\n *\r\n * @internal\r\n */\r\nfunction _registerComponent(component) {\r\n const componentName = component.name;\r\n if (_components.has(componentName)) {\r\n logger.debug(`There were multiple attempts to register component ${componentName}.`);\r\n return false;\r\n }\r\n _components.set(componentName, component);\r\n // add the component to existing app instances\r\n for (const app of _apps.values()) {\r\n _addComponent(app, component);\r\n }\r\n return true;\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n *\r\n * @returns the provider for the service with the matching name\r\n *\r\n * @internal\r\n */\r\nfunction _getProvider(app, name) {\r\n const heartbeatController = app.container\r\n .getProvider('heartbeat')\r\n .getImmediate({ optional: true });\r\n if (heartbeatController) {\r\n void heartbeatController.triggerHeartbeat();\r\n }\r\n return app.container.getProvider(name);\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\r\n *\r\n * @internal\r\n */\r\nfunction _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {\r\n _getProvider(app, name).clearInstance(instanceIdentifier);\r\n}\r\n/**\r\n * Test only\r\n *\r\n * @internal\r\n */\r\nfunction _clearComponents() {\r\n _components.clear();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERRORS = {\r\n [\"no-app\" /* AppError.NO_APP */]: \"No Firebase App '{$appName}' has been created - \" +\r\n 'call Firebase App.initializeApp()',\r\n [\"bad-app-name\" /* AppError.BAD_APP_NAME */]: \"Illegal App name: '{$appName}\",\r\n [\"duplicate-app\" /* AppError.DUPLICATE_APP */]: \"Firebase App named '{$appName}' already exists with different options or config\",\r\n [\"app-deleted\" /* AppError.APP_DELETED */]: \"Firebase App named '{$appName}' already deleted\",\r\n [\"no-options\" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',\r\n [\"invalid-app-argument\" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +\r\n 'Firebase App instance.',\r\n [\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',\r\n [\"idb-open\" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-get\" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-set\" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-delete\" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FirebaseAppImpl {\r\n constructor(options, config, container) {\r\n this._isDeleted = false;\r\n this._options = Object.assign({}, options);\r\n this._config = Object.assign({}, config);\r\n this._name = config.name;\r\n this._automaticDataCollectionEnabled =\r\n config.automaticDataCollectionEnabled;\r\n this._container = container;\r\n this.container.addComponent(new Component('app', () => this, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n }\r\n get automaticDataCollectionEnabled() {\r\n this.checkDestroyed();\r\n return this._automaticDataCollectionEnabled;\r\n }\r\n set automaticDataCollectionEnabled(val) {\r\n this.checkDestroyed();\r\n this._automaticDataCollectionEnabled = val;\r\n }\r\n get name() {\r\n this.checkDestroyed();\r\n return this._name;\r\n }\r\n get options() {\r\n this.checkDestroyed();\r\n return this._options;\r\n }\r\n get config() {\r\n this.checkDestroyed();\r\n return this._config;\r\n }\r\n get container() {\r\n return this._container;\r\n }\r\n get isDeleted() {\r\n return this._isDeleted;\r\n }\r\n set isDeleted(val) {\r\n this._isDeleted = val;\r\n }\r\n /**\r\n * This function will throw an Error if the App has already been deleted -\r\n * use before performing API actions on the App.\r\n */\r\n checkDestroyed() {\r\n if (this.isDeleted) {\r\n throw ERROR_FACTORY.create(\"app-deleted\" /* AppError.APP_DELETED */, { appName: this._name });\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The current SDK version.\r\n *\r\n * @public\r\n */\r\nconst SDK_VERSION = version;\r\nfunction initializeApp(_options, rawConfig = {}) {\r\n let options = _options;\r\n if (typeof rawConfig !== 'object') {\r\n const name = rawConfig;\r\n rawConfig = { name };\r\n }\r\n const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);\r\n const name = config.name;\r\n if (typeof name !== 'string' || !name) {\r\n throw ERROR_FACTORY.create(\"bad-app-name\" /* AppError.BAD_APP_NAME */, {\r\n appName: String(name)\r\n });\r\n }\r\n options || (options = getDefaultAppConfig());\r\n if (!options) {\r\n throw ERROR_FACTORY.create(\"no-options\" /* AppError.NO_OPTIONS */);\r\n }\r\n const existingApp = _apps.get(name);\r\n if (existingApp) {\r\n // return the existing app if options and config deep equal the ones in the existing app.\r\n if (deepEqual(options, existingApp.options) &&\r\n deepEqual(config, existingApp.config)) {\r\n return existingApp;\r\n }\r\n else {\r\n throw ERROR_FACTORY.create(\"duplicate-app\" /* AppError.DUPLICATE_APP */, { appName: name });\r\n }\r\n }\r\n const container = new ComponentContainer(name);\r\n for (const component of _components.values()) {\r\n container.addComponent(component);\r\n }\r\n const newApp = new FirebaseAppImpl(options, config, container);\r\n _apps.set(name, newApp);\r\n return newApp;\r\n}\r\n/**\r\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * When called with no arguments, the default app is returned. When an app name\r\n * is provided, the app corresponding to that name is returned.\r\n *\r\n * An exception is thrown if the app being retrieved has not yet been\r\n * initialized.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return the default app\r\n * const app = getApp();\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return a named app\r\n * const otherApp = getApp(\"otherApp\");\r\n * ```\r\n *\r\n * @param name - Optional name of the app to return. If no name is\r\n * provided, the default is `\"[DEFAULT]\"`.\r\n *\r\n * @returns The app corresponding to the provided app name.\r\n * If no app name is provided, the default app is returned.\r\n *\r\n * @public\r\n */\r\nfunction getApp(name = DEFAULT_ENTRY_NAME) {\r\n const app = _apps.get(name);\r\n if (!app && name === DEFAULT_ENTRY_NAME) {\r\n return initializeApp();\r\n }\r\n if (!app) {\r\n throw ERROR_FACTORY.create(\"no-app\" /* AppError.NO_APP */, { appName: name });\r\n }\r\n return app;\r\n}\r\n/**\r\n * A (read-only) array of all initialized apps.\r\n * @public\r\n */\r\nfunction getApps() {\r\n return Array.from(_apps.values());\r\n}\r\n/**\r\n * Renders this app unusable and frees the resources of all associated\r\n * services.\r\n *\r\n * @example\r\n * ```javascript\r\n * deleteApp(app)\r\n * .then(function() {\r\n * console.log(\"App deleted successfully\");\r\n * })\r\n * .catch(function(error) {\r\n * console.log(\"Error deleting app:\", error);\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nasync function deleteApp(app) {\r\n const name = app.name;\r\n if (_apps.has(name)) {\r\n _apps.delete(name);\r\n await Promise.all(app.container\r\n .getProviders()\r\n .map(provider => provider.delete()));\r\n app.isDeleted = true;\r\n }\r\n}\r\n/**\r\n * Registers a library's name and version for platform logging purposes.\r\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\r\n * @param version - Current version of that library.\r\n * @param variant - Bundle variant, e.g., node, rn, etc.\r\n *\r\n * @public\r\n */\r\nfunction registerVersion(libraryKeyOrName, version, variant) {\r\n var _a;\r\n // TODO: We can use this check to whitelist strings when/if we set up\r\n // a good whitelist system.\r\n let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;\r\n if (variant) {\r\n library += `-${variant}`;\r\n }\r\n const libraryMismatch = library.match(/\\s|\\//);\r\n const versionMismatch = version.match(/\\s|\\//);\r\n if (libraryMismatch || versionMismatch) {\r\n const warning = [\r\n `Unable to register library \"${library}\" with version \"${version}\":`\r\n ];\r\n if (libraryMismatch) {\r\n warning.push(`library name \"${library}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n if (libraryMismatch && versionMismatch) {\r\n warning.push('and');\r\n }\r\n if (versionMismatch) {\r\n warning.push(`version name \"${version}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n logger.warn(warning.join(' '));\r\n return;\r\n }\r\n _registerComponent(new Component(`${library}-version`, () => ({ library, version }), \"VERSION\" /* ComponentType.VERSION */));\r\n}\r\n/**\r\n * Sets log handler for all Firebase SDKs.\r\n * @param logCallback - An optional custom log handler that executes user code whenever\r\n * the Firebase SDK makes a logging call.\r\n *\r\n * @public\r\n */\r\nfunction onLog(logCallback, options) {\r\n if (logCallback !== null && typeof logCallback !== 'function') {\r\n throw ERROR_FACTORY.create(\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */);\r\n }\r\n setUserLogHandler(logCallback, options);\r\n}\r\n/**\r\n * Sets log level for all Firebase SDKs.\r\n *\r\n * All of the log types above the current log level are captured (i.e. if\r\n * you set the log level to `info`, errors are logged, but `debug` and\r\n * `verbose` logs are not).\r\n *\r\n * @public\r\n */\r\nfunction setLogLevel(logLevel) {\r\n setLogLevel$1(logLevel);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebase-heartbeat-database';\r\nconst DB_VERSION = 1;\r\nconst STORE_NAME = 'firebase-heartbeat-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DB_NAME, DB_VERSION, {\r\n upgrade: (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n db.createObjectStore(STORE_NAME);\r\n }\r\n }\r\n }).catch(e => {\r\n throw ERROR_FACTORY.create(\"idb-open\" /* AppError.IDB_OPEN */, {\r\n originalErrorMessage: e.message\r\n });\r\n });\r\n }\r\n return dbPromise;\r\n}\r\nasync function readHeartbeatsFromIndexedDB(app) {\r\n try {\r\n const db = await getDbPromise();\r\n return db\r\n .transaction(STORE_NAME)\r\n .objectStore(STORE_NAME)\r\n .get(computeKey(app));\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-get\" /* AppError.IDB_GET */, {\r\n originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nasync function writeHeartbeatsToIndexedDB(app, heartbeatObject) {\r\n try {\r\n const db = await getDbPromise();\r\n const tx = db.transaction(STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(STORE_NAME);\r\n await objectStore.put(heartbeatObject, computeKey(app));\r\n return tx.done;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-set\" /* AppError.IDB_WRITE */, {\r\n originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nfunction computeKey(app) {\r\n return `${app.name}!${app.options.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst MAX_HEADER_BYTES = 1024;\r\n// 30 days\r\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\r\nclass HeartbeatServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n /**\r\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\r\n * the header string.\r\n * Stores one record per date. This will be consolidated into the standard\r\n * format of one record per user agent string before being sent as a header.\r\n * Populated from indexedDB when the controller is instantiated and should\r\n * be kept in sync with indexedDB.\r\n * Leave public for easier testing.\r\n */\r\n this._heartbeatsCache = null;\r\n const app = this.container.getProvider('app').getImmediate();\r\n this._storage = new HeartbeatStorageImpl(app);\r\n this._heartbeatsCachePromise = this._storage.read().then(result => {\r\n this._heartbeatsCache = result;\r\n return result;\r\n });\r\n }\r\n /**\r\n * Called to report a heartbeat. The function will generate\r\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\r\n * to IndexedDB.\r\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\r\n * already logged, subsequent calls to this function in the same day will be ignored.\r\n */\r\n async triggerHeartbeat() {\r\n const platformLogger = this.container\r\n .getProvider('platform-logger')\r\n .getImmediate();\r\n // This is the \"Firebase user agent\" string from the platform logger\r\n // service, not the browser user agent.\r\n const agent = platformLogger.getPlatformInfoString();\r\n const date = getUTCDateString();\r\n if (this._heartbeatsCache === null) {\r\n this._heartbeatsCache = await this._heartbeatsCachePromise;\r\n }\r\n // Do not store a heartbeat if one is already stored for this day\r\n // or if a header has already been sent today.\r\n if (this._heartbeatsCache.lastSentHeartbeatDate === date ||\r\n this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {\r\n return;\r\n }\r\n else {\r\n // There is no entry for this date. Create one.\r\n this._heartbeatsCache.heartbeats.push({ date, agent });\r\n }\r\n // Remove entries older than 30 days.\r\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => {\r\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\r\n const now = Date.now();\r\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\r\n });\r\n return this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n /**\r\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\r\n * It also clears all heartbeats from memory as well as in IndexedDB.\r\n *\r\n * NOTE: Consuming product SDKs should not send the header if this method\r\n * returns an empty string.\r\n */\r\n async getHeartbeatsHeader() {\r\n if (this._heartbeatsCache === null) {\r\n await this._heartbeatsCachePromise;\r\n }\r\n // If it's still null or the array is empty, there is no data to send.\r\n if (this._heartbeatsCache === null ||\r\n this._heartbeatsCache.heartbeats.length === 0) {\r\n return '';\r\n }\r\n const date = getUTCDateString();\r\n // Extract as many heartbeats from the cache as will fit under the size limit.\r\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);\r\n const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));\r\n // Store last sent date to prevent another being logged/sent for the same day.\r\n this._heartbeatsCache.lastSentHeartbeatDate = date;\r\n if (unsentEntries.length > 0) {\r\n // Store any unsent entries if they exist.\r\n this._heartbeatsCache.heartbeats = unsentEntries;\r\n // This seems more likely than emptying the array (below) to lead to some odd state\r\n // since the cache isn't empty and this will be called again on the next request,\r\n // and is probably safest if we await it.\r\n await this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n else {\r\n this._heartbeatsCache.heartbeats = [];\r\n // Do not wait for this, to reduce latency.\r\n void this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n return headerString;\r\n }\r\n}\r\nfunction getUTCDateString() {\r\n const today = new Date();\r\n // Returns date format 'YYYY-MM-DD'\r\n return today.toISOString().substring(0, 10);\r\n}\r\nfunction extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {\r\n // Heartbeats grouped by user agent in the standard format to be sent in\r\n // the header.\r\n const heartbeatsToSend = [];\r\n // Single date format heartbeats that are not sent.\r\n let unsentEntries = heartbeatsCache.slice();\r\n for (const singleDateHeartbeat of heartbeatsCache) {\r\n // Look for an existing entry with the same user agent.\r\n const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);\r\n if (!heartbeatEntry) {\r\n // If no entry for this user agent exists, create one.\r\n heartbeatsToSend.push({\r\n agent: singleDateHeartbeat.agent,\r\n dates: [singleDateHeartbeat.date]\r\n });\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n // If the header would exceed max size, remove the added heartbeat\r\n // entry and stop adding to the header.\r\n heartbeatsToSend.pop();\r\n break;\r\n }\r\n }\r\n else {\r\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\r\n // If the header would exceed max size, remove the added date\r\n // and stop adding to the header.\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n heartbeatEntry.dates.pop();\r\n break;\r\n }\r\n }\r\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\r\n // quota and the loop breaks early.)\r\n unsentEntries = unsentEntries.slice(1);\r\n }\r\n return {\r\n heartbeatsToSend,\r\n unsentEntries\r\n };\r\n}\r\nclass HeartbeatStorageImpl {\r\n constructor(app) {\r\n this.app = app;\r\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\r\n }\r\n async runIndexedDBEnvironmentCheck() {\r\n if (!isIndexedDBAvailable()) {\r\n return false;\r\n }\r\n else {\r\n return validateIndexedDBOpenable()\r\n .then(() => true)\r\n .catch(() => false);\r\n }\r\n }\r\n /**\r\n * Read all heartbeats.\r\n */\r\n async read() {\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return { heartbeats: [] };\r\n }\r\n else {\r\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\r\n return idbHeartbeatObject || { heartbeats: [] };\r\n }\r\n }\r\n // overwrite the storage with the provided heartbeats\r\n async overwrite(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: heartbeatsObject.heartbeats\r\n });\r\n }\r\n }\r\n // add heartbeats\r\n async add(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: [\r\n ...existingHeartbeatsObject.heartbeats,\r\n ...heartbeatsObject.heartbeats\r\n ]\r\n });\r\n }\r\n }\r\n}\r\n/**\r\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\r\n * in a platform logging header JSON object, stringified, and converted\r\n * to base 64.\r\n */\r\nfunction countBytes(heartbeatsCache) {\r\n // base64 has a restricted set of characters, all of which should be 1 byte.\r\n return base64urlEncodeWithoutPadding(\r\n // heartbeatsCache wrapper properties\r\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerCoreComponents(variant) {\r\n _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n // Register `app` package.\r\n registerVersion(name$o, version$1, variant);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name$o, version$1, 'esm2017');\r\n // Register platform SDK identifier (no version).\r\n registerVersion('fire-js', '');\r\n}\n\n/**\r\n * Firebase App\r\n *\r\n * @remarks This package coordinates the communication between the different Firebase components\r\n * @packageDocumentation\r\n */\r\nregisterCoreComponents('');\n\nexport { SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _registerComponent, _removeServiceInstance, deleteApp, getApp, getApps, initializeApp, onLog, registerVersion, setLogLevel };\n//# sourceMappingURL=index.esm2017.js.map\n","import { registerVersion } from '@firebase/app';\nexport * from '@firebase/app';\n\nvar name = \"firebase\";\nvar version = \"9.19.1\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nregisterVersion(name, version, 'app');\n//# sourceMappingURL=index.esm.js.map\n","import { _getProvider, getApp, _registerComponent, registerVersion } from '@firebase/app';\nimport { Component } from '@firebase/component';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\nconst name = \"@firebase/installations\";\nconst version = \"0.6.4\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PENDING_TIMEOUT_MS = 10000;\r\nconst PACKAGE_VERSION = `w:${version}`;\r\nconst INTERNAL_AUTH_VERSION = 'FIS_v2';\r\nconst INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1';\r\nconst TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour\r\nconst SERVICE = 'installations';\r\nconst SERVICE_NAME = 'Installations';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERROR_DESCRIPTION_MAP = {\r\n [\"missing-app-config-values\" /* ErrorCode.MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: \"{$valueName}\"',\r\n [\"not-registered\" /* ErrorCode.NOT_REGISTERED */]: 'Firebase Installation is not registered.',\r\n [\"installation-not-found\" /* ErrorCode.INSTALLATION_NOT_FOUND */]: 'Firebase Installation not found.',\r\n [\"request-failed\" /* ErrorCode.REQUEST_FAILED */]: '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\r\n [\"app-offline\" /* ErrorCode.APP_OFFLINE */]: 'Could not process request. Application offline.',\r\n [\"delete-pending-registration\" /* ErrorCode.DELETE_PENDING_REGISTRATION */]: \"Can't delete installation while there is a pending registration request.\"\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);\r\n/** Returns true if error is a FirebaseError that is based on an error from the server. */\r\nfunction isServerError(error) {\r\n return (error instanceof FirebaseError &&\r\n error.code.includes(\"request-failed\" /* ErrorCode.REQUEST_FAILED */));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getInstallationsEndpoint({ projectId }) {\r\n return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;\r\n}\r\nfunction extractAuthTokenInfoFromResponse(response) {\r\n return {\r\n token: response.token,\r\n requestStatus: 2 /* RequestStatus.COMPLETED */,\r\n expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),\r\n creationTime: Date.now()\r\n };\r\n}\r\nasync function getErrorFromResponse(requestName, response) {\r\n const responseJson = await response.json();\r\n const errorData = responseJson.error;\r\n return ERROR_FACTORY.create(\"request-failed\" /* ErrorCode.REQUEST_FAILED */, {\r\n requestName,\r\n serverCode: errorData.code,\r\n serverMessage: errorData.message,\r\n serverStatus: errorData.status\r\n });\r\n}\r\nfunction getHeaders({ apiKey }) {\r\n return new Headers({\r\n 'Content-Type': 'application/json',\r\n Accept: 'application/json',\r\n 'x-goog-api-key': apiKey\r\n });\r\n}\r\nfunction getHeadersWithAuth(appConfig, { refreshToken }) {\r\n const headers = getHeaders(appConfig);\r\n headers.append('Authorization', getAuthorizationHeader(refreshToken));\r\n return headers;\r\n}\r\n/**\r\n * Calls the passed in fetch wrapper and returns the response.\r\n * If the returned response has a status of 5xx, re-runs the function once and\r\n * returns the response.\r\n */\r\nasync function retryIfServerError(fn) {\r\n const result = await fn();\r\n if (result.status >= 500 && result.status < 600) {\r\n // Internal Server Error. Retry request.\r\n return fn();\r\n }\r\n return result;\r\n}\r\nfunction getExpiresInFromResponseExpiresIn(responseExpiresIn) {\r\n // This works because the server will never respond with fractions of a second.\r\n return Number(responseExpiresIn.replace('s', '000'));\r\n}\r\nfunction getAuthorizationHeader(refreshToken) {\r\n return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function createInstallationRequest({ appConfig, heartbeatServiceProvider }, { fid }) {\r\n const endpoint = getInstallationsEndpoint(appConfig);\r\n const headers = getHeaders(appConfig);\r\n // If heartbeat service exists, add the heartbeat string to the header.\r\n const heartbeatService = heartbeatServiceProvider.getImmediate({\r\n optional: true\r\n });\r\n if (heartbeatService) {\r\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\r\n if (heartbeatsHeader) {\r\n headers.append('x-firebase-client', heartbeatsHeader);\r\n }\r\n }\r\n const body = {\r\n fid,\r\n authVersion: INTERNAL_AUTH_VERSION,\r\n appId: appConfig.appId,\r\n sdkVersion: PACKAGE_VERSION\r\n };\r\n const request = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (response.ok) {\r\n const responseValue = await response.json();\r\n const registeredInstallationEntry = {\r\n fid: responseValue.fid || fid,\r\n registrationStatus: 2 /* RequestStatus.COMPLETED */,\r\n refreshToken: responseValue.refreshToken,\r\n authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)\r\n };\r\n return registeredInstallationEntry;\r\n }\r\n else {\r\n throw await getErrorFromResponse('Create Installation', response);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a promise that resolves after given time passes. */\r\nfunction sleep(ms) {\r\n return new Promise(resolve => {\r\n setTimeout(resolve, ms);\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction bufferToBase64UrlSafe(array) {\r\n const b64 = btoa(String.fromCharCode(...array));\r\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst VALID_FID_PATTERN = /^[cdef][\\w-]{21}$/;\r\nconst INVALID_FID = '';\r\n/**\r\n * Generates a new FID using random values from Web Crypto API.\r\n * Returns an empty string if FID generation fails for any reason.\r\n */\r\nfunction generateFid() {\r\n try {\r\n // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5\r\n // bytes. our implementation generates a 17 byte array instead.\r\n const fidByteArray = new Uint8Array(17);\r\n const crypto = self.crypto || self.msCrypto;\r\n crypto.getRandomValues(fidByteArray);\r\n // Replace the first 4 random bits with the constant FID header of 0b0111.\r\n fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);\r\n const fid = encode(fidByteArray);\r\n return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;\r\n }\r\n catch (_a) {\r\n // FID generation errored\r\n return INVALID_FID;\r\n }\r\n}\r\n/** Converts a FID Uint8Array to a base64 string representation. */\r\nfunction encode(fidByteArray) {\r\n const b64String = bufferToBase64UrlSafe(fidByteArray);\r\n // Remove the 23rd character that was added because of the extra 4 bits at the\r\n // end of our 17 byte array, and the '=' padding.\r\n return b64String.substr(0, 22);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a string key that can be used to identify the app. */\r\nfunction getKey(appConfig) {\r\n return `${appConfig.appName}!${appConfig.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst fidChangeCallbacks = new Map();\r\n/**\r\n * Calls the onIdChange callbacks with the new FID value, and broadcasts the\r\n * change to other tabs.\r\n */\r\nfunction fidChanged(appConfig, fid) {\r\n const key = getKey(appConfig);\r\n callFidChangeCallbacks(key, fid);\r\n broadcastFidChange(key, fid);\r\n}\r\nfunction addCallback(appConfig, callback) {\r\n // Open the broadcast channel if it's not already open,\r\n // to be able to listen to change events from other tabs.\r\n getBroadcastChannel();\r\n const key = getKey(appConfig);\r\n let callbackSet = fidChangeCallbacks.get(key);\r\n if (!callbackSet) {\r\n callbackSet = new Set();\r\n fidChangeCallbacks.set(key, callbackSet);\r\n }\r\n callbackSet.add(callback);\r\n}\r\nfunction removeCallback(appConfig, callback) {\r\n const key = getKey(appConfig);\r\n const callbackSet = fidChangeCallbacks.get(key);\r\n if (!callbackSet) {\r\n return;\r\n }\r\n callbackSet.delete(callback);\r\n if (callbackSet.size === 0) {\r\n fidChangeCallbacks.delete(key);\r\n }\r\n // Close broadcast channel if there are no more callbacks.\r\n closeBroadcastChannel();\r\n}\r\nfunction callFidChangeCallbacks(key, fid) {\r\n const callbacks = fidChangeCallbacks.get(key);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n callback(fid);\r\n }\r\n}\r\nfunction broadcastFidChange(key, fid) {\r\n const channel = getBroadcastChannel();\r\n if (channel) {\r\n channel.postMessage({ key, fid });\r\n }\r\n closeBroadcastChannel();\r\n}\r\nlet broadcastChannel = null;\r\n/** Opens and returns a BroadcastChannel if it is supported by the browser. */\r\nfunction getBroadcastChannel() {\r\n if (!broadcastChannel && 'BroadcastChannel' in self) {\r\n broadcastChannel = new BroadcastChannel('[Firebase] FID Change');\r\n broadcastChannel.onmessage = e => {\r\n callFidChangeCallbacks(e.data.key, e.data.fid);\r\n };\r\n }\r\n return broadcastChannel;\r\n}\r\nfunction closeBroadcastChannel() {\r\n if (fidChangeCallbacks.size === 0 && broadcastChannel) {\r\n broadcastChannel.close();\r\n broadcastChannel = null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DATABASE_NAME = 'firebase-installations-database';\r\nconst DATABASE_VERSION = 1;\r\nconst OBJECT_STORE_NAME = 'firebase-installations-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\r\n upgrade: (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n db.createObjectStore(OBJECT_STORE_NAME);\r\n }\r\n }\r\n });\r\n }\r\n return dbPromise;\r\n}\r\n/** Assigns or overwrites the record for the given key with the given value. */\r\nasync function set(appConfig, value) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(OBJECT_STORE_NAME);\r\n const oldValue = (await objectStore.get(key));\r\n await objectStore.put(value, key);\r\n await tx.done;\r\n if (!oldValue || oldValue.fid !== value.fid) {\r\n fidChanged(appConfig, value.fid);\r\n }\r\n return value;\r\n}\r\n/** Removes record(s) from the objectStore that match the given key. */\r\nasync function remove(appConfig) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\r\n await tx.done;\r\n}\r\n/**\r\n * Atomically updates a record with the result of updateFn, which gets\r\n * called with the current value. If newValue is undefined, the record is\r\n * deleted instead.\r\n * @return Updated value\r\n */\r\nasync function update(appConfig, updateFn) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n const store = tx.objectStore(OBJECT_STORE_NAME);\r\n const oldValue = (await store.get(key));\r\n const newValue = updateFn(oldValue);\r\n if (newValue === undefined) {\r\n await store.delete(key);\r\n }\r\n else {\r\n await store.put(newValue, key);\r\n }\r\n await tx.done;\r\n if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {\r\n fidChanged(appConfig, newValue.fid);\r\n }\r\n return newValue;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates and returns the InstallationEntry from the database.\r\n * Also triggers a registration request if it is necessary and possible.\r\n */\r\nasync function getInstallationEntry(installations) {\r\n let registrationPromise;\r\n const installationEntry = await update(installations.appConfig, oldEntry => {\r\n const installationEntry = updateOrCreateInstallationEntry(oldEntry);\r\n const entryWithPromise = triggerRegistrationIfNecessary(installations, installationEntry);\r\n registrationPromise = entryWithPromise.registrationPromise;\r\n return entryWithPromise.installationEntry;\r\n });\r\n if (installationEntry.fid === INVALID_FID) {\r\n // FID generation failed. Waiting for the FID from the server.\r\n return { installationEntry: await registrationPromise };\r\n }\r\n return {\r\n installationEntry,\r\n registrationPromise\r\n };\r\n}\r\n/**\r\n * Creates a new Installation Entry if one does not exist.\r\n * Also clears timed out pending requests.\r\n */\r\nfunction updateOrCreateInstallationEntry(oldEntry) {\r\n const entry = oldEntry || {\r\n fid: generateFid(),\r\n registrationStatus: 0 /* RequestStatus.NOT_STARTED */\r\n };\r\n return clearTimedOutRequest(entry);\r\n}\r\n/**\r\n * If the Firebase Installation is not registered yet, this will trigger the\r\n * registration and return an InProgressInstallationEntry.\r\n *\r\n * If registrationPromise does not exist, the installationEntry is guaranteed\r\n * to be registered.\r\n */\r\nfunction triggerRegistrationIfNecessary(installations, installationEntry) {\r\n if (installationEntry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {\r\n if (!navigator.onLine) {\r\n // Registration required but app is offline.\r\n const registrationPromiseWithError = Promise.reject(ERROR_FACTORY.create(\"app-offline\" /* ErrorCode.APP_OFFLINE */));\r\n return {\r\n installationEntry,\r\n registrationPromise: registrationPromiseWithError\r\n };\r\n }\r\n // Try registering. Change status to IN_PROGRESS.\r\n const inProgressEntry = {\r\n fid: installationEntry.fid,\r\n registrationStatus: 1 /* RequestStatus.IN_PROGRESS */,\r\n registrationTime: Date.now()\r\n };\r\n const registrationPromise = registerInstallation(installations, inProgressEntry);\r\n return { installationEntry: inProgressEntry, registrationPromise };\r\n }\r\n else if (installationEntry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n return {\r\n installationEntry,\r\n registrationPromise: waitUntilFidRegistration(installations)\r\n };\r\n }\r\n else {\r\n return { installationEntry };\r\n }\r\n}\r\n/** This will be executed only once for each new Firebase Installation. */\r\nasync function registerInstallation(installations, installationEntry) {\r\n try {\r\n const registeredInstallationEntry = await createInstallationRequest(installations, installationEntry);\r\n return set(installations.appConfig, registeredInstallationEntry);\r\n }\r\n catch (e) {\r\n if (isServerError(e) && e.customData.serverCode === 409) {\r\n // Server returned a \"FID can not be used\" error.\r\n // Generate a new ID next time.\r\n await remove(installations.appConfig);\r\n }\r\n else {\r\n // Registration failed. Set FID as not registered.\r\n await set(installations.appConfig, {\r\n fid: installationEntry.fid,\r\n registrationStatus: 0 /* RequestStatus.NOT_STARTED */\r\n });\r\n }\r\n throw e;\r\n }\r\n}\r\n/** Call if FID registration is pending in another request. */\r\nasync function waitUntilFidRegistration(installations) {\r\n // Unfortunately, there is no way of reliably observing when a value in\r\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\r\n // so we need to poll.\r\n let entry = await updateInstallationRequest(installations.appConfig);\r\n while (entry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n // createInstallation request still in progress.\r\n await sleep(100);\r\n entry = await updateInstallationRequest(installations.appConfig);\r\n }\r\n if (entry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {\r\n // The request timed out or failed in a different call. Try again.\r\n const { installationEntry, registrationPromise } = await getInstallationEntry(installations);\r\n if (registrationPromise) {\r\n return registrationPromise;\r\n }\r\n else {\r\n // if there is no registrationPromise, entry is registered.\r\n return installationEntry;\r\n }\r\n }\r\n return entry;\r\n}\r\n/**\r\n * Called only if there is a CreateInstallation request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * CreateInstallation request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateInstallationRequest(appConfig) {\r\n return update(appConfig, oldEntry => {\r\n if (!oldEntry) {\r\n throw ERROR_FACTORY.create(\"installation-not-found\" /* ErrorCode.INSTALLATION_NOT_FOUND */);\r\n }\r\n return clearTimedOutRequest(oldEntry);\r\n });\r\n}\r\nfunction clearTimedOutRequest(entry) {\r\n if (hasInstallationRequestTimedOut(entry)) {\r\n return {\r\n fid: entry.fid,\r\n registrationStatus: 0 /* RequestStatus.NOT_STARTED */\r\n };\r\n }\r\n return entry;\r\n}\r\nfunction hasInstallationRequestTimedOut(installationEntry) {\r\n return (installationEntry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */ &&\r\n installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function generateAuthTokenRequest({ appConfig, heartbeatServiceProvider }, installationEntry) {\r\n const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\r\n const headers = getHeadersWithAuth(appConfig, installationEntry);\r\n // If heartbeat service exists, add the heartbeat string to the header.\r\n const heartbeatService = heartbeatServiceProvider.getImmediate({\r\n optional: true\r\n });\r\n if (heartbeatService) {\r\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\r\n if (heartbeatsHeader) {\r\n headers.append('x-firebase-client', heartbeatsHeader);\r\n }\r\n }\r\n const body = {\r\n installation: {\r\n sdkVersion: PACKAGE_VERSION,\r\n appId: appConfig.appId\r\n }\r\n };\r\n const request = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (response.ok) {\r\n const responseValue = await response.json();\r\n const completedAuthToken = extractAuthTokenInfoFromResponse(responseValue);\r\n return completedAuthToken;\r\n }\r\n else {\r\n throw await getErrorFromResponse('Generate Auth Token', response);\r\n }\r\n}\r\nfunction getGenerateAuthTokenEndpoint(appConfig, { fid }) {\r\n return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a valid authentication token for the installation. Generates a new\r\n * token if one doesn't exist, is expired or about to expire.\r\n *\r\n * Should only be called if the Firebase Installation is registered.\r\n */\r\nasync function refreshAuthToken(installations, forceRefresh = false) {\r\n let tokenPromise;\r\n const entry = await update(installations.appConfig, oldEntry => {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* ErrorCode.NOT_REGISTERED */);\r\n }\r\n const oldAuthToken = oldEntry.authToken;\r\n if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {\r\n // There is a valid token in the DB.\r\n return oldEntry;\r\n }\r\n else if (oldAuthToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n // There already is a token request in progress.\r\n tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);\r\n return oldEntry;\r\n }\r\n else {\r\n // No token or token expired.\r\n if (!navigator.onLine) {\r\n throw ERROR_FACTORY.create(\"app-offline\" /* ErrorCode.APP_OFFLINE */);\r\n }\r\n const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);\r\n tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);\r\n return inProgressEntry;\r\n }\r\n });\r\n const authToken = tokenPromise\r\n ? await tokenPromise\r\n : entry.authToken;\r\n return authToken;\r\n}\r\n/**\r\n * Call only if FID is registered and Auth Token request is in progress.\r\n *\r\n * Waits until the current pending request finishes. If the request times out,\r\n * tries once in this thread as well.\r\n */\r\nasync function waitUntilAuthTokenRequest(installations, forceRefresh) {\r\n // Unfortunately, there is no way of reliably observing when a value in\r\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\r\n // so we need to poll.\r\n let entry = await updateAuthTokenRequest(installations.appConfig);\r\n while (entry.authToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n // generateAuthToken still in progress.\r\n await sleep(100);\r\n entry = await updateAuthTokenRequest(installations.appConfig);\r\n }\r\n const authToken = entry.authToken;\r\n if (authToken.requestStatus === 0 /* RequestStatus.NOT_STARTED */) {\r\n // The request timed out or failed in a different call. Try again.\r\n return refreshAuthToken(installations, forceRefresh);\r\n }\r\n else {\r\n return authToken;\r\n }\r\n}\r\n/**\r\n * Called only if there is a GenerateAuthToken request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * GenerateAuthToken request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateAuthTokenRequest(appConfig) {\r\n return update(appConfig, oldEntry => {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* ErrorCode.NOT_REGISTERED */);\r\n }\r\n const oldAuthToken = oldEntry.authToken;\r\n if (hasAuthTokenRequestTimedOut(oldAuthToken)) {\r\n return Object.assign(Object.assign({}, oldEntry), { authToken: { requestStatus: 0 /* RequestStatus.NOT_STARTED */ } });\r\n }\r\n return oldEntry;\r\n });\r\n}\r\nasync function fetchAuthTokenFromServer(installations, installationEntry) {\r\n try {\r\n const authToken = await generateAuthTokenRequest(installations, installationEntry);\r\n const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken });\r\n await set(installations.appConfig, updatedInstallationEntry);\r\n return authToken;\r\n }\r\n catch (e) {\r\n if (isServerError(e) &&\r\n (e.customData.serverCode === 401 || e.customData.serverCode === 404)) {\r\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\r\n // Generate a new ID next time.\r\n await remove(installations.appConfig);\r\n }\r\n else {\r\n const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken: { requestStatus: 0 /* RequestStatus.NOT_STARTED */ } });\r\n await set(installations.appConfig, updatedInstallationEntry);\r\n }\r\n throw e;\r\n }\r\n}\r\nfunction isEntryRegistered(installationEntry) {\r\n return (installationEntry !== undefined &&\r\n installationEntry.registrationStatus === 2 /* RequestStatus.COMPLETED */);\r\n}\r\nfunction isAuthTokenValid(authToken) {\r\n return (authToken.requestStatus === 2 /* RequestStatus.COMPLETED */ &&\r\n !isAuthTokenExpired(authToken));\r\n}\r\nfunction isAuthTokenExpired(authToken) {\r\n const now = Date.now();\r\n return (now < authToken.creationTime ||\r\n authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER);\r\n}\r\n/** Returns an updated InstallationEntry with an InProgressAuthToken. */\r\nfunction makeAuthTokenRequestInProgressEntry(oldEntry) {\r\n const inProgressAuthToken = {\r\n requestStatus: 1 /* RequestStatus.IN_PROGRESS */,\r\n requestTime: Date.now()\r\n };\r\n return Object.assign(Object.assign({}, oldEntry), { authToken: inProgressAuthToken });\r\n}\r\nfunction hasAuthTokenRequestTimedOut(authToken) {\r\n return (authToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */ &&\r\n authToken.requestTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Creates a Firebase Installation if there isn't one for the app and\r\n * returns the Installation ID.\r\n * @param installations - The `Installations` instance.\r\n *\r\n * @public\r\n */\r\nasync function getId(installations) {\r\n const installationsImpl = installations;\r\n const { installationEntry, registrationPromise } = await getInstallationEntry(installationsImpl);\r\n if (registrationPromise) {\r\n registrationPromise.catch(console.error);\r\n }\r\n else {\r\n // If the installation is already registered, update the authentication\r\n // token if needed.\r\n refreshAuthToken(installationsImpl).catch(console.error);\r\n }\r\n return installationEntry.fid;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a Firebase Installations auth token, identifying the current\r\n * Firebase Installation.\r\n * @param installations - The `Installations` instance.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nasync function getToken(installations, forceRefresh = false) {\r\n const installationsImpl = installations;\r\n await completeInstallationRegistration(installationsImpl);\r\n // At this point we either have a Registered Installation in the DB, or we've\r\n // already thrown an error.\r\n const authToken = await refreshAuthToken(installationsImpl, forceRefresh);\r\n return authToken.token;\r\n}\r\nasync function completeInstallationRegistration(installations) {\r\n const { registrationPromise } = await getInstallationEntry(installations);\r\n if (registrationPromise) {\r\n // A createInstallation request is in progress. Wait until it finishes.\r\n await registrationPromise;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteInstallationRequest(appConfig, installationEntry) {\r\n const endpoint = getDeleteEndpoint(appConfig, installationEntry);\r\n const headers = getHeadersWithAuth(appConfig, installationEntry);\r\n const request = {\r\n method: 'DELETE',\r\n headers\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (!response.ok) {\r\n throw await getErrorFromResponse('Delete Installation', response);\r\n }\r\n}\r\nfunction getDeleteEndpoint(appConfig, { fid }) {\r\n return `${getInstallationsEndpoint(appConfig)}/${fid}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Deletes the Firebase Installation and all associated data.\r\n * @param installations - The `Installations` instance.\r\n *\r\n * @public\r\n */\r\nasync function deleteInstallations(installations) {\r\n const { appConfig } = installations;\r\n const entry = await update(appConfig, oldEntry => {\r\n if (oldEntry && oldEntry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {\r\n // Delete the unregistered entry without sending a deleteInstallation request.\r\n return undefined;\r\n }\r\n return oldEntry;\r\n });\r\n if (entry) {\r\n if (entry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n // Can't delete while trying to register.\r\n throw ERROR_FACTORY.create(\"delete-pending-registration\" /* ErrorCode.DELETE_PENDING_REGISTRATION */);\r\n }\r\n else if (entry.registrationStatus === 2 /* RequestStatus.COMPLETED */) {\r\n if (!navigator.onLine) {\r\n throw ERROR_FACTORY.create(\"app-offline\" /* ErrorCode.APP_OFFLINE */);\r\n }\r\n else {\r\n await deleteInstallationRequest(appConfig, entry);\r\n await remove(appConfig);\r\n }\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sets a new callback that will get called when Installation ID changes.\r\n * Returns an unsubscribe function that will remove the callback when called.\r\n * @param installations - The `Installations` instance.\r\n * @param callback - The callback function that is invoked when FID changes.\r\n * @returns A function that can be called to unsubscribe.\r\n *\r\n * @public\r\n */\r\nfunction onIdChange(installations, callback) {\r\n const { appConfig } = installations;\r\n addCallback(appConfig, callback);\r\n return () => {\r\n removeCallback(appConfig, callback);\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns an instance of {@link Installations} associated with the given\r\n * {@link @firebase/app#FirebaseApp} instance.\r\n * @param app - The {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * @public\r\n */\r\nfunction getInstallations(app = getApp()) {\r\n const installationsImpl = _getProvider(app, 'installations').getImmediate();\r\n return installationsImpl;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction extractAppConfig(app) {\r\n if (!app || !app.options) {\r\n throw getMissingValueError('App Configuration');\r\n }\r\n if (!app.name) {\r\n throw getMissingValueError('App Name');\r\n }\r\n // Required app config keys\r\n const configKeys = [\r\n 'projectId',\r\n 'apiKey',\r\n 'appId'\r\n ];\r\n for (const keyName of configKeys) {\r\n if (!app.options[keyName]) {\r\n throw getMissingValueError(keyName);\r\n }\r\n }\r\n return {\r\n appName: app.name,\r\n projectId: app.options.projectId,\r\n apiKey: app.options.apiKey,\r\n appId: app.options.appId\r\n };\r\n}\r\nfunction getMissingValueError(valueName) {\r\n return ERROR_FACTORY.create(\"missing-app-config-values\" /* ErrorCode.MISSING_APP_CONFIG_VALUES */, {\r\n valueName\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst INSTALLATIONS_NAME = 'installations';\r\nconst INSTALLATIONS_NAME_INTERNAL = 'installations-internal';\r\nconst publicFactory = (container) => {\r\n const app = container.getProvider('app').getImmediate();\r\n // Throws if app isn't configured properly.\r\n const appConfig = extractAppConfig(app);\r\n const heartbeatServiceProvider = _getProvider(app, 'heartbeat');\r\n const installationsImpl = {\r\n app,\r\n appConfig,\r\n heartbeatServiceProvider,\r\n _delete: () => Promise.resolve()\r\n };\r\n return installationsImpl;\r\n};\r\nconst internalFactory = (container) => {\r\n const app = container.getProvider('app').getImmediate();\r\n // Internal FIS instance relies on public FIS instance.\r\n const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();\r\n const installationsInternal = {\r\n getId: () => getId(installations),\r\n getToken: (forceRefresh) => getToken(installations, forceRefresh)\r\n };\r\n return installationsInternal;\r\n};\r\nfunction registerInstallations() {\r\n _registerComponent(new Component(INSTALLATIONS_NAME, publicFactory, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n _registerComponent(new Component(INSTALLATIONS_NAME_INTERNAL, internalFactory, \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n}\n\n/**\r\n * Firebase Installations\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterInstallations();\r\nregisterVersion(name, version);\r\n// BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\nregisterVersion(name, version, 'esm2017');\n\nexport { deleteInstallations, getId, getInstallations, getToken, onIdChange };\n//# sourceMappingURL=index.esm2017.js.map\n","import '@firebase/installations';\nimport { Component } from '@firebase/component';\nimport { openDB, deleteDB } from 'idb';\nimport { ErrorFactory, validateIndexedDBOpenable, isIndexedDBAvailable, areCookiesEnabled, getModularInstance } from '@firebase/util';\nimport { _registerComponent, registerVersion, _getProvider, getApp } from '@firebase/app';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_SW_PATH = '/firebase-messaging-sw.js';\r\nconst DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';\r\nconst DEFAULT_VAPID_KEY = 'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';\r\nconst ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';\r\nconst CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';\r\nconst CONSOLE_CAMPAIGN_NAME = 'google.c.a.c_l';\r\nconst CONSOLE_CAMPAIGN_TIME = 'google.c.a.ts';\r\n/** Set to '1' if Analytics is enabled for the campaign */\r\nconst CONSOLE_CAMPAIGN_ANALYTICS_ENABLED = 'google.c.a.e';\r\nvar MessageType$1;\r\n(function (MessageType) {\r\n MessageType[MessageType[\"DATA_MESSAGE\"] = 1] = \"DATA_MESSAGE\";\r\n MessageType[MessageType[\"DISPLAY_NOTIFICATION\"] = 3] = \"DISPLAY_NOTIFICATION\";\r\n})(MessageType$1 || (MessageType$1 = {}));\n\n/**\r\n * @license\r\n * Copyright 2018 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\r\n * in compliance with the License. You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software distributed under the License\r\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\r\n * or implied. See the License for the specific language governing permissions and limitations under\r\n * the License.\r\n */\r\nvar MessageType;\r\n(function (MessageType) {\r\n MessageType[\"PUSH_RECEIVED\"] = \"push-received\";\r\n MessageType[\"NOTIFICATION_CLICKED\"] = \"notification-clicked\";\r\n})(MessageType || (MessageType = {}));\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction arrayToBase64(array) {\r\n const uint8Array = new Uint8Array(array);\r\n const base64String = btoa(String.fromCharCode(...uint8Array));\r\n return base64String.replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\r\n}\r\nfunction base64ToArray(base64String) {\r\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4);\r\n const base64 = (base64String + padding)\r\n .replace(/\\-/g, '+')\r\n .replace(/_/g, '/');\r\n const rawData = atob(base64);\r\n const outputArray = new Uint8Array(rawData.length);\r\n for (let i = 0; i < rawData.length; ++i) {\r\n outputArray[i] = rawData.charCodeAt(i);\r\n }\r\n return outputArray;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst OLD_DB_NAME = 'fcm_token_details_db';\r\n/**\r\n * The last DB version of 'fcm_token_details_db' was 4. This is one higher, so that the upgrade\r\n * callback is called for all versions of the old DB.\r\n */\r\nconst OLD_DB_VERSION = 5;\r\nconst OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\r\nasync function migrateOldDatabase(senderId) {\r\n if ('databases' in indexedDB) {\r\n // indexedDb.databases() is an IndexedDB v3 API and does not exist in all browsers. TODO: Remove\r\n // typecast when it lands in TS types.\r\n const databases = await indexedDB.databases();\r\n const dbNames = databases.map(db => db.name);\r\n if (!dbNames.includes(OLD_DB_NAME)) {\r\n // old DB didn't exist, no need to open.\r\n return null;\r\n }\r\n }\r\n let tokenDetails = null;\r\n const db = await openDB(OLD_DB_NAME, OLD_DB_VERSION, {\r\n upgrade: async (db, oldVersion, newVersion, upgradeTransaction) => {\r\n var _a;\r\n if (oldVersion < 2) {\r\n // Database too old, skip migration.\r\n return;\r\n }\r\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\r\n // Database did not exist. Nothing to do.\r\n return;\r\n }\r\n const objectStore = upgradeTransaction.objectStore(OLD_OBJECT_STORE_NAME);\r\n const value = await objectStore.index('fcmSenderId').get(senderId);\r\n await objectStore.clear();\r\n if (!value) {\r\n // No entry in the database, nothing to migrate.\r\n return;\r\n }\r\n if (oldVersion === 2) {\r\n const oldDetails = value;\r\n if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {\r\n return;\r\n }\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: (_a = oldDetails.createTime) !== null && _a !== void 0 ? _a : Date.now(),\r\n subscriptionOptions: {\r\n auth: oldDetails.auth,\r\n p256dh: oldDetails.p256dh,\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: typeof oldDetails.vapidKey === 'string'\r\n ? oldDetails.vapidKey\r\n : arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n else if (oldVersion === 3) {\r\n const oldDetails = value;\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: oldDetails.createTime,\r\n subscriptionOptions: {\r\n auth: arrayToBase64(oldDetails.auth),\r\n p256dh: arrayToBase64(oldDetails.p256dh),\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n else if (oldVersion === 4) {\r\n const oldDetails = value;\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: oldDetails.createTime,\r\n subscriptionOptions: {\r\n auth: arrayToBase64(oldDetails.auth),\r\n p256dh: arrayToBase64(oldDetails.p256dh),\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n }\r\n });\r\n db.close();\r\n // Delete all old databases.\r\n await deleteDB(OLD_DB_NAME);\r\n await deleteDB('fcm_vapid_details_db');\r\n await deleteDB('undefined');\r\n return checkTokenDetails(tokenDetails) ? tokenDetails : null;\r\n}\r\nfunction checkTokenDetails(tokenDetails) {\r\n if (!tokenDetails || !tokenDetails.subscriptionOptions) {\r\n return false;\r\n }\r\n const { subscriptionOptions } = tokenDetails;\r\n return (typeof tokenDetails.createTime === 'number' &&\r\n tokenDetails.createTime > 0 &&\r\n typeof tokenDetails.token === 'string' &&\r\n tokenDetails.token.length > 0 &&\r\n typeof subscriptionOptions.auth === 'string' &&\r\n subscriptionOptions.auth.length > 0 &&\r\n typeof subscriptionOptions.p256dh === 'string' &&\r\n subscriptionOptions.p256dh.length > 0 &&\r\n typeof subscriptionOptions.endpoint === 'string' &&\r\n subscriptionOptions.endpoint.length > 0 &&\r\n typeof subscriptionOptions.swScope === 'string' &&\r\n subscriptionOptions.swScope.length > 0 &&\r\n typeof subscriptionOptions.vapidKey === 'string' &&\r\n subscriptionOptions.vapidKey.length > 0);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Exported for tests.\r\nconst DATABASE_NAME = 'firebase-messaging-database';\r\nconst DATABASE_VERSION = 1;\r\nconst OBJECT_STORE_NAME = 'firebase-messaging-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\r\n upgrade: (upgradeDb, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through behavior is what we want,\r\n // because if there are multiple versions between the old version and the current version, we\r\n // want ALL the migrations that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n upgradeDb.createObjectStore(OBJECT_STORE_NAME);\r\n }\r\n }\r\n });\r\n }\r\n return dbPromise;\r\n}\r\n/** Gets record(s) from the objectStore that match the given key. */\r\nasync function dbGet(firebaseDependencies) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tokenDetails = (await db\r\n .transaction(OBJECT_STORE_NAME)\r\n .objectStore(OBJECT_STORE_NAME)\r\n .get(key));\r\n if (tokenDetails) {\r\n return tokenDetails;\r\n }\r\n else {\r\n // Check if there is a tokenDetails object in the old DB.\r\n const oldTokenDetails = await migrateOldDatabase(firebaseDependencies.appConfig.senderId);\r\n if (oldTokenDetails) {\r\n await dbSet(firebaseDependencies, oldTokenDetails);\r\n return oldTokenDetails;\r\n }\r\n }\r\n}\r\n/** Assigns or overwrites the record for the given key with the given value. */\r\nasync function dbSet(firebaseDependencies, tokenDetails) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).put(tokenDetails, key);\r\n await tx.done;\r\n return tokenDetails;\r\n}\r\n/** Removes record(s) from the objectStore that match the given key. */\r\nasync function dbRemove(firebaseDependencies) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\r\n await tx.done;\r\n}\r\nfunction getKey({ appConfig }) {\r\n return appConfig.appId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERROR_MAP = {\r\n [\"missing-app-config-values\" /* ErrorCode.MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: \"{$valueName}\"',\r\n [\"only-available-in-window\" /* ErrorCode.AVAILABLE_IN_WINDOW */]: 'This method is available in a Window context.',\r\n [\"only-available-in-sw\" /* ErrorCode.AVAILABLE_IN_SW */]: 'This method is available in a service worker context.',\r\n [\"permission-default\" /* ErrorCode.PERMISSION_DEFAULT */]: 'The notification permission was not granted and dismissed instead.',\r\n [\"permission-blocked\" /* ErrorCode.PERMISSION_BLOCKED */]: 'The notification permission was not granted and blocked instead.',\r\n [\"unsupported-browser\" /* ErrorCode.UNSUPPORTED_BROWSER */]: \"This browser doesn't support the API's required to use the Firebase SDK.\",\r\n [\"indexed-db-unsupported\" /* ErrorCode.INDEXED_DB_UNSUPPORTED */]: \"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)\",\r\n [\"failed-service-worker-registration\" /* ErrorCode.FAILED_DEFAULT_REGISTRATION */]: 'We are unable to register the default service worker. {$browserErrorMessage}',\r\n [\"token-subscribe-failed\" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */]: 'A problem occurred while subscribing the user to FCM: {$errorInfo}',\r\n [\"token-subscribe-no-token\" /* ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN */]: 'FCM returned no token when subscribing the user to push.',\r\n [\"token-unsubscribe-failed\" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */]: 'A problem occurred while unsubscribing the ' +\r\n 'user from FCM: {$errorInfo}',\r\n [\"token-update-failed\" /* ErrorCode.TOKEN_UPDATE_FAILED */]: 'A problem occurred while updating the user from FCM: {$errorInfo}',\r\n [\"token-update-no-token\" /* ErrorCode.TOKEN_UPDATE_NO_TOKEN */]: 'FCM returned no token when updating the user to push.',\r\n [\"use-sw-after-get-token\" /* ErrorCode.USE_SW_AFTER_GET_TOKEN */]: 'The useServiceWorker() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your service worker is used.',\r\n [\"invalid-sw-registration\" /* ErrorCode.INVALID_SW_REGISTRATION */]: 'The input to useServiceWorker() must be a ServiceWorkerRegistration.',\r\n [\"invalid-bg-handler\" /* ErrorCode.INVALID_BG_HANDLER */]: 'The input to setBackgroundMessageHandler() must be a function.',\r\n [\"invalid-vapid-key\" /* ErrorCode.INVALID_VAPID_KEY */]: 'The public VAPID key must be a string.',\r\n [\"use-vapid-key-after-get-token\" /* ErrorCode.USE_VAPID_KEY_AFTER_GET_TOKEN */]: 'The usePublicVapidKey() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your VAPID key is used.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('messaging', 'Messaging', ERROR_MAP);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function requestGetToken(firebaseDependencies, subscriptionOptions) {\r\n const headers = await getHeaders(firebaseDependencies);\r\n const body = getBody(subscriptionOptions);\r\n const subscribeOptions = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n let responseData;\r\n try {\r\n const response = await fetch(getEndpoint(firebaseDependencies.appConfig), subscribeOptions);\r\n responseData = await response.json();\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-subscribe-failed\" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */, {\r\n errorInfo: err === null || err === void 0 ? void 0 : err.toString()\r\n });\r\n }\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-subscribe-failed\" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw ERROR_FACTORY.create(\"token-subscribe-no-token\" /* ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN */);\r\n }\r\n return responseData.token;\r\n}\r\nasync function requestUpdateToken(firebaseDependencies, tokenDetails) {\r\n const headers = await getHeaders(firebaseDependencies);\r\n const body = getBody(tokenDetails.subscriptionOptions);\r\n const updateOptions = {\r\n method: 'PATCH',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n let responseData;\r\n try {\r\n const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${tokenDetails.token}`, updateOptions);\r\n responseData = await response.json();\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-update-failed\" /* ErrorCode.TOKEN_UPDATE_FAILED */, {\r\n errorInfo: err === null || err === void 0 ? void 0 : err.toString()\r\n });\r\n }\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-update-failed\" /* ErrorCode.TOKEN_UPDATE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw ERROR_FACTORY.create(\"token-update-no-token\" /* ErrorCode.TOKEN_UPDATE_NO_TOKEN */);\r\n }\r\n return responseData.token;\r\n}\r\nasync function requestDeleteToken(firebaseDependencies, token) {\r\n const headers = await getHeaders(firebaseDependencies);\r\n const unsubscribeOptions = {\r\n method: 'DELETE',\r\n headers\r\n };\r\n try {\r\n const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${token}`, unsubscribeOptions);\r\n const responseData = await response.json();\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-unsubscribe-failed\" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-unsubscribe-failed\" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */, {\r\n errorInfo: err === null || err === void 0 ? void 0 : err.toString()\r\n });\r\n }\r\n}\r\nfunction getEndpoint({ projectId }) {\r\n return `${ENDPOINT}/projects/${projectId}/registrations`;\r\n}\r\nasync function getHeaders({ appConfig, installations }) {\r\n const authToken = await installations.getToken();\r\n return new Headers({\r\n 'Content-Type': 'application/json',\r\n Accept: 'application/json',\r\n 'x-goog-api-key': appConfig.apiKey,\r\n 'x-goog-firebase-installations-auth': `FIS ${authToken}`\r\n });\r\n}\r\nfunction getBody({ p256dh, auth, endpoint, vapidKey }) {\r\n const body = {\r\n web: {\r\n endpoint,\r\n auth,\r\n p256dh\r\n }\r\n };\r\n if (vapidKey !== DEFAULT_VAPID_KEY) {\r\n body.web.applicationPubKey = vapidKey;\r\n }\r\n return body;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// UpdateRegistration will be called once every week.\r\nconst TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\r\nasync function getTokenInternal(messaging) {\r\n const pushSubscription = await getPushSubscription(messaging.swRegistration, messaging.vapidKey);\r\n const subscriptionOptions = {\r\n vapidKey: messaging.vapidKey,\r\n swScope: messaging.swRegistration.scope,\r\n endpoint: pushSubscription.endpoint,\r\n auth: arrayToBase64(pushSubscription.getKey('auth')),\r\n p256dh: arrayToBase64(pushSubscription.getKey('p256dh'))\r\n };\r\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\r\n if (!tokenDetails) {\r\n // No token, get a new one.\r\n return getNewToken(messaging.firebaseDependencies, subscriptionOptions);\r\n }\r\n else if (!isTokenValid(tokenDetails.subscriptionOptions, subscriptionOptions)) {\r\n // Invalid token, get a new one.\r\n try {\r\n await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);\r\n }\r\n catch (e) {\r\n // Suppress errors because of #2364\r\n console.warn(e);\r\n }\r\n return getNewToken(messaging.firebaseDependencies, subscriptionOptions);\r\n }\r\n else if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {\r\n // Weekly token refresh\r\n return updateToken(messaging, {\r\n token: tokenDetails.token,\r\n createTime: Date.now(),\r\n subscriptionOptions\r\n });\r\n }\r\n else {\r\n // Valid token, nothing to do.\r\n return tokenDetails.token;\r\n }\r\n}\r\n/**\r\n * This method deletes the token from the database, unsubscribes the token from FCM, and unregisters\r\n * the push subscription if it exists.\r\n */\r\nasync function deleteTokenInternal(messaging) {\r\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\r\n if (tokenDetails) {\r\n await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);\r\n await dbRemove(messaging.firebaseDependencies);\r\n }\r\n // Unsubscribe from the push subscription.\r\n const pushSubscription = await messaging.swRegistration.pushManager.getSubscription();\r\n if (pushSubscription) {\r\n return pushSubscription.unsubscribe();\r\n }\r\n // If there's no SW, consider it a success.\r\n return true;\r\n}\r\nasync function updateToken(messaging, tokenDetails) {\r\n try {\r\n const updatedToken = await requestUpdateToken(messaging.firebaseDependencies, tokenDetails);\r\n const updatedTokenDetails = Object.assign(Object.assign({}, tokenDetails), { token: updatedToken, createTime: Date.now() });\r\n await dbSet(messaging.firebaseDependencies, updatedTokenDetails);\r\n return updatedToken;\r\n }\r\n catch (e) {\r\n await deleteTokenInternal(messaging);\r\n throw e;\r\n }\r\n}\r\nasync function getNewToken(firebaseDependencies, subscriptionOptions) {\r\n const token = await requestGetToken(firebaseDependencies, subscriptionOptions);\r\n const tokenDetails = {\r\n token,\r\n createTime: Date.now(),\r\n subscriptionOptions\r\n };\r\n await dbSet(firebaseDependencies, tokenDetails);\r\n return tokenDetails.token;\r\n}\r\n/**\r\n * Gets a PushSubscription for the current user.\r\n */\r\nasync function getPushSubscription(swRegistration, vapidKey) {\r\n const subscription = await swRegistration.pushManager.getSubscription();\r\n if (subscription) {\r\n return subscription;\r\n }\r\n return swRegistration.pushManager.subscribe({\r\n userVisibleOnly: true,\r\n // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key\r\n // submitted to pushManager#subscribe must be of type Uint8Array.\r\n applicationServerKey: base64ToArray(vapidKey)\r\n });\r\n}\r\n/**\r\n * Checks if the saved tokenDetails object matches the configuration provided.\r\n */\r\nfunction isTokenValid(dbOptions, currentOptions) {\r\n const isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;\r\n const isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;\r\n const isAuthEqual = currentOptions.auth === dbOptions.auth;\r\n const isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;\r\n return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction externalizePayload(internalPayload) {\r\n const payload = {\r\n from: internalPayload.from,\r\n // eslint-disable-next-line camelcase\r\n collapseKey: internalPayload.collapse_key,\r\n // eslint-disable-next-line camelcase\r\n messageId: internalPayload.fcmMessageId\r\n };\r\n propagateNotificationPayload(payload, internalPayload);\r\n propagateDataPayload(payload, internalPayload);\r\n propagateFcmOptions(payload, internalPayload);\r\n return payload;\r\n}\r\nfunction propagateNotificationPayload(payload, messagePayloadInternal) {\r\n if (!messagePayloadInternal.notification) {\r\n return;\r\n }\r\n payload.notification = {};\r\n const title = messagePayloadInternal.notification.title;\r\n if (!!title) {\r\n payload.notification.title = title;\r\n }\r\n const body = messagePayloadInternal.notification.body;\r\n if (!!body) {\r\n payload.notification.body = body;\r\n }\r\n const image = messagePayloadInternal.notification.image;\r\n if (!!image) {\r\n payload.notification.image = image;\r\n }\r\n const icon = messagePayloadInternal.notification.icon;\r\n if (!!icon) {\r\n payload.notification.icon = icon;\r\n }\r\n}\r\nfunction propagateDataPayload(payload, messagePayloadInternal) {\r\n if (!messagePayloadInternal.data) {\r\n return;\r\n }\r\n payload.data = messagePayloadInternal.data;\r\n}\r\nfunction propagateFcmOptions(payload, messagePayloadInternal) {\r\n var _a, _b, _c, _d, _e;\r\n // fcmOptions.link value is written into notification.click_action. see more in b/232072111\r\n if (!messagePayloadInternal.fcmOptions &&\r\n !((_a = messagePayloadInternal.notification) === null || _a === void 0 ? void 0 : _a.click_action)) {\r\n return;\r\n }\r\n payload.fcmOptions = {};\r\n const link = (_c = (_b = messagePayloadInternal.fcmOptions) === null || _b === void 0 ? void 0 : _b.link) !== null && _c !== void 0 ? _c : (_d = messagePayloadInternal.notification) === null || _d === void 0 ? void 0 : _d.click_action;\r\n if (!!link) {\r\n payload.fcmOptions.link = link;\r\n }\r\n // eslint-disable-next-line camelcase\r\n const analyticsLabel = (_e = messagePayloadInternal.fcmOptions) === null || _e === void 0 ? void 0 : _e.analytics_label;\r\n if (!!analyticsLabel) {\r\n payload.fcmOptions.analyticsLabel = analyticsLabel;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isConsoleMessage(data) {\r\n // This message has a campaign ID, meaning it was sent using the Firebase Console.\r\n return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n_mergeStrings('hts/frbslgigp.ogepscmv/ieo/eaylg', 'tp:/ieaeogn-agolai.o/1frlglgc/o');\r\n_mergeStrings('AzSCbw63g1R0nCw85jG8', 'Iaya3yLKwmgvh7cF0q4');\r\nfunction _mergeStrings(s1, s2) {\r\n const resultArray = [];\r\n for (let i = 0; i < s1.length; i++) {\r\n resultArray.push(s1.charAt(i));\r\n if (i < s2.length) {\r\n resultArray.push(s2.charAt(i));\r\n }\r\n }\r\n return resultArray.join('');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction extractAppConfig(app) {\r\n if (!app || !app.options) {\r\n throw getMissingValueError('App Configuration Object');\r\n }\r\n if (!app.name) {\r\n throw getMissingValueError('App Name');\r\n }\r\n // Required app config keys\r\n const configKeys = [\r\n 'projectId',\r\n 'apiKey',\r\n 'appId',\r\n 'messagingSenderId'\r\n ];\r\n const { options } = app;\r\n for (const keyName of configKeys) {\r\n if (!options[keyName]) {\r\n throw getMissingValueError(keyName);\r\n }\r\n }\r\n return {\r\n appName: app.name,\r\n projectId: options.projectId,\r\n apiKey: options.apiKey,\r\n appId: options.appId,\r\n senderId: options.messagingSenderId\r\n };\r\n}\r\nfunction getMissingValueError(valueName) {\r\n return ERROR_FACTORY.create(\"missing-app-config-values\" /* ErrorCode.MISSING_APP_CONFIG_VALUES */, {\r\n valueName\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MessagingService {\r\n constructor(app, installations, analyticsProvider) {\r\n // logging is only done with end user consent. Default to false.\r\n this.deliveryMetricsExportedToBigQueryEnabled = false;\r\n this.onBackgroundMessageHandler = null;\r\n this.onMessageHandler = null;\r\n this.logEvents = [];\r\n this.isLogServiceStarted = false;\r\n const appConfig = extractAppConfig(app);\r\n this.firebaseDependencies = {\r\n app,\r\n appConfig,\r\n installations,\r\n analyticsProvider\r\n };\r\n }\r\n _delete() {\r\n return Promise.resolve();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function registerDefaultSw(messaging) {\r\n try {\r\n messaging.swRegistration = await navigator.serviceWorker.register(DEFAULT_SW_PATH, {\r\n scope: DEFAULT_SW_SCOPE\r\n });\r\n // The timing when browser updates sw when sw has an update is unreliable from experiment. It\r\n // leads to version conflict when the SDK upgrades to a newer version in the main page, but sw\r\n // is stuck with the old version. For example,\r\n // https://github.com/firebase/firebase-js-sdk/issues/2590 The following line reliably updates\r\n // sw if there was an update.\r\n messaging.swRegistration.update().catch(() => {\r\n /* it is non blocking and we don't care if it failed */\r\n });\r\n }\r\n catch (e) {\r\n throw ERROR_FACTORY.create(\"failed-service-worker-registration\" /* ErrorCode.FAILED_DEFAULT_REGISTRATION */, {\r\n browserErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateSwReg(messaging, swRegistration) {\r\n if (!swRegistration && !messaging.swRegistration) {\r\n await registerDefaultSw(messaging);\r\n }\r\n if (!swRegistration && !!messaging.swRegistration) {\r\n return;\r\n }\r\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\r\n throw ERROR_FACTORY.create(\"invalid-sw-registration\" /* ErrorCode.INVALID_SW_REGISTRATION */);\r\n }\r\n messaging.swRegistration = swRegistration;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateVapidKey(messaging, vapidKey) {\r\n if (!!vapidKey) {\r\n messaging.vapidKey = vapidKey;\r\n }\r\n else if (!messaging.vapidKey) {\r\n messaging.vapidKey = DEFAULT_VAPID_KEY;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function getToken$1(messaging, options) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* ErrorCode.AVAILABLE_IN_WINDOW */);\r\n }\r\n if (Notification.permission === 'default') {\r\n await Notification.requestPermission();\r\n }\r\n if (Notification.permission !== 'granted') {\r\n throw ERROR_FACTORY.create(\"permission-blocked\" /* ErrorCode.PERMISSION_BLOCKED */);\r\n }\r\n await updateVapidKey(messaging, options === null || options === void 0 ? void 0 : options.vapidKey);\r\n await updateSwReg(messaging, options === null || options === void 0 ? void 0 : options.serviceWorkerRegistration);\r\n return getTokenInternal(messaging);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function logToScion(messaging, messageType, data) {\r\n const eventType = getEventType(messageType);\r\n const analytics = await messaging.firebaseDependencies.analyticsProvider.get();\r\n analytics.logEvent(eventType, {\r\n /* eslint-disable camelcase */\r\n message_id: data[CONSOLE_CAMPAIGN_ID],\r\n message_name: data[CONSOLE_CAMPAIGN_NAME],\r\n message_time: data[CONSOLE_CAMPAIGN_TIME],\r\n message_device_time: Math.floor(Date.now() / 1000)\r\n /* eslint-enable camelcase */\r\n });\r\n}\r\nfunction getEventType(messageType) {\r\n switch (messageType) {\r\n case MessageType.NOTIFICATION_CLICKED:\r\n return 'notification_open';\r\n case MessageType.PUSH_RECEIVED:\r\n return 'notification_foreground';\r\n default:\r\n throw new Error();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function messageEventListener(messaging, event) {\r\n const internalPayload = event.data;\r\n if (!internalPayload.isFirebaseMessaging) {\r\n return;\r\n }\r\n if (messaging.onMessageHandler &&\r\n internalPayload.messageType === MessageType.PUSH_RECEIVED) {\r\n if (typeof messaging.onMessageHandler === 'function') {\r\n messaging.onMessageHandler(externalizePayload(internalPayload));\r\n }\r\n else {\r\n messaging.onMessageHandler.next(externalizePayload(internalPayload));\r\n }\r\n }\r\n // Log to Scion if applicable\r\n const dataPayload = internalPayload.data;\r\n if (isConsoleMessage(dataPayload) &&\r\n dataPayload[CONSOLE_CAMPAIGN_ANALYTICS_ENABLED] === '1') {\r\n await logToScion(messaging, internalPayload.messageType, dataPayload);\r\n }\r\n}\n\nconst name = \"@firebase/messaging\";\nconst version = \"0.12.4\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst WindowMessagingFactory = (container) => {\r\n const messaging = new MessagingService(container.getProvider('app').getImmediate(), container.getProvider('installations-internal').getImmediate(), container.getProvider('analytics-internal'));\r\n navigator.serviceWorker.addEventListener('message', e => messageEventListener(messaging, e));\r\n return messaging;\r\n};\r\nconst WindowMessagingInternalFactory = (container) => {\r\n const messaging = container\r\n .getProvider('messaging')\r\n .getImmediate();\r\n const messagingInternal = {\r\n getToken: (options) => getToken$1(messaging, options)\r\n };\r\n return messagingInternal;\r\n};\r\nfunction registerMessagingInWindow() {\r\n _registerComponent(new Component('messaging', WindowMessagingFactory, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n _registerComponent(new Component('messaging-internal', WindowMessagingInternalFactory, \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n registerVersion(name, version);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Checks if all required APIs exist in the browser.\r\n * @returns a Promise that resolves to a boolean.\r\n *\r\n * @public\r\n */\r\nasync function isWindowSupported() {\r\n try {\r\n // This throws if open() is unsupported, so adding it to the conditional\r\n // statement below can cause an uncaught error.\r\n await validateIndexedDBOpenable();\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n // firebase-js-sdk/issues/2393 reveals that idb#open in Safari iframe and Firefox private browsing\r\n // might be prohibited to run. In these contexts, an error would be thrown during the messaging\r\n // instantiating phase, informing the developers to import/call isSupported for special handling.\r\n return (typeof window !== 'undefined' &&\r\n isIndexedDBAvailable() &&\r\n areCookiesEnabled() &&\r\n 'serviceWorker' in navigator &&\r\n 'PushManager' in window &&\r\n 'Notification' in window &&\r\n 'fetch' in window &&\r\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\r\n PushSubscription.prototype.hasOwnProperty('getKey'));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteToken$1(messaging) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* ErrorCode.AVAILABLE_IN_WINDOW */);\r\n }\r\n if (!messaging.swRegistration) {\r\n await registerDefaultSw(messaging);\r\n }\r\n return deleteTokenInternal(messaging);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction onMessage$1(messaging, nextOrObserver) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* ErrorCode.AVAILABLE_IN_WINDOW */);\r\n }\r\n messaging.onMessageHandler = nextOrObserver;\r\n return () => {\r\n messaging.onMessageHandler = null;\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Retrieves a Firebase Cloud Messaging instance.\r\n *\r\n * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.\r\n *\r\n * @public\r\n */\r\nfunction getMessagingInWindow(app = getApp()) {\r\n // Conscious decision to make this async check non-blocking during the messaging instance\r\n // initialization phase for performance consideration. An error would be thrown latter for\r\n // developer's information. Developers can then choose to import and call `isSupported` for\r\n // special handling.\r\n isWindowSupported().then(isSupported => {\r\n // If `isWindowSupported()` resolved, but returned false.\r\n if (!isSupported) {\r\n throw ERROR_FACTORY.create(\"unsupported-browser\" /* ErrorCode.UNSUPPORTED_BROWSER */);\r\n }\r\n }, _ => {\r\n // If `isWindowSupported()` rejected.\r\n throw ERROR_FACTORY.create(\"indexed-db-unsupported\" /* ErrorCode.INDEXED_DB_UNSUPPORTED */);\r\n });\r\n return _getProvider(getModularInstance(app), 'messaging').getImmediate();\r\n}\r\n/**\r\n * Subscribes the {@link Messaging} instance to push notifications. Returns an Firebase Cloud\r\n * Messaging registration token that can be used to send push messages to that {@link Messaging}\r\n * instance.\r\n *\r\n * If a notification permission isn't already granted, this method asks the user for permission. The\r\n * returned promise rejects if the user does not allow the app to show notifications.\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n * @param options - Provides an optional vapid key and an optinoal service worker registration\r\n *\r\n * @returns The promise resolves with an FCM registration token.\r\n *\r\n * @public\r\n */\r\nasync function getToken(messaging, options) {\r\n messaging = getModularInstance(messaging);\r\n return getToken$1(messaging, options);\r\n}\r\n/**\r\n * Deletes the registration token associated with this {@link Messaging} instance and unsubscribes\r\n * the {@link Messaging} instance from the push subscription.\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n *\r\n * @returns The promise resolves when the token has been successfully deleted.\r\n *\r\n * @public\r\n */\r\nfunction deleteToken(messaging) {\r\n messaging = getModularInstance(messaging);\r\n return deleteToken$1(messaging);\r\n}\r\n/**\r\n * When a push message is received and the user is currently on a page for your origin, the\r\n * message is passed to the page and an `onMessage()` event is dispatched with the payload of\r\n * the push message.\r\n *\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n * @param nextOrObserver - This function, or observer object with `next` defined,\r\n * is called when a message is received and the user is currently viewing your page.\r\n * @returns To stop listening for messages execute this returned function.\r\n *\r\n * @public\r\n */\r\nfunction onMessage(messaging, nextOrObserver) {\r\n messaging = getModularInstance(messaging);\r\n return onMessage$1(messaging, nextOrObserver);\r\n}\n\n/**\r\n * Firebase Cloud Messaging\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterMessagingInWindow();\n\nexport { deleteToken, getMessagingInWindow as getMessaging, getToken, isWindowSupported as isSupported, onMessage };\n//# sourceMappingURL=index.esm2017.js.map\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nexport default class Alert extends React.PureComponent {\n render() {\n return ( Visible for testing\r\n */\r\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\r\n/**\r\n * The percentage of backoff time to randomize by.\r\n * See\r\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\r\n * for context.\r\n *\r\n * Visible for testing\r\n */\r\nconst RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\r\n // Calculates an exponentially increasing value.\r\n // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n // and count to restore state.\r\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n // A random \"fuzz\" to avoid waves of retries.\r\n // Deviation: randomFactor is required.\r\n const randomWait = Math.round(\r\n // A fraction of the backoff value to add/subtract.\r\n // Deviation: changes multiplication order to improve readability.\r\n RANDOM_FACTOR *\r\n currBaseValue *\r\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n // if we add or subtract.\r\n (Math.random() - 0.5) *\r\n 2);\r\n // Limits backoff to max to avoid effectively permanent backoff.\r\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n if (!Number.isFinite(i)) {\r\n return `${i}`;\r\n }\r\n return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n i = Math.abs(i);\r\n const cent = i % 100;\r\n if (cent >= 10 && cent <= 20) {\r\n return 'th';\r\n }\r\n const dec = i % 10;\r\n if (dec === 1) {\r\n return 'st';\r\n }\r\n if (dec === 2) {\r\n return 'nd';\r\n }\r\n if (dec === 3) {\r\n return 'rd';\r\n }\r\n return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n if (service && service._delegate) {\r\n return service._delegate;\r\n }\r\n else {\r\n return service;\r\n }\r\n}\n\nexport { CONSTANTS, DecodeBase64StringError, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm2017.js.map\n","import { Deferred } from '@firebase/util';\n\n/**\r\n * Component for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass Component {\r\n /**\r\n *\r\n * @param name The public service name, e.g. app, auth, firestore, database\r\n * @param instanceFactory Service factory responsible for creating the public interface\r\n * @param type whether the service provided by the component is public or private\r\n */\r\n constructor(name, instanceFactory, type) {\r\n this.name = name;\r\n this.instanceFactory = instanceFactory;\r\n this.type = type;\r\n this.multipleInstances = false;\r\n /**\r\n * Properties to be added to the service namespace\r\n */\r\n this.serviceProps = {};\r\n this.instantiationMode = \"LAZY\" /* InstantiationMode.LAZY */;\r\n this.onInstanceCreated = null;\r\n }\r\n setInstantiationMode(mode) {\r\n this.instantiationMode = mode;\r\n return this;\r\n }\r\n setMultipleInstances(multipleInstances) {\r\n this.multipleInstances = multipleInstances;\r\n return this;\r\n }\r\n setServiceProps(props) {\r\n this.serviceProps = props;\r\n return this;\r\n }\r\n setInstanceCreatedCallback(callback) {\r\n this.onInstanceCreated = callback;\r\n return this;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\r\n * NameServiceMapping[T] is an alias for the type of the instance\r\n */\r\nclass Provider {\r\n constructor(name, container) {\r\n this.name = name;\r\n this.container = container;\r\n this.component = null;\r\n this.instances = new Map();\r\n this.instancesDeferred = new Map();\r\n this.instancesOptions = new Map();\r\n this.onInitCallbacks = new Map();\r\n }\r\n /**\r\n * @param identifier A provider can provide mulitple instances of a service\r\n * if this.component.multipleInstances is true.\r\n */\r\n get(identifier) {\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\r\n const deferred = new Deferred();\r\n this.instancesDeferred.set(normalizedIdentifier, deferred);\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n // initialize the service if it can be auto-initialized\r\n try {\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n if (instance) {\r\n deferred.resolve(instance);\r\n }\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception during get(), it should not cause\r\n // a fatal error. We just return the unresolved promise in this case.\r\n }\r\n }\r\n }\r\n return this.instancesDeferred.get(normalizedIdentifier).promise;\r\n }\r\n getImmediate(options) {\r\n var _a;\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);\r\n const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n try {\r\n return this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n }\r\n catch (e) {\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw e;\r\n }\r\n }\r\n }\r\n else {\r\n // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw Error(`Service ${this.name} is not available`);\r\n }\r\n }\r\n }\r\n getComponent() {\r\n return this.component;\r\n }\r\n setComponent(component) {\r\n if (component.name !== this.name) {\r\n throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);\r\n }\r\n if (this.component) {\r\n throw Error(`Component for ${this.name} has already been provided`);\r\n }\r\n this.component = component;\r\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\r\n if (!this.shouldAutoInitialize()) {\r\n return;\r\n }\r\n // if the service is eager, initialize the default instance\r\n if (isComponentEager(component)) {\r\n try {\r\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\r\n }\r\n catch (e) {\r\n // when the instance factory for an eager Component throws an exception during the eager\r\n // initialization, it should not cause a fatal error.\r\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\r\n // a fatal error in this case?\r\n }\r\n }\r\n // Create service instances for the pending promises and resolve them\r\n // NOTE: if this.multipleInstances is false, only the default instance will be created\r\n // and all promises with resolve with it regardless of the identifier.\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n try {\r\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n instanceDeferred.resolve(instance);\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception, it should not cause\r\n // a fatal error. We just leave the promise unresolved.\r\n }\r\n }\r\n }\r\n clearInstance(identifier = DEFAULT_ENTRY_NAME) {\r\n this.instancesDeferred.delete(identifier);\r\n this.instancesOptions.delete(identifier);\r\n this.instances.delete(identifier);\r\n }\r\n // app.delete() will call this method on every provider to delete the services\r\n // TODO: should we mark the provider as deleted?\r\n async delete() {\r\n const services = Array.from(this.instances.values());\r\n await Promise.all([\r\n ...services\r\n .filter(service => 'INTERNAL' in service) // legacy services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service.INTERNAL.delete()),\r\n ...services\r\n .filter(service => '_delete' in service) // modularized services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service._delete())\r\n ]);\r\n }\r\n isComponentSet() {\r\n return this.component != null;\r\n }\r\n isInitialized(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instances.has(identifier);\r\n }\r\n getOptions(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instancesOptions.get(identifier) || {};\r\n }\r\n initialize(opts = {}) {\r\n const { options = {} } = opts;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);\r\n if (this.isInitialized(normalizedIdentifier)) {\r\n throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);\r\n }\r\n if (!this.isComponentSet()) {\r\n throw Error(`Component ${this.name} has not been registered yet`);\r\n }\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier,\r\n options\r\n });\r\n // resolve any pending promise waiting for the service instance\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\r\n instanceDeferred.resolve(instance);\r\n }\r\n }\r\n return instance;\r\n }\r\n /**\r\n *\r\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\r\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\r\n *\r\n * @param identifier An optional instance identifier\r\n * @returns a function to unregister the callback\r\n */\r\n onInit(callback, identifier) {\r\n var _a;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();\r\n existingCallbacks.add(callback);\r\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\r\n const existingInstance = this.instances.get(normalizedIdentifier);\r\n if (existingInstance) {\r\n callback(existingInstance, normalizedIdentifier);\r\n }\r\n return () => {\r\n existingCallbacks.delete(callback);\r\n };\r\n }\r\n /**\r\n * Invoke onInit callbacks synchronously\r\n * @param instance the service instance`\r\n */\r\n invokeOnInitCallbacks(instance, identifier) {\r\n const callbacks = this.onInitCallbacks.get(identifier);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n try {\r\n callback(instance, identifier);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInit callback\r\n }\r\n }\r\n }\r\n getOrInitializeService({ instanceIdentifier, options = {} }) {\r\n let instance = this.instances.get(instanceIdentifier);\r\n if (!instance && this.component) {\r\n instance = this.component.instanceFactory(this.container, {\r\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\r\n options\r\n });\r\n this.instances.set(instanceIdentifier, instance);\r\n this.instancesOptions.set(instanceIdentifier, options);\r\n /**\r\n * Invoke onInit listeners.\r\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\r\n * while onInit listeners are registered by consumers of the provider.\r\n */\r\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\r\n /**\r\n * Order is important\r\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\r\n * makes `isInitialized()` return true.\r\n */\r\n if (this.component.onInstanceCreated) {\r\n try {\r\n this.component.onInstanceCreated(this.container, instanceIdentifier, instance);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInstanceCreatedCallback\r\n }\r\n }\r\n }\r\n return instance || null;\r\n }\r\n normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) {\r\n if (this.component) {\r\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\r\n }\r\n else {\r\n return identifier; // assume multiple instances are supported before the component is provided.\r\n }\r\n }\r\n shouldAutoInitialize() {\r\n return (!!this.component &&\r\n this.component.instantiationMode !== \"EXPLICIT\" /* InstantiationMode.EXPLICIT */);\r\n }\r\n}\r\n// undefined should be passed to the service factory for the default instance\r\nfunction normalizeIdentifierForFactory(identifier) {\r\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\r\n}\r\nfunction isComponentEager(component) {\r\n return component.instantiationMode === \"EAGER\" /* InstantiationMode.EAGER */;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass ComponentContainer {\r\n constructor(name) {\r\n this.name = name;\r\n this.providers = new Map();\r\n }\r\n /**\r\n *\r\n * @param component Component being added\r\n * @param overwrite When a component with the same name has already been registered,\r\n * if overwrite is true: overwrite the existing component with the new component and create a new\r\n * provider with the new component. It can be useful in tests where you want to use different mocks\r\n * for different tests.\r\n * if overwrite is false: throw an exception\r\n */\r\n addComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n throw new Error(`Component ${component.name} has already been registered with ${this.name}`);\r\n }\r\n provider.setComponent(component);\r\n }\r\n addOrOverwriteComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n // delete the existing provider from the container, so we can register the new component\r\n this.providers.delete(component.name);\r\n }\r\n this.addComponent(component);\r\n }\r\n /**\r\n * getProvider provides a type safe interface where it can only be called with a field name\r\n * present in NameServiceMapping interface.\r\n *\r\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\r\n * themselves.\r\n */\r\n getProvider(name) {\r\n if (this.providers.has(name)) {\r\n return this.providers.get(name);\r\n }\r\n // create a Provider for a service that hasn't registered with Firebase\r\n const provider = new Provider(name, this);\r\n this.providers.set(name, provider);\r\n return provider;\r\n }\r\n getProviders() {\r\n return Array.from(this.providers.values());\r\n }\r\n}\n\nexport { Component, ComponentContainer, Provider };\n//# sourceMappingURL=index.esm2017.js.map\n","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A container for all of the Logger instances\r\n */\r\nconst instances = [];\r\n/**\r\n * The JS SDK supports 5 log levels and also allows a user the ability to\r\n * silence the logs altogether.\r\n *\r\n * The order is a follows:\r\n * DEBUG < VERBOSE < INFO < WARN < ERROR\r\n *\r\n * All of the log types above the current log level will be captured (i.e. if\r\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\r\n * `VERBOSE` logs will not)\r\n */\r\nvar LogLevel;\r\n(function (LogLevel) {\r\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\r\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\r\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\r\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\r\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\r\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\r\n})(LogLevel || (LogLevel = {}));\r\nconst levelStringToEnum = {\r\n 'debug': LogLevel.DEBUG,\r\n 'verbose': LogLevel.VERBOSE,\r\n 'info': LogLevel.INFO,\r\n 'warn': LogLevel.WARN,\r\n 'error': LogLevel.ERROR,\r\n 'silent': LogLevel.SILENT\r\n};\r\n/**\r\n * The default log level\r\n */\r\nconst defaultLogLevel = LogLevel.INFO;\r\n/**\r\n * By default, `console.debug` is not displayed in the developer console (in\r\n * chrome). To avoid forcing users to have to opt-in to these logs twice\r\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\r\n * logs to the `console.log` function.\r\n */\r\nconst ConsoleMethod = {\r\n [LogLevel.DEBUG]: 'log',\r\n [LogLevel.VERBOSE]: 'log',\r\n [LogLevel.INFO]: 'info',\r\n [LogLevel.WARN]: 'warn',\r\n [LogLevel.ERROR]: 'error'\r\n};\r\n/**\r\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\r\n * messages on to their corresponding console counterparts (if the log method\r\n * is supported by the current log level)\r\n */\r\nconst defaultLogHandler = (instance, logType, ...args) => {\r\n if (logType < instance.logLevel) {\r\n return;\r\n }\r\n const now = new Date().toISOString();\r\n const method = ConsoleMethod[logType];\r\n if (method) {\r\n console[method](`[${now}] ${instance.name}:`, ...args);\r\n }\r\n else {\r\n throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);\r\n }\r\n};\r\nclass Logger {\r\n /**\r\n * Gives you an instance of a Logger to capture messages according to\r\n * Firebase's logging scheme.\r\n *\r\n * @param name The name that the logs will be associated with\r\n */\r\n constructor(name) {\r\n this.name = name;\r\n /**\r\n * The log level of the given Logger instance.\r\n */\r\n this._logLevel = defaultLogLevel;\r\n /**\r\n * The main (internal) log handler for the Logger instance.\r\n * Can be set to a new function in internal package code but not by user.\r\n */\r\n this._logHandler = defaultLogHandler;\r\n /**\r\n * The optional, additional, user-defined log handler for the Logger instance.\r\n */\r\n this._userLogHandler = null;\r\n /**\r\n * Capture the current instance for later use\r\n */\r\n instances.push(this);\r\n }\r\n get logLevel() {\r\n return this._logLevel;\r\n }\r\n set logLevel(val) {\r\n if (!(val in LogLevel)) {\r\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\r\n }\r\n this._logLevel = val;\r\n }\r\n // Workaround for setter/getter having to be the same type.\r\n setLogLevel(val) {\r\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\r\n }\r\n get logHandler() {\r\n return this._logHandler;\r\n }\r\n set logHandler(val) {\r\n if (typeof val !== 'function') {\r\n throw new TypeError('Value assigned to `logHandler` must be a function');\r\n }\r\n this._logHandler = val;\r\n }\r\n get userLogHandler() {\r\n return this._userLogHandler;\r\n }\r\n set userLogHandler(val) {\r\n this._userLogHandler = val;\r\n }\r\n /**\r\n * The functions below are all based on the `console` interface\r\n */\r\n debug(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\r\n this._logHandler(this, LogLevel.DEBUG, ...args);\r\n }\r\n log(...args) {\r\n this._userLogHandler &&\r\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\r\n this._logHandler(this, LogLevel.VERBOSE, ...args);\r\n }\r\n info(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\r\n this._logHandler(this, LogLevel.INFO, ...args);\r\n }\r\n warn(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\r\n this._logHandler(this, LogLevel.WARN, ...args);\r\n }\r\n error(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\r\n this._logHandler(this, LogLevel.ERROR, ...args);\r\n }\r\n}\r\nfunction setLogLevel(level) {\r\n instances.forEach(inst => {\r\n inst.setLogLevel(level);\r\n });\r\n}\r\nfunction setUserLogHandler(logCallback, options) {\r\n for (const instance of instances) {\r\n let customLogLevel = null;\r\n if (options && options.level) {\r\n customLogLevel = levelStringToEnum[options.level];\r\n }\r\n if (logCallback === null) {\r\n instance.userLogHandler = null;\r\n }\r\n else {\r\n instance.userLogHandler = (instance, level, ...args) => {\r\n const message = args\r\n .map(arg => {\r\n if (arg == null) {\r\n return null;\r\n }\r\n else if (typeof arg === 'string') {\r\n return arg;\r\n }\r\n else if (typeof arg === 'number' || typeof arg === 'boolean') {\r\n return arg.toString();\r\n }\r\n else if (arg instanceof Error) {\r\n return arg.message;\r\n }\r\n else {\r\n try {\r\n return JSON.stringify(arg);\r\n }\r\n catch (ignored) {\r\n return null;\r\n }\r\n }\r\n })\r\n .filter(arg => arg)\r\n .join(' ');\r\n if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) {\r\n logCallback({\r\n level: LogLevel[level].toLowerCase(),\r\n message,\r\n args,\r\n type: instance.name\r\n });\r\n }\r\n };\r\n }\r\n }\r\n}\n\nexport { LogLevel, Logger, setLogLevel, setUserLogHandler };\n//# sourceMappingURL=index.esm2017.js.map\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","import { Component, ComponentContainer } from '@firebase/component';\nimport { Logger, setUserLogHandler, setLogLevel as setLogLevel$1 } from '@firebase/logger';\nimport { ErrorFactory, getDefaultAppConfig, deepEqual, FirebaseError, base64urlEncodeWithoutPadding, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';\nexport { FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PlatformLoggerServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n }\r\n // In initial implementation, this will be called by installations on\r\n // auth token refresh, and installations will send this string.\r\n getPlatformInfoString() {\r\n const providers = this.container.getProviders();\r\n // Loop through providers and get library/version pairs from any that are\r\n // version components.\r\n return providers\r\n .map(provider => {\r\n if (isVersionServiceProvider(provider)) {\r\n const service = provider.getImmediate();\r\n return `${service.library}/${service.version}`;\r\n }\r\n else {\r\n return null;\r\n }\r\n })\r\n .filter(logString => logString)\r\n .join(' ');\r\n }\r\n}\r\n/**\r\n *\r\n * @param provider check if this provider provides a VersionService\r\n *\r\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\r\n * provides VersionService. The provider is not necessarily a 'app-version'\r\n * provider.\r\n */\r\nfunction isVersionServiceProvider(provider) {\r\n const component = provider.getComponent();\r\n return (component === null || component === void 0 ? void 0 : component.type) === \"VERSION\" /* ComponentType.VERSION */;\r\n}\n\nconst name$o = \"@firebase/app\";\nconst version$1 = \"0.9.7\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logger = new Logger('@firebase/app');\n\nconst name$n = \"@firebase/app-compat\";\n\nconst name$m = \"@firebase/analytics-compat\";\n\nconst name$l = \"@firebase/analytics\";\n\nconst name$k = \"@firebase/app-check-compat\";\n\nconst name$j = \"@firebase/app-check\";\n\nconst name$i = \"@firebase/auth\";\n\nconst name$h = \"@firebase/auth-compat\";\n\nconst name$g = \"@firebase/database\";\n\nconst name$f = \"@firebase/database-compat\";\n\nconst name$e = \"@firebase/functions\";\n\nconst name$d = \"@firebase/functions-compat\";\n\nconst name$c = \"@firebase/installations\";\n\nconst name$b = \"@firebase/installations-compat\";\n\nconst name$a = \"@firebase/messaging\";\n\nconst name$9 = \"@firebase/messaging-compat\";\n\nconst name$8 = \"@firebase/performance\";\n\nconst name$7 = \"@firebase/performance-compat\";\n\nconst name$6 = \"@firebase/remote-config\";\n\nconst name$5 = \"@firebase/remote-config-compat\";\n\nconst name$4 = \"@firebase/storage\";\n\nconst name$3 = \"@firebase/storage-compat\";\n\nconst name$2 = \"@firebase/firestore\";\n\nconst name$1 = \"@firebase/firestore-compat\";\n\nconst name = \"firebase\";\nconst version = \"9.19.1\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The default app name\r\n *\r\n * @internal\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\r\nconst PLATFORM_LOG_STRING = {\r\n [name$o]: 'fire-core',\r\n [name$n]: 'fire-core-compat',\r\n [name$l]: 'fire-analytics',\r\n [name$m]: 'fire-analytics-compat',\r\n [name$j]: 'fire-app-check',\r\n [name$k]: 'fire-app-check-compat',\r\n [name$i]: 'fire-auth',\r\n [name$h]: 'fire-auth-compat',\r\n [name$g]: 'fire-rtdb',\r\n [name$f]: 'fire-rtdb-compat',\r\n [name$e]: 'fire-fn',\r\n [name$d]: 'fire-fn-compat',\r\n [name$c]: 'fire-iid',\r\n [name$b]: 'fire-iid-compat',\r\n [name$a]: 'fire-fcm',\r\n [name$9]: 'fire-fcm-compat',\r\n [name$8]: 'fire-perf',\r\n [name$7]: 'fire-perf-compat',\r\n [name$6]: 'fire-rc',\r\n [name$5]: 'fire-rc-compat',\r\n [name$4]: 'fire-gcs',\r\n [name$3]: 'fire-gcs-compat',\r\n [name$2]: 'fire-fst',\r\n [name$1]: 'fire-fst-compat',\r\n 'fire-js': 'fire-js',\r\n [name]: 'fire-js-all'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @internal\r\n */\r\nconst _apps = new Map();\r\n/**\r\n * Registered components.\r\n *\r\n * @internal\r\n */\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nconst _components = new Map();\r\n/**\r\n * @param component - the component being added to this app's container\r\n *\r\n * @internal\r\n */\r\nfunction _addComponent(app, component) {\r\n try {\r\n app.container.addComponent(component);\r\n }\r\n catch (e) {\r\n logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);\r\n }\r\n}\r\n/**\r\n *\r\n * @internal\r\n */\r\nfunction _addOrOverwriteComponent(app, component) {\r\n app.container.addOrOverwriteComponent(component);\r\n}\r\n/**\r\n *\r\n * @param component - the component to register\r\n * @returns whether or not the component is registered successfully\r\n *\r\n * @internal\r\n */\r\nfunction _registerComponent(component) {\r\n const componentName = component.name;\r\n if (_components.has(componentName)) {\r\n logger.debug(`There were multiple attempts to register component ${componentName}.`);\r\n return false;\r\n }\r\n _components.set(componentName, component);\r\n // add the component to existing app instances\r\n for (const app of _apps.values()) {\r\n _addComponent(app, component);\r\n }\r\n return true;\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n *\r\n * @returns the provider for the service with the matching name\r\n *\r\n * @internal\r\n */\r\nfunction _getProvider(app, name) {\r\n const heartbeatController = app.container\r\n .getProvider('heartbeat')\r\n .getImmediate({ optional: true });\r\n if (heartbeatController) {\r\n void heartbeatController.triggerHeartbeat();\r\n }\r\n return app.container.getProvider(name);\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\r\n *\r\n * @internal\r\n */\r\nfunction _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {\r\n _getProvider(app, name).clearInstance(instanceIdentifier);\r\n}\r\n/**\r\n * Test only\r\n *\r\n * @internal\r\n */\r\nfunction _clearComponents() {\r\n _components.clear();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERRORS = {\r\n [\"no-app\" /* AppError.NO_APP */]: \"No Firebase App '{$appName}' has been created - \" +\r\n 'call Firebase App.initializeApp()',\r\n [\"bad-app-name\" /* AppError.BAD_APP_NAME */]: \"Illegal App name: '{$appName}\",\r\n [\"duplicate-app\" /* AppError.DUPLICATE_APP */]: \"Firebase App named '{$appName}' already exists with different options or config\",\r\n [\"app-deleted\" /* AppError.APP_DELETED */]: \"Firebase App named '{$appName}' already deleted\",\r\n [\"no-options\" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',\r\n [\"invalid-app-argument\" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +\r\n 'Firebase App instance.',\r\n [\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',\r\n [\"idb-open\" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-get\" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-set\" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-delete\" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FirebaseAppImpl {\r\n constructor(options, config, container) {\r\n this._isDeleted = false;\r\n this._options = Object.assign({}, options);\r\n this._config = Object.assign({}, config);\r\n this._name = config.name;\r\n this._automaticDataCollectionEnabled =\r\n config.automaticDataCollectionEnabled;\r\n this._container = container;\r\n this.container.addComponent(new Component('app', () => this, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n }\r\n get automaticDataCollectionEnabled() {\r\n this.checkDestroyed();\r\n return this._automaticDataCollectionEnabled;\r\n }\r\n set automaticDataCollectionEnabled(val) {\r\n this.checkDestroyed();\r\n this._automaticDataCollectionEnabled = val;\r\n }\r\n get name() {\r\n this.checkDestroyed();\r\n return this._name;\r\n }\r\n get options() {\r\n this.checkDestroyed();\r\n return this._options;\r\n }\r\n get config() {\r\n this.checkDestroyed();\r\n return this._config;\r\n }\r\n get container() {\r\n return this._container;\r\n }\r\n get isDeleted() {\r\n return this._isDeleted;\r\n }\r\n set isDeleted(val) {\r\n this._isDeleted = val;\r\n }\r\n /**\r\n * This function will throw an Error if the App has already been deleted -\r\n * use before performing API actions on the App.\r\n */\r\n checkDestroyed() {\r\n if (this.isDeleted) {\r\n throw ERROR_FACTORY.create(\"app-deleted\" /* AppError.APP_DELETED */, { appName: this._name });\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The current SDK version.\r\n *\r\n * @public\r\n */\r\nconst SDK_VERSION = version;\r\nfunction initializeApp(_options, rawConfig = {}) {\r\n let options = _options;\r\n if (typeof rawConfig !== 'object') {\r\n const name = rawConfig;\r\n rawConfig = { name };\r\n }\r\n const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);\r\n const name = config.name;\r\n if (typeof name !== 'string' || !name) {\r\n throw ERROR_FACTORY.create(\"bad-app-name\" /* AppError.BAD_APP_NAME */, {\r\n appName: String(name)\r\n });\r\n }\r\n options || (options = getDefaultAppConfig());\r\n if (!options) {\r\n throw ERROR_FACTORY.create(\"no-options\" /* AppError.NO_OPTIONS */);\r\n }\r\n const existingApp = _apps.get(name);\r\n if (existingApp) {\r\n // return the existing app if options and config deep equal the ones in the existing app.\r\n if (deepEqual(options, existingApp.options) &&\r\n deepEqual(config, existingApp.config)) {\r\n return existingApp;\r\n }\r\n else {\r\n throw ERROR_FACTORY.create(\"duplicate-app\" /* AppError.DUPLICATE_APP */, { appName: name });\r\n }\r\n }\r\n const container = new ComponentContainer(name);\r\n for (const component of _components.values()) {\r\n container.addComponent(component);\r\n }\r\n const newApp = new FirebaseAppImpl(options, config, container);\r\n _apps.set(name, newApp);\r\n return newApp;\r\n}\r\n/**\r\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * When called with no arguments, the default app is returned. When an app name\r\n * is provided, the app corresponding to that name is returned.\r\n *\r\n * An exception is thrown if the app being retrieved has not yet been\r\n * initialized.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return the default app\r\n * const app = getApp();\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return a named app\r\n * const otherApp = getApp(\"otherApp\");\r\n * ```\r\n *\r\n * @param name - Optional name of the app to return. If no name is\r\n * provided, the default is `\"[DEFAULT]\"`.\r\n *\r\n * @returns The app corresponding to the provided app name.\r\n * If no app name is provided, the default app is returned.\r\n *\r\n * @public\r\n */\r\nfunction getApp(name = DEFAULT_ENTRY_NAME) {\r\n const app = _apps.get(name);\r\n if (!app && name === DEFAULT_ENTRY_NAME) {\r\n return initializeApp();\r\n }\r\n if (!app) {\r\n throw ERROR_FACTORY.create(\"no-app\" /* AppError.NO_APP */, { appName: name });\r\n }\r\n return app;\r\n}\r\n/**\r\n * A (read-only) array of all initialized apps.\r\n * @public\r\n */\r\nfunction getApps() {\r\n return Array.from(_apps.values());\r\n}\r\n/**\r\n * Renders this app unusable and frees the resources of all associated\r\n * services.\r\n *\r\n * @example\r\n * ```javascript\r\n * deleteApp(app)\r\n * .then(function() {\r\n * console.log(\"App deleted successfully\");\r\n * })\r\n * .catch(function(error) {\r\n * console.log(\"Error deleting app:\", error);\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nasync function deleteApp(app) {\r\n const name = app.name;\r\n if (_apps.has(name)) {\r\n _apps.delete(name);\r\n await Promise.all(app.container\r\n .getProviders()\r\n .map(provider => provider.delete()));\r\n app.isDeleted = true;\r\n }\r\n}\r\n/**\r\n * Registers a library's name and version for platform logging purposes.\r\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\r\n * @param version - Current version of that library.\r\n * @param variant - Bundle variant, e.g., node, rn, etc.\r\n *\r\n * @public\r\n */\r\nfunction registerVersion(libraryKeyOrName, version, variant) {\r\n var _a;\r\n // TODO: We can use this check to whitelist strings when/if we set up\r\n // a good whitelist system.\r\n let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;\r\n if (variant) {\r\n library += `-${variant}`;\r\n }\r\n const libraryMismatch = library.match(/\\s|\\//);\r\n const versionMismatch = version.match(/\\s|\\//);\r\n if (libraryMismatch || versionMismatch) {\r\n const warning = [\r\n `Unable to register library \"${library}\" with version \"${version}\":`\r\n ];\r\n if (libraryMismatch) {\r\n warning.push(`library name \"${library}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n if (libraryMismatch && versionMismatch) {\r\n warning.push('and');\r\n }\r\n if (versionMismatch) {\r\n warning.push(`version name \"${version}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n logger.warn(warning.join(' '));\r\n return;\r\n }\r\n _registerComponent(new Component(`${library}-version`, () => ({ library, version }), \"VERSION\" /* ComponentType.VERSION */));\r\n}\r\n/**\r\n * Sets log handler for all Firebase SDKs.\r\n * @param logCallback - An optional custom log handler that executes user code whenever\r\n * the Firebase SDK makes a logging call.\r\n *\r\n * @public\r\n */\r\nfunction onLog(logCallback, options) {\r\n if (logCallback !== null && typeof logCallback !== 'function') {\r\n throw ERROR_FACTORY.create(\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */);\r\n }\r\n setUserLogHandler(logCallback, options);\r\n}\r\n/**\r\n * Sets log level for all Firebase SDKs.\r\n *\r\n * All of the log types above the current log level are captured (i.e. if\r\n * you set the log level to `info`, errors are logged, but `debug` and\r\n * `verbose` logs are not).\r\n *\r\n * @public\r\n */\r\nfunction setLogLevel(logLevel) {\r\n setLogLevel$1(logLevel);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebase-heartbeat-database';\r\nconst DB_VERSION = 1;\r\nconst STORE_NAME = 'firebase-heartbeat-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DB_NAME, DB_VERSION, {\r\n upgrade: (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n db.createObjectStore(STORE_NAME);\r\n }\r\n }\r\n }).catch(e => {\r\n throw ERROR_FACTORY.create(\"idb-open\" /* AppError.IDB_OPEN */, {\r\n originalErrorMessage: e.message\r\n });\r\n });\r\n }\r\n return dbPromise;\r\n}\r\nasync function readHeartbeatsFromIndexedDB(app) {\r\n try {\r\n const db = await getDbPromise();\r\n return db\r\n .transaction(STORE_NAME)\r\n .objectStore(STORE_NAME)\r\n .get(computeKey(app));\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-get\" /* AppError.IDB_GET */, {\r\n originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nasync function writeHeartbeatsToIndexedDB(app, heartbeatObject) {\r\n try {\r\n const db = await getDbPromise();\r\n const tx = db.transaction(STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(STORE_NAME);\r\n await objectStore.put(heartbeatObject, computeKey(app));\r\n return tx.done;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-set\" /* AppError.IDB_WRITE */, {\r\n originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nfunction computeKey(app) {\r\n return `${app.name}!${app.options.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst MAX_HEADER_BYTES = 1024;\r\n// 30 days\r\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\r\nclass HeartbeatServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n /**\r\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\r\n * the header string.\r\n * Stores one record per date. This will be consolidated into the standard\r\n * format of one record per user agent string before being sent as a header.\r\n * Populated from indexedDB when the controller is instantiated and should\r\n * be kept in sync with indexedDB.\r\n * Leave public for easier testing.\r\n */\r\n this._heartbeatsCache = null;\r\n const app = this.container.getProvider('app').getImmediate();\r\n this._storage = new HeartbeatStorageImpl(app);\r\n this._heartbeatsCachePromise = this._storage.read().then(result => {\r\n this._heartbeatsCache = result;\r\n return result;\r\n });\r\n }\r\n /**\r\n * Called to report a heartbeat. The function will generate\r\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\r\n * to IndexedDB.\r\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\r\n * already logged, subsequent calls to this function in the same day will be ignored.\r\n */\r\n async triggerHeartbeat() {\r\n const platformLogger = this.container\r\n .getProvider('platform-logger')\r\n .getImmediate();\r\n // This is the \"Firebase user agent\" string from the platform logger\r\n // service, not the browser user agent.\r\n const agent = platformLogger.getPlatformInfoString();\r\n const date = getUTCDateString();\r\n if (this._heartbeatsCache === null) {\r\n this._heartbeatsCache = await this._heartbeatsCachePromise;\r\n }\r\n // Do not store a heartbeat if one is already stored for this day\r\n // or if a header has already been sent today.\r\n if (this._heartbeatsCache.lastSentHeartbeatDate === date ||\r\n this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {\r\n return;\r\n }\r\n else {\r\n // There is no entry for this date. Create one.\r\n this._heartbeatsCache.heartbeats.push({ date, agent });\r\n }\r\n // Remove entries older than 30 days.\r\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => {\r\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\r\n const now = Date.now();\r\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\r\n });\r\n return this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n /**\r\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\r\n * It also clears all heartbeats from memory as well as in IndexedDB.\r\n *\r\n * NOTE: Consuming product SDKs should not send the header if this method\r\n * returns an empty string.\r\n */\r\n async getHeartbeatsHeader() {\r\n if (this._heartbeatsCache === null) {\r\n await this._heartbeatsCachePromise;\r\n }\r\n // If it's still null or the array is empty, there is no data to send.\r\n if (this._heartbeatsCache === null ||\r\n this._heartbeatsCache.heartbeats.length === 0) {\r\n return '';\r\n }\r\n const date = getUTCDateString();\r\n // Extract as many heartbeats from the cache as will fit under the size limit.\r\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);\r\n const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));\r\n // Store last sent date to prevent another being logged/sent for the same day.\r\n this._heartbeatsCache.lastSentHeartbeatDate = date;\r\n if (unsentEntries.length > 0) {\r\n // Store any unsent entries if they exist.\r\n this._heartbeatsCache.heartbeats = unsentEntries;\r\n // This seems more likely than emptying the array (below) to lead to some odd state\r\n // since the cache isn't empty and this will be called again on the next request,\r\n // and is probably safest if we await it.\r\n await this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n else {\r\n this._heartbeatsCache.heartbeats = [];\r\n // Do not wait for this, to reduce latency.\r\n void this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n return headerString;\r\n }\r\n}\r\nfunction getUTCDateString() {\r\n const today = new Date();\r\n // Returns date format 'YYYY-MM-DD'\r\n return today.toISOString().substring(0, 10);\r\n}\r\nfunction extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {\r\n // Heartbeats grouped by user agent in the standard format to be sent in\r\n // the header.\r\n const heartbeatsToSend = [];\r\n // Single date format heartbeats that are not sent.\r\n let unsentEntries = heartbeatsCache.slice();\r\n for (const singleDateHeartbeat of heartbeatsCache) {\r\n // Look for an existing entry with the same user agent.\r\n const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);\r\n if (!heartbeatEntry) {\r\n // If no entry for this user agent exists, create one.\r\n heartbeatsToSend.push({\r\n agent: singleDateHeartbeat.agent,\r\n dates: [singleDateHeartbeat.date]\r\n });\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n // If the header would exceed max size, remove the added heartbeat\r\n // entry and stop adding to the header.\r\n heartbeatsToSend.pop();\r\n break;\r\n }\r\n }\r\n else {\r\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\r\n // If the header would exceed max size, remove the added date\r\n // and stop adding to the header.\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n heartbeatEntry.dates.pop();\r\n break;\r\n }\r\n }\r\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\r\n // quota and the loop breaks early.)\r\n unsentEntries = unsentEntries.slice(1);\r\n }\r\n return {\r\n heartbeatsToSend,\r\n unsentEntries\r\n };\r\n}\r\nclass HeartbeatStorageImpl {\r\n constructor(app) {\r\n this.app = app;\r\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\r\n }\r\n async runIndexedDBEnvironmentCheck() {\r\n if (!isIndexedDBAvailable()) {\r\n return false;\r\n }\r\n else {\r\n return validateIndexedDBOpenable()\r\n .then(() => true)\r\n .catch(() => false);\r\n }\r\n }\r\n /**\r\n * Read all heartbeats.\r\n */\r\n async read() {\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return { heartbeats: [] };\r\n }\r\n else {\r\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\r\n return idbHeartbeatObject || { heartbeats: [] };\r\n }\r\n }\r\n // overwrite the storage with the provided heartbeats\r\n async overwrite(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: heartbeatsObject.heartbeats\r\n });\r\n }\r\n }\r\n // add heartbeats\r\n async add(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: [\r\n ...existingHeartbeatsObject.heartbeats,\r\n ...heartbeatsObject.heartbeats\r\n ]\r\n });\r\n }\r\n }\r\n}\r\n/**\r\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\r\n * in a platform logging header JSON object, stringified, and converted\r\n * to base 64.\r\n */\r\nfunction countBytes(heartbeatsCache) {\r\n // base64 has a restricted set of characters, all of which should be 1 byte.\r\n return base64urlEncodeWithoutPadding(\r\n // heartbeatsCache wrapper properties\r\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerCoreComponents(variant) {\r\n _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n // Register `app` package.\r\n registerVersion(name$o, version$1, variant);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name$o, version$1, 'esm2017');\r\n // Register platform SDK identifier (no version).\r\n registerVersion('fire-js', '');\r\n}\n\n/**\r\n * Firebase App\r\n *\r\n * @remarks This package coordinates the communication between the different Firebase components\r\n * @packageDocumentation\r\n */\r\nregisterCoreComponents('');\n\nexport { SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _registerComponent, _removeServiceInstance, deleteApp, getApp, getApps, initializeApp, onLog, registerVersion, setLogLevel };\n//# sourceMappingURL=index.esm2017.js.map\n","import { registerVersion } from '@firebase/app';\nexport * from '@firebase/app';\n\nvar name = \"firebase\";\nvar version = \"9.19.1\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nregisterVersion(name, version, 'app');\n//# sourceMappingURL=index.esm.js.map\n","import { _getProvider, getApp, _registerComponent, registerVersion } from '@firebase/app';\nimport { Component } from '@firebase/component';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\nconst name = \"@firebase/installations\";\nconst version = \"0.6.4\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PENDING_TIMEOUT_MS = 10000;\r\nconst PACKAGE_VERSION = `w:${version}`;\r\nconst INTERNAL_AUTH_VERSION = 'FIS_v2';\r\nconst INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1';\r\nconst TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour\r\nconst SERVICE = 'installations';\r\nconst SERVICE_NAME = 'Installations';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERROR_DESCRIPTION_MAP = {\r\n [\"missing-app-config-values\" /* ErrorCode.MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: \"{$valueName}\"',\r\n [\"not-registered\" /* ErrorCode.NOT_REGISTERED */]: 'Firebase Installation is not registered.',\r\n [\"installation-not-found\" /* ErrorCode.INSTALLATION_NOT_FOUND */]: 'Firebase Installation not found.',\r\n [\"request-failed\" /* ErrorCode.REQUEST_FAILED */]: '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\r\n [\"app-offline\" /* ErrorCode.APP_OFFLINE */]: 'Could not process request. Application offline.',\r\n [\"delete-pending-registration\" /* ErrorCode.DELETE_PENDING_REGISTRATION */]: \"Can't delete installation while there is a pending registration request.\"\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);\r\n/** Returns true if error is a FirebaseError that is based on an error from the server. */\r\nfunction isServerError(error) {\r\n return (error instanceof FirebaseError &&\r\n error.code.includes(\"request-failed\" /* ErrorCode.REQUEST_FAILED */));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getInstallationsEndpoint({ projectId }) {\r\n return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;\r\n}\r\nfunction extractAuthTokenInfoFromResponse(response) {\r\n return {\r\n token: response.token,\r\n requestStatus: 2 /* RequestStatus.COMPLETED */,\r\n expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),\r\n creationTime: Date.now()\r\n };\r\n}\r\nasync function getErrorFromResponse(requestName, response) {\r\n const responseJson = await response.json();\r\n const errorData = responseJson.error;\r\n return ERROR_FACTORY.create(\"request-failed\" /* ErrorCode.REQUEST_FAILED */, {\r\n requestName,\r\n serverCode: errorData.code,\r\n serverMessage: errorData.message,\r\n serverStatus: errorData.status\r\n });\r\n}\r\nfunction getHeaders({ apiKey }) {\r\n return new Headers({\r\n 'Content-Type': 'application/json',\r\n Accept: 'application/json',\r\n 'x-goog-api-key': apiKey\r\n });\r\n}\r\nfunction getHeadersWithAuth(appConfig, { refreshToken }) {\r\n const headers = getHeaders(appConfig);\r\n headers.append('Authorization', getAuthorizationHeader(refreshToken));\r\n return headers;\r\n}\r\n/**\r\n * Calls the passed in fetch wrapper and returns the response.\r\n * If the returned response has a status of 5xx, re-runs the function once and\r\n * returns the response.\r\n */\r\nasync function retryIfServerError(fn) {\r\n const result = await fn();\r\n if (result.status >= 500 && result.status < 600) {\r\n // Internal Server Error. Retry request.\r\n return fn();\r\n }\r\n return result;\r\n}\r\nfunction getExpiresInFromResponseExpiresIn(responseExpiresIn) {\r\n // This works because the server will never respond with fractions of a second.\r\n return Number(responseExpiresIn.replace('s', '000'));\r\n}\r\nfunction getAuthorizationHeader(refreshToken) {\r\n return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function createInstallationRequest({ appConfig, heartbeatServiceProvider }, { fid }) {\r\n const endpoint = getInstallationsEndpoint(appConfig);\r\n const headers = getHeaders(appConfig);\r\n // If heartbeat service exists, add the heartbeat string to the header.\r\n const heartbeatService = heartbeatServiceProvider.getImmediate({\r\n optional: true\r\n });\r\n if (heartbeatService) {\r\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\r\n if (heartbeatsHeader) {\r\n headers.append('x-firebase-client', heartbeatsHeader);\r\n }\r\n }\r\n const body = {\r\n fid,\r\n authVersion: INTERNAL_AUTH_VERSION,\r\n appId: appConfig.appId,\r\n sdkVersion: PACKAGE_VERSION\r\n };\r\n const request = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (response.ok) {\r\n const responseValue = await response.json();\r\n const registeredInstallationEntry = {\r\n fid: responseValue.fid || fid,\r\n registrationStatus: 2 /* RequestStatus.COMPLETED */,\r\n refreshToken: responseValue.refreshToken,\r\n authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)\r\n };\r\n return registeredInstallationEntry;\r\n }\r\n else {\r\n throw await getErrorFromResponse('Create Installation', response);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a promise that resolves after given time passes. */\r\nfunction sleep(ms) {\r\n return new Promise(resolve => {\r\n setTimeout(resolve, ms);\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction bufferToBase64UrlSafe(array) {\r\n const b64 = btoa(String.fromCharCode(...array));\r\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst VALID_FID_PATTERN = /^[cdef][\\w-]{21}$/;\r\nconst INVALID_FID = '';\r\n/**\r\n * Generates a new FID using random values from Web Crypto API.\r\n * Returns an empty string if FID generation fails for any reason.\r\n */\r\nfunction generateFid() {\r\n try {\r\n // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5\r\n // bytes. our implementation generates a 17 byte array instead.\r\n const fidByteArray = new Uint8Array(17);\r\n const crypto = self.crypto || self.msCrypto;\r\n crypto.getRandomValues(fidByteArray);\r\n // Replace the first 4 random bits with the constant FID header of 0b0111.\r\n fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);\r\n const fid = encode(fidByteArray);\r\n return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;\r\n }\r\n catch (_a) {\r\n // FID generation errored\r\n return INVALID_FID;\r\n }\r\n}\r\n/** Converts a FID Uint8Array to a base64 string representation. */\r\nfunction encode(fidByteArray) {\r\n const b64String = bufferToBase64UrlSafe(fidByteArray);\r\n // Remove the 23rd character that was added because of the extra 4 bits at the\r\n // end of our 17 byte array, and the '=' padding.\r\n return b64String.substr(0, 22);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a string key that can be used to identify the app. */\r\nfunction getKey(appConfig) {\r\n return `${appConfig.appName}!${appConfig.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst fidChangeCallbacks = new Map();\r\n/**\r\n * Calls the onIdChange callbacks with the new FID value, and broadcasts the\r\n * change to other tabs.\r\n */\r\nfunction fidChanged(appConfig, fid) {\r\n const key = getKey(appConfig);\r\n callFidChangeCallbacks(key, fid);\r\n broadcastFidChange(key, fid);\r\n}\r\nfunction addCallback(appConfig, callback) {\r\n // Open the broadcast channel if it's not already open,\r\n // to be able to listen to change events from other tabs.\r\n getBroadcastChannel();\r\n const key = getKey(appConfig);\r\n let callbackSet = fidChangeCallbacks.get(key);\r\n if (!callbackSet) {\r\n callbackSet = new Set();\r\n fidChangeCallbacks.set(key, callbackSet);\r\n }\r\n callbackSet.add(callback);\r\n}\r\nfunction removeCallback(appConfig, callback) {\r\n const key = getKey(appConfig);\r\n const callbackSet = fidChangeCallbacks.get(key);\r\n if (!callbackSet) {\r\n return;\r\n }\r\n callbackSet.delete(callback);\r\n if (callbackSet.size === 0) {\r\n fidChangeCallbacks.delete(key);\r\n }\r\n // Close broadcast channel if there are no more callbacks.\r\n closeBroadcastChannel();\r\n}\r\nfunction callFidChangeCallbacks(key, fid) {\r\n const callbacks = fidChangeCallbacks.get(key);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n callback(fid);\r\n }\r\n}\r\nfunction broadcastFidChange(key, fid) {\r\n const channel = getBroadcastChannel();\r\n if (channel) {\r\n channel.postMessage({ key, fid });\r\n }\r\n closeBroadcastChannel();\r\n}\r\nlet broadcastChannel = null;\r\n/** Opens and returns a BroadcastChannel if it is supported by the browser. */\r\nfunction getBroadcastChannel() {\r\n if (!broadcastChannel && 'BroadcastChannel' in self) {\r\n broadcastChannel = new BroadcastChannel('[Firebase] FID Change');\r\n broadcastChannel.onmessage = e => {\r\n callFidChangeCallbacks(e.data.key, e.data.fid);\r\n };\r\n }\r\n return broadcastChannel;\r\n}\r\nfunction closeBroadcastChannel() {\r\n if (fidChangeCallbacks.size === 0 && broadcastChannel) {\r\n broadcastChannel.close();\r\n broadcastChannel = null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DATABASE_NAME = 'firebase-installations-database';\r\nconst DATABASE_VERSION = 1;\r\nconst OBJECT_STORE_NAME = 'firebase-installations-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\r\n upgrade: (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n db.createObjectStore(OBJECT_STORE_NAME);\r\n }\r\n }\r\n });\r\n }\r\n return dbPromise;\r\n}\r\n/** Assigns or overwrites the record for the given key with the given value. */\r\nasync function set(appConfig, value) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(OBJECT_STORE_NAME);\r\n const oldValue = (await objectStore.get(key));\r\n await objectStore.put(value, key);\r\n await tx.done;\r\n if (!oldValue || oldValue.fid !== value.fid) {\r\n fidChanged(appConfig, value.fid);\r\n }\r\n return value;\r\n}\r\n/** Removes record(s) from the objectStore that match the given key. */\r\nasync function remove(appConfig) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\r\n await tx.done;\r\n}\r\n/**\r\n * Atomically updates a record with the result of updateFn, which gets\r\n * called with the current value. If newValue is undefined, the record is\r\n * deleted instead.\r\n * @return Updated value\r\n */\r\nasync function update(appConfig, updateFn) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n const store = tx.objectStore(OBJECT_STORE_NAME);\r\n const oldValue = (await store.get(key));\r\n const newValue = updateFn(oldValue);\r\n if (newValue === undefined) {\r\n await store.delete(key);\r\n }\r\n else {\r\n await store.put(newValue, key);\r\n }\r\n await tx.done;\r\n if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {\r\n fidChanged(appConfig, newValue.fid);\r\n }\r\n return newValue;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates and returns the InstallationEntry from the database.\r\n * Also triggers a registration request if it is necessary and possible.\r\n */\r\nasync function getInstallationEntry(installations) {\r\n let registrationPromise;\r\n const installationEntry = await update(installations.appConfig, oldEntry => {\r\n const installationEntry = updateOrCreateInstallationEntry(oldEntry);\r\n const entryWithPromise = triggerRegistrationIfNecessary(installations, installationEntry);\r\n registrationPromise = entryWithPromise.registrationPromise;\r\n return entryWithPromise.installationEntry;\r\n });\r\n if (installationEntry.fid === INVALID_FID) {\r\n // FID generation failed. Waiting for the FID from the server.\r\n return { installationEntry: await registrationPromise };\r\n }\r\n return {\r\n installationEntry,\r\n registrationPromise\r\n };\r\n}\r\n/**\r\n * Creates a new Installation Entry if one does not exist.\r\n * Also clears timed out pending requests.\r\n */\r\nfunction updateOrCreateInstallationEntry(oldEntry) {\r\n const entry = oldEntry || {\r\n fid: generateFid(),\r\n registrationStatus: 0 /* RequestStatus.NOT_STARTED */\r\n };\r\n return clearTimedOutRequest(entry);\r\n}\r\n/**\r\n * If the Firebase Installation is not registered yet, this will trigger the\r\n * registration and return an InProgressInstallationEntry.\r\n *\r\n * If registrationPromise does not exist, the installationEntry is guaranteed\r\n * to be registered.\r\n */\r\nfunction triggerRegistrationIfNecessary(installations, installationEntry) {\r\n if (installationEntry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {\r\n if (!navigator.onLine) {\r\n // Registration required but app is offline.\r\n const registrationPromiseWithError = Promise.reject(ERROR_FACTORY.create(\"app-offline\" /* ErrorCode.APP_OFFLINE */));\r\n return {\r\n installationEntry,\r\n registrationPromise: registrationPromiseWithError\r\n };\r\n }\r\n // Try registering. Change status to IN_PROGRESS.\r\n const inProgressEntry = {\r\n fid: installationEntry.fid,\r\n registrationStatus: 1 /* RequestStatus.IN_PROGRESS */,\r\n registrationTime: Date.now()\r\n };\r\n const registrationPromise = registerInstallation(installations, inProgressEntry);\r\n return { installationEntry: inProgressEntry, registrationPromise };\r\n }\r\n else if (installationEntry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n return {\r\n installationEntry,\r\n registrationPromise: waitUntilFidRegistration(installations)\r\n };\r\n }\r\n else {\r\n return { installationEntry };\r\n }\r\n}\r\n/** This will be executed only once for each new Firebase Installation. */\r\nasync function registerInstallation(installations, installationEntry) {\r\n try {\r\n const registeredInstallationEntry = await createInstallationRequest(installations, installationEntry);\r\n return set(installations.appConfig, registeredInstallationEntry);\r\n }\r\n catch (e) {\r\n if (isServerError(e) && e.customData.serverCode === 409) {\r\n // Server returned a \"FID can not be used\" error.\r\n // Generate a new ID next time.\r\n await remove(installations.appConfig);\r\n }\r\n else {\r\n // Registration failed. Set FID as not registered.\r\n await set(installations.appConfig, {\r\n fid: installationEntry.fid,\r\n registrationStatus: 0 /* RequestStatus.NOT_STARTED */\r\n });\r\n }\r\n throw e;\r\n }\r\n}\r\n/** Call if FID registration is pending in another request. */\r\nasync function waitUntilFidRegistration(installations) {\r\n // Unfortunately, there is no way of reliably observing when a value in\r\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\r\n // so we need to poll.\r\n let entry = await updateInstallationRequest(installations.appConfig);\r\n while (entry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n // createInstallation request still in progress.\r\n await sleep(100);\r\n entry = await updateInstallationRequest(installations.appConfig);\r\n }\r\n if (entry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {\r\n // The request timed out or failed in a different call. Try again.\r\n const { installationEntry, registrationPromise } = await getInstallationEntry(installations);\r\n if (registrationPromise) {\r\n return registrationPromise;\r\n }\r\n else {\r\n // if there is no registrationPromise, entry is registered.\r\n return installationEntry;\r\n }\r\n }\r\n return entry;\r\n}\r\n/**\r\n * Called only if there is a CreateInstallation request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * CreateInstallation request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateInstallationRequest(appConfig) {\r\n return update(appConfig, oldEntry => {\r\n if (!oldEntry) {\r\n throw ERROR_FACTORY.create(\"installation-not-found\" /* ErrorCode.INSTALLATION_NOT_FOUND */);\r\n }\r\n return clearTimedOutRequest(oldEntry);\r\n });\r\n}\r\nfunction clearTimedOutRequest(entry) {\r\n if (hasInstallationRequestTimedOut(entry)) {\r\n return {\r\n fid: entry.fid,\r\n registrationStatus: 0 /* RequestStatus.NOT_STARTED */\r\n };\r\n }\r\n return entry;\r\n}\r\nfunction hasInstallationRequestTimedOut(installationEntry) {\r\n return (installationEntry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */ &&\r\n installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function generateAuthTokenRequest({ appConfig, heartbeatServiceProvider }, installationEntry) {\r\n const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\r\n const headers = getHeadersWithAuth(appConfig, installationEntry);\r\n // If heartbeat service exists, add the heartbeat string to the header.\r\n const heartbeatService = heartbeatServiceProvider.getImmediate({\r\n optional: true\r\n });\r\n if (heartbeatService) {\r\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\r\n if (heartbeatsHeader) {\r\n headers.append('x-firebase-client', heartbeatsHeader);\r\n }\r\n }\r\n const body = {\r\n installation: {\r\n sdkVersion: PACKAGE_VERSION,\r\n appId: appConfig.appId\r\n }\r\n };\r\n const request = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (response.ok) {\r\n const responseValue = await response.json();\r\n const completedAuthToken = extractAuthTokenInfoFromResponse(responseValue);\r\n return completedAuthToken;\r\n }\r\n else {\r\n throw await getErrorFromResponse('Generate Auth Token', response);\r\n }\r\n}\r\nfunction getGenerateAuthTokenEndpoint(appConfig, { fid }) {\r\n return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a valid authentication token for the installation. Generates a new\r\n * token if one doesn't exist, is expired or about to expire.\r\n *\r\n * Should only be called if the Firebase Installation is registered.\r\n */\r\nasync function refreshAuthToken(installations, forceRefresh = false) {\r\n let tokenPromise;\r\n const entry = await update(installations.appConfig, oldEntry => {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* ErrorCode.NOT_REGISTERED */);\r\n }\r\n const oldAuthToken = oldEntry.authToken;\r\n if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {\r\n // There is a valid token in the DB.\r\n return oldEntry;\r\n }\r\n else if (oldAuthToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n // There already is a token request in progress.\r\n tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);\r\n return oldEntry;\r\n }\r\n else {\r\n // No token or token expired.\r\n if (!navigator.onLine) {\r\n throw ERROR_FACTORY.create(\"app-offline\" /* ErrorCode.APP_OFFLINE */);\r\n }\r\n const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);\r\n tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);\r\n return inProgressEntry;\r\n }\r\n });\r\n const authToken = tokenPromise\r\n ? await tokenPromise\r\n : entry.authToken;\r\n return authToken;\r\n}\r\n/**\r\n * Call only if FID is registered and Auth Token request is in progress.\r\n *\r\n * Waits until the current pending request finishes. If the request times out,\r\n * tries once in this thread as well.\r\n */\r\nasync function waitUntilAuthTokenRequest(installations, forceRefresh) {\r\n // Unfortunately, there is no way of reliably observing when a value in\r\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\r\n // so we need to poll.\r\n let entry = await updateAuthTokenRequest(installations.appConfig);\r\n while (entry.authToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n // generateAuthToken still in progress.\r\n await sleep(100);\r\n entry = await updateAuthTokenRequest(installations.appConfig);\r\n }\r\n const authToken = entry.authToken;\r\n if (authToken.requestStatus === 0 /* RequestStatus.NOT_STARTED */) {\r\n // The request timed out or failed in a different call. Try again.\r\n return refreshAuthToken(installations, forceRefresh);\r\n }\r\n else {\r\n return authToken;\r\n }\r\n}\r\n/**\r\n * Called only if there is a GenerateAuthToken request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * GenerateAuthToken request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateAuthTokenRequest(appConfig) {\r\n return update(appConfig, oldEntry => {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* ErrorCode.NOT_REGISTERED */);\r\n }\r\n const oldAuthToken = oldEntry.authToken;\r\n if (hasAuthTokenRequestTimedOut(oldAuthToken)) {\r\n return Object.assign(Object.assign({}, oldEntry), { authToken: { requestStatus: 0 /* RequestStatus.NOT_STARTED */ } });\r\n }\r\n return oldEntry;\r\n });\r\n}\r\nasync function fetchAuthTokenFromServer(installations, installationEntry) {\r\n try {\r\n const authToken = await generateAuthTokenRequest(installations, installationEntry);\r\n const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken });\r\n await set(installations.appConfig, updatedInstallationEntry);\r\n return authToken;\r\n }\r\n catch (e) {\r\n if (isServerError(e) &&\r\n (e.customData.serverCode === 401 || e.customData.serverCode === 404)) {\r\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\r\n // Generate a new ID next time.\r\n await remove(installations.appConfig);\r\n }\r\n else {\r\n const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken: { requestStatus: 0 /* RequestStatus.NOT_STARTED */ } });\r\n await set(installations.appConfig, updatedInstallationEntry);\r\n }\r\n throw e;\r\n }\r\n}\r\nfunction isEntryRegistered(installationEntry) {\r\n return (installationEntry !== undefined &&\r\n installationEntry.registrationStatus === 2 /* RequestStatus.COMPLETED */);\r\n}\r\nfunction isAuthTokenValid(authToken) {\r\n return (authToken.requestStatus === 2 /* RequestStatus.COMPLETED */ &&\r\n !isAuthTokenExpired(authToken));\r\n}\r\nfunction isAuthTokenExpired(authToken) {\r\n const now = Date.now();\r\n return (now < authToken.creationTime ||\r\n authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER);\r\n}\r\n/** Returns an updated InstallationEntry with an InProgressAuthToken. */\r\nfunction makeAuthTokenRequestInProgressEntry(oldEntry) {\r\n const inProgressAuthToken = {\r\n requestStatus: 1 /* RequestStatus.IN_PROGRESS */,\r\n requestTime: Date.now()\r\n };\r\n return Object.assign(Object.assign({}, oldEntry), { authToken: inProgressAuthToken });\r\n}\r\nfunction hasAuthTokenRequestTimedOut(authToken) {\r\n return (authToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */ &&\r\n authToken.requestTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Creates a Firebase Installation if there isn't one for the app and\r\n * returns the Installation ID.\r\n * @param installations - The `Installations` instance.\r\n *\r\n * @public\r\n */\r\nasync function getId(installations) {\r\n const installationsImpl = installations;\r\n const { installationEntry, registrationPromise } = await getInstallationEntry(installationsImpl);\r\n if (registrationPromise) {\r\n registrationPromise.catch(console.error);\r\n }\r\n else {\r\n // If the installation is already registered, update the authentication\r\n // token if needed.\r\n refreshAuthToken(installationsImpl).catch(console.error);\r\n }\r\n return installationEntry.fid;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a Firebase Installations auth token, identifying the current\r\n * Firebase Installation.\r\n * @param installations - The `Installations` instance.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nasync function getToken(installations, forceRefresh = false) {\r\n const installationsImpl = installations;\r\n await completeInstallationRegistration(installationsImpl);\r\n // At this point we either have a Registered Installation in the DB, or we've\r\n // already thrown an error.\r\n const authToken = await refreshAuthToken(installationsImpl, forceRefresh);\r\n return authToken.token;\r\n}\r\nasync function completeInstallationRegistration(installations) {\r\n const { registrationPromise } = await getInstallationEntry(installations);\r\n if (registrationPromise) {\r\n // A createInstallation request is in progress. Wait until it finishes.\r\n await registrationPromise;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteInstallationRequest(appConfig, installationEntry) {\r\n const endpoint = getDeleteEndpoint(appConfig, installationEntry);\r\n const headers = getHeadersWithAuth(appConfig, installationEntry);\r\n const request = {\r\n method: 'DELETE',\r\n headers\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (!response.ok) {\r\n throw await getErrorFromResponse('Delete Installation', response);\r\n }\r\n}\r\nfunction getDeleteEndpoint(appConfig, { fid }) {\r\n return `${getInstallationsEndpoint(appConfig)}/${fid}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Deletes the Firebase Installation and all associated data.\r\n * @param installations - The `Installations` instance.\r\n *\r\n * @public\r\n */\r\nasync function deleteInstallations(installations) {\r\n const { appConfig } = installations;\r\n const entry = await update(appConfig, oldEntry => {\r\n if (oldEntry && oldEntry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {\r\n // Delete the unregistered entry without sending a deleteInstallation request.\r\n return undefined;\r\n }\r\n return oldEntry;\r\n });\r\n if (entry) {\r\n if (entry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */) {\r\n // Can't delete while trying to register.\r\n throw ERROR_FACTORY.create(\"delete-pending-registration\" /* ErrorCode.DELETE_PENDING_REGISTRATION */);\r\n }\r\n else if (entry.registrationStatus === 2 /* RequestStatus.COMPLETED */) {\r\n if (!navigator.onLine) {\r\n throw ERROR_FACTORY.create(\"app-offline\" /* ErrorCode.APP_OFFLINE */);\r\n }\r\n else {\r\n await deleteInstallationRequest(appConfig, entry);\r\n await remove(appConfig);\r\n }\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sets a new callback that will get called when Installation ID changes.\r\n * Returns an unsubscribe function that will remove the callback when called.\r\n * @param installations - The `Installations` instance.\r\n * @param callback - The callback function that is invoked when FID changes.\r\n * @returns A function that can be called to unsubscribe.\r\n *\r\n * @public\r\n */\r\nfunction onIdChange(installations, callback) {\r\n const { appConfig } = installations;\r\n addCallback(appConfig, callback);\r\n return () => {\r\n removeCallback(appConfig, callback);\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns an instance of {@link Installations} associated with the given\r\n * {@link @firebase/app#FirebaseApp} instance.\r\n * @param app - The {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * @public\r\n */\r\nfunction getInstallations(app = getApp()) {\r\n const installationsImpl = _getProvider(app, 'installations').getImmediate();\r\n return installationsImpl;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction extractAppConfig(app) {\r\n if (!app || !app.options) {\r\n throw getMissingValueError('App Configuration');\r\n }\r\n if (!app.name) {\r\n throw getMissingValueError('App Name');\r\n }\r\n // Required app config keys\r\n const configKeys = [\r\n 'projectId',\r\n 'apiKey',\r\n 'appId'\r\n ];\r\n for (const keyName of configKeys) {\r\n if (!app.options[keyName]) {\r\n throw getMissingValueError(keyName);\r\n }\r\n }\r\n return {\r\n appName: app.name,\r\n projectId: app.options.projectId,\r\n apiKey: app.options.apiKey,\r\n appId: app.options.appId\r\n };\r\n}\r\nfunction getMissingValueError(valueName) {\r\n return ERROR_FACTORY.create(\"missing-app-config-values\" /* ErrorCode.MISSING_APP_CONFIG_VALUES */, {\r\n valueName\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst INSTALLATIONS_NAME = 'installations';\r\nconst INSTALLATIONS_NAME_INTERNAL = 'installations-internal';\r\nconst publicFactory = (container) => {\r\n const app = container.getProvider('app').getImmediate();\r\n // Throws if app isn't configured properly.\r\n const appConfig = extractAppConfig(app);\r\n const heartbeatServiceProvider = _getProvider(app, 'heartbeat');\r\n const installationsImpl = {\r\n app,\r\n appConfig,\r\n heartbeatServiceProvider,\r\n _delete: () => Promise.resolve()\r\n };\r\n return installationsImpl;\r\n};\r\nconst internalFactory = (container) => {\r\n const app = container.getProvider('app').getImmediate();\r\n // Internal FIS instance relies on public FIS instance.\r\n const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();\r\n const installationsInternal = {\r\n getId: () => getId(installations),\r\n getToken: (forceRefresh) => getToken(installations, forceRefresh)\r\n };\r\n return installationsInternal;\r\n};\r\nfunction registerInstallations() {\r\n _registerComponent(new Component(INSTALLATIONS_NAME, publicFactory, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n _registerComponent(new Component(INSTALLATIONS_NAME_INTERNAL, internalFactory, \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n}\n\n/**\r\n * Firebase Installations\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterInstallations();\r\nregisterVersion(name, version);\r\n// BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\nregisterVersion(name, version, 'esm2017');\n\nexport { deleteInstallations, getId, getInstallations, getToken, onIdChange };\n//# sourceMappingURL=index.esm2017.js.map\n","import '@firebase/installations';\nimport { Component } from '@firebase/component';\nimport { openDB, deleteDB } from 'idb';\nimport { ErrorFactory, validateIndexedDBOpenable, isIndexedDBAvailable, areCookiesEnabled, getModularInstance } from '@firebase/util';\nimport { _registerComponent, registerVersion, _getProvider, getApp } from '@firebase/app';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_SW_PATH = '/firebase-messaging-sw.js';\r\nconst DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';\r\nconst DEFAULT_VAPID_KEY = 'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';\r\nconst ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';\r\nconst CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';\r\nconst CONSOLE_CAMPAIGN_NAME = 'google.c.a.c_l';\r\nconst CONSOLE_CAMPAIGN_TIME = 'google.c.a.ts';\r\n/** Set to '1' if Analytics is enabled for the campaign */\r\nconst CONSOLE_CAMPAIGN_ANALYTICS_ENABLED = 'google.c.a.e';\r\nvar MessageType$1;\r\n(function (MessageType) {\r\n MessageType[MessageType[\"DATA_MESSAGE\"] = 1] = \"DATA_MESSAGE\";\r\n MessageType[MessageType[\"DISPLAY_NOTIFICATION\"] = 3] = \"DISPLAY_NOTIFICATION\";\r\n})(MessageType$1 || (MessageType$1 = {}));\n\n/**\r\n * @license\r\n * Copyright 2018 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\r\n * in compliance with the License. You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software distributed under the License\r\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\r\n * or implied. See the License for the specific language governing permissions and limitations under\r\n * the License.\r\n */\r\nvar MessageType;\r\n(function (MessageType) {\r\n MessageType[\"PUSH_RECEIVED\"] = \"push-received\";\r\n MessageType[\"NOTIFICATION_CLICKED\"] = \"notification-clicked\";\r\n})(MessageType || (MessageType = {}));\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction arrayToBase64(array) {\r\n const uint8Array = new Uint8Array(array);\r\n const base64String = btoa(String.fromCharCode(...uint8Array));\r\n return base64String.replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\r\n}\r\nfunction base64ToArray(base64String) {\r\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4);\r\n const base64 = (base64String + padding)\r\n .replace(/\\-/g, '+')\r\n .replace(/_/g, '/');\r\n const rawData = atob(base64);\r\n const outputArray = new Uint8Array(rawData.length);\r\n for (let i = 0; i < rawData.length; ++i) {\r\n outputArray[i] = rawData.charCodeAt(i);\r\n }\r\n return outputArray;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst OLD_DB_NAME = 'fcm_token_details_db';\r\n/**\r\n * The last DB version of 'fcm_token_details_db' was 4. This is one higher, so that the upgrade\r\n * callback is called for all versions of the old DB.\r\n */\r\nconst OLD_DB_VERSION = 5;\r\nconst OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\r\nasync function migrateOldDatabase(senderId) {\r\n if ('databases' in indexedDB) {\r\n // indexedDb.databases() is an IndexedDB v3 API and does not exist in all browsers. TODO: Remove\r\n // typecast when it lands in TS types.\r\n const databases = await indexedDB.databases();\r\n const dbNames = databases.map(db => db.name);\r\n if (!dbNames.includes(OLD_DB_NAME)) {\r\n // old DB didn't exist, no need to open.\r\n return null;\r\n }\r\n }\r\n let tokenDetails = null;\r\n const db = await openDB(OLD_DB_NAME, OLD_DB_VERSION, {\r\n upgrade: async (db, oldVersion, newVersion, upgradeTransaction) => {\r\n var _a;\r\n if (oldVersion < 2) {\r\n // Database too old, skip migration.\r\n return;\r\n }\r\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\r\n // Database did not exist. Nothing to do.\r\n return;\r\n }\r\n const objectStore = upgradeTransaction.objectStore(OLD_OBJECT_STORE_NAME);\r\n const value = await objectStore.index('fcmSenderId').get(senderId);\r\n await objectStore.clear();\r\n if (!value) {\r\n // No entry in the database, nothing to migrate.\r\n return;\r\n }\r\n if (oldVersion === 2) {\r\n const oldDetails = value;\r\n if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {\r\n return;\r\n }\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: (_a = oldDetails.createTime) !== null && _a !== void 0 ? _a : Date.now(),\r\n subscriptionOptions: {\r\n auth: oldDetails.auth,\r\n p256dh: oldDetails.p256dh,\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: typeof oldDetails.vapidKey === 'string'\r\n ? oldDetails.vapidKey\r\n : arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n else if (oldVersion === 3) {\r\n const oldDetails = value;\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: oldDetails.createTime,\r\n subscriptionOptions: {\r\n auth: arrayToBase64(oldDetails.auth),\r\n p256dh: arrayToBase64(oldDetails.p256dh),\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n else if (oldVersion === 4) {\r\n const oldDetails = value;\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: oldDetails.createTime,\r\n subscriptionOptions: {\r\n auth: arrayToBase64(oldDetails.auth),\r\n p256dh: arrayToBase64(oldDetails.p256dh),\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n }\r\n });\r\n db.close();\r\n // Delete all old databases.\r\n await deleteDB(OLD_DB_NAME);\r\n await deleteDB('fcm_vapid_details_db');\r\n await deleteDB('undefined');\r\n return checkTokenDetails(tokenDetails) ? tokenDetails : null;\r\n}\r\nfunction checkTokenDetails(tokenDetails) {\r\n if (!tokenDetails || !tokenDetails.subscriptionOptions) {\r\n return false;\r\n }\r\n const { subscriptionOptions } = tokenDetails;\r\n return (typeof tokenDetails.createTime === 'number' &&\r\n tokenDetails.createTime > 0 &&\r\n typeof tokenDetails.token === 'string' &&\r\n tokenDetails.token.length > 0 &&\r\n typeof subscriptionOptions.auth === 'string' &&\r\n subscriptionOptions.auth.length > 0 &&\r\n typeof subscriptionOptions.p256dh === 'string' &&\r\n subscriptionOptions.p256dh.length > 0 &&\r\n typeof subscriptionOptions.endpoint === 'string' &&\r\n subscriptionOptions.endpoint.length > 0 &&\r\n typeof subscriptionOptions.swScope === 'string' &&\r\n subscriptionOptions.swScope.length > 0 &&\r\n typeof subscriptionOptions.vapidKey === 'string' &&\r\n subscriptionOptions.vapidKey.length > 0);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Exported for tests.\r\nconst DATABASE_NAME = 'firebase-messaging-database';\r\nconst DATABASE_VERSION = 1;\r\nconst OBJECT_STORE_NAME = 'firebase-messaging-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\r\n upgrade: (upgradeDb, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through behavior is what we want,\r\n // because if there are multiple versions between the old version and the current version, we\r\n // want ALL the migrations that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n upgradeDb.createObjectStore(OBJECT_STORE_NAME);\r\n }\r\n }\r\n });\r\n }\r\n return dbPromise;\r\n}\r\n/** Gets record(s) from the objectStore that match the given key. */\r\nasync function dbGet(firebaseDependencies) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tokenDetails = (await db\r\n .transaction(OBJECT_STORE_NAME)\r\n .objectStore(OBJECT_STORE_NAME)\r\n .get(key));\r\n if (tokenDetails) {\r\n return tokenDetails;\r\n }\r\n else {\r\n // Check if there is a tokenDetails object in the old DB.\r\n const oldTokenDetails = await migrateOldDatabase(firebaseDependencies.appConfig.senderId);\r\n if (oldTokenDetails) {\r\n await dbSet(firebaseDependencies, oldTokenDetails);\r\n return oldTokenDetails;\r\n }\r\n }\r\n}\r\n/** Assigns or overwrites the record for the given key with the given value. */\r\nasync function dbSet(firebaseDependencies, tokenDetails) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).put(tokenDetails, key);\r\n await tx.done;\r\n return tokenDetails;\r\n}\r\n/** Removes record(s) from the objectStore that match the given key. */\r\nasync function dbRemove(firebaseDependencies) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\r\n await tx.done;\r\n}\r\nfunction getKey({ appConfig }) {\r\n return appConfig.appId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERROR_MAP = {\r\n [\"missing-app-config-values\" /* ErrorCode.MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: \"{$valueName}\"',\r\n [\"only-available-in-window\" /* ErrorCode.AVAILABLE_IN_WINDOW */]: 'This method is available in a Window context.',\r\n [\"only-available-in-sw\" /* ErrorCode.AVAILABLE_IN_SW */]: 'This method is available in a service worker context.',\r\n [\"permission-default\" /* ErrorCode.PERMISSION_DEFAULT */]: 'The notification permission was not granted and dismissed instead.',\r\n [\"permission-blocked\" /* ErrorCode.PERMISSION_BLOCKED */]: 'The notification permission was not granted and blocked instead.',\r\n [\"unsupported-browser\" /* ErrorCode.UNSUPPORTED_BROWSER */]: \"This browser doesn't support the API's required to use the Firebase SDK.\",\r\n [\"indexed-db-unsupported\" /* ErrorCode.INDEXED_DB_UNSUPPORTED */]: \"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)\",\r\n [\"failed-service-worker-registration\" /* ErrorCode.FAILED_DEFAULT_REGISTRATION */]: 'We are unable to register the default service worker. {$browserErrorMessage}',\r\n [\"token-subscribe-failed\" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */]: 'A problem occurred while subscribing the user to FCM: {$errorInfo}',\r\n [\"token-subscribe-no-token\" /* ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN */]: 'FCM returned no token when subscribing the user to push.',\r\n [\"token-unsubscribe-failed\" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */]: 'A problem occurred while unsubscribing the ' +\r\n 'user from FCM: {$errorInfo}',\r\n [\"token-update-failed\" /* ErrorCode.TOKEN_UPDATE_FAILED */]: 'A problem occurred while updating the user from FCM: {$errorInfo}',\r\n [\"token-update-no-token\" /* ErrorCode.TOKEN_UPDATE_NO_TOKEN */]: 'FCM returned no token when updating the user to push.',\r\n [\"use-sw-after-get-token\" /* ErrorCode.USE_SW_AFTER_GET_TOKEN */]: 'The useServiceWorker() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your service worker is used.',\r\n [\"invalid-sw-registration\" /* ErrorCode.INVALID_SW_REGISTRATION */]: 'The input to useServiceWorker() must be a ServiceWorkerRegistration.',\r\n [\"invalid-bg-handler\" /* ErrorCode.INVALID_BG_HANDLER */]: 'The input to setBackgroundMessageHandler() must be a function.',\r\n [\"invalid-vapid-key\" /* ErrorCode.INVALID_VAPID_KEY */]: 'The public VAPID key must be a string.',\r\n [\"use-vapid-key-after-get-token\" /* ErrorCode.USE_VAPID_KEY_AFTER_GET_TOKEN */]: 'The usePublicVapidKey() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your VAPID key is used.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('messaging', 'Messaging', ERROR_MAP);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function requestGetToken(firebaseDependencies, subscriptionOptions) {\r\n const headers = await getHeaders(firebaseDependencies);\r\n const body = getBody(subscriptionOptions);\r\n const subscribeOptions = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n let responseData;\r\n try {\r\n const response = await fetch(getEndpoint(firebaseDependencies.appConfig), subscribeOptions);\r\n responseData = await response.json();\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-subscribe-failed\" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */, {\r\n errorInfo: err === null || err === void 0 ? void 0 : err.toString()\r\n });\r\n }\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-subscribe-failed\" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw ERROR_FACTORY.create(\"token-subscribe-no-token\" /* ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN */);\r\n }\r\n return responseData.token;\r\n}\r\nasync function requestUpdateToken(firebaseDependencies, tokenDetails) {\r\n const headers = await getHeaders(firebaseDependencies);\r\n const body = getBody(tokenDetails.subscriptionOptions);\r\n const updateOptions = {\r\n method: 'PATCH',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n let responseData;\r\n try {\r\n const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${tokenDetails.token}`, updateOptions);\r\n responseData = await response.json();\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-update-failed\" /* ErrorCode.TOKEN_UPDATE_FAILED */, {\r\n errorInfo: err === null || err === void 0 ? void 0 : err.toString()\r\n });\r\n }\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-update-failed\" /* ErrorCode.TOKEN_UPDATE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw ERROR_FACTORY.create(\"token-update-no-token\" /* ErrorCode.TOKEN_UPDATE_NO_TOKEN */);\r\n }\r\n return responseData.token;\r\n}\r\nasync function requestDeleteToken(firebaseDependencies, token) {\r\n const headers = await getHeaders(firebaseDependencies);\r\n const unsubscribeOptions = {\r\n method: 'DELETE',\r\n headers\r\n };\r\n try {\r\n const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${token}`, unsubscribeOptions);\r\n const responseData = await response.json();\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-unsubscribe-failed\" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-unsubscribe-failed\" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */, {\r\n errorInfo: err === null || err === void 0 ? void 0 : err.toString()\r\n });\r\n }\r\n}\r\nfunction getEndpoint({ projectId }) {\r\n return `${ENDPOINT}/projects/${projectId}/registrations`;\r\n}\r\nasync function getHeaders({ appConfig, installations }) {\r\n const authToken = await installations.getToken();\r\n return new Headers({\r\n 'Content-Type': 'application/json',\r\n Accept: 'application/json',\r\n 'x-goog-api-key': appConfig.apiKey,\r\n 'x-goog-firebase-installations-auth': `FIS ${authToken}`\r\n });\r\n}\r\nfunction getBody({ p256dh, auth, endpoint, vapidKey }) {\r\n const body = {\r\n web: {\r\n endpoint,\r\n auth,\r\n p256dh\r\n }\r\n };\r\n if (vapidKey !== DEFAULT_VAPID_KEY) {\r\n body.web.applicationPubKey = vapidKey;\r\n }\r\n return body;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// UpdateRegistration will be called once every week.\r\nconst TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\r\nasync function getTokenInternal(messaging) {\r\n const pushSubscription = await getPushSubscription(messaging.swRegistration, messaging.vapidKey);\r\n const subscriptionOptions = {\r\n vapidKey: messaging.vapidKey,\r\n swScope: messaging.swRegistration.scope,\r\n endpoint: pushSubscription.endpoint,\r\n auth: arrayToBase64(pushSubscription.getKey('auth')),\r\n p256dh: arrayToBase64(pushSubscription.getKey('p256dh'))\r\n };\r\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\r\n if (!tokenDetails) {\r\n // No token, get a new one.\r\n return getNewToken(messaging.firebaseDependencies, subscriptionOptions);\r\n }\r\n else if (!isTokenValid(tokenDetails.subscriptionOptions, subscriptionOptions)) {\r\n // Invalid token, get a new one.\r\n try {\r\n await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);\r\n }\r\n catch (e) {\r\n // Suppress errors because of #2364\r\n console.warn(e);\r\n }\r\n return getNewToken(messaging.firebaseDependencies, subscriptionOptions);\r\n }\r\n else if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {\r\n // Weekly token refresh\r\n return updateToken(messaging, {\r\n token: tokenDetails.token,\r\n createTime: Date.now(),\r\n subscriptionOptions\r\n });\r\n }\r\n else {\r\n // Valid token, nothing to do.\r\n return tokenDetails.token;\r\n }\r\n}\r\n/**\r\n * This method deletes the token from the database, unsubscribes the token from FCM, and unregisters\r\n * the push subscription if it exists.\r\n */\r\nasync function deleteTokenInternal(messaging) {\r\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\r\n if (tokenDetails) {\r\n await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);\r\n await dbRemove(messaging.firebaseDependencies);\r\n }\r\n // Unsubscribe from the push subscription.\r\n const pushSubscription = await messaging.swRegistration.pushManager.getSubscription();\r\n if (pushSubscription) {\r\n return pushSubscription.unsubscribe();\r\n }\r\n // If there's no SW, consider it a success.\r\n return true;\r\n}\r\nasync function updateToken(messaging, tokenDetails) {\r\n try {\r\n const updatedToken = await requestUpdateToken(messaging.firebaseDependencies, tokenDetails);\r\n const updatedTokenDetails = Object.assign(Object.assign({}, tokenDetails), { token: updatedToken, createTime: Date.now() });\r\n await dbSet(messaging.firebaseDependencies, updatedTokenDetails);\r\n return updatedToken;\r\n }\r\n catch (e) {\r\n await deleteTokenInternal(messaging);\r\n throw e;\r\n }\r\n}\r\nasync function getNewToken(firebaseDependencies, subscriptionOptions) {\r\n const token = await requestGetToken(firebaseDependencies, subscriptionOptions);\r\n const tokenDetails = {\r\n token,\r\n createTime: Date.now(),\r\n subscriptionOptions\r\n };\r\n await dbSet(firebaseDependencies, tokenDetails);\r\n return tokenDetails.token;\r\n}\r\n/**\r\n * Gets a PushSubscription for the current user.\r\n */\r\nasync function getPushSubscription(swRegistration, vapidKey) {\r\n const subscription = await swRegistration.pushManager.getSubscription();\r\n if (subscription) {\r\n return subscription;\r\n }\r\n return swRegistration.pushManager.subscribe({\r\n userVisibleOnly: true,\r\n // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key\r\n // submitted to pushManager#subscribe must be of type Uint8Array.\r\n applicationServerKey: base64ToArray(vapidKey)\r\n });\r\n}\r\n/**\r\n * Checks if the saved tokenDetails object matches the configuration provided.\r\n */\r\nfunction isTokenValid(dbOptions, currentOptions) {\r\n const isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;\r\n const isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;\r\n const isAuthEqual = currentOptions.auth === dbOptions.auth;\r\n const isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;\r\n return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction externalizePayload(internalPayload) {\r\n const payload = {\r\n from: internalPayload.from,\r\n // eslint-disable-next-line camelcase\r\n collapseKey: internalPayload.collapse_key,\r\n // eslint-disable-next-line camelcase\r\n messageId: internalPayload.fcmMessageId\r\n };\r\n propagateNotificationPayload(payload, internalPayload);\r\n propagateDataPayload(payload, internalPayload);\r\n propagateFcmOptions(payload, internalPayload);\r\n return payload;\r\n}\r\nfunction propagateNotificationPayload(payload, messagePayloadInternal) {\r\n if (!messagePayloadInternal.notification) {\r\n return;\r\n }\r\n payload.notification = {};\r\n const title = messagePayloadInternal.notification.title;\r\n if (!!title) {\r\n payload.notification.title = title;\r\n }\r\n const body = messagePayloadInternal.notification.body;\r\n if (!!body) {\r\n payload.notification.body = body;\r\n }\r\n const image = messagePayloadInternal.notification.image;\r\n if (!!image) {\r\n payload.notification.image = image;\r\n }\r\n const icon = messagePayloadInternal.notification.icon;\r\n if (!!icon) {\r\n payload.notification.icon = icon;\r\n }\r\n}\r\nfunction propagateDataPayload(payload, messagePayloadInternal) {\r\n if (!messagePayloadInternal.data) {\r\n return;\r\n }\r\n payload.data = messagePayloadInternal.data;\r\n}\r\nfunction propagateFcmOptions(payload, messagePayloadInternal) {\r\n var _a, _b, _c, _d, _e;\r\n // fcmOptions.link value is written into notification.click_action. see more in b/232072111\r\n if (!messagePayloadInternal.fcmOptions &&\r\n !((_a = messagePayloadInternal.notification) === null || _a === void 0 ? void 0 : _a.click_action)) {\r\n return;\r\n }\r\n payload.fcmOptions = {};\r\n const link = (_c = (_b = messagePayloadInternal.fcmOptions) === null || _b === void 0 ? void 0 : _b.link) !== null && _c !== void 0 ? _c : (_d = messagePayloadInternal.notification) === null || _d === void 0 ? void 0 : _d.click_action;\r\n if (!!link) {\r\n payload.fcmOptions.link = link;\r\n }\r\n // eslint-disable-next-line camelcase\r\n const analyticsLabel = (_e = messagePayloadInternal.fcmOptions) === null || _e === void 0 ? void 0 : _e.analytics_label;\r\n if (!!analyticsLabel) {\r\n payload.fcmOptions.analyticsLabel = analyticsLabel;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isConsoleMessage(data) {\r\n // This message has a campaign ID, meaning it was sent using the Firebase Console.\r\n return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n_mergeStrings('hts/frbslgigp.ogepscmv/ieo/eaylg', 'tp:/ieaeogn-agolai.o/1frlglgc/o');\r\n_mergeStrings('AzSCbw63g1R0nCw85jG8', 'Iaya3yLKwmgvh7cF0q4');\r\nfunction _mergeStrings(s1, s2) {\r\n const resultArray = [];\r\n for (let i = 0; i < s1.length; i++) {\r\n resultArray.push(s1.charAt(i));\r\n if (i < s2.length) {\r\n resultArray.push(s2.charAt(i));\r\n }\r\n }\r\n return resultArray.join('');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction extractAppConfig(app) {\r\n if (!app || !app.options) {\r\n throw getMissingValueError('App Configuration Object');\r\n }\r\n if (!app.name) {\r\n throw getMissingValueError('App Name');\r\n }\r\n // Required app config keys\r\n const configKeys = [\r\n 'projectId',\r\n 'apiKey',\r\n 'appId',\r\n 'messagingSenderId'\r\n ];\r\n const { options } = app;\r\n for (const keyName of configKeys) {\r\n if (!options[keyName]) {\r\n throw getMissingValueError(keyName);\r\n }\r\n }\r\n return {\r\n appName: app.name,\r\n projectId: options.projectId,\r\n apiKey: options.apiKey,\r\n appId: options.appId,\r\n senderId: options.messagingSenderId\r\n };\r\n}\r\nfunction getMissingValueError(valueName) {\r\n return ERROR_FACTORY.create(\"missing-app-config-values\" /* ErrorCode.MISSING_APP_CONFIG_VALUES */, {\r\n valueName\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MessagingService {\r\n constructor(app, installations, analyticsProvider) {\r\n // logging is only done with end user consent. Default to false.\r\n this.deliveryMetricsExportedToBigQueryEnabled = false;\r\n this.onBackgroundMessageHandler = null;\r\n this.onMessageHandler = null;\r\n this.logEvents = [];\r\n this.isLogServiceStarted = false;\r\n const appConfig = extractAppConfig(app);\r\n this.firebaseDependencies = {\r\n app,\r\n appConfig,\r\n installations,\r\n analyticsProvider\r\n };\r\n }\r\n _delete() {\r\n return Promise.resolve();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function registerDefaultSw(messaging) {\r\n try {\r\n messaging.swRegistration = await navigator.serviceWorker.register(DEFAULT_SW_PATH, {\r\n scope: DEFAULT_SW_SCOPE\r\n });\r\n // The timing when browser updates sw when sw has an update is unreliable from experiment. It\r\n // leads to version conflict when the SDK upgrades to a newer version in the main page, but sw\r\n // is stuck with the old version. For example,\r\n // https://github.com/firebase/firebase-js-sdk/issues/2590 The following line reliably updates\r\n // sw if there was an update.\r\n messaging.swRegistration.update().catch(() => {\r\n /* it is non blocking and we don't care if it failed */\r\n });\r\n }\r\n catch (e) {\r\n throw ERROR_FACTORY.create(\"failed-service-worker-registration\" /* ErrorCode.FAILED_DEFAULT_REGISTRATION */, {\r\n browserErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateSwReg(messaging, swRegistration) {\r\n if (!swRegistration && !messaging.swRegistration) {\r\n await registerDefaultSw(messaging);\r\n }\r\n if (!swRegistration && !!messaging.swRegistration) {\r\n return;\r\n }\r\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\r\n throw ERROR_FACTORY.create(\"invalid-sw-registration\" /* ErrorCode.INVALID_SW_REGISTRATION */);\r\n }\r\n messaging.swRegistration = swRegistration;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateVapidKey(messaging, vapidKey) {\r\n if (!!vapidKey) {\r\n messaging.vapidKey = vapidKey;\r\n }\r\n else if (!messaging.vapidKey) {\r\n messaging.vapidKey = DEFAULT_VAPID_KEY;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function getToken$1(messaging, options) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* ErrorCode.AVAILABLE_IN_WINDOW */);\r\n }\r\n if (Notification.permission === 'default') {\r\n await Notification.requestPermission();\r\n }\r\n if (Notification.permission !== 'granted') {\r\n throw ERROR_FACTORY.create(\"permission-blocked\" /* ErrorCode.PERMISSION_BLOCKED */);\r\n }\r\n await updateVapidKey(messaging, options === null || options === void 0 ? void 0 : options.vapidKey);\r\n await updateSwReg(messaging, options === null || options === void 0 ? void 0 : options.serviceWorkerRegistration);\r\n return getTokenInternal(messaging);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function logToScion(messaging, messageType, data) {\r\n const eventType = getEventType(messageType);\r\n const analytics = await messaging.firebaseDependencies.analyticsProvider.get();\r\n analytics.logEvent(eventType, {\r\n /* eslint-disable camelcase */\r\n message_id: data[CONSOLE_CAMPAIGN_ID],\r\n message_name: data[CONSOLE_CAMPAIGN_NAME],\r\n message_time: data[CONSOLE_CAMPAIGN_TIME],\r\n message_device_time: Math.floor(Date.now() / 1000)\r\n /* eslint-enable camelcase */\r\n });\r\n}\r\nfunction getEventType(messageType) {\r\n switch (messageType) {\r\n case MessageType.NOTIFICATION_CLICKED:\r\n return 'notification_open';\r\n case MessageType.PUSH_RECEIVED:\r\n return 'notification_foreground';\r\n default:\r\n throw new Error();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function messageEventListener(messaging, event) {\r\n const internalPayload = event.data;\r\n if (!internalPayload.isFirebaseMessaging) {\r\n return;\r\n }\r\n if (messaging.onMessageHandler &&\r\n internalPayload.messageType === MessageType.PUSH_RECEIVED) {\r\n if (typeof messaging.onMessageHandler === 'function') {\r\n messaging.onMessageHandler(externalizePayload(internalPayload));\r\n }\r\n else {\r\n messaging.onMessageHandler.next(externalizePayload(internalPayload));\r\n }\r\n }\r\n // Log to Scion if applicable\r\n const dataPayload = internalPayload.data;\r\n if (isConsoleMessage(dataPayload) &&\r\n dataPayload[CONSOLE_CAMPAIGN_ANALYTICS_ENABLED] === '1') {\r\n await logToScion(messaging, internalPayload.messageType, dataPayload);\r\n }\r\n}\n\nconst name = \"@firebase/messaging\";\nconst version = \"0.12.4\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst WindowMessagingFactory = (container) => {\r\n const messaging = new MessagingService(container.getProvider('app').getImmediate(), container.getProvider('installations-internal').getImmediate(), container.getProvider('analytics-internal'));\r\n navigator.serviceWorker.addEventListener('message', e => messageEventListener(messaging, e));\r\n return messaging;\r\n};\r\nconst WindowMessagingInternalFactory = (container) => {\r\n const messaging = container\r\n .getProvider('messaging')\r\n .getImmediate();\r\n const messagingInternal = {\r\n getToken: (options) => getToken$1(messaging, options)\r\n };\r\n return messagingInternal;\r\n};\r\nfunction registerMessagingInWindow() {\r\n _registerComponent(new Component('messaging', WindowMessagingFactory, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n _registerComponent(new Component('messaging-internal', WindowMessagingInternalFactory, \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n registerVersion(name, version);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Checks if all required APIs exist in the browser.\r\n * @returns a Promise that resolves to a boolean.\r\n *\r\n * @public\r\n */\r\nasync function isWindowSupported() {\r\n try {\r\n // This throws if open() is unsupported, so adding it to the conditional\r\n // statement below can cause an uncaught error.\r\n await validateIndexedDBOpenable();\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n // firebase-js-sdk/issues/2393 reveals that idb#open in Safari iframe and Firefox private browsing\r\n // might be prohibited to run. In these contexts, an error would be thrown during the messaging\r\n // instantiating phase, informing the developers to import/call isSupported for special handling.\r\n return (typeof window !== 'undefined' &&\r\n isIndexedDBAvailable() &&\r\n areCookiesEnabled() &&\r\n 'serviceWorker' in navigator &&\r\n 'PushManager' in window &&\r\n 'Notification' in window &&\r\n 'fetch' in window &&\r\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\r\n PushSubscription.prototype.hasOwnProperty('getKey'));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteToken$1(messaging) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* ErrorCode.AVAILABLE_IN_WINDOW */);\r\n }\r\n if (!messaging.swRegistration) {\r\n await registerDefaultSw(messaging);\r\n }\r\n return deleteTokenInternal(messaging);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction onMessage$1(messaging, nextOrObserver) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* ErrorCode.AVAILABLE_IN_WINDOW */);\r\n }\r\n messaging.onMessageHandler = nextOrObserver;\r\n return () => {\r\n messaging.onMessageHandler = null;\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Retrieves a Firebase Cloud Messaging instance.\r\n *\r\n * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.\r\n *\r\n * @public\r\n */\r\nfunction getMessagingInWindow(app = getApp()) {\r\n // Conscious decision to make this async check non-blocking during the messaging instance\r\n // initialization phase for performance consideration. An error would be thrown latter for\r\n // developer's information. Developers can then choose to import and call `isSupported` for\r\n // special handling.\r\n isWindowSupported().then(isSupported => {\r\n // If `isWindowSupported()` resolved, but returned false.\r\n if (!isSupported) {\r\n throw ERROR_FACTORY.create(\"unsupported-browser\" /* ErrorCode.UNSUPPORTED_BROWSER */);\r\n }\r\n }, _ => {\r\n // If `isWindowSupported()` rejected.\r\n throw ERROR_FACTORY.create(\"indexed-db-unsupported\" /* ErrorCode.INDEXED_DB_UNSUPPORTED */);\r\n });\r\n return _getProvider(getModularInstance(app), 'messaging').getImmediate();\r\n}\r\n/**\r\n * Subscribes the {@link Messaging} instance to push notifications. Returns an Firebase Cloud\r\n * Messaging registration token that can be used to send push messages to that {@link Messaging}\r\n * instance.\r\n *\r\n * If a notification permission isn't already granted, this method asks the user for permission. The\r\n * returned promise rejects if the user does not allow the app to show notifications.\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n * @param options - Provides an optional vapid key and an optinoal service worker registration\r\n *\r\n * @returns The promise resolves with an FCM registration token.\r\n *\r\n * @public\r\n */\r\nasync function getToken(messaging, options) {\r\n messaging = getModularInstance(messaging);\r\n return getToken$1(messaging, options);\r\n}\r\n/**\r\n * Deletes the registration token associated with this {@link Messaging} instance and unsubscribes\r\n * the {@link Messaging} instance from the push subscription.\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n *\r\n * @returns The promise resolves when the token has been successfully deleted.\r\n *\r\n * @public\r\n */\r\nfunction deleteToken(messaging) {\r\n messaging = getModularInstance(messaging);\r\n return deleteToken$1(messaging);\r\n}\r\n/**\r\n * When a push message is received and the user is currently on a page for your origin, the\r\n * message is passed to the page and an `onMessage()` event is dispatched with the payload of\r\n * the push message.\r\n *\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n * @param nextOrObserver - This function, or observer object with `next` defined,\r\n * is called when a message is received and the user is currently viewing your page.\r\n * @returns To stop listening for messages execute this returned function.\r\n *\r\n * @public\r\n */\r\nfunction onMessage(messaging, nextOrObserver) {\r\n messaging = getModularInstance(messaging);\r\n return onMessage$1(messaging, nextOrObserver);\r\n}\n\n/**\r\n * Firebase Cloud Messaging\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterMessagingInWindow();\n\nexport { deleteToken, getMessagingInWindow as getMessaging, getToken, isWindowSupported as isSupported, onMessage };\n//# sourceMappingURL=index.esm2017.js.map\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nexport default class Alert extends React.PureComponent {\n render() {\n return ( {shown} Supports conversion of user keyboard input to formatted text: Supports conversion of user keyboard input to formatted text: Supports conversion of user keyboard input to formatted text: Supports conversion of user keyboard input to formatted text:.\n el = UploadingImage;\n }\n\n return el;\n}\n\n// Additional processing of image data.\nfunction handleVideoData(el, data, attr) {\n if (!data) {\n attr.src = 'img/broken_video.png';\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n };\n return el;\n }\n attr.className = 'inline-image';\n const dim = fitImageSize(data.width, data.height,\n this.viewportWidth > 0 ? Math.min(this.viewportWidth - REM_SIZE * 6.5, REM_SIZE * 34.5) :\n REM_SIZE * 34.5, REM_SIZE * 24, false) ||\n {dstWidth: NO_DIMENSIONS_VIDEO, dstHeight: NO_DIMENSIONS_VIDEO};\n attr.style = {\n width: dim.dstWidth + 'px',\n height: dim.dstHeight + 'px',\n // Looks like a Chrome bug: broken image does not respect 'width' and 'height'.\n minWidth: dim.dstWidth + 'px',\n minHeight: dim.dstHeight + 'px'\n };\n if (!Drafty.isProcessing(data)) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'image'));\n attr.alt = data.name;\n if (data.ref || data.val) {\n attr.onClick = this.onVideoPreview;\n attr.loading = 'lazy';\n }\n el = InlineVideo;\n } else {\n // Use custom element instead of
.\n el = UploadingImage;\n }\n\n return el;\n}\n\n// Converts Drafty object into a one-line preview. 'this' is set by the caller.\n// 'this' must contain:\n// formatMessage: this.props.intl.formatMessage\n// messages: formatjs messages defined with defineMessages.\nexport function previewFormatter(style, data, values, key) {\n if (!style) {\n // Unformatted.\n return values;\n }\n\n let el = Drafty.tagName(style);\n const attr = { key: key };\n switch (style) {\n case 'AU':\n // Voicemail as '[mic] 0:00'.\n el = React.Fragment;\n values = [mic, ' ', secondsToTime(data.duration/1000)];\n break;\n case 'BR':\n // Replace new line with a space.\n el = React.Fragment;\n values = [' '];\n break;\n case 'HL':\n // Make highlight less prominent in preview.\n attr.className = 'highlight preview';\n break;\n case 'LN':\n case 'MN':\n // Disable links in previews.\n el = 'span';\n break;\n case 'IM':\n // Replace image with '[icon] Image'.\n el = React.Fragment;\n values = [photo, ' ', this.formatMessage(messages.drafty_image)];\n break;\n case 'BN':\n el = 'span';\n attr.className = 'flat-button faux';\n break;\n case 'FM':\n el = React.Fragment;\n values = [dashboard,\n this.formatMessage(messages.drafty_form)].concat(' ', values || []);\n break;\n case 'RW':\n el = React.Fragment;\n break;\n case 'EX':\n if (data) {\n if (data.mime == 'application/json') {\n // Ignore JSON attachments: they are form response payloads.\n return null;\n }\n // Clear payload.\n delete data.val;\n delete data.ref;\n }\n el = React.Fragment;\n values = [attachment, ' ', this.formatMessage(messages.drafty_attachment)];\n break;\n case 'VC':\n el = CallStatus;\n if (data) {\n attr.callState = data.state;\n attr.incoming = data.incoming;\n attr.duration = data.duration;\n }\n values = null;\n break;\n case 'QQ':\n case 'HD':\n el = null;\n values = null;\n break;\n case 'VD':\n // Replace image with '[icon] Video'.\n el = React.Fragment;\n values = [play_circle_outline, ' ', this.formatMessage(messages.drafty_video)];\n break;\n default:\n if (!el) {\n // Unknown element.\n el = React.Fragment;\n values = [extension, ' ', this.formatMessage(messages.drafty_unknown)];\n }\n break;\n }\n if (!el) {\n return values;\n }\n return React.createElement(el, attr, values);\n};\n\n// Converts Drafty object into a quoted reply; 'this' is set by the caller.\nfunction inlineImageAttr(attr, data) {\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n maxWidth: IMAGE_THUMBNAIL_DIM + 'px',\n maxHeight: IMAGE_THUMBNAIL_DIM + 'px',\n }\n attr.className = 'inline-image';\n attr.alt = this.formatMessage(messages.drafty_image);\n if (!data) {\n attr.src = 'img/broken_image.png';\n } else {\n attr.src = attr.src || 'img/broken_image.png';\n }\n attr.title = attr.alt;\n return attr;\n}\n\n// Converts Drafty object into a quoted reply; 'this' is set by the caller.\nfunction inlineVideoAttr(attr, data) {\n const dim = fitImageSize(data.width, data.height, VIDEO_THUMBNAIL_WIDTH, IMAGE_THUMBNAIL_DIM);\n attr.style = {\n width: dim.width + 'px',\n height: dim.height + 'px',\n maxWidth: VIDEO_THUMBNAIL_WIDTH + 'px',\n maxHeight: IMAGE_THUMBNAIL_DIM + 'px',\n }\n attr.className = 'inline-image';\n attr.alt = this.formatMessage(messages.drafty_video);\n attr.title = attr.alt;\n if (!data) {\n attr.src = 'img/broken_video.png';\n } else {\n attr.src = attr.src || 'img/broken_video.png';\n }\n return attr;\n}\n\n// Displays a portion of Drafty within 'QQ' quotes. 'this' is set by the caller.\n// 'this' must contain:\n// formatMessage: this.props.intl.formatMessage\n// messages: formatjs messages defined with defineMessages.\n// authorizeURL: this.props.tinode.authorizeURL\n// onQuoteClick: this.handleQuoteClick (optional)\nfunction quoteFormatter(style, data, values, key) {\n if (['BR', 'EX', 'IM', 'MN', 'VD'].includes(style)) {\n let el = Drafty.tagName(style);\n let attr = Drafty.attrValue(style, data) || {};\n attr.key = key;\n switch(style) {\n case 'BR':\n values = null;\n break;\n case 'IM':\n attr = inlineImageAttr.call(this, attr, data);\n values = [React.createElement('img', attr, null), ' ', attr.alt];\n el = React.Fragment;\n // Fragment attributes.\n attr = {key: key};\n break;\n case 'VD':\n attr = inlineVideoAttr.call(this, attr, data);\n values = [React.createElement('img', attr, null), ' ', attr.alt];\n el = React.Fragment;\n // Fragment attributes.\n attr = {key: key};\n break;\n case 'MN':\n el = 'span';\n attr.className = 'mention'\n if (data) {\n attr.className += ' ' + idToColorClass(data.val, false, true);\n }\n break;\n case 'EX':\n let fname;\n if (data) {\n if (data.mime == 'application/json') {\n // Ignore JSON attachments: they are form response payloads.\n return null;\n }\n fname = data.name;\n // Clear payload.\n delete data.val;\n delete data.ref;\n }\n el = React.Fragment;\n values = [attachment,\n shortenFileName(fname, 16) || this.formatMessage(messages.drafty_attachment)];\n break;\n }\n return React.createElement(el, attr, values);\n }\n return previewFormatter.call(this, style, data, values, key);\n}\n\n// Create image thumbnail suitable for inclusion in a quote.\nfunction quoteImageOrVideo(data, isVideo) {\n let promise;\n let bits, ref, mime;\n if (isVideo) {\n bits = data.preview;\n mime = data.premime || 'image/jpeg';\n ref = data.preref;\n } else {\n bits = data.val;\n mime = data.mime;\n ref = data.ref;\n }\n // Get the blob from the image data.\n if (bits) {\n const blob = base64ToBlob(bits, mime);\n if (!blob) {\n throw new Error(\"Invalid image\");\n }\n promise = Promise.resolve(blob);\n } else if (ref) {\n promise = fetch(this.authorizeURL(sanitizeUrlForMime(ref, 'image')))\n .then(evt => {\n if (evt.ok) {\n return evt.blob();\n } else {\n throw new Error(`Image fetch unsuccessful: ${evt.status} ${evt.statusText}`);\n }\n });\n } else {\n throw new Error(\"Missing image data\");\n }\n\n // Scale the blob.\n return promise\n .then(blob => {\n // If it's an image, cut the square from the center of the image and shrink it.\n // If it's a video, allow it to be rectantular.\n return imageScaled(blob, isVideo ? VIDEO_THUMBNAIL_WIDTH : IMAGE_THUMBNAIL_DIM, IMAGE_THUMBNAIL_DIM, -1, !isVideo)\n }).then(scaled => {\n if (isVideo) {\n data.premime = scaled.mime;\n } else {\n data.mime = scaled.mime;\n }\n data.size = scaled.blob.size;\n data.width = scaled.width;\n data.height = scaled.height;\n delete data.ref;\n delete data.preref;\n // Keeping the original file name, if provided: ex.data.name;\n\n data.src = URL.createObjectURL(scaled.blob);\n return blobToBase64(scaled.blob);\n }).then(b64 => {\n if (isVideo) {\n data.preview = b64.bits;\n } else {\n data.val = b64.bits;\n }\n return data;\n }).catch(err => {\n delete data.val;\n delete data.preview;\n delete data.src;\n data.width = IMAGE_THUMBNAIL_DIM;\n data.height = IMAGE_THUMBNAIL_DIM;\n // Rethrow.\n throw err;\n });\n}\n\n// Create a preview of a reply.\nexport function replyFormatter(style, data, values, key, stack) {\n if (style == 'IM' || style == 'VD') {\n const isImage = style == 'IM';\n const attr = isImage ? inlineImageAttr.call(this, {key: key}, data) :\n inlineVideoAttr.call(this, {key: key}, data);\n\n let loadedPromise;\n try {\n loadedPromise = cancelablePromise(quoteImageOrVideo.call(this, data, style == 'VD'));\n } catch (error) {\n console.warn(\"Failed to quote image:\", error.message);\n loadedPromise = cancelablePromise(error);\n }\n attr.whenDone = loadedPromise;\n values = [React.createElement(LazyImage, attr, null), ' ', attr.alt];\n return React.createElement(React.Fragment, {key: key}, values);\n } else if (style == 'QQ') {\n if (stack.includes('QQ')) {\n // Quote inside quote when forwarding a message.\n return React.createElement('span', {key: key},\n [format_quote, ' ']);\n }\n\n const attr = Drafty.attrValue('QQ', data) || {};\n attr.key = key;\n attr.className = 'reply-quote'\n return React.createElement(Drafty.tagName('QQ'), attr, values);\n }\n return quoteFormatter.call(this, style, data, values, key);\n}\n","import { KNOWN_HOSTS, DEFAULT_HOST } from '../config.js';\n\n// Detect server address from the URL\nexport function detectServerAddress() {\n let host = DEFAULT_HOST;\n if (typeof window.location == 'object') {\n if (window.location.protocol == 'file:' || window.location.hostname == 'localhost') {\n host = KNOWN_HOSTS.local;\n } else if (window.location.hostname) {\n host = window.location.hostname + (window.location.port ? ':' + window.location.port : '');\n }\n }\n return host;\n}\n\n// Detect if the page is served over HTTPS.\nexport function isSecureConnection() {\n if (typeof window.location == 'object') {\n return window.location.protocol == 'https:';\n }\n return false;\n}\n\nexport function isLocalHost() {\n if (typeof window.location == 'object') {\n return window.location.hostname == 'localhost';\n }\n return false;\n}\n","// Helper functions for storing values in localStorage.\n// By default localStorage can store only strings, not objects or other types.\n\nexport default class LocalStorageUtil {\n // Replace old object with the new one.\n static setObject(key, value) {\n localStorage.setItem(key, JSON.stringify(value));\n }\n\n // Get stored object.\n static getObject(key) {\n const value = localStorage.getItem(key);\n return value && JSON.parse(value);\n }\n\n // Partially or wholly update stored object.\n static updateObject(key, value) {\n const oldVal = this.getObject(key);\n this.setObject(key, Object.assign(oldVal || {}, value));\n }\n\n // Just a wrapper.\n static removeItem(key) {\n localStorage.removeItem(key);\n }\n}\n","// Utility class for hash navigation.\n\nexport default class HashNavigation {\n // Parse hash as in http://www.example.com/path#hash as if it were\n // path and arguments.\n static parseUrlHash(hash) {\n // Split path from args, path -> parts[0], args->path[1]\n const parts = hash.split('?', 2);\n const params = {};\n let path = [];\n if (parts[0]) {\n path = parts[0].replace('#', '').split('/');\n }\n if (parts[1]) {\n parts[1].split('&').forEach((arg) => {\n // Can't use split() because the value may contain '='.\n const eq = arg.indexOf('=');\n if (eq > 0) {\n params[arg.slice(0, eq)] = decodeURIComponent(arg.slice(eq + 1));\n }\n });\n }\n return {path: path, params: params};\n }\n\n static navigateTo(url) {\n window.location.hash = url;\n }\n\n static composeUrlHash(path, params) {\n let url = path.join('/');\n const args = [];\n for (const key in params) {\n if (params.hasOwnProperty(key)) {\n args.push(key + '=' + encodeURIComponent(params[key]));\n }\n }\n if (args.length > 0) {\n url += '?' + args.join('&');\n }\n return url;\n }\n\n static addUrlParam(hash, key, value) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.params[key] = value;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static removeUrlParam(hash, key) {\n const parsed = HashNavigation.parseUrlHash(hash);\n delete parsed.params[key];\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlSidePanel(hash, sidepanel) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.path[0] = sidepanel;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlInfoPanel(hash, infopanel) {\n const parsed = HashNavigation.parseUrlHash(hash);\n if (infopanel) {\n parsed.params.info = infopanel;\n } else {\n delete parsed.params.info;\n }\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlTopic(hash, topic) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.path[1] = topic;\n // Close InfoView on topic change.\n delete parsed.params.info;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n}\n","// Short representation of time in the past.\nexport function shortDateFormat(then, locale) {\n locale = locale || window.navigator.userLanguage || window.navigator.language;\n const now = new Date();\n if (then.getFullYear() == now.getFullYear()) {\n // Same year.\n if (then.getMonth() == now.getMonth() && then.getDate() == now.getDate()) {\n // Same month and day, show time only.\n return then.toLocaleTimeString(locale, {hour12: false, hour: '2-digit', minute: '2-digit'});\n }\n // Different month and/or day, show month day, time.\n return then.toLocaleDateString(locale,\n {hour12: false, month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'});\n }\n // Different year: just show the date.\n return then.toLocaleDateString(locale, {year: 'numeric', month: 'short', day: 'numeric'});\n}\n\n// Representation a date relative to now.\nexport function relativeDateFormat(then, locale) {\n locale = locale || window.navigator.userLanguage || window.navigator.language;\n const now = new Date();\n const thenDays = Math.floor((then.getTime() - then.getTimezoneOffset() * 60_000) / 86_400_000);\n const nowDays = Math.floor((now.getTime() - now.getTimezoneOffset() * 60_000) / 86_400_000);\n const diff = thenDays - nowDays;\n if (Math.abs(diff) < 2) {\n // Today or yesterday.\n return new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(diff, 'day')\n }\n // More than two days: just show the date.\n return new Intl.DateTimeFormat(locale).format(then);\n}\n\n// Convert seconds to [hours:]minutes:seconds, i.e. 156 sec -> 2:36, 3756 sec -> 1:02:36.\n// If
fixedMins is true, then minutes are represented by at least two digits.\nexport function secondsToTime(seconds, fixedMin) {\n if (typeof seconds != 'number') {\n return '';\n }\n\n let min = (Math.floor(seconds / 60) | 0) % 60;\n let hours = Math.floor(seconds / 3600) | 0;\n\n if (fixedMin || hours > 0) {\n min = min < 10 ? `0${min}` : min;\n }\n let sec = (seconds | 0) % 60;\n sec = sec < 10 ? `0${sec}` : sec;\n if (hours == 0) {\n return `${min}:${sec}`;\n }\n return `${hours}:${min}:${sec}`;\n}\n\n// Convert a number of bytes to human-readable format.\nexport function bytesToHumanSize(bytes) {\n if (!bytes || bytes == 0) {\n return '0 Bytes';\n }\n\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];\n const bucket = Math.min(Math.floor(Math.log2(bytes) / 10) | 0, sizes.length-1);\n const count = bytes / Math.pow(1024, bucket);\n const round = bucket > 0 ? (count < 3 ? 2 : (count < 30 ? 1 : 0)) : 0;\n return count.toFixed(round) + ' ' + sizes[bucket];\n}\n\n// Shorten a file name to be under maxLength by clipping out the middle.\nexport function shortenFileName(filename, maxLength) {\n if (typeof filename != 'string') {\n return filename;\n }\n return filename.length > maxLength ?\n filename.slice(0, maxLength/2 - 1) + '…' + filename.slice(1 - maxLength/2) : filename;\n}\n\n// Get 32 bit integer hash value for a string. Ideally it should produce the same value\n// as Java's String#hash().\nfunction stringToColorHash(value) {\n let hash = 0;\n value = '' + value;\n for (let i = 0; i < value.length; i++) {\n hash = ((hash << 5) - hash) + value.charCodeAt(i);\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash;\n}\n\n// User avatar letter color id.\nexport function letterTileColorId(userId) {\n return Math.abs(stringToColorHash(userId)) % 16;\n}\n\n// Converts user or topic ID to a CSS color class. Ideally it should produce the same color value as Java version.\n// params:\n// - {string} id: user or topic ID\n// - {boolean} light: light or dark version of the color.\n// - {boolean} fg: foreground (text) or background color.\nexport function idToColorClass(id, light, fg) {\n return (light ? 'lt-' : 'dk-') + (fg ? 'fg-' : 'bg-') + letterTileColorId(id);\n}\n\n// Takes ISO Alpha-2 country code, like 'US' and converts it to a flag emoji.\nexport function flagEmoji(countryCode) {\n const codePoints = countryCode\n .toUpperCase()\n .split('')\n .map(char => 0x1F1A5 + char.charCodeAt());\n return String.fromCodePoint(...codePoints);\n}\n","// Odds and ends\n\nimport { Tinode } from 'tinode-sdk';\n\n// Make shortcut icon appear with a green dot + show unread count in title.\nexport function updateFavicon(count) {\n const oldIcon = document.getElementById('shortcut-icon');\n const head = document.head || document.getElementsByTagName('head')[0];\n const newIcon = document.createElement('link');\n newIcon.type = 'image/png';\n newIcon.id = 'shortcut-icon';\n newIcon.rel = 'shortcut icon';\n newIcon.href = 'img/logo32x32' + (count > 0 ? 'a' : '') + '.png';\n if (oldIcon) {\n head.removeChild(oldIcon);\n }\n head.appendChild(newIcon);\n\n document.title = (count > 0 ? '('+count+') ' : '') + 'Tinode';\n}\n\n// Create theCard which represents user's or topic's \"public\" info.\nexport function theCard(fn, imageUrl, imageMimeType, note) {\n let card = null;\n fn = fn && fn.trim();\n note = note && note.trim();\n\n if (fn) {\n card = {\n fn: fn\n };\n }\n\n if (typeof note == 'string') {\n card = card || {};\n card.note = note ? note : Tinode.DEL_CHAR;\n }\n\n if (imageUrl) {\n card = card || {};\n let mimeType = imageMimeType;\n // Is this a data URL \"data:[ field: the URL must be a relative URL or\n// have http:, https:, blob: or data: scheme.\n// In case of data: scheme, the URL must must be of the right MIME type such as 'data:{mimeMajor}/XXXX;base64,'.\nexport function sanitizeUrlForMime(url, mimeMajor) {\n if (!url) {\n return null;\n }\n\n const sanitizedUrl = sanitizeUrl(url);\n if (sanitizedUrl) {\n return sanitizedUrl;\n }\n\n // Is this a data: URL of the appropriate mime type?\n const re = new RegExp(`data:${mimeMajor}\\/[a-z0-9.-]+;base64,`, 'i');\n if (re.test(url.trim())) {\n return url;\n }\n\n return null;\n}\n\n// Given message's received status, return name and color of a delivery indicator icon.\nexport function deliveryMarker(received) {\n switch (received) {\n case Tinode.MESSAGE_STATUS_SENDING:\n return { name: 'access_time' }; // watch face\n case Tinode.MESSAGE_STATUS_FAILED:\n case Tinode.MESSAGE_STATUS_FATAL:\n return { name: 'warning', color: 'danger-color' }; // yellow icon /!\\\n case Tinode.MESSAGE_STATUS_SENT:\n return { name: 'done' }; // checkmark\n case Tinode.MESSAGE_STATUS_RECEIVED:\n return { name: 'done_all' }; // double checkmark\n case Tinode.MESSAGE_STATUS_READ:\n return { name: 'done_all', color: 'blue' }; // blue double checkmark\n }\n return null;\n}\n\n// Wraps a promise to make it cancelable.\n// The parameter can be either a promise or an error. If it's an error, the wrapped promise is\n// created in a rejected state.\nexport function cancelablePromise(promise) {\n let hasCanceled = false;\n\n const wrappedPromise = promise instanceof Error ?\n Promise.reject(promise) :\n new Promise((resolve, reject) => {\n promise.then(\n result => hasCanceled ? reject({isCanceled: true}) : resolve(result),\n error => hasCanceled ? reject({isCanceled: true}) : reject(error)\n );\n });\n\n return {\n promise: wrappedPromise,\n cancel() {\n hasCanceled = true;\n },\n };\n};\n\n// Clips string to the specified length.\nexport function clipStr(str, length) {\n return str && str.substring(0, length);\n}\n","// This is a generated file. Don't edit.\n\nexport const PACKAGE_VERSION = \"0.23.0-rc1\";\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport CheckBox from '../widgets/checkbox.jsx';\n\nexport default class EditAccountView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleCheckboxClick = this.handleCheckboxClick.bind(this);\n }\n\n handleCheckboxClick(what, checked) {\n if (what == 'sound') {\n this.props.onToggleMessageSounds(checked);\n } else if (what == 'alert') {\n this.props.onTogglePushNotifications(checked);\n } else if (what == 'incognito') {\n this.props.onToggleIncognitoMode(checked);\n }\n }\n\n render() {\n return (\n
: null}\n {messageNodes}\n
\n :\n this.props.readOnly && this.props.uid ?\n
\n {contactNodes}\n
\n :\n null\n }\n
: null}\n \n {menu}\n
\n );\n }\n}\n\nexport default injectIntl(ContextMenu);\n","// Image zoom and crop widget.\n\nimport React from 'react';\n\nconst DEFAULT_MAX_ZOOM = 2.5;\n\nexport default class Cropper extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n // Coordinates of the top left corner of the image in container coordinates.\n panX: 0,\n panY: 0,\n // Origin of the zoom in image coordinates.\n originX: 0,\n originY: 0,\n // Zoom scale.\n zoom: 1,\n // Zoom min and max.\n minZoom: 0,\n maxZoom: DEFAULT_MAX_ZOOM,\n };\n\n // References to DOM elements for hooking up events and getting screen dimensions.\n // The transparent element which captures mouse moves (moves with the image).\n this.overlay = React.createRef();\n // The image cutout window or view port (static).\n this.cutout = React.createRef();\n // Scaled and translated image preview.\n this.preview = React.createRef();\n // The main container (static).\n this.boundingBox = React.createRef();\n\n // The original image width and height before any scaling.\n this.imageWidth = 0;\n this.imageHeight = 0;\n\n // Mouse position when dragging.\n this.mouseX = 0\n this.mouseY = 0;\n // Length of the previous mouse move when dragging.\n this.prevDistance = 0;\n\n // Bounding rectangles of static elements.\n this.cutoutRect = {};\n this.bBoxRect = {};\n // Center of the bounding box.\n this.originX = 0;\n this.originY = 0;\n\n this.initScaling = this.initScaling.bind(this);\n this.onZoom = this.onZoom.bind(this);\n this.handleZoom = this.handleZoom.bind(this);\n this.mouseDown = this.mouseDown.bind(this);\n this.mouseUp = this.mouseUp.bind(this);\n this.mouseMove = this.mouseMove.bind(this);\n this.mouseTouch = this.mouseTouch.bind(this);\n this.positionAll = this.positionAll.bind(this);\n this.translate = this.translate.bind(this);\n }\n\n componentDidMount() {\n this.overlay.current.addEventListener('mousedown', this.mouseDown, { passive: true });\n this.overlay.current.addEventListener('touchstart', this.mouseDown, { passive: true });\n\n // The rectangle position is in viewport coordinates.\n this.bBoxRect = this.boundingBox.current.getBoundingClientRect();\n // Center of the bounding box in container coordinates.\n this.originX = this.bBoxRect.width / 2;\n this.originY = this.bBoxRect.height / 2;\n\n // The rectangle position is in viewport coordinates.\n this.cutoutRect = this.cutout.current.getBoundingClientRect();\n }\n\n componentWillUnmount() {\n this.overlay.current.removeEventListener('mousedown', this.mouseDown);\n this.overlay.current.removeEventListener('touchstart', this.mouseDown);\n }\n\n // Position all elements.\n positionAll(panX, panY, zoom) {\n // Zoom origin in image preview coordinates.\n this.setState({\n panX: panX,\n panY: panY,\n zoom: zoom,\n originX: this.originX - panX,\n originY: this.originY - panY,\n });\n\n // Pass cut out coordinates to caller.\n const left = (this.originX - panX) * zoom - this.originX;\n const top = (this.originY - panY) * zoom - this.originY;\n this.props.onChange(\n (left + this.cutoutRect.left - this.bBoxRect.left) / zoom,\n (top + this.cutoutRect.top - this.bBoxRect.top) / zoom,\n this.cutoutRect.width / zoom,\n this.cutoutRect.height / zoom,\n zoom);\n }\n\n // Check if new location is within the limits.\n static checkBound(currPan, img, cutout, delta) {\n let nextDiff = Math.min(0, cutout[0] - img[0] - delta, img[1] - cutout[1] + delta);\n if (nextDiff == 0) {\n // Cutout is completely within the image.\n currPan += delta;\n } else if (Math.min(0, cutout[0] - img[0], img[1] - cutout[1]) < nextDiff) {\n // Cutout is outside of the range but closer to the bound.\n currPan += delta;\n }\n return currPan;\n }\n\n initScaling() {\n // Initialize components.\n const imgRect = this.preview.current.getBoundingClientRect();\n\n this.imageWidth = imgRect.width;\n this.imageHeight = imgRect.height;\n\n // Set zoom slider's min and max values. Make sure the scaled image cannot be smaller than the cutout.\n const minZoom = Math.max(this.cutoutRect.width / imgRect.width, this.cutoutRect.height / imgRect.height);\n this.setState({\n minZoom: minZoom,\n maxZoom: Math.max(DEFAULT_MAX_ZOOM, minZoom + 1)\n });\n\n // Initial zoom level fills the bounding box at the smallest image dimension and overflows the largest, i.e. \"fill\" not \"fit\".\n const zoom = Math.max(this.bBoxRect.width / imgRect.width, this.bBoxRect.height / imgRect.height);\n // Converting from viewport coordinates to container, then panning.\n const panX = this.cutoutRect.left - this.bBoxRect.left -\n (imgRect.width - this.cutoutRect.width) / 2;\n const panY = this.cutoutRect.top - this.bBoxRect.top -\n (imgRect.height - this.cutoutRect.height) / 2;\n\n this.positionAll(panX, panY, zoom);\n }\n\n onZoom(e) {\n this.handleZoom(e.target.value);\n }\n\n handleZoom(zoom) {\n let panX = this.state.panX;\n let panY = this.state.panY;\n\n // Ensure that the image at the new zoom is not outside of the cutout boundaries.\n // Calculate image coordinates at the new zoom.\n const imgLeft = this.originX - (this.originX - panX) * zoom;\n const imgRight = imgLeft + this.imageWidth * zoom;\n // Cutout in the same coordinates as the image.\n const coLeft = this.cutoutRect.left - this.bBoxRect.left;\n const coRight = coLeft + this.cutoutRect.width;\n if (coLeft < imgLeft) {\n panX -= imgLeft - coLeft;\n } else if (coRight > imgRight) {\n panX += coRight - imgRight;\n }\n const imgTop = this.originY - (this.originY - panY) * zoom;\n const imgBottom = imgTop + this.imageHeight * zoom;\n const coTop = this.cutoutRect.top - this.bBoxRect.top;\n const coBottom = coTop + this.cutoutRect.height;\n if (coTop < imgTop) {\n panY -= imgTop - coTop;\n } else if (coBottom > imgBottom) {\n panY += coBottom - imgBottom;\n }\n\n this.positionAll(panX, panY, zoom);\n }\n\n mouseDown(e) {\n if (e.touches) {\n this.mouseX = e.touches[0].pageX;\n this.mouseY = e.touches[0].pageY;\n } else {\n this.mouseX = e.pageX;\n this.mouseY = e.pageY;\n }\n\n window.addEventListener('mousemove', this.mouseMove, { passive: false });\n window.addEventListener('touchmove', this.mouseTouch, { passive: false });\n window.addEventListener('mouseup', this.mouseUp, { passive: true });\n window.addEventListener('touchend', this.mouseUp, { passive: true });\n // Disable text selection in the entire document.\n document.body.style['userSelect'] = 'none';\n }\n\n // Perform image panning.\n translate(pageX, pageY) {\n const dX = pageX - this.mouseX;\n const dY = pageY - this.mouseY;\n\n this.mouseX = pageX;\n this.mouseY = pageY;\n\n // Make sure the image is within the cutout window.\n const imgRect = this.preview.current.getBoundingClientRect();\n\n // Check if the new position is within the boundaries, and if not if it's closer to them.\n let panX = Cropper.checkBound(this.state.panX, [imgRect.left, imgRect.right],\n [this.cutoutRect.left, this.cutoutRect.right], dX);\n let panY = Cropper.checkBound(this.state.panY, [imgRect.top, imgRect.bottom],\n [this.cutoutRect.top, this.cutoutRect.bottom], dY);\n\n this.positionAll(panX, panY, this.state.zoom);\n }\n\n // Image panning.\n mouseMove(e) {\n e.preventDefault();\n this.translate(e.pageX, e.pageY);\n }\n\n mouseTouch(e) {\n e.preventDefault();\n\n if (e.touches.length == 1) {\n this.translate(e.touches[0].pageX, e.touches[0].pageY);\n return;\n }\n\n // Image zooming by pinching.\n const [touch0, touch1] = e.touches;\n const distance = Math.sqrt((touch0.pageX - touch1.pageX) * (touch0.pageX - touch1.pageX) +\n (touch0.pageY - touch1.pageY) * (touch0.pageY - touch1.pageY));\n\n if (!this.prevDistance) {\n this.prevDistance = distance / this.state.zoom;\n }\n\n let scale = (distance / this.prevDistance);\n this.handleZoom(Math.max(this.minZoom, Math.min(this.maxZoom, scale)));\n }\n\n mouseUp(e) {\n window.removeEventListener('mousemove', this.mouseMove);\n window.removeEventListener('touchmove', this.mouseTouch);\n window.removeEventListener('mouseup', this.mouseUp);\n window.removeEventListener('touchend', this.mouseUp);\n // Re-enable text selection.\n document.body.style['userSelect'] = '';\n\n this.positionAll(this.state.panX, this.state.panY, this.state.zoom);\n }\n\n render() {\n // transform3d: position and scale.\n const t3d = `translate3d(${this.state.panX}px, ${this.state.panY}px, 0) scale(${this.state.zoom})`;\n // transformOrigin: zoom origin.\n const orig = `${this.state.originX}px ${this.state.originY}px`;\n\n // Overlay position and size are exactly equal to the position and size of the transformed image\n // except it uses different coordinates.\n const overlay = {\n top: `${this.originY - this.state.originY * this.state.zoom}px`,\n left: `${this.originX - this.state.originX * this.state.zoom}px`,\n width: `${this.imageWidth * this.state.zoom}px`,\n height: `${this.imageHeight * this.state.zoom}px`\n };\n return (\n \n \n \n
\n
}\n {e.target.onerror = null; e.target.src=\"../img/broken_image.png\"}} />;\n } else {\n avatar = null;\n }\n return avatar;\n }\n}\n","import React from 'react';\n\nexport default class LoadSpinner extends React.PureComponent {\n render() {\n const className = 'load-spinner-box' + (this.props.large ? ' large' : '')\n + (this.props.clear ? ' clear' : '') + (this.props.centered ? ' centered' : '');\n return (this.props.show ?\n
\n \n );\n }\n\n return (\n {names[c]} \n {skip.indexOf(c) < 0 ?\n {this.props.compare ? \n : null}\n
: null}\n \n \n {this.props.compare ?\n
\n \n :\n null}\n \n {items}\n {this.props.modeTitle} \n {this.props.compareTitle} \n
\n .\n el = UploadingImage;\n }\n\n return el;\n}\n\n// Additional processing of image data.\nfunction handleVideoData(el, data, attr) {\n if (!data) {\n attr.src = 'img/broken_video.png';\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n };\n return el;\n }\n attr.className = 'inline-image';\n const dim = fitImageSize(data.width, data.height,\n this.viewportWidth > 0 ? Math.min(this.viewportWidth - REM_SIZE * 6.5, REM_SIZE * 34.5) :\n REM_SIZE * 34.5, REM_SIZE * 24, false) ||\n {dstWidth: NO_DIMENSIONS_VIDEO, dstHeight: NO_DIMENSIONS_VIDEO};\n attr.style = {\n width: dim.dstWidth + 'px',\n height: dim.dstHeight + 'px',\n // Looks like a Chrome bug: broken image does not respect 'width' and 'height'.\n minWidth: dim.dstWidth + 'px',\n minHeight: dim.dstHeight + 'px'\n };\n if (!Drafty.isProcessing(data)) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'image'));\n attr.alt = data.name;\n if (data.ref || data.val) {\n attr.onClick = this.onVideoPreview;\n attr.loading = 'lazy';\n }\n el = InlineVideo;\n } else {\n // Use custom element instead of
.\n el = UploadingImage;\n }\n\n return el;\n}\n\n// Converts Drafty object into a one-line preview. 'this' is set by the caller.\n// 'this' must contain:\n// formatMessage: this.props.intl.formatMessage\n// messages: formatjs messages defined with defineMessages.\nexport function previewFormatter(style, data, values, key) {\n if (!style) {\n // Unformatted.\n return values;\n }\n\n let el = Drafty.tagName(style);\n const attr = { key: key };\n switch (style) {\n case 'AU':\n // Voicemail as '[mic] 0:00'.\n el = React.Fragment;\n values = [mic, ' ', secondsToTime(data.duration/1000)];\n break;\n case 'BR':\n // Replace new line with a space.\n el = React.Fragment;\n values = [' '];\n break;\n case 'HL':\n // Make highlight less prominent in preview.\n attr.className = 'highlight preview';\n break;\n case 'LN':\n case 'MN':\n // Disable links in previews.\n el = 'span';\n break;\n case 'IM':\n // Replace image with '[icon] Image'.\n el = React.Fragment;\n values = [photo, ' ', this.formatMessage(messages.drafty_image)];\n break;\n case 'BN':\n el = 'span';\n attr.className = 'flat-button faux';\n break;\n case 'FM':\n el = React.Fragment;\n values = [dashboard,\n this.formatMessage(messages.drafty_form)].concat(' ', values || []);\n break;\n case 'RW':\n el = React.Fragment;\n break;\n case 'EX':\n if (data) {\n if (data.mime == 'application/json') {\n // Ignore JSON attachments: they are form response payloads.\n return null;\n }\n // Clear payload.\n delete data.val;\n delete data.ref;\n }\n el = React.Fragment;\n values = [attachment, ' ', this.formatMessage(messages.drafty_attachment)];\n break;\n case 'VC':\n el = CallStatus;\n if (data) {\n attr.callState = data.state;\n attr.incoming = data.incoming;\n attr.duration = data.duration;\n }\n values = null;\n break;\n case 'QQ':\n case 'HD':\n el = null;\n values = null;\n break;\n case 'VD':\n // Replace image with '[icon] Video'.\n el = React.Fragment;\n values = [play_circle_outline, ' ', this.formatMessage(messages.drafty_video)];\n break;\n default:\n if (!el) {\n // Unknown element.\n el = React.Fragment;\n values = [extension, ' ', this.formatMessage(messages.drafty_unknown)];\n }\n break;\n }\n if (!el) {\n return values;\n }\n return React.createElement(el, attr, values);\n};\n\n// Converts Drafty object into a quoted reply; 'this' is set by the caller.\nfunction inlineImageAttr(attr, data) {\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n maxWidth: IMAGE_THUMBNAIL_DIM + 'px',\n maxHeight: IMAGE_THUMBNAIL_DIM + 'px',\n }\n attr.className = 'inline-image';\n attr.alt = this.formatMessage(messages.drafty_image);\n if (!data) {\n attr.src = 'img/broken_image.png';\n } else {\n attr.src = attr.src || 'img/broken_image.png';\n }\n attr.title = attr.alt;\n return attr;\n}\n\n// Converts Drafty object into a quoted reply; 'this' is set by the caller.\nfunction inlineVideoAttr(attr, data) {\n const dim = fitImageSize(data.width, data.height, VIDEO_THUMBNAIL_WIDTH, IMAGE_THUMBNAIL_DIM);\n attr.style = {\n width: dim.width + 'px',\n height: dim.height + 'px',\n maxWidth: VIDEO_THUMBNAIL_WIDTH + 'px',\n maxHeight: IMAGE_THUMBNAIL_DIM + 'px',\n }\n attr.className = 'inline-image';\n attr.alt = this.formatMessage(messages.drafty_video);\n attr.title = attr.alt;\n if (!data) {\n attr.src = 'img/broken_video.png';\n } else {\n attr.src = attr.src || 'img/broken_video.png';\n }\n return attr;\n}\n\n// Displays a portion of Drafty within 'QQ' quotes. 'this' is set by the caller.\n// 'this' must contain:\n// formatMessage: this.props.intl.formatMessage\n// messages: formatjs messages defined with defineMessages.\n// authorizeURL: this.props.tinode.authorizeURL\n// onQuoteClick: this.handleQuoteClick (optional)\nfunction quoteFormatter(style, data, values, key) {\n if (['BR', 'EX', 'IM', 'MN', 'VD'].includes(style)) {\n let el = Drafty.tagName(style);\n let attr = Drafty.attrValue(style, data) || {};\n attr.key = key;\n switch(style) {\n case 'BR':\n values = null;\n break;\n case 'IM':\n attr = inlineImageAttr.call(this, attr, data);\n values = [React.createElement('img', attr, null), ' ', attr.alt];\n el = React.Fragment;\n // Fragment attributes.\n attr = {key: key};\n break;\n case 'VD':\n attr = inlineVideoAttr.call(this, attr, data);\n values = [React.createElement('img', attr, null), ' ', attr.alt];\n el = React.Fragment;\n // Fragment attributes.\n attr = {key: key};\n break;\n case 'MN':\n el = 'span';\n attr.className = 'mention'\n if (data) {\n attr.className += ' ' + idToColorClass(data.val, false, true);\n }\n break;\n case 'EX':\n let fname;\n if (data) {\n if (data.mime == 'application/json') {\n // Ignore JSON attachments: they are form response payloads.\n return null;\n }\n fname = data.name;\n // Clear payload.\n delete data.val;\n delete data.ref;\n }\n el = React.Fragment;\n values = [attachment,\n shortenFileName(fname, 16) || this.formatMessage(messages.drafty_attachment)];\n break;\n }\n return React.createElement(el, attr, values);\n }\n return previewFormatter.call(this, style, data, values, key);\n}\n\n// Create image thumbnail suitable for inclusion in a quote.\nfunction quoteImageOrVideo(data, isVideo) {\n let promise;\n let bits, ref, mime;\n if (isVideo) {\n bits = data.preview;\n mime = data.premime || 'image/jpeg';\n ref = data.preref;\n } else {\n bits = data.val;\n mime = data.mime;\n ref = data.ref;\n }\n // Get the blob from the image data.\n if (bits) {\n const blob = base64ToBlob(bits, mime);\n if (!blob) {\n throw new Error(\"Invalid image\");\n }\n promise = Promise.resolve(blob);\n } else if (ref) {\n promise = fetch(this.authorizeURL(sanitizeUrlForMime(ref, 'image')))\n .then(evt => {\n if (evt.ok) {\n return evt.blob();\n } else {\n throw new Error(`Image fetch unsuccessful: ${evt.status} ${evt.statusText}`);\n }\n });\n } else {\n throw new Error(\"Missing image data\");\n }\n\n // Scale the blob.\n return promise\n .then(blob => {\n // If it's an image, cut the square from the center of the image and shrink it.\n // If it's a video, allow it to be rectantular.\n return imageScaled(blob, isVideo ? VIDEO_THUMBNAIL_WIDTH : IMAGE_THUMBNAIL_DIM, IMAGE_THUMBNAIL_DIM, -1, !isVideo)\n }).then(scaled => {\n if (isVideo) {\n data.premime = scaled.mime;\n } else {\n data.mime = scaled.mime;\n }\n data.size = scaled.blob.size;\n data.width = scaled.width;\n data.height = scaled.height;\n delete data.ref;\n delete data.preref;\n // Keeping the original file name, if provided: ex.data.name;\n\n data.src = URL.createObjectURL(scaled.blob);\n return blobToBase64(scaled.blob);\n }).then(b64 => {\n if (isVideo) {\n data.preview = b64.bits;\n } else {\n data.val = b64.bits;\n }\n return data;\n }).catch(err => {\n delete data.val;\n delete data.preview;\n delete data.src;\n data.width = IMAGE_THUMBNAIL_DIM;\n data.height = IMAGE_THUMBNAIL_DIM;\n // Rethrow.\n throw err;\n });\n}\n\n// Create a preview of a reply.\nexport function replyFormatter(style, data, values, key, stack) {\n if (style == 'IM' || style == 'VD') {\n const isImage = style == 'IM';\n const attr = isImage ? inlineImageAttr.call(this, {key: key}, data) :\n inlineVideoAttr.call(this, {key: key}, data);\n\n let loadedPromise;\n try {\n loadedPromise = cancelablePromise(quoteImageOrVideo.call(this, data, style == 'VD'));\n } catch (error) {\n console.warn(\"Failed to quote image:\", error.message);\n loadedPromise = cancelablePromise(error);\n }\n attr.whenDone = loadedPromise;\n values = [React.createElement(LazyImage, attr, null), ' ', attr.alt];\n return React.createElement(React.Fragment, {key: key}, values);\n } else if (style == 'QQ') {\n if (stack.includes('QQ')) {\n // Quote inside quote when forwarding a message.\n return React.createElement('span', {key: key},\n [format_quote, ' ']);\n }\n\n const attr = Drafty.attrValue('QQ', data) || {};\n attr.key = key;\n attr.className = 'reply-quote'\n return React.createElement(Drafty.tagName('QQ'), attr, values);\n }\n return quoteFormatter.call(this, style, data, values, key);\n}\n","import { KNOWN_HOSTS, DEFAULT_HOST } from '../config.js';\n\n// Detect server address from the URL\nexport function detectServerAddress() {\n let host = DEFAULT_HOST;\n if (typeof window.location == 'object') {\n if (window.location.protocol == 'file:' || window.location.hostname == 'localhost') {\n host = KNOWN_HOSTS.local;\n } else if (window.location.hostname) {\n host = window.location.hostname + (window.location.port ? ':' + window.location.port : '');\n }\n }\n return host;\n}\n\n// Detect if the page is served over HTTPS.\nexport function isSecureConnection() {\n if (typeof window.location == 'object') {\n return window.location.protocol == 'https:';\n }\n return false;\n}\n\nexport function isLocalHost() {\n if (typeof window.location == 'object') {\n return window.location.hostname == 'localhost';\n }\n return false;\n}\n","// Helper functions for storing values in localStorage.\n// By default localStorage can store only strings, not objects or other types.\n\nexport default class LocalStorageUtil {\n // Replace old object with the new one.\n static setObject(key, value) {\n localStorage.setItem(key, JSON.stringify(value));\n }\n\n // Get stored object.\n static getObject(key) {\n const value = localStorage.getItem(key);\n return value && JSON.parse(value);\n }\n\n // Partially or wholly update stored object.\n static updateObject(key, value) {\n const oldVal = this.getObject(key);\n this.setObject(key, Object.assign(oldVal || {}, value));\n }\n\n // Just a wrapper.\n static removeItem(key) {\n localStorage.removeItem(key);\n }\n}\n","// Utility class for hash navigation.\n\nexport default class HashNavigation {\n // Parse hash as in http://www.example.com/path#hash as if it were\n // path and arguments.\n static parseUrlHash(hash) {\n // Split path from args, path -> parts[0], args->path[1]\n const parts = hash.split('?', 2);\n const params = {};\n let path = [];\n if (parts[0]) {\n path = parts[0].replace('#', '').split('/');\n }\n if (parts[1]) {\n parts[1].split('&').forEach((arg) => {\n // Can't use split() because the value may contain '='.\n const eq = arg.indexOf('=');\n if (eq > 0) {\n params[arg.slice(0, eq)] = decodeURIComponent(arg.slice(eq + 1));\n }\n });\n }\n return {path: path, params: params};\n }\n\n static navigateTo(url) {\n window.location.hash = url;\n }\n\n static composeUrlHash(path, params) {\n let url = path.join('/');\n const args = [];\n for (const key in params) {\n if (params.hasOwnProperty(key)) {\n args.push(key + '=' + encodeURIComponent(params[key]));\n }\n }\n if (args.length > 0) {\n url += '?' + args.join('&');\n }\n return url;\n }\n\n static addUrlParam(hash, key, value) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.params[key] = value;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static removeUrlParam(hash, key) {\n const parsed = HashNavigation.parseUrlHash(hash);\n delete parsed.params[key];\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlSidePanel(hash, sidepanel) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.path[0] = sidepanel;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlInfoPanel(hash, infopanel) {\n const parsed = HashNavigation.parseUrlHash(hash);\n if (infopanel) {\n parsed.params.info = infopanel;\n } else {\n delete parsed.params.info;\n }\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlTopic(hash, topic) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.path[1] = topic;\n // Close InfoView on topic change.\n delete parsed.params.info;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n}\n","// Short representation of time in the past.\nexport function shortDateFormat(then, locale) {\n locale = locale || window.navigator.userLanguage || window.navigator.language;\n const now = new Date();\n if (then.getFullYear() == now.getFullYear()) {\n // Same year.\n if (then.getMonth() == now.getMonth() && then.getDate() == now.getDate()) {\n // Same month and day, show time only.\n return then.toLocaleTimeString(locale, {hour12: false, hour: '2-digit', minute: '2-digit'});\n }\n // Different month and/or day, show month day, time.\n return then.toLocaleDateString(locale,\n {hour12: false, month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'});\n }\n // Different year: just show the date.\n return then.toLocaleDateString(locale, {year: 'numeric', month: 'short', day: 'numeric'});\n}\n\n// Representation a date relative to now.\nexport function relativeDateFormat(then, locale) {\n locale = locale || window.navigator.userLanguage || window.navigator.language;\n const now = new Date();\n const thenDays = Math.floor((then.getTime() - then.getTimezoneOffset() * 60_000) / 86_400_000);\n const nowDays = Math.floor((now.getTime() - now.getTimezoneOffset() * 60_000) / 86_400_000);\n const diff = thenDays - nowDays;\n if (Math.abs(diff) < 2) {\n // Today or yesterday.\n return new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(diff, 'day')\n }\n // More than two days: just show the date.\n return new Intl.DateTimeFormat(locale).format(then);\n}\n\n// Convert seconds to [hours:]minutes:seconds, i.e. 156 sec -> 2:36, 3756 sec -> 1:02:36.\n// If
fixedMins is true, then minutes are represented by at least two digits.\nexport function secondsToTime(seconds, fixedMin) {\n if (typeof seconds != 'number') {\n return '';\n }\n\n let min = (Math.floor(seconds / 60) | 0) % 60;\n let hours = Math.floor(seconds / 3600) | 0;\n\n if (fixedMin || hours > 0) {\n min = min < 10 ? `0${min}` : min;\n }\n let sec = (seconds | 0) % 60;\n sec = sec < 10 ? `0${sec}` : sec;\n if (hours == 0) {\n return `${min}:${sec}`;\n }\n return `${hours}:${min}:${sec}`;\n}\n\n// Convert a number of bytes to human-readable format.\nexport function bytesToHumanSize(bytes) {\n if (!bytes || bytes == 0) {\n return '0 Bytes';\n }\n\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];\n const bucket = Math.min(Math.floor(Math.log2(bytes) / 10) | 0, sizes.length-1);\n const count = bytes / Math.pow(1024, bucket);\n const round = bucket > 0 ? (count < 3 ? 2 : (count < 30 ? 1 : 0)) : 0;\n return count.toFixed(round) + ' ' + sizes[bucket];\n}\n\n// Shorten a file name to be under maxLength by clipping out the middle.\nexport function shortenFileName(filename, maxLength) {\n if (typeof filename != 'string') {\n return filename;\n }\n return filename.length > maxLength ?\n filename.slice(0, maxLength/2 - 1) + '…' + filename.slice(1 - maxLength/2) : filename;\n}\n\n// Get 32 bit integer hash value for a string. Ideally it should produce the same value\n// as Java's String#hash().\nfunction stringToColorHash(value) {\n let hash = 0;\n value = '' + value;\n for (let i = 0; i < value.length; i++) {\n hash = ((hash << 5) - hash) + value.charCodeAt(i);\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash;\n}\n\n// User avatar letter color id.\nexport function letterTileColorId(userId) {\n return Math.abs(stringToColorHash(userId)) % 16;\n}\n\n// Converts user or topic ID to a CSS color class. Ideally it should produce the same color value as Java version.\n// params:\n// - {string} id: user or topic ID\n// - {boolean} light: light or dark version of the color.\n// - {boolean} fg: foreground (text) or background color.\nexport function idToColorClass(id, light, fg) {\n return (light ? 'lt-' : 'dk-') + (fg ? 'fg-' : 'bg-') + letterTileColorId(id);\n}\n\n// Takes ISO Alpha-2 country code, like 'US' and converts it to a flag emoji.\nexport function flagEmoji(countryCode) {\n const codePoints = countryCode\n .toUpperCase()\n .split('')\n .map(char => 0x1F1A5 + char.charCodeAt());\n return String.fromCodePoint(...codePoints);\n}\n","// Odds and ends\n\nimport { Tinode } from 'tinode-sdk';\n\n// Make shortcut icon appear with a green dot + show unread count in title.\nexport function updateFavicon(count) {\n const oldIcon = document.getElementById('shortcut-icon');\n const head = document.head || document.getElementsByTagName('head')[0];\n const newIcon = document.createElement('link');\n newIcon.type = 'image/png';\n newIcon.id = 'shortcut-icon';\n newIcon.rel = 'shortcut icon';\n newIcon.href = 'img/logo32x32' + (count > 0 ? 'a' : '') + '.png';\n if (oldIcon) {\n head.removeChild(oldIcon);\n }\n head.appendChild(newIcon);\n\n document.title = (count > 0 ? '('+count+') ' : '') + 'Tinode';\n}\n\n// Create theCard which represents user's or topic's \"public\" info.\nexport function theCard(fn, imageUrl, imageMimeType, note) {\n let card = null;\n fn = fn && fn.trim();\n note = note && note.trim();\n\n if (fn) {\n card = {\n fn: fn\n };\n }\n\n if (typeof note == 'string') {\n card = card || {};\n card.note = note ? note : Tinode.DEL_CHAR;\n }\n\n if (imageUrl) {\n card = card || {};\n let mimeType = imageMimeType;\n // Is this a data URL \"data:[ field: the URL must be a relative URL or\n// have http:, https:, blob: or data: scheme.\n// In case of data: scheme, the URL must must be of the right MIME type such as 'data:{mimeMajor}/XXXX;base64,'.\nexport function sanitizeUrlForMime(url, mimeMajor) {\n if (!url) {\n return null;\n }\n\n const sanitizedUrl = sanitizeUrl(url);\n if (sanitizedUrl) {\n return sanitizedUrl;\n }\n\n // Is this a data: URL of the appropriate mime type?\n const re = new RegExp(`data:${mimeMajor}\\/[a-z0-9.-]+;base64,`, 'i');\n if (re.test(url.trim())) {\n return url;\n }\n\n return null;\n}\n\n// Given message's received status, return name and color of a delivery indicator icon.\nexport function deliveryMarker(received) {\n switch (received) {\n case Tinode.MESSAGE_STATUS_SENDING:\n return { name: 'access_time' }; // watch face\n case Tinode.MESSAGE_STATUS_FAILED:\n case Tinode.MESSAGE_STATUS_FATAL:\n return { name: 'warning', color: 'danger-color' }; // yellow icon /!\\\n case Tinode.MESSAGE_STATUS_SENT:\n return { name: 'done' }; // checkmark\n case Tinode.MESSAGE_STATUS_RECEIVED:\n return { name: 'done_all' }; // double checkmark\n case Tinode.MESSAGE_STATUS_READ:\n return { name: 'done_all', color: 'blue' }; // blue double checkmark\n }\n return null;\n}\n\n// Wraps a promise to make it cancelable.\n// The parameter can be either a promise or an error. If it's an error, the wrapped promise is\n// created in a rejected state.\nexport function cancelablePromise(promise) {\n let hasCanceled = false;\n\n const wrappedPromise = promise instanceof Error ?\n Promise.reject(promise) :\n new Promise((resolve, reject) => {\n promise.then(\n result => hasCanceled ? reject({isCanceled: true}) : resolve(result),\n error => hasCanceled ? reject({isCanceled: true}) : reject(error)\n );\n });\n\n return {\n promise: wrappedPromise,\n cancel() {\n hasCanceled = true;\n },\n };\n};\n\n// Clips string to the specified length.\nexport function clipStr(str, length) {\n return str && str.substring(0, length);\n}\n","// This is a generated file. Don't edit.\n\nexport const PACKAGE_VERSION = \"0.23.0-rc1\";\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport CheckBox from '../widgets/checkbox.jsx';\n\nexport default class EditAccountView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleCheckboxClick = this.handleCheckboxClick.bind(this);\n }\n\n handleCheckboxClick(what, checked) {\n if (what == 'sound') {\n this.props.onToggleMessageSounds(checked);\n } else if (what == 'alert') {\n this.props.onTogglePushNotifications(checked);\n } else if (what == 'incognito') {\n this.props.onToggleIncognitoMode(checked);\n }\n }\n\n render() {\n return (\n
: null}\n {messageNodes}\n
\n :\n this.props.readOnly && this.props.uid ?\n
\n {contactNodes}\n
\n :\n null\n }\n
: null}\n \n {menu}\n
\n );\n }\n}\n\nexport default injectIntl(ContextMenu);\n","// Image zoom and crop widget.\n\nimport React from 'react';\n\nconst DEFAULT_MAX_ZOOM = 2.5;\n\nexport default class Cropper extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n // Coordinates of the top left corner of the image in container coordinates.\n panX: 0,\n panY: 0,\n // Origin of the zoom in image coordinates.\n originX: 0,\n originY: 0,\n // Zoom scale.\n zoom: 1,\n // Zoom min and max.\n minZoom: 0,\n maxZoom: DEFAULT_MAX_ZOOM,\n };\n\n // References to DOM elements for hooking up events and getting screen dimensions.\n // The transparent element which captures mouse moves (moves with the image).\n this.overlay = React.createRef();\n // The image cutout window or view port (static).\n this.cutout = React.createRef();\n // Scaled and translated image preview.\n this.preview = React.createRef();\n // The main container (static).\n this.boundingBox = React.createRef();\n\n // The original image width and height before any scaling.\n this.imageWidth = 0;\n this.imageHeight = 0;\n\n // Mouse position when dragging.\n this.mouseX = 0\n this.mouseY = 0;\n // Length of the previous mouse move when dragging.\n this.prevDistance = 0;\n\n // Bounding rectangles of static elements.\n this.cutoutRect = {};\n this.bBoxRect = {};\n // Center of the bounding box.\n this.originX = 0;\n this.originY = 0;\n\n this.initScaling = this.initScaling.bind(this);\n this.onZoom = this.onZoom.bind(this);\n this.handleZoom = this.handleZoom.bind(this);\n this.mouseDown = this.mouseDown.bind(this);\n this.mouseUp = this.mouseUp.bind(this);\n this.mouseMove = this.mouseMove.bind(this);\n this.mouseTouch = this.mouseTouch.bind(this);\n this.positionAll = this.positionAll.bind(this);\n this.translate = this.translate.bind(this);\n }\n\n componentDidMount() {\n this.overlay.current.addEventListener('mousedown', this.mouseDown, { passive: true });\n this.overlay.current.addEventListener('touchstart', this.mouseDown, { passive: true });\n\n // The rectangle position is in viewport coordinates.\n this.bBoxRect = this.boundingBox.current.getBoundingClientRect();\n // Center of the bounding box in container coordinates.\n this.originX = this.bBoxRect.width / 2;\n this.originY = this.bBoxRect.height / 2;\n\n // The rectangle position is in viewport coordinates.\n this.cutoutRect = this.cutout.current.getBoundingClientRect();\n }\n\n componentWillUnmount() {\n this.overlay.current.removeEventListener('mousedown', this.mouseDown);\n this.overlay.current.removeEventListener('touchstart', this.mouseDown);\n }\n\n // Position all elements.\n positionAll(panX, panY, zoom) {\n // Zoom origin in image preview coordinates.\n this.setState({\n panX: panX,\n panY: panY,\n zoom: zoom,\n originX: this.originX - panX,\n originY: this.originY - panY,\n });\n\n // Pass cut out coordinates to caller.\n const left = (this.originX - panX) * zoom - this.originX;\n const top = (this.originY - panY) * zoom - this.originY;\n this.props.onChange(\n (left + this.cutoutRect.left - this.bBoxRect.left) / zoom,\n (top + this.cutoutRect.top - this.bBoxRect.top) / zoom,\n this.cutoutRect.width / zoom,\n this.cutoutRect.height / zoom,\n zoom);\n }\n\n // Check if new location is within the limits.\n static checkBound(currPan, img, cutout, delta) {\n let nextDiff = Math.min(0, cutout[0] - img[0] - delta, img[1] - cutout[1] + delta);\n if (nextDiff == 0) {\n // Cutout is completely within the image.\n currPan += delta;\n } else if (Math.min(0, cutout[0] - img[0], img[1] - cutout[1]) < nextDiff) {\n // Cutout is outside of the range but closer to the bound.\n currPan += delta;\n }\n return currPan;\n }\n\n initScaling() {\n // Initialize components.\n const imgRect = this.preview.current.getBoundingClientRect();\n\n this.imageWidth = imgRect.width;\n this.imageHeight = imgRect.height;\n\n // Set zoom slider's min and max values. Make sure the scaled image cannot be smaller than the cutout.\n const minZoom = Math.max(this.cutoutRect.width / imgRect.width, this.cutoutRect.height / imgRect.height);\n this.setState({\n minZoom: minZoom,\n maxZoom: Math.max(DEFAULT_MAX_ZOOM, minZoom + 1)\n });\n\n // Initial zoom level fills the bounding box at the smallest image dimension and overflows the largest, i.e. \"fill\" not \"fit\".\n const zoom = Math.max(this.bBoxRect.width / imgRect.width, this.bBoxRect.height / imgRect.height);\n // Converting from viewport coordinates to container, then panning.\n const panX = this.cutoutRect.left - this.bBoxRect.left -\n (imgRect.width - this.cutoutRect.width) / 2;\n const panY = this.cutoutRect.top - this.bBoxRect.top -\n (imgRect.height - this.cutoutRect.height) / 2;\n\n this.positionAll(panX, panY, zoom);\n }\n\n onZoom(e) {\n this.handleZoom(e.target.value);\n }\n\n handleZoom(zoom) {\n let panX = this.state.panX;\n let panY = this.state.panY;\n\n // Ensure that the image at the new zoom is not outside of the cutout boundaries.\n // Calculate image coordinates at the new zoom.\n const imgLeft = this.originX - (this.originX - panX) * zoom;\n const imgRight = imgLeft + this.imageWidth * zoom;\n // Cutout in the same coordinates as the image.\n const coLeft = this.cutoutRect.left - this.bBoxRect.left;\n const coRight = coLeft + this.cutoutRect.width;\n if (coLeft < imgLeft) {\n panX -= imgLeft - coLeft;\n } else if (coRight > imgRight) {\n panX += coRight - imgRight;\n }\n const imgTop = this.originY - (this.originY - panY) * zoom;\n const imgBottom = imgTop + this.imageHeight * zoom;\n const coTop = this.cutoutRect.top - this.bBoxRect.top;\n const coBottom = coTop + this.cutoutRect.height;\n if (coTop < imgTop) {\n panY -= imgTop - coTop;\n } else if (coBottom > imgBottom) {\n panY += coBottom - imgBottom;\n }\n\n this.positionAll(panX, panY, zoom);\n }\n\n mouseDown(e) {\n if (e.touches) {\n this.mouseX = e.touches[0].pageX;\n this.mouseY = e.touches[0].pageY;\n } else {\n this.mouseX = e.pageX;\n this.mouseY = e.pageY;\n }\n\n window.addEventListener('mousemove', this.mouseMove, { passive: false });\n window.addEventListener('touchmove', this.mouseTouch, { passive: false });\n window.addEventListener('mouseup', this.mouseUp, { passive: true });\n window.addEventListener('touchend', this.mouseUp, { passive: true });\n // Disable text selection in the entire document.\n document.body.style['userSelect'] = 'none';\n }\n\n // Perform image panning.\n translate(pageX, pageY) {\n const dX = pageX - this.mouseX;\n const dY = pageY - this.mouseY;\n\n this.mouseX = pageX;\n this.mouseY = pageY;\n\n // Make sure the image is within the cutout window.\n const imgRect = this.preview.current.getBoundingClientRect();\n\n // Check if the new position is within the boundaries, and if not if it's closer to them.\n let panX = Cropper.checkBound(this.state.panX, [imgRect.left, imgRect.right],\n [this.cutoutRect.left, this.cutoutRect.right], dX);\n let panY = Cropper.checkBound(this.state.panY, [imgRect.top, imgRect.bottom],\n [this.cutoutRect.top, this.cutoutRect.bottom], dY);\n\n this.positionAll(panX, panY, this.state.zoom);\n }\n\n // Image panning.\n mouseMove(e) {\n e.preventDefault();\n this.translate(e.pageX, e.pageY);\n }\n\n mouseTouch(e) {\n e.preventDefault();\n\n if (e.touches.length == 1) {\n this.translate(e.touches[0].pageX, e.touches[0].pageY);\n return;\n }\n\n // Image zooming by pinching.\n const [touch0, touch1] = e.touches;\n const distance = Math.sqrt((touch0.pageX - touch1.pageX) * (touch0.pageX - touch1.pageX) +\n (touch0.pageY - touch1.pageY) * (touch0.pageY - touch1.pageY));\n\n if (!this.prevDistance) {\n this.prevDistance = distance / this.state.zoom;\n }\n\n let scale = (distance / this.prevDistance);\n this.handleZoom(Math.max(this.minZoom, Math.min(this.maxZoom, scale)));\n }\n\n mouseUp(e) {\n window.removeEventListener('mousemove', this.mouseMove);\n window.removeEventListener('touchmove', this.mouseTouch);\n window.removeEventListener('mouseup', this.mouseUp);\n window.removeEventListener('touchend', this.mouseUp);\n // Re-enable text selection.\n document.body.style['userSelect'] = '';\n\n this.positionAll(this.state.panX, this.state.panY, this.state.zoom);\n }\n\n render() {\n // transform3d: position and scale.\n const t3d = `translate3d(${this.state.panX}px, ${this.state.panY}px, 0) scale(${this.state.zoom})`;\n // transformOrigin: zoom origin.\n const orig = `${this.state.originX}px ${this.state.originY}px`;\n\n // Overlay position and size are exactly equal to the position and size of the transformed image\n // except it uses different coordinates.\n const overlay = {\n top: `${this.originY - this.state.originY * this.state.zoom}px`,\n left: `${this.originX - this.state.originX * this.state.zoom}px`,\n width: `${this.imageWidth * this.state.zoom}px`,\n height: `${this.imageHeight * this.state.zoom}px`\n };\n return (\n \n \n \n
\n
}\n {e.target.onerror = null; e.target.src=\"../img/broken_image.png\"}} />;\n } else {\n avatar = null;\n }\n return avatar;\n }\n}\n","import React from 'react';\n\nexport default class LoadSpinner extends React.PureComponent {\n render() {\n const className = 'load-spinner-box' + (this.props.large ? ' large' : '')\n + (this.props.clear ? ' clear' : '') + (this.props.centered ? ' centered' : '');\n return (this.props.show ?\n
\n \n );\n }\n\n return (\n {names[c]} \n {skip.indexOf(c) < 0 ?\n {this.props.compare ? \n : null}\n
: null}\n \n \n {this.props.compare ?\n
\n \n :\n null}\n \n {items}\n {this.props.modeTitle} \n {this.props.compareTitle} \n
\n
"},{type:0,value:"¯∖_(ツ)_/¯"}]},(e=>t().createElement(zs,{tinode:this.props.tinode,connected:this.props.connected,contacts:this.state.contactList,emptyListMessage:e,topicSelected:this.props.topicSelected,myUserId:this.props.myUserId,showOnline:!0,showUnread:!0,onTopicSelected:this.props.onTopicSelected,showContextMenu:this.props.showContextMenu,onAction:this.handleAction})))}}class gi extends t().PureComponent{constructor(e){super(e),this.handleCheckboxClick=this.handleCheckboxClick.bind(this)}handleCheckboxClick(e,t){"sound"==e?this.props.onToggleMessageSounds(t):"alert"==e?this.props.onTogglePushNotifications(t):"incognito"==e&&this.props.onToggleIncognitoMode(t)}render(){return t().createElement("div",{className:"scrollable-panel"},t().createElement("div",{className:"panel-form-row"},t().createElement("label",{htmlFor:"message-sound"},t().createElement(a.FormattedMessage,{id:"label_message_sound",defaultMessage:[{type:0,value:"Message sound:"}]})),t().createElement(ta.Z,{name:"sound",id:"message-sound",checked:this.props.messageSounds,onChange:this.handleCheckboxClick})),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{htmlFor:"desktop-alerts"},this.props.desktopAlertsEnabled?t().createElement(a.FormattedMessage,{id:"label_push_notifications",defaultMessage:[{type:0,value:"Notification alerts:"}]}):t().createElement(a.FormattedMessage,{id:"label_push_notifications_disabled",defaultMessage:[{type:0,value:"Notification alerts (requires HTTPS):"}]})),t().createElement(ta.Z,{name:"alert",id:"desktop-alerts",checked:this.props.desktopAlerts,onChange:this.props.desktopAlertsEnabled?this.handleCheckboxClick:null})),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{htmlFor:"incognito-mode"},t().createElement(a.FormattedMessage,{id:"label_incognito_mode",defaultMessage:[{type:0,value:"Incognito mode:"}]})),t().createElement(ta.Z,{name:"incognito",id:"incognito-mode",checked:this.props.incognitoMode,onChange:this.handleCheckboxClick})))}}const fi=(0,a.defineMessages)({delete_account:{id:"delete_account",defaultMessage:[{type:0,value:"Delete account"}]},delete_account_warning:{id:"delete_account_warning",defaultMessage:[{type:0,value:"Are you sure you want to delete your account? It cannot be undone."}]}});class vi extends t().Component{constructor(e){super(e);const t=this.props.tinode.getMeTopic();let s=0;t.contacts((e=>{e.acs&&!e.acs.isJoiner()&&s++}));const a=t.getDefaultAccess();this.state={auth:a?a.auth:null,anon:a?a.anon:null,showPermissionEditorFor:void 0,blockedCount:s},this.handlePasswordUpdate=this.handlePasswordUpdate.bind(this),this.handleLaunchPermissionsEditor=this.handleLaunchPermissionsEditor.bind(this),this.handleHidePermissionsEditor=this.handleHidePermissionsEditor.bind(this),this.handlePermissionsChanged=this.handlePermissionsChanged.bind(this),this.handleDeleteAccount=this.handleDeleteAccount.bind(this)}handlePasswordUpdate(e){this.setState({password:e}),this.props.onUpdatePassword(e)}handleLaunchPermissionsEditor(e){this.setState({showPermissionEditorFor:e,editedPermissions:this.state[e]})}handleHidePermissionsEditor(){this.setState({showPermissionEditorFor:void 0})}handlePermissionsChanged(e){let t={};t[this.state.showPermissionEditorFor]=e,this.props.onUpdateAccountDesc("me",void 0,void 0,t);let s={showPermissionEditorFor:void 0};s[this.state.showPermissionEditorFor]=e,this.setState(s)}handleDeleteAccount(e){e.preventDefault();const{formatMessage:t}=this.props.intl;this.props.onShowAlert(t(fi.delete_account),t(fi.delete_account_warning),(e=>this.props.onDeleteAccount()),null,!0,null)}render(){return t().createElement(t().Fragment,null,this.state.showPermissionEditorFor?t().createElement(ha,{mode:this.state.editedPermissions,skip:"O",onSubmit:this.handlePermissionsChanged,onCancel:this.handleHidePermissionsEditor}):t().createElement("div",{className:"scrollable-panel"},t().createElement("div",{className:"panel-form-column"},t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_password",defaultMessage:[{type:0,value:"Password"}]})),t().createElement("div",null,t().createElement(a.FormattedMessage,{id:"password_unchanged_prompt",defaultMessage:[{type:0,value:"Unchanged"}]},(e=>t().createElement(ma,{placeholder:e,type:"password",onFinished:this.handlePasswordUpdate}))))),t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-column"},t().createElement("a",{href:"#",className:"danger flat-button",onClick:e=>{e.preventDefault(),this.props.onLogout()}},t().createElement("i",{className:"material-icons"},"exit_to_app")," ",t().createElement(a.FormattedMessage,{id:"button_logout",defaultMessage:[{type:0,value:"Logout"}]})),t().createElement("a",{href:"#",className:"danger flat-button",onClick:e=>{this.handleDeleteAccount(e)}},t().createElement("i",{className:"material-icons"},"delete")," ",t().createElement(a.FormattedMessage,{id:"button_delete_account",defaultMessage:[{type:0,value:"Delete account"}]}))),t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-column"},t().createElement("div",null,t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_default_access_mode",defaultMessage:[{type:0,value:"Default access mode:"}]}))),t().createElement("div",{className:"quoted"},t().createElement("div",null,"Auth: ",t().createElement("tt",{className:"clickable",onClick:this.handleLaunchPermissionsEditor.bind(this,"auth")},this.state.auth)),t().createElement("div",null,"Anon: ",t().createElement("tt",{className:"clickable",onClick:this.handleLaunchPermissionsEditor.bind(this,"anon")},this.state.anon)))),this.state.blockedCount>0?t().createElement(t().Fragment,null,t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-row"},t().createElement("i",{className:"material-icons"},"block")," ",t().createElement("a",{href:"#",className:"gray",onClick:e=>{e.preventDefault(),this.props.onShowBlocked()}},t().createElement(a.FormattedMessage,{id:"blocked_contacts_link",defaultMessage:[{type:0,value:"Blocked contacts ("},{type:1,value:"count"},{type:0,value:")"}],values:{count:this.state.blockedCount}})))):null))}}const bi=(0,a.injectIntl)(vi);class Ei extends t().PureComponent{render(){return t().createElement("div",{className:"scrollable-panel"},t().createElement("div",{className:"panel-form-column"},t().createElement("a",{href:hs.li,className:"flat-button",target:"_blank"},t().createElement("i",{className:"material-icons"},"email")," ",t().createElement(a.FormattedMessage,{id:"link_contact_us",defaultMessage:[{type:0,value:"Contact Us"}]})),t().createElement("a",{href:hs.S9,className:"flat-button",target:"_blank"},t().createElement("i",{className:"material-icons"},"description")," ",t().createElement(a.FormattedMessage,{id:"link_terms_of_service",defaultMessage:[{type:0,value:"Terms of Service"}]})),t().createElement("a",{href:hs.NW,className:"flat-button",target:"_blank"},t().createElement("i",{className:"material-icons"},"policy")," ",t().createElement(a.FormattedMessage,{id:"link_privacy_policy",defaultMessage:[{type:0,value:"Privacy Policy"}]}))),t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-column"},t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_client",defaultMessage:[{type:0,value:"Client:"}]})),hs.iC),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_sdk",defaultMessage:[{type:0,value:"SDK:"}]})),cs.Tinode.getLibrary()),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_server",defaultMessage:[{type:0,value:"Server:"}]})),this.props.serverVersion),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_server_address",defaultMessage:[{type:0,value:"Server address:"}]})),this.props.serverAddress)))}}class yi extends t().Component{constructor(e){super(e),this.state={login:e.login,password:"",hostName:e.serverAddress,saveToken:e.persist},this.handleLoginChange=this.handleLoginChange.bind(this),this.handlePasswordChange=this.handlePasswordChange.bind(this),this.handleToggleSaveToken=this.handleToggleSaveToken.bind(this),this.handleSubmit=this.handleSubmit.bind(this)}handleLoginChange(e){this.setState({login:e.target.value})}handlePasswordChange(e){this.setState({password:e.target.value})}handleToggleSaveToken(){this.props.onPersistenceChange(!this.state.saveToken),this.setState({saveToken:!this.state.saveToken})}handleSubmit(e){e.preventDefault(),this.props.onLogin(this.state.login.trim(),this.state.password.trim())}render(){let e="primary";return this.props.disabled&&(e+=" disabled"),t().createElement("form",{id:"login-form",onSubmit:this.handleSubmit},t().createElement(a.FormattedMessage,{id:"login_prompt",defaultMessage:[{type:0,value:"Login"}]},(e=>t().createElement("input",{type:"text",id:"inputLogin",placeholder:e,autoComplete:"username",autoCorrect:"off",autoCapitalize:"none",value:this.state.login,onChange:this.handleLoginChange,required:!0,autoFocus:!0}))),t().createElement(a.FormattedMessage,{id:"password_prompt",defaultMessage:[{type:0,value:"Password"}]},(e=>t().createElement(ua.Z,{type:"password",id:"inputPassword",placeholder:e,autoComplete:"current-password",value:this.state.password,onChange:this.handlePasswordChange,required:!0}))),t().createElement("div",{className:"panel-form-row"},t().createElement(ta.Z,{id:"save-token",name:"save-token",checked:this.state.saveToken,onChange:this.handleToggleSaveToken}),t().createElement("label",{htmlFor:"save-token"}," ",t().createElement(a.FormattedMessage,{id:"stay_logged_in",defaultMessage:[{type:0,value:"Stay logged in"}]})),t().createElement("a",{href:"#reset"},t().createElement(a.FormattedMessage,{id:"forgot_password_link",defaultMessage:[{type:0,value:"Forgot password?"}]}))),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{className:e,type:"submit"},t().createElement(a.FormattedMessage,{id:"button_sign_in",defaultMessage:[{type:0,value:"Sign in"}]}))))}}const wi=(0,a.defineMessages)({invalid_id:{id:"error_invalid_id",defaultMessage:[{type:0,value:"Invalid ID"}]}});class Ci extends t().PureComponent{constructor(e){super(e),this.state={groupId:""},this.handleChange=this.handleChange.bind(this),this.handleKeyPress=this.handleKeyPress.bind(this),this.handleSubmit=this.handleSubmit.bind(this)}handleChange(e){this.setState({groupId:e.target.value})}handleKeyPress(e){"Enter"===e.key&&this.handleSubmit(e)}handleSubmit(e){if(e.preventDefault(),this.state.groupId){const e=this.state.groupId.trim(),t=e.substr(0,3);e.length>3&&["usr","grp","chn"].includes(t)?this.props.onSubmit(e):this.props.onError(this.props.intl.formatMessage(wi.invalid_id),"err")}}render(){return t().createElement("div",{className:"panel-form"},t().createElement("div",{className:"panel-form-row"},t().createElement(a.FormattedMessage,{id:"group_user_id_prompt",defaultMessage:[{type:0,value:"Group or User ID"}]},(e=>t().createElement("input",{type:"text",placeholder:e,value:this.state.groupId,onChange:this.handleChange,onKeyPress:this.handleKeyPress,required:!0,autoFocus:!0})))),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{className:"primary",onClick:this.handleSubmit},t().createElement(a.FormattedMessage,{id:"button_subscribe",defaultMessage:[{type:0,value:"Subscribe"}]}))))}}const Si=(0,a.injectIntl)(Ci);class Mi extends t().PureComponent{constructor(e){super(e),this.fullName=t().createRef(),this.state={fullName:"",private:"",description:"",imageUrl:null,tags:[],isChannel:!1,newAvatar:null,newAvatarMime:null},this.handleFieldEdit=this.handleFieldEdit.bind(this),this.handleImageChanged=this.handleImageChanged.bind(this),this.handleAvatarCropped=this.handleAvatarCropped.bind(this),this.handleAvatarCropCancel=this.handleAvatarCropCancel.bind(this),this.uploadAvatar=this.uploadAvatar.bind(this),this.handleTagsChanged=this.handleTagsChanged.bind(this),this.handleChannelToggle=this.handleChannelToggle.bind(this),this.handleSubmit=this.handleSubmit.bind(this)}componentDidMount(){}handleFieldEdit(e,t){this.setState({[e]:t.target.value||""})}handleImageChanged(e,t){this.setState({newAvatar:t,newAvatarMime:e})}handleAvatarCropped(e,t,s,a){const i=t?URL.createObjectURL(t):null;this.setState({imageUrl:i,newAvatar:null,newAvatarMime:null}),t&&this.uploadAvatar(e,t,s,a)}handleAvatarCropCancel(){this.setState({newAvatar:null,newAvatarMime:null})}uploadAvatar(e,t,s,a){const i=e=>{let{mime:t,blob:s}=e;if(s.size>hs.uv){this.props.tinode.getLargeFileHelper().upload(s).then((e=>this.setState({imageUrl:e}))).catch((e=>this.props.onError(e.message,"err")))}else(0,ks.w8)(s).then((e=>this.setState({imageUrl:(0,ks.PD)({data:e.bits,type:t})})))};s>hs.IX||a>hs.IX||s!=a?(0,ks.EA)(t,hs.IX,hs.IX,hs.GQ,!0).then((e=>i(e))).catch((e=>this.props.onError(e.message,"err"))):i({mime:e,blob:t,width:s,height:a})}handleTagsChanged(e){this.setState({tags:e})}handleChannelToggle(){this.setState({isChannel:!this.state.isChannel})}handleSubmit(e){e.preventDefault();const t=this.state.fullName.trim().substring(0,hs.S8),s=this.state.private.trim().substring(0,hs.S8),a=this.state.description.trim().substring(0,hs.EI);t&&this.props.onSubmit(t,a,this.state.imageUrl,s,this.state.tags,this.state.isChannel)}render(){if(this.state.newAvatar)return t().createElement(pa.Z,{avatar:this.state.newAvatar,mime:this.state.newAvatarMime,onSubmit:this.handleAvatarCropped,onCancel:this.handleAvatarCropCancel,onError:this.props.onError});let e="primary";return this.props.disabled&&(e+=" disabled"),t().createElement("form",{className:"panel-form",onSubmit:this.handleSubmit},t().createElement("div",{className:"panel-form-column"},t().createElement("center",null,t().createElement(ea.Z,{tinode:this.props.tinode,avatar:this.state.imageUrl,onError:this.props.onError,onImageUpdated:this.handleImageChanged})),t().createElement("div",{className:"group"},t().createElement("label",{className:"small",htmlFor:"new-topic-fn"},t().createElement(a.FormattedMessage,{id:"label_topic_name",defaultMessage:[{type:0,value:"Name"}]})),t().createElement(a.FormattedMessage,{id:"topic_name_editing_placeholder",defaultMessage:[{type:0,value:"Freeform name of the group"}]},(e=>t().createElement("input",{type:"text",id:"new-topic-fn",placeholder:e,ref:this.fullName,value:this.state.fullName,onChange:this.handleFieldEdit.bind(this,"fullName"),autoFocus:!0,required:!0,tabIndex:0})))),t().createElement("div",{className:"group"},t().createElement("label",{className:"small",htmlFor:"new-topic-priv"},t().createElement(a.FormattedMessage,{id:"label_private",defaultMessage:[{type:0,value:"Private comment"}]})),t().createElement(a.FormattedMessage,{id:"private_editing_placeholder",defaultMessage:[{type:0,value:"Visible to you only"}]},(e=>t().createElement("input",{type:"text",id:"new-topic-priv",placeholder:e,value:this.state.private,onChange:this.handleFieldEdit.bind(this,"private"),tabIndex:1})))),t().createElement("div",{className:"group"},t().createElement("label",{className:"small",htmlFor:"new-topic-desc"},t().createElement(a.FormattedMessage,{id:"label_description",defaultMessage:[{type:0,value:"Description"}]})),t().createElement(a.FormattedMessage,{id:"description_editing_placeholder",defaultMessage:[{type:0,value:"Description (optional)"}]},(e=>t().createElement("input",{type:"text",id:"new-topic-desc",placeholder:e,value:this.state.description,onChange:this.handleFieldEdit.bind(this,"description"),tabIndex:2}))))),t().createElement("div",{className:"panel-form-row"},t().createElement(ta.Z,{checked:this.state.isChannel,tabIndex:3,onChange:this.handleChannelToggle})," ",t().createElement("label",{onClick:this.handleChannelToggle},t().createElement(a.FormattedMessage,{id:"channel_prompt",defaultMessage:[{type:0,value:"This is a channel"}]}))),t().createElement(a.FormattedMessage,{id:"title_tag_manager",defaultMessage:[{type:0,value:"Tags (search & discovery)"}]},(e=>t().createElement(ga,{tinode:this.props.tinode,tags:this.state.tags,activated:!0,onTagsChanged:this.handleTagsChanged,tabIndex:4,title:e}))),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{className:e},t().createElement(a.FormattedMessage,{id:"button_create",defaultMessage:[{type:0,value:"Create"}]}))))}}const _i=(0,a.defineMessages)({search_for_contacts:{id:"search_for_contacts",defaultMessage:[{type:0,value:"Use search to find contacts"}]},search_no_results:{id:"search_no_results",defaultMessage:[{type:0,value:"Search returned no results"}]},search_placeholder:{id:"search_placeholder",defaultMessage:[{type:0,value:"List like alice@example.com, +17025550003..."}]}});class Ti extends t().Component{constructor(e){super(e),this.state={tabSelected:"find",searchQuery:null},this.handleTabClick=this.handleTabClick.bind(this),this.handleSearchContacts=this.handleSearchContacts.bind(this),this.handleSearchResultSelected=this.handleSearchResultSelected.bind(this),this.handleNewGroupSubmit=this.handleNewGroupSubmit.bind(this),this.handleGroupByID=this.handleGroupByID.bind(this)}componentDidMount(){this.props.onInitFind()}handleTabClick(e){e.preventDefault(),si.Z.navigateTo(si.Z.addUrlParam(window.location.hash,"tab",e.currentTarget.dataset.id)),this.setState({tabSelected:e.currentTarget.dataset.id})}handleSearchContacts(e){this.props.onSearchContacts(e),this.setState({searchQuery:cs.Tinode.isNullValue(e)?null:e})}handleSearchResultSelected(e){"find"==this.state.tabSelected&&(si.Z.navigateTo(si.Z.removeUrlParam(window.location.hash,"tab")),this.props.onCreateTopic(e))}handleNewGroupSubmit(e,t,s,a,i,n){si.Z.navigateTo(si.Z.removeUrlParam(window.location.hash,"tab")),this.props.onCreateTopic(void 0,{public:(0,Ds.n$)(e,s,null,t),private:a,tags:i},n)}handleGroupByID(e){si.Z.navigateTo(si.Z.removeUrlParam(window.location.hash,"tab")),this.props.onCreateTopic(e)}render(){const{formatMessage:e}=this.props.intl,s=e(this.state.searchQuery?_i.search_no_results:_i.search_for_contacts),i=e(_i.search_placeholder);return t().createElement("div",{className:"flex-column"},t().createElement("ul",{className:"tabbar"},t().createElement("li",{className:"find"===this.state.tabSelected?"active":null},t().createElement("a",{href:"#","data-id":"find",onClick:this.handleTabClick},t().createElement(a.FormattedMessage,{id:"tabtitle_find_user",defaultMessage:[{type:0,value:"find"}]}))),t().createElement("li",{className:"grp"===this.state.tabSelected?"active":null},t().createElement("a",{href:"#","data-id":"grp",onClick:this.handleTabClick},t().createElement(a.FormattedMessage,{id:"tabtitle_new_group",defaultMessage:[{type:0,value:"new group"}]}))),t().createElement("li",{className:"byid"===this.state.tabSelected?"active":null},t().createElement("a",{href:"#","data-id":"byid",onClick:this.handleTabClick},t().createElement(a.FormattedMessage,{id:"tabtitle_group_by_id",defaultMessage:[{type:0,value:"by id"}]})))),"grp"===this.state.tabSelected?t().createElement(Mi,{tinode:this.props.tinode,onSubmit:this.handleNewGroupSubmit,onError:this.props.onError}):"byid"===this.state.tabSelected?t().createElement(Si,{onSubmit:this.handleGroupByID,onError:this.props.onError}):t().createElement("div",{className:"flex-column"},t().createElement(Zs,{placeholder:i,onSearchContacts:this.handleSearchContacts}),t().createElement(zs,{tinode:this.props.tinode,contacts:this.props.searchResults,myUserId:this.props.myUserId,emptyListMessage:s,showOnline:!1,showUnread:!1,showContextMenu:!1,onTopicSelected:this.handleSearchResultSelected})))}}const ki=(0,a.injectIntl)(Ti);class Di extends t().PureComponent{constructor(e){super(e),this.state={hostName:e.serverAddress,changed:!1},this.handleHostNameChange=this.handleHostNameChange.bind(this),this.handleEditingFinished=this.handleEditingFinished.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this)}handleHostNameChange(e){this.setState({hostName:e.target.value,changed:!0})}handleEditingFinished(){this.state.changed&&(this.setState({changed:!1}),this.props.onServerAddressChange(this.state.hostName.trim()))}handleKeyDown(e){"Enter"==e.key&&this.handleEditingFinished()}render(){const e=[];for(let s in hs.Rc){let a=hs.Rc[s];e.push(t().createElement("option",{key:a,value:a}))}return t().createElement("div",{className:"panel-form-row"},t().createElement("input",{type:"search",id:"host-name",placeholder:this.props.hostName,list:"known-hosts",className:"quoted",value:this.state.hostName,onChange:this.handleHostNameChange,onBlur:this.handleEditingFinished,onKeyDown:this.handleKeyDown,required:!0}),t().createElement("datalist",{id:"known-hosts"},e))}}class Ni extends t().PureComponent{constructor(e){super(e),this.state={transport:e.transport||"def",serverAddress:e.serverAddress,secureConnection:e.secureConnection},this.handleSubmit=this.handleSubmit.bind(this),this.handleTransportSelected=this.handleTransportSelected.bind(this),this.handleServerAddressChange=this.handleServerAddressChange.bind(this),this.handleToggleSecure=this.handleToggleSecure.bind(this)}handleSubmit(e){e.preventDefault(),this.props.onUpdate({transport:this.state.transport,serverAddress:this.state.serverAddress,secureConnection:this.state.secureConnection})}handleTransportSelected(e){this.setState({transport:e.currentTarget.value})}handleServerAddressChange(e){this.setState({serverAddress:e})}handleToggleSecure(e){this.setState({secureConnection:!this.state.secureConnection})}render(){const e={def:"default",ws:"websocket",lp:"long polling"},s=[];return["def","ws","lp"].forEach((a=>{const i="transport-"+a,n=e[a];s.push(t().createElement("li",{key:a},t().createElement("input",{type:"radio",id:i,name:"transport-select",value:a,checked:this.state.transport===a,onChange:this.handleTransportSelected}),t().createElement("label",{htmlFor:i},n)))})),t().createElement("form",{id:"settings-form",className:"panel-form",onSubmit:this.handleSubmit},t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_server_to_use",defaultMessage:[{type:0,value:"Server to use:"}]}))),t().createElement(Di,{serverAddress:this.state.serverAddress,onServerAddressChange:this.handleServerAddressChange}),t().createElement("div",{className:"panel-form-row"},t().createElement(ta.Z,{id:"secure-connection",name:"secure-connection",checked:this.state.secureConnection,className:"quoted",onChange:this.handleToggleSecure}),t().createElement("label",{htmlFor:"secure-connection"},t().createElement(a.FormattedMessage,{id:"label_use_secure_connection",defaultMessage:[{type:0,value:"Use secure connection"}]}))),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_wire_transport",defaultMessage:[{type:0,value:"Wire transport:"}]}))),t().createElement("div",{className:"panel-form-row"},t().createElement("ul",{className:"quoted"},s)),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{type:"submit",className:"primary"},t().createElement(a.FormattedMessage,{id:"button_update",defaultMessage:[{type:0,value:"Update"}]}))))}}const Ai=(0,a.defineMessages)({phone:{id:"phone_dative",defaultMessage:[{type:0,value:"phone"}]},email:{id:"email_dative",defaultMessage:[{type:0,value:"email"}]}});class Pi extends t().PureComponent{constructor(e){super(e),this.state={code:e.credCode||"",codeReceived:e.credCode},this.handleCodeChange=this.handleCodeChange.bind(this),this.handleKeyPress=this.handleKeyPress.bind(this),this.handleSubmit=this.handleSubmit.bind(this),this.handleCancel=this.handleCancel.bind(this)}static getDerivedStateFromProps(e,t){return e.credCode!=t.codeReceived?{code:e.credCode||"",codeReceived:e.credCode}:t}componentDidMount(){this.props.credCode&&this.props.onSubmit(this.props.credMethod,this.props.credCode,this.props.credToken)}componentDidUpdate(e,t){this.state.codeReceived&&this.state.code&&this.state.code!=t.code&&this.props.onSubmit(this.props.credMethod,this.state.code,this.props.credToken)}handleCodeChange(e){this.setState({code:e.target.value.replace(/[^\d]/g,"")})}handleKeyPress(e){"Enter"===e.key?this.handleSubmit(e):"Escape"==e.key&&this.handleCancel(e)}handleSubmit(e){e.preventDefault(),this.state.code&&this.state.code.trim()&&this.props.onSubmit(this.props.credMethod,this.state.code.trim(),this.props.credToken)}handleCancel(e){e.preventDefault(),this.props.onCancel()}render(){const{formatMessage:e}=this.props.intl,s={email:e(Ai.email),tel:e(Ai.phone)}[this.props.credMethod]||this.props.credMethod;return t().createElement("div",{className:"panel-form"},t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small gray",htmlFor:"enter-confirmation-code"},t().createElement(a.FormattedMessage,{id:"enter_confirmation_code_prompt",defaultMessage:[{type:0,value:"Confirmation code"}],values:{method:s}}))),t().createElement("div",{className:"panel-form-row"},t().createElement(a.FormattedMessage,{id:"numeric_confirmation_code_prompt",defaultMessage:[{type:0,value:"Numbers only"}]},(e=>t().createElement("input",{type:"text",id:"enter-confirmation-code",placeholder:e,value:this.state.code,onChange:this.handleCodeChange,onKeyPress:this.handleKeyPress,required:!0})))),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{className:"secondary",onClick:this.handleCancel},t().createElement(a.FormattedMessage,{id:"button_cancel",defaultMessage:[{type:0,value:"Cancel"}]})),t().createElement("button",{className:"primary",onClick:this.handleSubmit},t().createElement(a.FormattedMessage,{id:"button_confirm",defaultMessage:[{type:0,value:"Confirm"}]}))))}}const Ii=(0,a.injectIntl)(Pi),Ri=t().lazy((e=>Promise.all([o.e(203),o.e(365)]).then(o.bind(o,1365)))),xi=t().lazy((e=>Promise.all([o.e(203),o.e(327)]).then(o.bind(o,327)))),Fi=t().lazy((e=>Promise.all([o.e(203),o.e(311)]).then(o.bind(o,1311)))),Ui=(0,a.defineMessages)({login:{id:"sidepanel_title_login",defaultMessage:[{type:0,value:"Sign In"}]},register:{id:"sidepanel_title_register",defaultMessage:[{type:0,value:"Create Account"}]},settings:{id:"sidepanel_title_settings",defaultMessage:[{type:0,value:"Settings"}]},edit:{id:"sidepanel_title_account_settings",defaultMessage:[{type:0,value:"Account Settings"}]},general:{id:"panel_title_general",defaultMessage:[{type:0,value:"General"}]},security:{id:"panel_title_security",defaultMessage:[{type:0,value:"Security"}]},crop:{id:"panel_title_crop",defaultMessage:[{type:0,value:"Drag to Adjust"}]},notif:{id:"sidepanel_title_acc_notifications",defaultMessage:[{type:0,value:"Notifications"}]},support:{id:"sidepanel_title_acc_support",defaultMessage:[{type:0,value:"Support"}]},newtpk:{id:"sidepanel_title_newtpk",defaultMessage:[{type:0,value:"Start New Chat"}]},cred:{id:"sidepanel_title_cred",defaultMessage:[{type:0,value:"Confirm Credentials"}]},reset:{id:"sidepanel_title_reset",defaultMessage:[{type:0,value:"Reset Password"}]},archive:{id:"sidepanel_title_archive",defaultMessage:[{type:0,value:"Archived Chats"}]},blocked:{id:"sidepanel_title_blocked",defaultMessage:[{type:0,value:"Blocked Chats"}]}});class Li extends t().PureComponent{constructor(e){super(e),this.handleNewTopic=this.handleNewTopic.bind(this)}handleNewTopic(){this.props.onNavigate("newtpk")}render(){const{formatMessage:s}=this.props.intl,i=this.props.state||(this.props.myUserId?"contacts":"login");let n,o,r,l;return"contacts"==i?(n=this.props.title,o=!this.props.avatar||this.props.avatar,r=this.props.trustedBadges):(n=s(Ui[i]),o=!1,r=null),-1==["login","contacts"].indexOf(i)&&(l=this.props.onCancel),t().createElement("div",{id:"sidepanel"},t().createElement(pi,{state:i,title:n,avatar:o,tinode:this.props.tinode,trustedBadges:r,myUserId:this.props.myUserId,onSignUp:this.props.onSignUp,onSettings:this.props.onSettings,onNewTopic:this.handleNewTopic,onCancel:l}),t().createElement(aa,{level:this.props.errorLevel,text:this.props.errorText,action:this.props.errorAction,actionText:this.props.errorActionText,onClearError:this.props.onError}),t().createElement($a.Z,{show:this.props.loadSpinnerVisible}),"login"===i?t().createElement(yi,{login:this.props.login,disabled:this.props.loginDisabled,persist:this.props.persist,onLogin:this.props.onLoginRequest,onPersistenceChange:this.props.onPersistenceChange}):"register"===i?t().createElement(e.Suspense,{fallback:t().createElement("div",{className:"panel-form-row"},t().createElement(a.FormattedMessage,{id:"loading_note",defaultMessage:[{type:0,value:"Loading..."}]}))},t().createElement(xi,{tinode:this.props.tinode,reqCredMethod:this.props.reqCredMethod,onShowCountrySelector:this.props.onShowCountrySelector,onCreateAccount:this.props.onCreateAccount,onCancel:this.props.onCancel,onError:this.props.onError})):"settings"===i?t().createElement(Ni,{transport:this.props.transport,serverAddress:this.props.serverAddress,secureConnection:this.props.secureConnection,onCancel:this.props.onCancel,onUpdate:this.props.onGlobalSettings}):"edit"===i?t().createElement(e.Suspense,{fallback:t().createElement("div",{className:"panel-form-row"},t().createElement(a.FormattedMessage,{id:"loading_note",defaultMessage:[{type:0,value:"Loading..."}]}))},t().createElement(Ri,{tinode:this.props.tinode,myUserId:this.props.myUserId,trustedBadges:this.props.trustedBadges,onShowCountrySelector:this.props.onShowCountrySelector,onNavigate:this.props.onNavigate,onCredAdd:this.props.onCredAdd,onCredDelete:this.props.onCredDelete,onCredConfirm:this.props.onCredConfirm,onError:this.props.onError})):"general"===i||"crop"===i?t().createElement(va,{topic:"me",tinode:this.props.tinode,myUserId:this.props.myUserId,reqCredMethod:this.props.reqCredMethod,onUpdateTopicDesc:this.props.onUpdateAccountDesc,onUpdateTagsRequest:this.props.onUpdateAccountTags,onError:this.props.onError}):"notif"===i?t().createElement(gi,{messageSounds:this.props.messageSounds,desktopAlerts:this.props.desktopAlerts,desktopAlertsEnabled:this.props.desktopAlertsEnabled,incognitoMode:this.props.incognitoMode,onTogglePushNotifications:this.props.onTogglePushNotifications,onToggleMessageSounds:this.props.onToggleMessageSounds,onToggleIncognitoMode:this.props.onToggleIncognitoMode}):"security"===i?t().createElement(bi,{tinode:this.props.tinode,onUpdateAccountDesc:this.props.onUpdateAccountDesc,onUpdatePassword:this.props.onUpdatePassword,onLogout:this.props.onLogout,onDeleteAccount:this.props.onDeleteAccount,onShowAlert:this.props.onShowAlert,onShowBlocked:this.props.onShowBlocked}):"support"===i?t().createElement(Ei,{serverAddress:this.props.serverAddress,serverVersion:this.props.serverVersion}):"contacts"===i||"archive"==i||"blocked"==i?t().createElement(mi,{tinode:this.props.tinode,myUserId:this.props.myUserId,connected:this.props.connected,topicSelected:this.props.topicSelected,archive:"archive"==i,blocked:"blocked"==i,chatList:this.props.chatList,showContextMenu:this.props.showContextMenu,onTopicSelected:this.props.onTopicSelected,onShowArchive:this.props.onShowArchive}):"newtpk"===i?t().createElement(ki,{tinode:this.props.tinode,searchResults:this.props.searchResults,onInitFind:this.props.onInitFind,onSearchContacts:this.props.onSearchContacts,onCreateTopic:this.props.onCreateTopic,onError:this.props.onError}):"cred"===i?t().createElement(Ii,{credCode:this.props.credCode,credMethod:this.props.credMethod,credToken:this.props.credToken,onSubmit:this.props.onValidateCredentials,onCancel:this.props.onCancel}):"reset"===i?t().createElement(e.Suspense,{fallback:t().createElement("div",{className:"panel-form-row"},t().createElement(a.FormattedMessage,{id:"loading_note",defaultMessage:[{type:0,value:"Loading..."}]}))},t().createElement(Fi,{tinode:this.props.tinode,reqCredMethod:this.props.reqCredMethod,onShowCountrySelector:this.props.onShowCountrySelector,onRequest:this.props.onPasswordResetRequest,onReset:this.props.onResetPassword,onCancel:this.props.onCancel,onError:this.props.onError})):null)}}const Oi=(0,a.injectIntl)(Li);var Bi=o(3119);function qi(){let e=hs.Mv;return"object"==typeof window.location&&("file:"==window.location.protocol||"localhost"==window.location.hostname?e=hs.Rc.local:window.location.hostname&&(e=window.location.hostname+(window.location.port?":"+window.location.port:""))),e}function ji(){return"object"==typeof window.location&&"https:"==window.location.protocol}var Hi=o(320);const Vi=t().lazy((e=>o.e(290).then(o.bind(o,1290)))),Wi=new Audio("audio/msg.m4a"),zi=(0,a.defineMessages)({reconnect_countdown:{id:"reconnect_countdown",defaultMessage:[{type:0,value:"Disconnected. Reconnecting in "},{type:1,value:"seconds"},{type:0,value:"…"}]},reconnect_now:{id:"reconnect_now",defaultMessage:[{type:0,value:"Try now"}]},push_init_failed:{id:"push_init_failed",defaultMessage:[{type:0,value:"Failed to initialize push notifications"}]},invalid_security_token:{id:"invalid_security_token",defaultMessage:[{type:0,value:"Invalid security token"}]},no_connection:{id:"no_connection",defaultMessage:[{type:0,value:"No connection"}]},code_doesnot_match:{id:"code_doesnot_match",defaultMessage:[{type:0,value:"Code does not match"}]},menu_item_info:{id:"menu_item_info",defaultMessage:[{type:0,value:"Info"}]},menu_item_audio_call:{id:"menu_item_audio_call",defaultMessage:[{type:0,value:"Call"}]},menu_item_video_call:{id:"menu_item_video_call",defaultMessage:[{type:0,value:"Video call"}]},cred_confirmed_successfully:{id:"cred_confirmed_successfully",defaultMessage:[{type:0,value:"Confirmed successfully"}]}});class Zi extends t().Component{constructor(e){super(e),this.selfRef=t().createRef(),this.state=this.getBlankState(),this.handleResize=this.handleResize.bind(this),this.handleHashRoute=this.handleHashRoute.bind(this),this.handleOnline=this.handleOnline.bind(this),this.checkForAppUpdate=this.checkForAppUpdate.bind(this),this.handleVisibilityEvent=this.handleVisibilityEvent.bind(this),this.handleError=this.handleError.bind(this),this.handleLoginRequest=this.handleLoginRequest.bind(this),this.handlePersistenceChange=this.handlePersistenceChange.bind(this),this.handleConnected=this.handleConnected.bind(this),this.handleAutoreconnectIteration=this.handleAutoreconnectIteration.bind(this),this.doLogin=this.doLogin.bind(this),this.handleLoginSuccessful=this.handleLoginSuccessful.bind(this),this.handleDisconnect=this.handleDisconnect.bind(this),this.tnMeMetaDesc=this.tnMeMetaDesc.bind(this),this.tnMeContactUpdate=this.tnMeContactUpdate.bind(this),this.tnMeSubsUpdated=this.tnMeSubsUpdated.bind(this),this.resetContactList=this.resetContactList.bind(this),this.tnInitFind=this.tnInitFind.bind(this),this.tnFndSubsUpdated=this.tnFndSubsUpdated.bind(this),this.handleSearchContacts=this.handleSearchContacts.bind(this),this.handleTopicSelected=this.handleTopicSelected.bind(this),this.handleHideMessagesView=this.handleHideMessagesView.bind(this),this.handleSendMessage=this.handleSendMessage.bind(this),this.handleNewChatInvitation=this.handleNewChatInvitation.bind(this),this.handleNewAccount=this.handleNewAccount.bind(this),this.handleNewAccountRequest=this.handleNewAccountRequest.bind(this),this.handleUpdatePasswordRequest=this.handleUpdatePasswordRequest.bind(this),this.handleUpdateAccountTagsRequest=this.handleUpdateAccountTagsRequest.bind(this),this.handleToggleIncognitoMode=this.handleToggleIncognitoMode.bind(this),this.handleSettings=this.handleSettings.bind(this),this.handleGlobalSettings=this.handleGlobalSettings.bind(this),this.handleShowArchive=this.handleShowArchive.bind(this),this.handleShowBlocked=this.handleShowBlocked.bind(this),this.handleToggleMessageSounds=this.handleToggleMessageSounds.bind(this),this.handleCredAdd=this.handleCredAdd.bind(this),this.handleCredDelete=this.handleCredDelete.bind(this),this.handleCredConfirm=this.handleCredConfirm.bind(this),this.initFCMessaging=this.initFCMessaging.bind(this),this.toggleFCMToken=this.toggleFCMToken.bind(this),this.handlePushMessage=this.handlePushMessage.bind(this),this.handleSidepanelCancel=this.handleSidepanelCancel.bind(this),this.handleStartTopicRequest=this.handleStartTopicRequest.bind(this),this.handleNewTopicCreated=this.handleNewTopicCreated.bind(this),this.handleTopicUpdateRequest=this.handleTopicUpdateRequest.bind(this),this.handleUnarchive=this.handleUnarchive.bind(this),this.handleChangePermissions=this.handleChangePermissions.bind(this),this.handleTagsUpdateRequest=this.handleTagsUpdateRequest.bind(this),this.handleLogout=this.handleLogout.bind(this),this.handleDeleteAccount=this.handleDeleteAccount.bind(this),this.handleDeleteTopicRequest=this.handleDeleteTopicRequest.bind(this),this.handleDeleteMessagesRequest=this.handleDeleteMessagesRequest.bind(this),this.handleLeaveUnsubRequest=this.handleLeaveUnsubRequest.bind(this),this.handleBlockTopicRequest=this.handleBlockTopicRequest.bind(this),this.handleReportTopic=this.handleReportTopic.bind(this),this.handleShowContextMenu=this.handleShowContextMenu.bind(this),this.defaultTopicContextMenu=this.defaultTopicContextMenu.bind(this),this.handleHideContextMenu=this.handleHideContextMenu.bind(this),this.handleShowAlert=this.handleShowAlert.bind(this),this.handleShowInfoView=this.handleShowInfoView.bind(this),this.handleMemberUpdateRequest=this.handleMemberUpdateRequest.bind(this),this.handleValidateCredentialsRequest=this.handleValidateCredentialsRequest.bind(this),this.handlePasswordResetRequest=this.handlePasswordResetRequest.bind(this),this.handleResetPassword=this.handleResetPassword.bind(this),this.handleContextMenuAction=this.handleContextMenuAction.bind(this),this.handleShowCountrySelector=this.handleShowCountrySelector.bind(this),this.handleShowForwardDialog=this.handleShowForwardDialog.bind(this),this.handleHideForwardDialog=this.handleHideForwardDialog.bind(this),this.handleStartVideoCall=this.handleStartVideoCall.bind(this),this.handleStartAudioCall=this.handleStartAudioCall.bind(this),this.handleInfoMessage=this.handleInfoMessage.bind(this),this.handleDataMessage=this.handleDataMessage.bind(this),this.handleCallClose=this.handleCallClose.bind(this),this.handleCallInvite=this.handleCallInvite.bind(this),this.handleCallRinging=this.handleCallRinging.bind(this),this.handleCallHangup=this.handleCallHangup.bind(this),this.handleCallSendOffer=this.handleCallSendOffer.bind(this),this.handleCallIceCandidate=this.handleCallIceCandidate.bind(this),this.handleCallSendAnswer=this.handleCallSendAnswer.bind(this),this.handleCallAccept=this.handleCallAccept.bind(this),this.sendMessageToTopic=this.sendMessageToTopic.bind(this),this.callTimeoutTimer=null}getBlankState(){const e=Hi.Z.getObject("settings")||{},t=!!Hi.Z.getObject("keep-logged-in");return{connected:!1,ready:!1,autoLogin:!1,transport:e.transport||null,serverAddress:e.serverAddress||qi(),secureConnection:void 0===e.secureConnection?ji():e.secureConnection,serverVersion:"no connection",messageSounds:!e.messageSoundsOff,incognitoMode:!1,desktopAlerts:t&&!!e.desktopAlerts,desktopAlertsEnabled:(ji()||"object"==typeof window.location&&"localhost"==window.location.hostname)&&void 0!==de&&"undefined"!=typeof navigator&&"undefined"!=typeof FIREBASE_INIT,firebaseToken:t?Hi.Z.getObject("firebase-token"):null,applicationVisible:!document.hidden,errorText:"",errorLevel:null,errorAction:void 0,errorActionText:null,sidePanelSelected:"login",sidePanelTitle:null,sidePanelAvatar:null,myTrustedBadges:[],loadSpinnerVisible:!1,login:"",password:"",persist:t,myUserId:null,liveConnection:navigator.onLine,topicSelected:"",topicSelectedOnline:!1,topicSelectedAcs:null,newTopicParams:null,loginDisabled:!1,displayMobile:window.innerWidth<=hs.yl,infoPanel:void 0,mobilePanel:"sidepanel",callTopic:void 0,callState:0,callAudioOnly:void 0,callShouldStart:!1,contextMenuVisible:!1,contextMenuBounds:null,contextMenuClickAt:null,contextMenuParams:null,contextMenuItems:[],forwardDialogVisible:!1,forwardMessage:null,alertVisible:!1,alertParams:{},chatList:[],searchResults:[],searchableContacts:[],reqCredMethod:void 0,credMethod:void 0,credCode:void 0,credToken:void 0,requestedTopic:void 0}}componentDidMount(){if(window.addEventListener("resize",this.handleResize),this.handleOnlineOn=e=>{this.handleOnline(!0)},window.addEventListener("online",this.handleOnlineOn),this.handleOnlineOff=e=>{this.handleOnline(!1)},window.addEventListener("offline",this.handleOnlineOff),window.addEventListener("hashchange",this.handleHashRoute),"function"==typeof BroadcastChannel){new BroadcastChannel("tinode-sw").addEventListener("message",this.handlePushMessage)}else console.warn("Your browser does not support BroadcastChannel. Some features will not be available");document.addEventListener("visibilitychange",this.handleVisibilityEvent),this.setState({viewportWidth:document.documentElement.clientWidth,viewportHeight:document.documentElement.clientHeight}),new Promise(((e,t)=>{this.tinode=Zi.tnSetup(this.state.serverAddress,ji(),this.state.transport,this.props.intl.locale,this.state.persist,e),this.tinode.onConnect=this.handleConnected,this.tinode.onDisconnect=this.handleDisconnect,this.tinode.onAutoreconnectIteration=this.handleAutoreconnectIteration,this.tinode.onInfoMessage=this.handleInfoMessage,this.tinode.onDataMessage=this.handleDataMessage})).then((e=>{this.state.desktopAlertsEnabled&&this.initFCMessaging().catch((e=>{})),this.resetContactList();const t=this.state.persist?Hi.Z.getObject("auth-token"):void 0;t&&(this.setState({autoLogin:!0}),t.expires=new Date(t.expires),this.tinode.setAuthToken(t),this.tinode.connect().catch((e=>{this.handleError(e.message,"err")}))),this.readTimer=null,this.readTimerCallback=null;const s=si.Z.parseUrlHash(window.location.hash);if(["cred","reset","register"].includes(s.path[0]))this.handleHashRoute();else{this.setState({requestedTopic:s.path[1]});const e=s.params&&s.params.cred_done?si.Z.addUrlParam("","cred_done",s.params.cred_done):"";si.Z.navigateTo(e)}}))}componentWillUnmount(){window.removeEventListener("resize",this.handleResize),window.removeEventListener("hashchange",this.handleHashRoute),window.removeEventListener("online",this.handleOnlineOn),window.removeEventListener("offline",this.handleOnlineOff),document.removeEventListener("visibilitychange",this.handleVisibilityEvent)}static tnSetup(e,t,s,a,i,n){const o=new cs.Tinode({appName:hs.iC,host:e,apiKey:hs.$h,transport:s,secure:t,persist:i},n);return o.setHumanLanguage(a),o.enableLogging(hs.JG,!0),o}handlePushMessage(e){this.tinode.oobNotification(e.data||{})}initFCMessaging(){const{formatMessage:e,locale:t}=this.props.intl,s=(t,s)=>{console.error(t,s),this.handleError(e(zi.push_init_failed),"err"),this.setState({firebaseToken:null}),Hi.Z.updateObject("settings",{desktopAlerts:!1})};try{return this.fcm=ns(de(FIREBASE_INIT,hs.iC)),navigator.serviceWorker.getRegistration("/service-worker.js").then((e=>e||navigator.serviceWorker.register("/service-worker.js").then((e=>(this.checkForAppUpdate(e),e))))).then((e=>((e.active||e.installing).postMessage(JSON.stringify({locale:t,version:Bi.l})),Zi.requestFCMToken(this.fcm,e)))).then((e=>{const t=Hi.Z.getObject("keep-logged-in");e!=this.state.firebaseToken&&(this.tinode.setDeviceToken(e),t&&Hi.Z.setObject("firebase-token",e)),this.setState({firebaseToken:e,desktopAlerts:!0}),t&&Hi.Z.updateObject("settings",{desktopAlerts:!0}),ls(this.fcm,(e=>{this.handlePushMessage(e)}))})).catch((e=>{throw s(e),e}))}catch(e){return s(e),Promise.reject(e)}}static requestFCMToken(e,t){return os(e,{serviceWorkerRegistration:t,vapidKey:FIREBASE_INIT.messagingVapidKey}).then((t=>{if(t)return t;if("undefined"!=typeof Notification)return Notification.requestPermission().then((t=>{if("granted"===t)return os(e,{serviceWorkerRegistration:reg,vapidKey:FIREBASE_INIT.messagingVapidKey}).then((e=>{if(e)return e;throw new Error("Failed to initialize notifications")}));throw new Error("No permission to send notifications: "+t)}));throw new Error("Notifications are not supported")}))}handleResize(){const e=document.documentElement.clientWidth<=hs.yl;this.setState({viewportWidth:document.documentElement.clientWidth,viewportHeight:document.documentElement.clientHeight}),this.state.displayMobile!=e&&this.setState({displayMobile:e})}checkForAppUpdate(e){e.onupdatefound=s=>{const i=e.installing;i.onstatechange=e=>{if("installed"==i.state&&navigator.serviceWorker.controller){const e=t().createElement(t().Fragment,null,t().createElement(a.FormattedMessage,{id:"update_available",defaultMessage:[{type:0,value:"Update available."}]})," ",t().createElement("a",{href:""},t().createElement(a.FormattedMessage,{id:"reload_update",defaultMessage:[{type:0,value:"Reload"}]})),".");this.handleError(e,"info")}}}}handleHashRoute(){const e=si.Z.parseUrlHash(window.location.hash),t={infoPanel:e.params.info,newTopicTabSelected:e.params.tab};if(e.path&&e.path.length>0){["register","settings","edit","notif","security","support","general","crop","cred","reset","newtpk","archive","blocked","contacts",""].includes(e.path[0])?t.sidePanelSelected=e.path[0]:console.warn("Unknown sidepanel view",e.path[0]);let s=e.path[1]||null;s!=this.state.topicSelected&&(cs.Tinode.topicType(s)?t.mobilePanel="topic-view":(s=null,t.mobilePanel="sidepanel"),Object.assign(t,{topicSelected:s,topicSelectedAcs:this.tinode.getTopicAccessMode(s)}))}else Object.assign(t,{sidePanelSelected:"",topicSelected:null});e.params.method&&(t.credMethod=e.params.method),e.params.code&&(t.credCode=e.params.code),e.params.token&&(t.credToken=e.params.token),e.params.cred_done&&Object.assign(t,Zi.stateForError(this.props.intl.formatMessage(zi.cred_confirmed_successfully),"info")),this.setState(t)}handleOnline(e){e?(this.handleError(),clearInterval(this.reconnectCountdown),this.tinode.reconnect()):this.handleError(this.props.intl.formatMessage(zi.no_connection),"warn"),this.setState({liveConnection:e})}handleVisibilityEvent(){this.setState({applicationVisible:!document.hidden})}static stateForError(e,t,s,a){return{errorText:e,errorLevel:t,errorAction:s,errorActionText:a,callShouldStart:!1}}handleError(e,t,s,a){this.setState(Zi.stateForError(e,t,s,a))}handleLoginRequest(e,t){this.setState({loginDisabled:!0,login:e,password:t,loadSpinnerVisible:!0,autoLogin:!0}),this.handleError("",null),this.tinode.isConnected()?this.doLogin(e,t,null,{meth:this.state.credMethod,resp:this.state.credCode}):this.tinode.connect().catch((e=>{this.setState({loginDisabled:!1,autoLogin:!1,loadSpinnerVisible:!1}),this.handleError(e.message,"err")})),this.state.desktopAlertsEnabled&&!this.state.firebaseToken&&this.initFCMessaging()}handlePersistenceChange(e){e?this.tinode.initStorage().then((e=>{Hi.Z.setObject("keep-logged-in",!0),this.setState({persist:!0})})):this.tinode.clearStorage().then((e=>{Hi.Z.setObject("keep-logged-in",!1),this.setState({persist:!1})}))}handleConnected(){clearInterval(this.reconnectCountdown),this.handleError();const e=this.tinode.getServerInfo();this.setState({serverVersion:e.ver+" "+(e.build?e.build:"none"),reqCredMethod:((e.reqCred||{}).auth||[])[0]||"email"}),this.state.autoLogin&&this.doLogin(this.state.login,this.state.password,null,{meth:this.state.credMethod,resp:this.state.credCode})}handleAutoreconnectIteration(e,t){if(clearInterval(this.reconnectCountdown),e<0)return void this.handleError();if(t)return void t.then((e=>{this.handleError()})).catch((e=>{this.handleError(e.message,"err")}));const{formatMessage:s}=this.props.intl;let a=e/1e3;a|=a,this.reconnectCountdown=setInterval((e=>{if(a<-10)return clearInterval(this.reconnectCountdown),void this.tinode.reconnect();const t=a>99?(0,ys.nH)(a):a;this.handleError(s(zi.reconnect_countdown,{seconds:t}),"warn",(e=>{clearInterval(this.reconnectCountdown),this.tinode.reconnect()}),s(zi.reconnect_now)),a-=1}),1e3)}handleDisconnect(e){this.setState({connected:!1,ready:!1,topicSelectedOnline:!1,errorText:e&&e.message?e.message:"Disconnected",errorLevel:e&&e.message?"err":"warn",loginDisabled:!1,contextMenuVisible:!1,forwardDialogVisible:!1,serverVersion:"no connection"})}doLogin(e,t,s,a){if(this.tinode.isAuthenticated())return void si.Z.navigateTo("");let i=s||(this.tinode.getAuthToken()||{}).token;if(!(e&&t||i))return si.Z.navigateTo(""),void this.setState({loginDisabled:!1});a=cs.Tinode.credential(a);let n,o=this.tinode.isConnected()?Promise.resolve():this.tinode.connect();e&&t?(i=null,this.setState({password:null}),n=o.then((s=>this.tinode.loginBasic(e,t,a)))):n=o.then((e=>this.tinode.loginToken(i,a))),n.then((e=>{e.code>=300&&"validate credentials"===e.text?(this.setState({loadSpinnerVisible:!1}),a&&this.handleError(this.props.intl.formatMessage(zi.code_doesnot_match),"warn"),Zi.navigateToCredentialsView(e.params)):this.handleLoginSuccessful()})).catch((e=>{const t=e.code>=500;this.setState({loginDisabled:!1,credMethod:void 0,credCode:void 0,loadSpinnerVisible:!1,autoLogin:t}),this.handleError(e.message,"err"),console.warn("Login failed",e),t||(i&&this.handleLogout(),si.Z.navigateTo(""))}))}static navigateToCredentialsView(e){const t=si.Z.parseUrlHash(window.location.hash);t.path[0]="cred",t.params.method=e.cred[0],t.params.token=e.token,si.Z.navigateTo(si.Z.composeUrlHash(t.path,t.params))}handleLoginSuccessful(){this.handleError(),Hi.Z.getObject("keep-logged-in")&&Hi.Z.setObject("auth-token",this.tinode.getAuthToken());const e=this.state.requestedTopic,t=this.tinode.getMeTopic();t.onMetaDesc=this.tnMeMetaDesc,t.onContactUpdate=this.tnMeContactUpdate,t.onSubsUpdated=this.tnMeSubsUpdated,this.setState({connected:!0,credMethod:void 0,credCode:void 0,credToken:void 0,myUserId:this.tinode.getCurrentUserID(),autoLogin:!0,requestedTopic:void 0}),t.subscribe(t.startMetaQuery().withLaterSub().withDesc().withTags().withCred().build()).catch((e=>{this.tinode.disconnect(),localStorage.removeItem("auth-token"),this.handleError(e.message,"err"),si.Z.navigateTo("")})).finally((e=>{this.setState({loadSpinnerVisible:!1})}));let s=si.Z.setUrlSidePanel(window.location.hash,"contacts");e&&(s=si.Z.setUrlTopic(s,e)),si.Z.navigateTo(s)}tnMeMetaDesc(e){if(e){if(e.public&&this.setState({sidePanelTitle:e.public.fn,sidePanelAvatar:(0,ks.PD)(e.public.photo)}),e.trusted){const t=[];for(const[s,a]of Object.entries(e.trusted))a&&t.push(s);this.setState({myTrustedBadges:t})}e.acs&&this.setState({incognitoMode:!e.acs.isPresencer()})}}tnMeContactUpdate(e,t){if("on"==e||"off"==e)this.resetContactList(),this.state.topicSelected==t.topic&&this.setState({topicSelectedOnline:"on"==e});else if("read"==e)this.resetContactList();else if("msg"==e){const e=this.tinode.getTopic(t.topic),s=e&&e.isArchived();t.unread>0&&this.state.messageSounds&&!s&&(document.hidden||this.state.topicSelected!=t.topic)&&Wi.play().catch((e=>{})),this.resetContactList()}else"recv"==e||("gone"==e||"unsub"==e?(this.state.topicSelected==t.topic&&this.handleTopicSelected(null),this.resetContactList()):"acs"==e?this.state.topicSelected==t.topic&&this.setState({topicSelectedAcs:t.acs}):"del"==e||"upd"==e||"call"==e||console.info("Unsupported (yet) presence update:",e,"in",t.topic))}tnMeSubsUpdated(e){this.resetContactList()}static prepareSearchableContacts(e,t){const s={};for(const t of e)cs.Tinode.isP2PTopicName(t.topic)&&(s[t.topic]={user:t.topic,updated:t.updated,public:t.public,private:t.private,acs:t.acs});for(const e of t)s[e.user]||(s[e.user]=e);return Object.values(s)}resetContactList(){const e={chatList:[]};this.state.ready||(e.ready=!0),this.tinode.getMeTopic().contacts((t=>{t.topic||t.user||(t.topic=t.name),e.chatList.push(t),this.state.topicSelected==t.topic&&(e.topicSelectedOnline=t.online,e.topicSelectedAcs=t.acs)}));const t=new Date(0);e.chatList.sort(((e,s)=>(e.touched||t).getTime()-(s.touched||t).getTime())),e.searchableContacts=Zi.prepareSearchableContacts(e.chatList,this.state.searchResults),this.setState(e)}tnInitFind(){const e=this.tinode.getFndTopic();e.onSubsUpdated=this.tnFndSubsUpdated,e.isSubscribed()?this.tnFndSubsUpdated():e.subscribe(e.startMetaQuery().withSub().build()).catch((e=>{this.handleError(e.message,"err")}))}tnFndSubsUpdated(){const e=[];this.tinode.getFndTopic().contacts((t=>{e.push(t)})),this.setState({searchResults:e,searchableContacts:Zi.prepareSearchableContacts(this.state.chatList,e)})}handleSearchContacts(e){const t=this.tinode.getFndTopic();t.setMeta({desc:{public:e}}).then((e=>t.getMeta(t.startMetaQuery().withSub().build()))).catch((e=>this.handleError(e.message,"err")))}handleTopicSelected(e){this.state.newTopicParams&&this.state.newTopicParams._topicName!=e&&this.setState({newTopicParams:null}),e?(this.setState({errorText:"",errorLevel:null,mobilePanel:"topic-view",infoPanel:void 0}),this.state.topicSelected!=e&&(this.setState({topicSelectedOnline:this.tinode.isTopicOnline(e),topicSelectedAcs:this.tinode.getTopicAccessMode(e),forwardMessage:null}),si.Z.navigateTo(si.Z.setUrlTopic("",e)))):(this.setState({errorText:"",errorLevel:null,mobilePanel:"sidepanel",topicSelectedOnline:!1,topicSelectedAcs:null,infoPanel:void 0,forwardMessage:null}),si.Z.navigateTo(si.Z.setUrlTopic("",null)))}handleHideMessagesView(){this.setState({mobilePanel:"sidepanel"}),si.Z.navigateTo(si.Z.setUrlTopic(window.location.hash,null))}handleSendMessage(e,t,s,a){const i=this.tinode.getTopic(this.state.topicSelected);return this.sendMessageToTopic(i,e,t,s,a)}sendMessageToTopic(e,t,s,a,i){(t=e.createMessage(t,!1))._uploader=a,i&&(t.head=Object.assign(t.head||{},i));const n=[];if(s&&n.push(s),!e.isSubscribed()){const s=e.subscribe().then((s=>{let a=[];e.queuedMessages((s=>{s._sending||s.seq==t.seq||(s.head&&s.head.webrtc?a.push(s.seq):e.isSubscribed()&&e.publishMessage(s))})),a.length>0&&e.delMessagesList(a,!0)}));n.push(s)}return e.publishDraft(t,Promise.all(n)).then((t=>(e.isArchived()&&e.archive(!1),t))).catch((e=>this.handleError(e.message,"err")))}handleNewChatInvitation(e,t){const s=this.tinode.getTopic(e);let a=null;switch(t){case"accept":const i=s.getAccessMode().getGiven();a=s.setMeta({sub:{mode:i}}),s.isP2PType()&&(a=a.then((t=>s.setMeta({sub:{user:e,mode:i}}))));break;case"delete":a=s.delTopic(!0);break;case"block":const n=s.getAccessMode().updateWant("-JP").getWant();a=s.setMeta({sub:{mode:n}}).then((e=>this.handleTopicSelected(null)));break;default:console.warn("Unknown invitation action",'"'+t+'""')}null!=a&&a.catch((e=>this.handleError(e.message,"err")))}handleNewAccount(){this.handleError(),si.Z.navigateTo(si.Z.setUrlSidePanel(window.location.hash,"register"))}handleNewAccountRequest(e,t,s,a,i){this.handleError(),this.tinode.connect(this.state.serverAddress).then((n=>{let o;return s&&s.photo&&s.photo.ref&&(o=[s.photo.ref]),this.tinode.createAccountBasic(e,t,{public:s,tags:i,cred:cs.Tinode.credential(a),attachments:o})})).then((e=>{e.code>=300&&"validate credentials"==e.text?Zi.navigateToCredentialsView(e.params):this.handleLoginSuccessful(this)})).catch((e=>{this.handleError(e.message,"err")}))}handleToggleIncognitoMode(e){this.setState({incognitoMode:null});const t=this.tinode.getMeTopic(),s=t.getAccessMode().updateWant(e?"-P":"+P").getWant();t.setMeta({sub:{mode:s}}).catch((t=>{this.setState({incognitoMode:!e}),this.handleError(t.message,"err")}))}handleUpdateAccountTagsRequest(e,t){this.tinode.getMeTopic().setMeta({tags:t}).catch((e=>this.handleError(e.message,"err")))}handleSettings(){this.handleError(),si.Z.navigateTo(si.Z.setUrlSidePanel(window.location.hash,this.state.myUserId?"edit":"settings"))}handleGlobalSettings(e){const t=e.serverAddress||this.state.serverAddress,s=e.transport||this.state.transport,a=void 0===e.secureConnection?this.state.secureConnection:e.secureConnection;this.tinode&&(this.tinode.clearStorage(),this.tinode.onDisconnect=void 0,this.tinode.disconnect()),this.tinode=Zi.tnSetup(t,a,s,this.props.intl.locale,Hi.Z.getObject("keep-logged-in")),this.tinode.onConnect=this.handleConnected,this.tinode.onDisconnect=this.handleDisconnect,this.tinode.onAutoreconnectIteration=this.handleAutoreconnectIteration,this.tinode.onInfoMessage=this.handleInfoMessage,this.tinode.onDataMessage=this.handleDataMessage,this.setState({serverAddress:t,transport:s,secureConnection:a}),Hi.Z.setObject("settings",{serverAddress:t,transport:s,secureConnection:a}),si.Z.navigateTo(si.Z.setUrlSidePanel(window.location.hash,""))}handleShowArchive(){si.Z.navigateTo(si.Z.setUrlSidePanel(window.location.hash,this.state.myUserId?"archive":""))}handleShowBlocked(){si.Z.navigateTo(si.Z.setUrlSidePanel(window.location.hash,this.state.myUserId?"blocked":""))}toggleFCMToken(e){e?(this.setState({desktopAlerts:null}),this.state.firebaseToken?(this.setState({desktopAlerts:!0}),Hi.Z.getObject("keep-logged-in")&&Hi.Z.updateObject("settings",{desktopAlerts:!0})):this.initFCMessaging()):this.state.firebaseToken&&this.fcm?rs(this.fcm).catch((e=>{console.error("Unable to delete token.",e)})).finally((e=>{Hi.Z.updateObject("settings",{desktopAlerts:!1}),localStorage.removeItem("firebase-token"),this.setState({desktopAlerts:!1,firebaseToken:null}),this.tinode.setDeviceToken(null)})):(this.setState({desktopAlerts:!1,firebaseToken:null}),Hi.Z.updateObject("settings",{desktopAlerts:!1}))}handleToggleMessageSounds(e){this.setState({messageSounds:e}),Hi.Z.updateObject("settings",{messageSoundsOff:!e})}handleCredAdd(e,t){this.tinode.getMeTopic().setMeta({cred:{meth:e,val:t}}).catch((e=>this.handleError(e.message,"err")))}handleCredDelete(e,t){this.tinode.getMeTopic().delCredential(e,t).catch((e=>this.handleError(e.message,"err")))}handleCredConfirm(e,t){Zi.navigateToCredentialsView({cred:[e]})}handleSidepanelCancel(){const e=si.Z.parseUrlHash(window.location.hash);let t="";["security","support","general","notif"].includes(e.path[0])?t="edit":"crop"==e.path[0]?t="general":"blocked"==e.path[0]?t="security":this.state.myUserId&&(t="contacts"),e.path[0]=t,e.params&&(delete e.params.code,delete e.params.method,delete e.params.tab,delete e.params.scheme,delete e.params.token),si.Z.navigateTo(si.Z.composeUrlHash(e.path,e.params)),this.setState({errorText:"",errorLevel:null})}basicNavigator(e){si.Z.navigateTo(si.Z.setUrlSidePanel(window.location.hash,e))}infoNavigator(e){si.Z.navigateTo(si.Z.setUrlInfoPanel(window.location.hash,e))}handleStartTopicRequest(e,t,s){if(e&&this.tinode.isTopicCached(e))return void this.handleTopicSelected(e);const a={};cs.Tinode.isP2PTopicName(e)?(a.sub={mode:hs.RK},a.desc={defacs:{auth:hs.RK}}):(e=e||this.tinode.newGroupTopicName(s),t&&(a.desc={public:t.public,private:{comment:t.private}},a.tags=t.tags)),a._topicName=e,this.setState({newTopicParams:a},(t=>{this.handleTopicSelected(e)}))}handleNewTopicCreated(e,t){let s={};this.state.callShouldStart&&(s={callState:Qs,callShouldStart:!1}),this.state.topicSelected==e&&e!=t&&(s.topicSelected=t),this.setState(s,(e=>{si.Z.navigateTo(si.Z.setUrlTopic("",t))}))}handleTopicUpdateRequest(e,t,s,a){this.handleError();const i=this.tinode.getTopic(e);if(i){const e={};let n;t&&(t.photo&&(t.photo.ref&&t.photo.ref!=cs.Tinode.DEL_CHAR?n=[t.photo.ref]:t.photo.data&&t.photo.data!=cs.Tinode.DEL_CHAR||(t.photo=cs.Tinode.DEL_CHAR)),e.public=t),"string"==typeof s&&(e.private=s===cs.Tinode.DEL_CHAR?cs.Tinode.DEL_CHAR:{comment:s}),a&&(e.defacs=a),i.setMeta({desc:e,attachments:n}).catch((e=>this.handleError(e.message,"err")))}}handleUnarchive(e){const t=this.tinode.getTopic(e);t&&t.archive(!1).catch((e=>this.handleError(e.message,"err")))}handleUpdatePasswordRequest(e){this.handleError(),e&&this.tinode.updateAccountBasic(null,this.tinode.getCurrentLogin(),e).catch((e=>this.handleError(e.message,"err")))}handleChangePermissions(e,t,s){const a=this.tinode.getTopic(e);if(a){const e=a.getAccessMode();s?(e.updateGiven(t),t=e.getGiven()):(e.updateWant(t),t=e.getWant()),a.setMeta({sub:{user:s,mode:t}}).catch((e=>this.handleError(e.message,"err")))}}handleTagsUpdateRequest(e,t){const s=this.tinode.getTopic(e);s&&s.setMeta({tags:t}).catch((e=>this.handleError(e.message,"err")))}handleLogout(){let e;(0,Ds.J_)(0),localStorage.removeItem("auth-token"),localStorage.removeItem("firebase-token"),localStorage.removeItem("settings"),this.state.firebaseToken&&rs(this.fcm),clearInterval(this.reconnectCountdown),this.tinode?(e=this.tinode.clearStorage(),this.tinode.onDisconnect=void 0,this.tinode.disconnect()):e=Promose.resolve(),this.setState(this.getBlankState()),e.then((e=>{this.tinode=Zi.tnSetup(this.state.serverAddress,ji(),this.state.transport,this.props.intl.locale,Hi.Z.getObject("keep-logged-in"),(e=>{this.tinode.onConnect=this.handleConnected,this.tinode.onDisconnect=this.handleDisconnect,this.tinode.onAutoreconnectIteration=this.handleAutoreconnectIteration,this.tinode.onInfoMessage=this.handleInfoMessage,this.tinode.onDataMessage=this.handleDataMessage,si.Z.navigateTo("")}))}))}handleDeleteAccount(){this.tinode.delCurrentUser(!0).then((e=>{this.handleLogout()}))}handleDeleteTopicRequest(e){const t=this.tinode.getTopic(e);t&&t.delTopic(!0).then((e=>{si.Z.navigateTo(si.Z.setUrlTopic(window.location.hash,""))})).catch((e=>{this.handleError(e.message,"err")}))}handleDeleteMessagesRequest(e){const t=this.tinode.getTopic(e);t&&t.delMessagesAll(!0).catch((e=>this.handleError(e.message,"err")))}handleLeaveUnsubRequest(e){const t=this.tinode.getTopic(e);t&&t.leave(!0).then((e=>{si.Z.navigateTo(si.Z.setUrlTopic(window.location.hash,""))})).catch((e=>{this.handleError(e.message,"err")}))}handleBlockTopicRequest(e){const t=this.tinode.getTopic(e);t&&t.updateMode(null,"-JP").then((e=>{si.Z.navigateTo(si.Z.setUrlTopic(window.location.hash,""))})).catch((e=>this.handleError(e.message,"err")))}handleReportTopic(e){const t=this.tinode.getTopic(e);t&&(this.tinode.report("report",e),t.updateMode(null,"-JP").then((e=>{si.Z.navigateTo(si.Z.setUrlTopic(window.location.hash,""))})).catch((e=>this.handleError(e.message,"err"))))}handleShowContextMenu(e,t){this.setState({contextMenuVisible:!0,contextMenuClickAt:{x:e.x,y:e.y},contextMenuParams:e,contextMenuItems:t||this.defaultTopicContextMenu(e.topicName),contextMenuBounds:this.selfRef.current.getBoundingClientRect()})}handleShowForwardDialog(e){"newtpk"==this.state.sidePanelSelected&&this.handleSidepanelCancel();const t="➦ "+e.userName,s="string"==typeof e.content?cs.Drafty.init(e.content):cs.Drafty.forwardedContent(e.content),a=cs.Drafty.preview(s,hs.vX,!0),i=cs.Drafty.append(cs.Drafty.appendLineBreak(cs.Drafty.mention(t,e.userFrom)),s),n=cs.Drafty.quote(t,e.userFrom,a),o={forwarded:e.topicName+":"+e.seq};this.setState({forwardDialogVisible:!0,forwardMessage:{head:o,msg:i,preview:n}})}defaultTopicContextMenu(e){const t=this.tinode.getTopic(e);if(t._deleted)return["topic_delete"];let s=!1,a=!1,i=!1,n=!1,o=!1,r=!1,l=!1;if(t){n=t.isSubscribed(),r=t.isArchived();const e=t.getAccessMode();e&&(s=e.isMuted(),a=!e.isJoiner(),i=!e.isJoiner("want"),o=e.isDeleter())}return l=!!this.tinode.getServerParam("iceServers"),[n?{title:this.props.intl.formatMessage(zi.menu_item_info),handler:this.handleShowInfoView}:null,n&&cs.Tinode.isP2PTopicName(e)&&l?{title:this.props.intl.formatMessage(zi.menu_item_audio_call),handler:this.handleStartAudioCall}:null,n&&cs.Tinode.isP2PTopicName(e)&&l?{title:this.props.intl.formatMessage(zi.menu_item_video_call),handler:this.handleStartVideoCall}:null,n?"messages_clear":null,n&&o?"messages_clear_hard":null,s?a?null:"topic_unmute":"topic_mute",i?"topic_unblock":"topic_block",r?"topic_restore":"topic_archive","topic_delete"]}handleHideContextMenu(){this.setState({contextMenuVisible:!1,contextMenuClickAt:null,contextMenuParams:null,contextMenuBounds:null})}handleHideForwardDialog(e){this.setState({forwardDialogVisible:!1,forwardMessage:e?this.state.forwardMessage:null})}handleContextMenuAction(e,t,s){"topic_archive"==e?t&&s.topicName&&s.topicName==this.state.topicSelected&&t.then((e=>{this.handleTopicSelected(null)})):"menu_item_forward"==e&&this.handleShowForwardDialog(s)}handleShowAlert(e,t,s,a,i,n){this.setState({alertVisible:!0,alertParams:{title:e,content:t,onConfirm:s,confirm:a,onReject:i,reject:n}})}handleShowInfoView(){si.Z.navigateTo(si.Z.addUrlParam(window.location.hash,"info","info")),this.setState({infoPanel:"info"})}handleMemberUpdateRequest(e,t,s){if(!e)return;const a=this.tinode.getTopic(e);a&&(t&&t.length>0&&t.forEach((e=>{a.invite(e,null).catch((e=>this.handleError(e.message,"err")))})),s&&s.length>0&&s.forEach((e=>{a.delSubscription(e).catch((e=>this.handleError(e.message,"err")))})))}handleValidateCredentialsRequest(e,t,s){this.tinode.isAuthenticated()?this.tinode.getMeTopic().setMeta({cred:{meth:e,resp:t}}).catch((e=>this.handleError(e.message,"err"))):(this.setState({credMethod:e,credCode:t,credToken:s}),this.doLogin(null,null,s,{meth:e,resp:t}))}handlePasswordResetRequest(e,t){return this.tinode.connect().then((s=>this.tinode.requestResetAuthSecret("basic",e,t))).catch((e=>{this.handleError(e.message,"err")}))}handleResetPassword(e,t){const s=(0,ks.DC)(t.secret);s&&t.scheme?this.tinode.connect().then((a=>this.tinode.updateAccountBasic(null,null,e,{scheme:t.scheme,secret:s}))).then((e=>si.Z.navigateTo(""))).catch((e=>{this.handleError(e.message,"err")})):this.handleError(this.props.intl.formatMessage(zi.invalid_security_token),"err")}handleShowCountrySelector(s,i,n){this.handleShowAlert("Select country",t().createElement(e.Suspense,{fallback:t().createElement("div",null,t().createElement(a.FormattedMessage,{id:"loading_note",defaultMessage:[{type:0,value:"Loading..."}]}))},t().createElement(Vi,{selected:s,onSubmit:(e,t)=>{this.setState({alertVisible:!1}),n(e,t)}})),null,null,(e=>{}),"Cancel")}handleStartVideoCall(){this.setState({callTopic:this.state.topicSelected,callState:Gs,callAudioOnly:!1})}handleStartAudioCall(){this.setState({callTopic:this.state.topicSelected,callState:Gs,callAudioOnly:!0})}handleCallInvite(e,t,s,a){switch(s){case Gs:const s={webrtc:Xs,aonly:!!a};this.handleSendMessage(cs.Drafty.videoCall(a),void 0,void 0,s).then((e=>{e.code<200||e.code>=300||!e.params||!e.params.seq?this.handleCallClose():this.setState({callSeq:e.params.seq})}));break;case Qs:const i=this.tinode.getTopic(e);if(!i)return;i.videoCall("accept",t)}}handleCallRinging(e,t){const s=this.tinode.getTopic(e);s&&s.videoCall("ringing",t)}handleCallHangup(e,t){const s=this.tinode.getTopic(e);s&&s.videoCall("hang-up",t)}handleCallSendOffer(e,t,s){const a=this.tinode.getTopic(e);a&&a.videoCall("offer",t,s)}handleCallIceCandidate(e,t,s){const a=this.tinode.getTopic(e);a&&a.videoCall("ice-candidate",t,s)}handleCallSendAnswer(e,t,s){const a=this.tinode.getTopic(e);a&&a.videoCall("answer",t,s)}handleCallClose(){this.callTimeoutTimer&&clearTimeout(this.callTimeoutTimer),this.setState({callTopic:void 0,callState:0,callAudioOnly:void 0})}handleCallAccept(e){const t=this.tinode.getTopic(e);t&&(t.isSubscribed()?(this.handleTopicSelected(this.state.callTopic),this.setState({callState:Qs})):this.setState({callShouldStart:!0},(e=>this.handleTopicSelected(this.state.callTopic))))}handleInfoMessage(e){if("call"==e.what)switch(e.event){case"accept":if(cs.Tinode.isMeTopicName(e.topic)&&this.tinode.isMe(e.from))return void this.setState({callTopic:null,callState:0,callSeq:null,callAudioOnly:void 0});e.topic==this.state.callTopic&&this.setState({callState:Qs});break;case"hang-up":this.handleCallClose()}}handleDataMessage(e){if(e.head&&e.head.webrtc&&e.head.webrtc==Xs){const t=this.tinode.getTopic(e.topic);if(t){const s=t.latestMsgVersion(e.seq)||e;s.head&&s.head.webrtc&&s.head.webrtc==Xs&&e.from!=this.state.myUserId&&(0==this.state.callState?this.setState({callTopic:e.topic,callState:2,callSeq:e.seq,callAudioOnly:!!s.head.aonly}):this.handleCallHangup(e.topic,e.seq))}else console.warn("Received vc data message from unknown topic",e.topic)}}render(){return t().createElement("div",{id:"app-container",ref:this.selfRef},this.state.contextMenuVisible?t().createElement(ms,{tinode:this.tinode,bounds:this.state.contextMenuBounds,clickAt:this.state.contextMenuClickAt,params:this.state.contextMenuParams,items:this.state.contextMenuItems,hide:this.handleHideContextMenu,onShowAlert:this.handleShowAlert,onAction:this.handleContextMenuAction,onTopicRemoved:e=>{e==this.state.topicSelected&&this.handleTopicSelected(null)},onError:this.handleError}):null,this.state.forwardDialogVisible?t().createElement(Ks,{tinode:this.tinode,contacts:this.state.chatList,topicSelected:this.state.topicSelected,myUserId:this.state.myUserId,hide:this.handleHideForwardDialog,onInitFind:this.tnInitFind,searchResults:this.state.searchResults,onSearchContacts:this.handleSearchContacts,onTopicSelected:this.handleStartTopicRequest}):null,this.state.callTopic&&2==this.state.callState?t().createElement(Js,{tinode:this.tinode,topic:this.state.callTopic,seq:this.state.callSeq,callState:this.state.callState,audioOnly:this.state.callAudioOnly,onClose:this.handleCallClose,onRinging:this.handleCallRinging,onAcceptCall:this.handleCallAccept,onReject:this.handleCallHangup}):null,this.state.alertVisible?t().createElement(ds,{title:this.state.alertParams.title,content:this.state.alertParams.content,onReject:this.state.alertParams.onReject?e=>this.setState({alertVisible:!1}):null,reject:this.state.alertParams.reject,onConfirm:this.state.alertParams.onConfirm?e=>{this.setState({alertVisible:!1}),this.state.alertParams.onConfirm()}:null,confirm:this.state.alertParams.confirm}):null,this.state.displayMobile&&"sidepanel"!=this.state.mobilePanel?null:t().createElement(Oi,{tinode:this.tinode,connected:this.state.connected,displayMobile:this.state.displayMobile,state:this.state.sidePanelSelected,title:this.state.sidePanelTitle,avatar:this.state.sidePanelAvatar,trustedBadges:this.state.myTrustedBadges,login:this.state.login,persist:this.state.persist,myUserId:this.state.myUserId,loginDisabled:this.state.loginDisabled,loadSpinnerVisible:this.state.loadSpinnerVisible,errorText:this.state.errorText,errorLevel:this.state.errorLevel,errorAction:this.state.errorAction,errorActionText:this.state.errorActionText,topicSelected:this.state.topicSelected,chatList:this.state.chatList,credMethod:this.state.credMethod,credCode:this.state.credCode,credToken:this.state.credToken,transport:this.state.transport,messageSounds:this.state.messageSounds,desktopAlerts:this.state.desktopAlerts,desktopAlertsEnabled:this.state.desktopAlertsEnabled,incognitoMode:this.state.incognitoMode,serverAddress:this.state.serverAddress,secureConnection:this.state.secureConnection,serverVersion:this.state.serverVersion,reqCredMethod:this.state.reqCredMethod,onGlobalSettings:this.handleGlobalSettings,onSignUp:this.handleNewAccount,onSettings:this.handleSettings,onNavigate:this.basicNavigator,onLoginRequest:this.handleLoginRequest,onPersistenceChange:this.handlePersistenceChange,onCreateAccount:this.handleNewAccountRequest,onUpdateAccountDesc:this.handleTopicUpdateRequest,onUpdatePassword:this.handleUpdatePasswordRequest,onUpdateAccountTags:this.handleUpdateAccountTagsRequest,onTogglePushNotifications:this.toggleFCMToken,onToggleMessageSounds:this.handleToggleMessageSounds,onToggleIncognitoMode:this.handleToggleIncognitoMode,onCredAdd:this.handleCredAdd,onCredDelete:this.handleCredDelete,onCredConfirm:this.handleCredConfirm,onTopicSelected:this.handleTopicSelected,onCreateTopic:this.handleStartTopicRequest,onLogout:this.handleLogout,onDeleteAccount:this.handleDeleteAccount,onShowAlert:this.handleShowAlert,onCancel:this.handleSidepanelCancel,onError:this.handleError,onValidateCredentials:this.handleValidateCredentialsRequest,onPasswordResetRequest:this.handlePasswordResetRequest,onResetPassword:this.handleResetPassword,onShowArchive:this.handleShowArchive,onShowBlocked:this.handleShowBlocked,onShowCountrySelector:this.handleShowCountrySelector,onInitFind:this.tnInitFind,searchResults:this.state.searchResults,onSearchContacts:this.handleSearchContacts,showContextMenu:this.handleShowContextMenu}),!this.state.displayMobile||"topic-view"==this.state.mobilePanel&&!this.state.infoPanel?t().createElement(li,{tinode:this.tinode,connected:this.state.connected,ready:this.state.ready,online:this.state.topicSelectedOnline,acs:this.state.topicSelectedAcs,displayMobile:this.state.displayMobile,viewportWidth:this.state.viewportWidth,viewportHeight:this.state.viewportHeight,topic:this.state.topicSelected,myUserId:this.state.myUserId,myUserName:this.state.sidePanelTitle,serverVersion:this.state.serverVersion,serverAddress:this.state.serverAddress,applicationVisible:this.state.applicationVisible,forwardMessage:this.state.forwardMessage,onCancelForwardMessage:this.handleHideForwardDialog,callTopic:this.state.callTopic,callSeq:this.state.callSeq,callState:this.state.callState,callAudioOnly:this.state.callAudioOnly,onCallHangup:this.handleCallHangup,onCallInvite:this.handleCallInvite,onCallSendOffer:this.handleCallSendOffer,onCallIceCandidate:this.handleCallIceCandidate,onCallSendAnswer:this.handleCallSendAnswer,errorText:this.state.errorText,errorLevel:this.state.errorLevel,errorAction:this.state.errorAction,errorActionText:this.state.errorActionText,newTopicParams:this.state.newTopicParams,onHideMessagesView:this.handleHideMessagesView,onError:this.handleError,onNewTopicCreated:this.handleNewTopicCreated,showContextMenu:this.handleShowContextMenu,onChangePermissions:this.handleChangePermissions,onNewChat:this.handleNewChatInvitation,sendMessage:this.handleSendMessage,onVideoCallClosed:this.handleCallClose}):null,this.state.infoPanel?t().createElement(Sa,{tinode:this.tinode,connected:this.state.connected,displayMobile:this.state.displayMobile,topic:this.state.topicSelected,searchableContacts:this.state.searchableContacts,myUserId:this.state.myUserId,panel:this.state.infoPanel,errorText:this.state.errorText,errorLevel:this.state.errorLevel,errorAction:this.state.errorAction,errorActionText:this.state.errorActionText,onNavigate:this.infoNavigator,onTopicDescUpdateRequest:this.handleTopicUpdateRequest,onShowAlert:this.handleShowAlert,onChangePermissions:this.handleChangePermissions,onMemberUpdateRequest:this.handleMemberUpdateRequest,onDeleteTopic:this.handleDeleteTopicRequest,onDeleteMessages:this.handleDeleteMessagesRequest,onLeaveTopic:this.handleLeaveUnsubRequest,onBlockTopic:this.handleBlockTopicRequest,onReportTopic:this.handleReportTopic,onAddMember:this.handleManageGroupMembers,onTopicTagsUpdateRequest:this.handleTagsUpdateRequest,onTopicUnArchive:this.handleUnarchive,onInitFind:this.tnInitFind,onError:this.handleError,showContextMenu:this.handleShowContextMenu}):null)}}const Ki=(0,a.injectIntl)(Zi);if("undefined"!=typeof FIREBASE_INIT&&FIREBASE_INIT&&FIREBASE_INIT.measurementId){const tn=document.getElementsByTagName("head")[0];let sn=document.createElement("script");function an(){dataLayer.push(arguments)}sn.src="https://www.googletagmanager.com/gtag/js?id="+FIREBASE_INIT.measurementId,sn.async=!0,tn.prepend(sn),window.dataLayer=window.dataLayer||[],an("js",new Date),an("config",FIREBASE_INIT.measurementId)}const $i={de:e=>o.e(92).then(o.t.bind(o,6092,19)),en:e=>o.e(514).then(o.t.bind(o,4514,19)),es:e=>o.e(932).then(o.t.bind(o,9932,19)),fr:e=>o.e(107).then(o.t.bind(o,107,19)),ko:e=>o.e(898).then(o.t.bind(o,898,19)),ro:e=>o.e(817).then(o.t.bind(o,4817,19)),ru:e=>o.e(734).then(o.t.bind(o,3734,19)),zh:e=>o.e(700).then(o.t.bind(o,5700,19)),"zh-TW":e=>o.e(226).then(o.t.bind(o,5226,19))},{params:Gi}=si.Z.parseUrlHash(window.location.hash),Qi=Gi&&Gi.hl||navigator.languages&&navigator.languages[0]||navigator.language||navigator.userLanguage||"en",Xi=Qi.replace("_","-"),Yi=Xi.split("-")[0].toLowerCase(),Ji=$i[Xi]?Qi:$i[Yi]?Yi:"en";document.getElementsByTagName("html")[0].setAttribute("lang",Ji);const en=(0,s.s)(document.getElementById("mountPoint"));$i[Ji]().then((e=>en.render(t().createElement(a.IntlProvider,{locale:Qi,messages:e,textComponent:t().Fragment},t().createElement(Ki,null)))))})()})();
+(()=>{"use strict";var e,t,s,a,i={8962:(e,t,s)=>{s.d(t,{$_:()=>k,$h:()=>i,EI:()=>P,FX:()=>H,GQ:()=>S,H2:()=>_,Hm:()=>w,IX:()=>v,JG:()=>r,Mv:()=>o,NW:()=>q,RK:()=>u,Rc:()=>n,S8:()=>A,S9:()=>j,VL:()=>d,Zd:()=>D,Zf:()=>O,cG:()=>h,cl:()=>x,dm:()=>N,gD:()=>I,iC:()=>a,kd:()=>C,l8:()=>c,li:()=>B,ly:()=>T,mc:()=>l,nT:()=>U,o6:()=>f,pM:()=>p,rV:()=>R,rX:()=>L,sA:()=>E,uv:()=>b,vX:()=>F,wO:()=>y,xt:()=>m,yW:()=>M,yl:()=>g});const a="TinodeWeb/"+(s(3119).l||"0.21"),i="AQEAAAABAAD_rAp4DJh05a1HAwFT3A6K",n={hosted:"web.tinode.co",local:"localhost:6060"},o=n.hosted,r=!0,l=3e3,c=1500,d=2,h=96,p=16,u="JRWPS",m="N",g=640,f=13,v=384,b=4096,E=32,y=128,w=24,C=262144,S=1<<23,M=1024,_=64,T=96,k=36,D=48,N=4,A=60,P=360,I=20,R=80,x=30,F=84,U=48,L=2e3,O=6e5,B="mailto:support@tinode.co",q="https://tinode.co/privacy.html",j="https://tinode.co/terms.html",H=!1},8405:(e,t,s)=>{s.d(t,{DC:()=>u,EA:()=>l,Id:()=>c,JG:()=>g,Jr:()=>m,PD:()=>n,Y:()=>p,ay:()=>f,rS:()=>o,sT:()=>d,w8:()=>h});const a=["image/jpeg","image/gif","image/png","image/svg","image/svg+xml"],i=["jpg","gif","png","svg","svg"];function n(e){if(e&&"object"==typeof e){if(e.ref)return e.ref;if(e.data&&e.type){return"data:"+(e.type.startsWith("image/")?e.type:"image/"+e.type)+";base64,"+e.data}}return null}function o(e,t,s,a,i){if(t|=0,s|=0,a|=0,(e|=0)<=0||t<=0||s<=0||a<=0)return null;i&&(s=a=Math.min(s,a));const n=Math.min(Math.min(e,s)/e,Math.min(t,a)/t),o={dstWidth:e*n|0,dstHeight:t*n|0};return i?(o.dstWidth=o.dstHeight=Math.min(o.dstWidth,o.dstHeight),o.srcWidth=o.srcHeight=Math.min(e,t),o.xoffset=(e-o.srcWidth)/2|0,o.yoffset=(t-o.srcWidth)/2|0):(o.xoffset=o.yoffset=0,o.srcWidth=e,o.srcHeight=t),o}function r(e,t){const s=a.indexOf(t);if(s<0||!e)return e;const n=i[s],o=e.lastIndexOf(".");return o>=0&&(e=e.substring(0,o)),e+"."+n}function l(e,t,s,i,n){return new Promise(((l,c)=>{const d=new Image;d.crossOrigin="Anonymous",d.onerror=function(e){c(new Error("Image format unrecognized"))},d.onload=async function(){URL.revokeObjectURL(d.src);const h=o(d.width,d.height,t,s,n);if(!h)return void c(new Error("Invalid image"));let p=document.createElement("canvas");p.width=h.dstWidth,p.height=h.dstHeight;let u=p.getContext("2d");u.imageSmoothingEnabled=!0,u.drawImage(d,h.xoffset,h.yoffset,h.srcWidth,h.srcHeight,0,0,h.dstWidth,h.dstHeight);const m=a.includes(e.type)?e.type:"image/jpeg";let g=await new Promise((e=>p.toBlob(e,m)));if(g){for(;i>0&&g.length>i;)h.dstWidth=.70710678118*h.dstWidth|0,h.dstHeight=.70710678118*h.dstHeight|0,p.width=h.dstWidth,p.height=h.dstHeight,u=p.getContext("2d"),u.clearRect(0,0,p.width,p.height),u.drawImage(d,h.xoffset,h.yoffset,h.srcWidth,h.srcHeight,0,0,h.dstWidth,h.dstHeight),g=await new Promise((e=>p.toBlob(e,m)));p=null,l({mime:m,blob:g,width:h.dstWidth,height:h.dstHeight,name:r(e.name,m)})}else c(new Error("Unsupported image format"))},d.src=URL.createObjectURL(e)}))}function c(e,t,s,i,n,o,r){return new Promise(((l,c)=>{const d=new Image;d.crossOrigin="Anonymous",d.onerror=e=>{c(new Error("Image format unrecognized"))},d.onload=t=>{URL.revokeObjectURL(d.src);let h=document.createElement("canvas");h.width=n*r,h.height=o*r;let p=h.getContext("2d");p.imageSmoothingEnabled=!0,p.drawImage(d,s,i,n,o,0,0,h.width,h.height),e=a.includes(e)?e:"image/jpeg",h.toBlob((t=>{h=null,t?l({mime:e,blob:t,width:n,height:o}):c(new Error("Unsupported image format"))}),e)},d.src=t}))}function d(e){return new Promise(((t,s)=>{const a=new FileReader;a.onerror=e=>{s(a.error)},a.onload=s=>{t({mime:e.type,bits:a.result.split(",")[1],name:e.name})},a.readAsDataURL(e)}))}function h(e){return new Promise(((t,s)=>{const a=new FileReader;a.onerror=e=>{s(a.error)},a.onload=s=>{t({mime:e.type,bits:a.result.split(",")[1]})},a.readAsDataURL(e)}))}function p(e,t,s,a){const i=(e.clipboardData||e.originalEvent.clipboardData||{}).items;if(!i||!i.length)return!1;for(let e in i){const n=i[e];if("file"===n.kind){const e=n.getAsFile();if(!e){console.error("Failed to get file object from pasted file item",n.kind,n.type),a("Failed to get file object from pasted file item");continue}return e.type&&"image"==e.type.split("/")[0]?t(e):s(e),!0}}return!1}function u(e){if(e){e=e.replace(/-/g,"+").replace(/_/g,"/");try{e=btoa(atob(e))}catch(t){console.error("Failed to base64 re-encode string.",t),e=null}}return e}function m(e,t){if(!e)return null;try{const s=atob(e),a=s.length,i=new ArrayBuffer(a),n=new Uint8Array(i);for(let e=0;et+=String.fromCharCode(e))),window.btoa(t)}catch(e){}return null}function f(e){const t=[];try{return[...window.atob(e)].forEach((e=>{t.push(e.charCodeAt(0))})),t}catch(e){}return null}},320:(e,t,s)=>{s.d(t,{Z:()=>a});class a{static setObject(e,t){localStorage.setItem(e,JSON.stringify(t))}static getObject(e){const t=localStorage.getItem(e);return t&&JSON.parse(t)}static updateObject(e,t){const s=this.getObject(e);this.setObject(e,Object.assign(s||{},t))}static removeItem(e){localStorage.removeItem(e)}}},5030:(e,t,s)=>{s.d(t,{Z:()=>a});class a{static parseUrlHash(e){const t=e.split("?",2),s={};let a=[];return t[0]&&(a=t[0].replace("#","").split("/")),t[1]&&t[1].split("&").forEach((e=>{const t=e.indexOf("=");t>0&&(s[e.slice(0,t)]=decodeURIComponent(e.slice(t+1)))})),{path:a,params:s}}static navigateTo(e){window.location.hash=e}static composeUrlHash(e,t){let s=e.join("/");const a=[];for(const e in t)t.hasOwnProperty(e)&&a.push(e+"="+encodeURIComponent(t[e]));return a.length>0&&(s+="?"+a.join("&")),s}static addUrlParam(e,t,s){const i=a.parseUrlHash(e);return i.params[t]=s,a.composeUrlHash(i.path,i.params)}static removeUrlParam(e,t){const s=a.parseUrlHash(e);return delete s.params[t],a.composeUrlHash(s.path,s.params)}static setUrlSidePanel(e,t){const s=a.parseUrlHash(e);return s.path[0]=t,a.composeUrlHash(s.path,s.params)}static setUrlInfoPanel(e,t){const s=a.parseUrlHash(e);return t?s.params.info=t:delete s.params.info,a.composeUrlHash(s.path,s.params)}static setUrlTopic(e,t){const s=a.parseUrlHash(e);return s.path[1]=t,delete s.params.info,a.composeUrlHash(s.path,s.params)}}},3905:(e,t,s)=>{function a(e,t){t=t||window.navigator.userLanguage||window.navigator.language;const s=new Date;return e.getFullYear()==s.getFullYear()?e.getMonth()==s.getMonth()&&e.getDate()==s.getDate()?e.toLocaleTimeString(t,{hour12:!1,hour:"2-digit",minute:"2-digit"}):e.toLocaleDateString(t,{hour12:!1,month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):e.toLocaleDateString(t,{year:"numeric",month:"short",day:"numeric"})}function i(e,t){t=t||window.navigator.userLanguage||window.navigator.language;const s=new Date,a=Math.floor((e.getTime()-6e4*e.getTimezoneOffset())/864e5)-Math.floor((s.getTime()-6e4*s.getTimezoneOffset())/864e5);return Math.abs(a)<2?new Intl.RelativeTimeFormat(t,{numeric:"auto"}).format(a,"day"):new Intl.DateTimeFormat(t).format(e)}function n(e,t){if("number"!=typeof e)return"";let s=(0|Math.floor(e/60))%60,a=0|Math.floor(e/3600);(t||a>0)&&(s=s<10?`0${s}`:s);let i=(0|e)%60;return i=i<10?`0${i}`:i,0==a?`${s}:${i}`:`${a}:${s}:${i}`}function o(e){if(!e||0==e)return"0 Bytes";const t=["Bytes","KB","MB","GB","TB","PB"],s=Math.min(0|Math.floor(Math.log2(e)/10),t.length-1),a=e/Math.pow(1024,s),i=s>0?a<3?2:a<30?1:0:0;return a.toFixed(i)+" "+t[s]}function r(e,t){return"string"!=typeof e?e:e.length>t?e.slice(0,t/2-1)+"…"+e.slice(1-t/2):e}function l(e,t,s){return(t?"lt-":"dk-")+(s?"fg-":"bg-")+(a=e,Math.abs(function(e){let t=0;e=""+e;for(let s=0;s
"},{type:0,value:"¯∖_(ツ)_/¯"}]},(e=>t().createElement(zs,{tinode:this.props.tinode,connected:this.props.connected,contacts:this.state.contactList,emptyListMessage:e,topicSelected:this.props.topicSelected,myUserId:this.props.myUserId,showOnline:!0,showUnread:!0,onTopicSelected:this.props.onTopicSelected,showContextMenu:this.props.showContextMenu,onAction:this.handleAction})))}}class gi extends t().PureComponent{constructor(e){super(e),this.handleCheckboxClick=this.handleCheckboxClick.bind(this)}handleCheckboxClick(e,t){"sound"==e?this.props.onToggleMessageSounds(t):"alert"==e?this.props.onTogglePushNotifications(t):"incognito"==e&&this.props.onToggleIncognitoMode(t)}render(){return t().createElement("div",{className:"scrollable-panel"},t().createElement("div",{className:"panel-form-row"},t().createElement("label",{htmlFor:"message-sound"},t().createElement(a.FormattedMessage,{id:"label_message_sound",defaultMessage:[{type:0,value:"Message sound:"}]})),t().createElement(ta.Z,{name:"sound",id:"message-sound",checked:this.props.messageSounds,onChange:this.handleCheckboxClick})),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{htmlFor:"desktop-alerts"},this.props.desktopAlertsEnabled?t().createElement(a.FormattedMessage,{id:"label_push_notifications",defaultMessage:[{type:0,value:"Notification alerts:"}]}):t().createElement(a.FormattedMessage,{id:"label_push_notifications_disabled",defaultMessage:[{type:0,value:"Notification alerts (requires HTTPS):"}]})),t().createElement(ta.Z,{name:"alert",id:"desktop-alerts",checked:this.props.desktopAlerts,onChange:this.props.desktopAlertsEnabled?this.handleCheckboxClick:null})),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{htmlFor:"incognito-mode"},t().createElement(a.FormattedMessage,{id:"label_incognito_mode",defaultMessage:[{type:0,value:"Incognito mode:"}]})),t().createElement(ta.Z,{name:"incognito",id:"incognito-mode",checked:this.props.incognitoMode,onChange:this.handleCheckboxClick})))}}const fi=(0,a.defineMessages)({delete_account:{id:"delete_account",defaultMessage:[{type:0,value:"Delete account"}]},delete_account_warning:{id:"delete_account_warning",defaultMessage:[{type:0,value:"Are you sure you want to delete your account? It cannot be undone."}]}});class vi extends t().Component{constructor(e){super(e);const t=this.props.tinode.getMeTopic();let s=0;t.contacts((e=>{e.acs&&!e.acs.isJoiner()&&s++}));const a=t.getDefaultAccess();this.state={auth:a?a.auth:null,anon:a?a.anon:null,showPermissionEditorFor:void 0,blockedCount:s},this.handlePasswordUpdate=this.handlePasswordUpdate.bind(this),this.handleLaunchPermissionsEditor=this.handleLaunchPermissionsEditor.bind(this),this.handleHidePermissionsEditor=this.handleHidePermissionsEditor.bind(this),this.handlePermissionsChanged=this.handlePermissionsChanged.bind(this),this.handleDeleteAccount=this.handleDeleteAccount.bind(this)}handlePasswordUpdate(e){this.setState({password:e}),this.props.onUpdatePassword(e)}handleLaunchPermissionsEditor(e){this.setState({showPermissionEditorFor:e,editedPermissions:this.state[e]})}handleHidePermissionsEditor(){this.setState({showPermissionEditorFor:void 0})}handlePermissionsChanged(e){let t={};t[this.state.showPermissionEditorFor]=e,this.props.onUpdateAccountDesc("me",void 0,void 0,t);let s={showPermissionEditorFor:void 0};s[this.state.showPermissionEditorFor]=e,this.setState(s)}handleDeleteAccount(e){e.preventDefault();const{formatMessage:t}=this.props.intl;this.props.onShowAlert(t(fi.delete_account),t(fi.delete_account_warning),(e=>this.props.onDeleteAccount()),null,!0,null)}render(){return t().createElement(t().Fragment,null,this.state.showPermissionEditorFor?t().createElement(ha,{mode:this.state.editedPermissions,skip:"O",onSubmit:this.handlePermissionsChanged,onCancel:this.handleHidePermissionsEditor}):t().createElement("div",{className:"scrollable-panel"},t().createElement("div",{className:"panel-form-column"},t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_password",defaultMessage:[{type:0,value:"Password"}]})),t().createElement("div",null,t().createElement(a.FormattedMessage,{id:"password_unchanged_prompt",defaultMessage:[{type:0,value:"Unchanged"}]},(e=>t().createElement(ma,{placeholder:e,type:"password",onFinished:this.handlePasswordUpdate}))))),t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-column"},t().createElement("a",{href:"#",className:"danger flat-button",onClick:e=>{e.preventDefault(),this.props.onLogout()}},t().createElement("i",{className:"material-icons"},"exit_to_app")," ",t().createElement(a.FormattedMessage,{id:"button_logout",defaultMessage:[{type:0,value:"Logout"}]})),t().createElement("a",{href:"#",className:"danger flat-button",onClick:e=>{this.handleDeleteAccount(e)}},t().createElement("i",{className:"material-icons"},"delete")," ",t().createElement(a.FormattedMessage,{id:"button_delete_account",defaultMessage:[{type:0,value:"Delete account"}]}))),t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-column"},t().createElement("div",null,t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_default_access_mode",defaultMessage:[{type:0,value:"Default access mode:"}]}))),t().createElement("div",{className:"quoted"},t().createElement("div",null,"Auth: ",t().createElement("tt",{className:"clickable",onClick:this.handleLaunchPermissionsEditor.bind(this,"auth")},this.state.auth)),t().createElement("div",null,"Anon: ",t().createElement("tt",{className:"clickable",onClick:this.handleLaunchPermissionsEditor.bind(this,"anon")},this.state.anon)))),this.state.blockedCount>0?t().createElement(t().Fragment,null,t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-row"},t().createElement("i",{className:"material-icons"},"block")," ",t().createElement("a",{href:"#",className:"gray",onClick:e=>{e.preventDefault(),this.props.onShowBlocked()}},t().createElement(a.FormattedMessage,{id:"blocked_contacts_link",defaultMessage:[{type:0,value:"Blocked contacts ("},{type:1,value:"count"},{type:0,value:")"}],values:{count:this.state.blockedCount}})))):null))}}const bi=(0,a.injectIntl)(vi);class Ei extends t().PureComponent{render(){return t().createElement("div",{className:"scrollable-panel"},t().createElement("div",{className:"panel-form-column"},t().createElement("a",{href:hs.li,className:"flat-button",target:"_blank"},t().createElement("i",{className:"material-icons"},"email")," ",t().createElement(a.FormattedMessage,{id:"link_contact_us",defaultMessage:[{type:0,value:"Contact Us"}]})),t().createElement("a",{href:hs.S9,className:"flat-button",target:"_blank"},t().createElement("i",{className:"material-icons"},"description")," ",t().createElement(a.FormattedMessage,{id:"link_terms_of_service",defaultMessage:[{type:0,value:"Terms of Service"}]})),t().createElement("a",{href:hs.NW,className:"flat-button",target:"_blank"},t().createElement("i",{className:"material-icons"},"policy")," ",t().createElement(a.FormattedMessage,{id:"link_privacy_policy",defaultMessage:[{type:0,value:"Privacy Policy"}]}))),t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-column"},t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_client",defaultMessage:[{type:0,value:"Client:"}]})),hs.iC),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_sdk",defaultMessage:[{type:0,value:"SDK:"}]})),cs.Tinode.getLibrary()),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_server",defaultMessage:[{type:0,value:"Server:"}]})),this.props.serverVersion),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_server_address",defaultMessage:[{type:0,value:"Server address:"}]})),this.props.serverAddress)))}}class yi extends t().Component{constructor(e){super(e),this.state={login:e.login,password:"",hostName:e.serverAddress,saveToken:e.persist},this.handleLoginChange=this.handleLoginChange.bind(this),this.handlePasswordChange=this.handlePasswordChange.bind(this),this.handleToggleSaveToken=this.handleToggleSaveToken.bind(this),this.handleSubmit=this.handleSubmit.bind(this)}handleLoginChange(e){this.setState({login:e.target.value})}handlePasswordChange(e){this.setState({password:e.target.value})}handleToggleSaveToken(){this.props.onPersistenceChange(!this.state.saveToken),this.setState({saveToken:!this.state.saveToken})}handleSubmit(e){e.preventDefault(),this.props.onLogin(this.state.login.trim(),this.state.password.trim())}render(){let e="primary";return this.props.disabled&&(e+=" disabled"),t().createElement("form",{id:"login-form",onSubmit:this.handleSubmit},t().createElement(a.FormattedMessage,{id:"login_prompt",defaultMessage:[{type:0,value:"Login"}]},(e=>t().createElement("input",{type:"text",id:"inputLogin",placeholder:e,autoComplete:"username",autoCorrect:"off",autoCapitalize:"none",value:this.state.login,onChange:this.handleLoginChange,required:!0,autoFocus:!0}))),t().createElement(a.FormattedMessage,{id:"password_prompt",defaultMessage:[{type:0,value:"Password"}]},(e=>t().createElement(ua.Z,{type:"password",id:"inputPassword",placeholder:e,autoComplete:"current-password",value:this.state.password,onChange:this.handlePasswordChange,required:!0}))),t().createElement("div",{className:"panel-form-row"},t().createElement(ta.Z,{id:"save-token",name:"save-token",checked:this.state.saveToken,onChange:this.handleToggleSaveToken}),t().createElement("label",{htmlFor:"save-token"}," ",t().createElement(a.FormattedMessage,{id:"stay_logged_in",defaultMessage:[{type:0,value:"Stay logged in"}]})),t().createElement("a",{href:"#reset"},t().createElement(a.FormattedMessage,{id:"forgot_password_link",defaultMessage:[{type:0,value:"Forgot password?"}]}))),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{className:e,type:"submit"},t().createElement(a.FormattedMessage,{id:"button_sign_in",defaultMessage:[{type:0,value:"Sign in"}]}))))}}const wi=(0,a.defineMessages)({invalid_id:{id:"error_invalid_id",defaultMessage:[{type:0,value:"Invalid ID"}]}});class Ci extends t().PureComponent{constructor(e){super(e),this.state={groupId:""},this.handleChange=this.handleChange.bind(this),this.handleKeyPress=this.handleKeyPress.bind(this),this.handleSubmit=this.handleSubmit.bind(this)}handleChange(e){this.setState({groupId:e.target.value})}handleKeyPress(e){"Enter"===e.key&&this.handleSubmit(e)}handleSubmit(e){if(e.preventDefault(),this.state.groupId){const e=this.state.groupId.trim(),t=e.substr(0,3);e.length>3&&["usr","grp","chn"].includes(t)?this.props.onSubmit(e):this.props.onError(this.props.intl.formatMessage(wi.invalid_id),"err")}}render(){return t().createElement("div",{className:"panel-form"},t().createElement("div",{className:"panel-form-row"},t().createElement(a.FormattedMessage,{id:"group_user_id_prompt",defaultMessage:[{type:0,value:"Group or User ID"}]},(e=>t().createElement("input",{type:"text",placeholder:e,value:this.state.groupId,onChange:this.handleChange,onKeyPress:this.handleKeyPress,required:!0,autoFocus:!0})))),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{className:"primary",onClick:this.handleSubmit},t().createElement(a.FormattedMessage,{id:"button_subscribe",defaultMessage:[{type:0,value:"Subscribe"}]}))))}}const Si=(0,a.injectIntl)(Ci);class Mi extends t().PureComponent{constructor(e){super(e),this.fullName=t().createRef(),this.state={fullName:"",private:"",description:"",imageUrl:null,tags:[],isChannel:!1,newAvatar:null,newAvatarMime:null},this.handleFieldEdit=this.handleFieldEdit.bind(this),this.handleImageChanged=this.handleImageChanged.bind(this),this.handleAvatarCropped=this.handleAvatarCropped.bind(this),this.handleAvatarCropCancel=this.handleAvatarCropCancel.bind(this),this.uploadAvatar=this.uploadAvatar.bind(this),this.handleTagsChanged=this.handleTagsChanged.bind(this),this.handleChannelToggle=this.handleChannelToggle.bind(this),this.handleSubmit=this.handleSubmit.bind(this)}componentDidMount(){}handleFieldEdit(e,t){this.setState({[e]:t.target.value||""})}handleImageChanged(e,t){this.setState({newAvatar:t,newAvatarMime:e})}handleAvatarCropped(e,t,s,a){const i=t?URL.createObjectURL(t):null;this.setState({imageUrl:i,newAvatar:null,newAvatarMime:null}),t&&this.uploadAvatar(e,t,s,a)}handleAvatarCropCancel(){this.setState({newAvatar:null,newAvatarMime:null})}uploadAvatar(e,t,s,a){const i=e=>{let{mime:t,blob:s}=e;if(s.size>hs.uv){this.props.tinode.getLargeFileHelper().upload(s).then((e=>this.setState({imageUrl:e}))).catch((e=>this.props.onError(e.message,"err")))}else(0,ks.w8)(s).then((e=>this.setState({imageUrl:(0,ks.PD)({data:e.bits,type:t})})))};s>hs.IX||a>hs.IX||s!=a?(0,ks.EA)(t,hs.IX,hs.IX,hs.GQ,!0).then((e=>i(e))).catch((e=>this.props.onError(e.message,"err"))):i({mime:e,blob:t,width:s,height:a})}handleTagsChanged(e){this.setState({tags:e})}handleChannelToggle(){this.setState({isChannel:!this.state.isChannel})}handleSubmit(e){e.preventDefault();const t=this.state.fullName.trim().substring(0,hs.S8),s=this.state.private.trim().substring(0,hs.S8),a=this.state.description.trim().substring(0,hs.EI);t&&this.props.onSubmit(t,a,this.state.imageUrl,s,this.state.tags,this.state.isChannel)}render(){if(this.state.newAvatar)return t().createElement(pa.Z,{avatar:this.state.newAvatar,mime:this.state.newAvatarMime,onSubmit:this.handleAvatarCropped,onCancel:this.handleAvatarCropCancel,onError:this.props.onError});let e="primary";return this.props.disabled&&(e+=" disabled"),t().createElement("form",{className:"panel-form",onSubmit:this.handleSubmit},t().createElement("div",{className:"panel-form-column"},t().createElement("center",null,t().createElement(ea.Z,{tinode:this.props.tinode,avatar:this.state.imageUrl,onError:this.props.onError,onImageUpdated:this.handleImageChanged})),t().createElement("div",{className:"group"},t().createElement("label",{className:"small",htmlFor:"new-topic-fn"},t().createElement(a.FormattedMessage,{id:"label_topic_name",defaultMessage:[{type:0,value:"Name"}]})),t().createElement(a.FormattedMessage,{id:"topic_name_editing_placeholder",defaultMessage:[{type:0,value:"Freeform name of the group"}]},(e=>t().createElement("input",{type:"text",id:"new-topic-fn",placeholder:e,ref:this.fullName,value:this.state.fullName,onChange:this.handleFieldEdit.bind(this,"fullName"),autoFocus:!0,required:!0,tabIndex:0})))),t().createElement("div",{className:"group"},t().createElement("label",{className:"small",htmlFor:"new-topic-priv"},t().createElement(a.FormattedMessage,{id:"label_private",defaultMessage:[{type:0,value:"Private comment"}]})),t().createElement(a.FormattedMessage,{id:"private_editing_placeholder",defaultMessage:[{type:0,value:"Visible to you only"}]},(e=>t().createElement("input",{type:"text",id:"new-topic-priv",placeholder:e,value:this.state.private,onChange:this.handleFieldEdit.bind(this,"private"),tabIndex:1})))),t().createElement("div",{className:"group"},t().createElement("label",{className:"small",htmlFor:"new-topic-desc"},t().createElement(a.FormattedMessage,{id:"label_description",defaultMessage:[{type:0,value:"Description"}]})),t().createElement(a.FormattedMessage,{id:"description_editing_placeholder",defaultMessage:[{type:0,value:"Description (optional)"}]},(e=>t().createElement("input",{type:"text",id:"new-topic-desc",placeholder:e,value:this.state.description,onChange:this.handleFieldEdit.bind(this,"description"),tabIndex:2}))))),t().createElement("div",{className:"panel-form-row"},t().createElement(ta.Z,{checked:this.state.isChannel,tabIndex:3,onChange:this.handleChannelToggle})," ",t().createElement("label",{onClick:this.handleChannelToggle},t().createElement(a.FormattedMessage,{id:"channel_prompt",defaultMessage:[{type:0,value:"This is a channel"}]}))),t().createElement(a.FormattedMessage,{id:"title_tag_manager",defaultMessage:[{type:0,value:"Tags (search & discovery)"}]},(e=>t().createElement(ga,{tinode:this.props.tinode,tags:this.state.tags,activated:!0,onTagsChanged:this.handleTagsChanged,tabIndex:4,title:e}))),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{className:e},t().createElement(a.FormattedMessage,{id:"button_create",defaultMessage:[{type:0,value:"Create"}]}))))}}const _i=(0,a.defineMessages)({search_for_contacts:{id:"search_for_contacts",defaultMessage:[{type:0,value:"Use search to find contacts"}]},search_no_results:{id:"search_no_results",defaultMessage:[{type:0,value:"Search returned no results"}]},search_placeholder:{id:"search_placeholder",defaultMessage:[{type:0,value:"List like alice@example.com, +17025550003..."}]}});class Ti extends t().Component{constructor(e){super(e),this.state={tabSelected:"find",searchQuery:null},this.handleTabClick=this.handleTabClick.bind(this),this.handleSearchContacts=this.handleSearchContacts.bind(this),this.handleSearchResultSelected=this.handleSearchResultSelected.bind(this),this.handleNewGroupSubmit=this.handleNewGroupSubmit.bind(this),this.handleGroupByID=this.handleGroupByID.bind(this)}componentDidMount(){this.props.onInitFind()}handleTabClick(e){e.preventDefault(),si.Z.navigateTo(si.Z.addUrlParam(window.location.hash,"tab",e.currentTarget.dataset.id)),this.setState({tabSelected:e.currentTarget.dataset.id})}handleSearchContacts(e){this.props.onSearchContacts(e),this.setState({searchQuery:cs.Tinode.isNullValue(e)?null:e})}handleSearchResultSelected(e){"find"==this.state.tabSelected&&(si.Z.navigateTo(si.Z.removeUrlParam(window.location.hash,"tab")),this.props.onCreateTopic(e))}handleNewGroupSubmit(e,t,s,a,i,n){si.Z.navigateTo(si.Z.removeUrlParam(window.location.hash,"tab")),this.props.onCreateTopic(void 0,{public:(0,Ds.n$)(e,s,null,t),private:a,tags:i},n)}handleGroupByID(e){si.Z.navigateTo(si.Z.removeUrlParam(window.location.hash,"tab")),this.props.onCreateTopic(e)}render(){const{formatMessage:e}=this.props.intl,s=e(this.state.searchQuery?_i.search_no_results:_i.search_for_contacts),i=e(_i.search_placeholder);return t().createElement("div",{className:"flex-column"},t().createElement("ul",{className:"tabbar"},t().createElement("li",{className:"find"===this.state.tabSelected?"active":null},t().createElement("a",{href:"#","data-id":"find",onClick:this.handleTabClick},t().createElement(a.FormattedMessage,{id:"tabtitle_find_user",defaultMessage:[{type:0,value:"find"}]}))),t().createElement("li",{className:"grp"===this.state.tabSelected?"active":null},t().createElement("a",{href:"#","data-id":"grp",onClick:this.handleTabClick},t().createElement(a.FormattedMessage,{id:"tabtitle_new_group",defaultMessage:[{type:0,value:"new group"}]}))),t().createElement("li",{className:"byid"===this.state.tabSelected?"active":null},t().createElement("a",{href:"#","data-id":"byid",onClick:this.handleTabClick},t().createElement(a.FormattedMessage,{id:"tabtitle_group_by_id",defaultMessage:[{type:0,value:"by id"}]})))),"grp"===this.state.tabSelected?t().createElement(Mi,{tinode:this.props.tinode,onSubmit:this.handleNewGroupSubmit,onError:this.props.onError}):"byid"===this.state.tabSelected?t().createElement(Si,{onSubmit:this.handleGroupByID,onError:this.props.onError}):t().createElement("div",{className:"flex-column"},t().createElement(Zs,{placeholder:i,onSearchContacts:this.handleSearchContacts}),t().createElement(zs,{tinode:this.props.tinode,contacts:this.props.searchResults,myUserId:this.props.myUserId,emptyListMessage:s,showOnline:!1,showUnread:!1,showContextMenu:!1,onTopicSelected:this.handleSearchResultSelected})))}}const ki=(0,a.injectIntl)(Ti);class Di extends t().PureComponent{constructor(e){super(e),this.state={hostName:e.serverAddress,changed:!1},this.handleHostNameChange=this.handleHostNameChange.bind(this),this.handleEditingFinished=this.handleEditingFinished.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this)}handleHostNameChange(e){this.setState({hostName:e.target.value,changed:!0})}handleEditingFinished(){this.state.changed&&(this.setState({changed:!1}),this.props.onServerAddressChange(this.state.hostName.trim()))}handleKeyDown(e){"Enter"==e.key&&this.handleEditingFinished()}render(){const e=[];for(let s in hs.Rc){let a=hs.Rc[s];e.push(t().createElement("option",{key:a,value:a}))}return t().createElement("div",{className:"panel-form-row"},t().createElement("input",{type:"search",id:"host-name",placeholder:this.props.hostName,list:"known-hosts",className:"quoted",value:this.state.hostName,onChange:this.handleHostNameChange,onBlur:this.handleEditingFinished,onKeyDown:this.handleKeyDown,required:!0}),t().createElement("datalist",{id:"known-hosts"},e))}}class Ni extends t().PureComponent{constructor(e){super(e),this.state={transport:e.transport||"def",serverAddress:e.serverAddress,secureConnection:e.secureConnection},this.handleSubmit=this.handleSubmit.bind(this),this.handleTransportSelected=this.handleTransportSelected.bind(this),this.handleServerAddressChange=this.handleServerAddressChange.bind(this),this.handleToggleSecure=this.handleToggleSecure.bind(this)}handleSubmit(e){e.preventDefault(),this.props.onUpdate({transport:this.state.transport,serverAddress:this.state.serverAddress,secureConnection:this.state.secureConnection})}handleTransportSelected(e){this.setState({transport:e.currentTarget.value})}handleServerAddressChange(e){this.setState({serverAddress:e})}handleToggleSecure(e){this.setState({secureConnection:!this.state.secureConnection})}render(){const e={def:"default",ws:"websocket",lp:"long polling"},s=[];return["def","ws","lp"].forEach((a=>{const i="transport-"+a,n=e[a];s.push(t().createElement("li",{key:a},t().createElement("input",{type:"radio",id:i,name:"transport-select",value:a,checked:this.state.transport===a,onChange:this.handleTransportSelected}),t().createElement("label",{htmlFor:i},n)))})),t().createElement("form",{id:"settings-form",className:"panel-form",onSubmit:this.handleSubmit},t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_server_to_use",defaultMessage:[{type:0,value:"Server to use:"}]}))),t().createElement(Di,{serverAddress:this.state.serverAddress,onServerAddressChange:this.handleServerAddressChange}),t().createElement("div",{className:"panel-form-row"},t().createElement(ta.Z,{id:"secure-connection",name:"secure-connection",checked:this.state.secureConnection,className:"quoted",onChange:this.handleToggleSecure}),t().createElement("label",{htmlFor:"secure-connection"},t().createElement(a.FormattedMessage,{id:"label_use_secure_connection",defaultMessage:[{type:0,value:"Use secure connection"}]}))),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(a.FormattedMessage,{id:"label_wire_transport",defaultMessage:[{type:0,value:"Wire transport:"}]}))),t().createElement("div",{className:"panel-form-row"},t().createElement("ul",{className:"quoted"},s)),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{type:"submit",className:"primary"},t().createElement(a.FormattedMessage,{id:"button_update",defaultMessage:[{type:0,value:"Update"}]}))))}}const Ai=(0,a.defineMessages)({phone:{id:"phone_dative",defaultMessage:[{type:0,value:"phone"}]},email:{id:"email_dative",defaultMessage:[{type:0,value:"email"}]}});class Pi extends t().PureComponent{constructor(e){super(e),this.state={code:e.credCode||"",codeReceived:e.credCode},this.handleCodeChange=this.handleCodeChange.bind(this),this.handleKeyPress=this.handleKeyPress.bind(this),this.handleSubmit=this.handleSubmit.bind(this),this.handleCancel=this.handleCancel.bind(this)}static getDerivedStateFromProps(e,t){return e.credCode!=t.codeReceived?{code:e.credCode||"",codeReceived:e.credCode}:t}componentDidMount(){this.props.credCode&&this.props.onSubmit(this.props.credMethod,this.props.credCode,this.props.credToken)}componentDidUpdate(e,t){this.state.codeReceived&&this.state.code&&this.state.code!=t.code&&this.props.onSubmit(this.props.credMethod,this.state.code,this.props.credToken)}handleCodeChange(e){this.setState({code:e.target.value.replace(/[^\d]/g,"")})}handleKeyPress(e){"Enter"===e.key?this.handleSubmit(e):"Escape"==e.key&&this.handleCancel(e)}handleSubmit(e){e.preventDefault(),this.state.code&&this.state.code.trim()&&this.props.onSubmit(this.props.credMethod,this.state.code.trim(),this.props.credToken)}handleCancel(e){e.preventDefault(),this.props.onCancel()}render(){const{formatMessage:e}=this.props.intl,s={email:e(Ai.email),tel:e(Ai.phone)}[this.props.credMethod]||this.props.credMethod;return t().createElement("div",{className:"panel-form"},t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small gray",htmlFor:"enter-confirmation-code"},t().createElement(a.FormattedMessage,{id:"enter_confirmation_code_prompt",defaultMessage:[{type:0,value:"Confirmation code"}],values:{method:s}}))),t().createElement("div",{className:"panel-form-row"},t().createElement(a.FormattedMessage,{id:"numeric_confirmation_code_prompt",defaultMessage:[{type:0,value:"Numbers only"}]},(e=>t().createElement("input",{type:"text",id:"enter-confirmation-code",placeholder:e,value:this.state.code,onChange:this.handleCodeChange,onKeyPress:this.handleKeyPress,required:!0})))),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{className:"secondary",onClick:this.handleCancel},t().createElement(a.FormattedMessage,{id:"button_cancel",defaultMessage:[{type:0,value:"Cancel"}]})),t().createElement("button",{className:"primary",onClick:this.handleSubmit},t().createElement(a.FormattedMessage,{id:"button_confirm",defaultMessage:[{type:0,value:"Confirm"}]}))))}}const Ii=(0,a.injectIntl)(Pi),Ri=t().lazy((e=>Promise.all([o.e(203),o.e(365)]).then(o.bind(o,1365)))),xi=t().lazy((e=>Promise.all([o.e(203),o.e(327)]).then(o.bind(o,327)))),Fi=t().lazy((e=>Promise.all([o.e(203),o.e(311)]).then(o.bind(o,1311)))),Ui=(0,a.defineMessages)({login:{id:"sidepanel_title_login",defaultMessage:[{type:0,value:"Sign In"}]},register:{id:"sidepanel_title_register",defaultMessage:[{type:0,value:"Create Account"}]},settings:{id:"sidepanel_title_settings",defaultMessage:[{type:0,value:"Settings"}]},edit:{id:"sidepanel_title_account_settings",defaultMessage:[{type:0,value:"Account Settings"}]},general:{id:"panel_title_general",defaultMessage:[{type:0,value:"General"}]},security:{id:"panel_title_security",defaultMessage:[{type:0,value:"Security"}]},crop:{id:"panel_title_crop",defaultMessage:[{type:0,value:"Drag to Adjust"}]},notif:{id:"sidepanel_title_acc_notifications",defaultMessage:[{type:0,value:"Notifications"}]},support:{id:"sidepanel_title_acc_support",defaultMessage:[{type:0,value:"Support"}]},newtpk:{id:"sidepanel_title_newtpk",defaultMessage:[{type:0,value:"Start New Chat"}]},cred:{id:"sidepanel_title_cred",defaultMessage:[{type:0,value:"Confirm Credentials"}]},reset:{id:"sidepanel_title_reset",defaultMessage:[{type:0,value:"Reset Password"}]},archive:{id:"sidepanel_title_archive",defaultMessage:[{type:0,value:"Archived Chats"}]},blocked:{id:"sidepanel_title_blocked",defaultMessage:[{type:0,value:"Blocked Chats"}]}});class Li extends t().PureComponent{constructor(e){super(e),this.handleNewTopic=this.handleNewTopic.bind(this)}handleNewTopic(){this.props.onNavigate("newtpk")}render(){const{formatMessage:s}=this.props.intl,i=this.props.state||(this.props.myUserId?"contacts":"login");let n,o,r,l;return"contacts"==i?(n=this.props.title,o=!this.props.avatar||this.props.avatar,r=this.props.trustedBadges):(n=s(Ui[i]),o=!1,r=null),-1==["login","contacts"].indexOf(i)&&(l=this.props.onCancel),t().createElement("div",{id:"sidepanel"},t().createElement(pi,{state:i,title:n,avatar:o,tinode:this.props.tinode,trustedBadges:r,myUserId:this.props.myUserId,onSignUp:this.props.onSignUp,onSettings:this.props.onSettings,onNewTopic:this.handleNewTopic,onCancel:l}),t().createElement(aa,{level:this.props.errorLevel,text:this.props.errorText,action:this.props.errorAction,actionText:this.props.errorActionText,onClearError:this.props.onError}),t().createElement($a.Z,{show:this.props.loadSpinnerVisible}),"login"===i?t().createElement(yi,{login:this.props.login,disabled:this.props.loginDisabled,persist:this.props.persist,onLogin:this.props.onLoginRequest,onPersistenceChange:this.props.onPersistenceChange}):"register"===i?t().createElement(e.Suspense,{fallback:t().createElement("div",{className:"panel-form-row"},t().createElement(a.FormattedMessage,{id:"loading_note",defaultMessage:[{type:0,value:"Loading..."}]}))},t().createElement(xi,{tinode:this.props.tinode,reqCredMethod:this.props.reqCredMethod,onShowCountrySelector:this.props.onShowCountrySelector,onCreateAccount:this.props.onCreateAccount,onCancel:this.props.onCancel,onError:this.props.onError})):"settings"===i?t().createElement(Ni,{transport:this.props.transport,serverAddress:this.props.serverAddress,secureConnection:this.props.secureConnection,onCancel:this.props.onCancel,onUpdate:this.props.onGlobalSettings}):"edit"===i?t().createElement(e.Suspense,{fallback:t().createElement("div",{className:"panel-form-row"},t().createElement(a.FormattedMessage,{id:"loading_note",defaultMessage:[{type:0,value:"Loading..."}]}))},t().createElement(Ri,{tinode:this.props.tinode,myUserId:this.props.myUserId,trustedBadges:this.props.trustedBadges,onShowCountrySelector:this.props.onShowCountrySelector,onNavigate:this.props.onNavigate,onCredAdd:this.props.onCredAdd,onCredDelete:this.props.onCredDelete,onCredConfirm:this.props.onCredConfirm,onError:this.props.onError})):"general"===i||"crop"===i?t().createElement(va,{topic:"me",tinode:this.props.tinode,myUserId:this.props.myUserId,reqCredMethod:this.props.reqCredMethod,onUpdateTopicDesc:this.props.onUpdateAccountDesc,onUpdateTagsRequest:this.props.onUpdateAccountTags,onError:this.props.onError}):"notif"===i?t().createElement(gi,{messageSounds:this.props.messageSounds,desktopAlerts:this.props.desktopAlerts,desktopAlertsEnabled:this.props.desktopAlertsEnabled,incognitoMode:this.props.incognitoMode,onTogglePushNotifications:this.props.onTogglePushNotifications,onToggleMessageSounds:this.props.onToggleMessageSounds,onToggleIncognitoMode:this.props.onToggleIncognitoMode}):"security"===i?t().createElement(bi,{tinode:this.props.tinode,onUpdateAccountDesc:this.props.onUpdateAccountDesc,onUpdatePassword:this.props.onUpdatePassword,onLogout:this.props.onLogout,onDeleteAccount:this.props.onDeleteAccount,onShowAlert:this.props.onShowAlert,onShowBlocked:this.props.onShowBlocked}):"support"===i?t().createElement(Ei,{serverAddress:this.props.serverAddress,serverVersion:this.props.serverVersion}):"contacts"===i||"archive"==i||"blocked"==i?t().createElement(mi,{tinode:this.props.tinode,myUserId:this.props.myUserId,connected:this.props.connected,topicSelected:this.props.topicSelected,archive:"archive"==i,blocked:"blocked"==i,chatList:this.props.chatList,showContextMenu:this.props.showContextMenu,onTopicSelected:this.props.onTopicSelected,onShowArchive:this.props.onShowArchive}):"newtpk"===i?t().createElement(ki,{tinode:this.props.tinode,searchResults:this.props.searchResults,onInitFind:this.props.onInitFind,onSearchContacts:this.props.onSearchContacts,onCreateTopic:this.props.onCreateTopic,onError:this.props.onError}):"cred"===i?t().createElement(Ii,{credCode:this.props.credCode,credMethod:this.props.credMethod,credToken:this.props.credToken,onSubmit:this.props.onValidateCredentials,onCancel:this.props.onCancel}):"reset"===i?t().createElement(e.Suspense,{fallback:t().createElement("div",{className:"panel-form-row"},t().createElement(a.FormattedMessage,{id:"loading_note",defaultMessage:[{type:0,value:"Loading..."}]}))},t().createElement(Fi,{tinode:this.props.tinode,reqCredMethod:this.props.reqCredMethod,onShowCountrySelector:this.props.onShowCountrySelector,onRequest:this.props.onPasswordResetRequest,onReset:this.props.onResetPassword,onCancel:this.props.onCancel,onError:this.props.onError})):null)}}const Oi=(0,a.injectIntl)(Li);var Bi=o(3119);function qi(){let e=hs.Mv;return"object"==typeof window.location&&("file:"==window.location.protocol||"localhost"==window.location.hostname?e=hs.Rc.local:window.location.hostname&&(e=window.location.hostname+(window.location.port?":"+window.location.port:""))),e}function ji(){return"object"==typeof window.location&&"https:"==window.location.protocol}var Hi=o(320);const Vi=t().lazy((e=>o.e(290).then(o.bind(o,1290)))),Wi=new Audio("audio/msg.m4a"),zi=(0,a.defineMessages)({reconnect_countdown:{id:"reconnect_countdown",defaultMessage:[{type:0,value:"Disconnected. Reconnecting in "},{type:1,value:"seconds"},{type:0,value:"…"}]},reconnect_now:{id:"reconnect_now",defaultMessage:[{type:0,value:"Try now"}]},push_init_failed:{id:"push_init_failed",defaultMessage:[{type:0,value:"Failed to initialize push notifications"}]},invalid_security_token:{id:"invalid_security_token",defaultMessage:[{type:0,value:"Invalid security token"}]},no_connection:{id:"no_connection",defaultMessage:[{type:0,value:"No connection"}]},code_doesnot_match:{id:"code_doesnot_match",defaultMessage:[{type:0,value:"Code does not match"}]},menu_item_info:{id:"menu_item_info",defaultMessage:[{type:0,value:"Info"}]},menu_item_audio_call:{id:"menu_item_audio_call",defaultMessage:[{type:0,value:"Call"}]},menu_item_video_call:{id:"menu_item_video_call",defaultMessage:[{type:0,value:"Video call"}]},cred_confirmed_successfully:{id:"cred_confirmed_successfully",defaultMessage:[{type:0,value:"Confirmed successfully"}]}});class Zi extends t().Component{constructor(e){super(e),this.selfRef=t().createRef(),this.state=this.getBlankState(),this.handleResize=this.handleResize.bind(this),this.handleHashRoute=this.handleHashRoute.bind(this),this.handleOnline=this.handleOnline.bind(this),this.checkForAppUpdate=this.checkForAppUpdate.bind(this),this.handleVisibilityEvent=this.handleVisibilityEvent.bind(this),this.handleError=this.handleError.bind(this),this.handleLoginRequest=this.handleLoginRequest.bind(this),this.handlePersistenceChange=this.handlePersistenceChange.bind(this),this.handleConnected=this.handleConnected.bind(this),this.handleAutoreconnectIteration=this.handleAutoreconnectIteration.bind(this),this.doLogin=this.doLogin.bind(this),this.handleLoginSuccessful=this.handleLoginSuccessful.bind(this),this.handleDisconnect=this.handleDisconnect.bind(this),this.tnMeMetaDesc=this.tnMeMetaDesc.bind(this),this.tnMeContactUpdate=this.tnMeContactUpdate.bind(this),this.tnMeSubsUpdated=this.tnMeSubsUpdated.bind(this),this.resetContactList=this.resetContactList.bind(this),this.tnInitFind=this.tnInitFind.bind(this),this.tnFndSubsUpdated=this.tnFndSubsUpdated.bind(this),this.handleSearchContacts=this.handleSearchContacts.bind(this),this.handleTopicSelected=this.handleTopicSelected.bind(this),this.handleHideMessagesView=this.handleHideMessagesView.bind(this),this.handleSendMessage=this.handleSendMessage.bind(this),this.handleNewChatInvitation=this.handleNewChatInvitation.bind(this),this.handleNewAccount=this.handleNewAccount.bind(this),this.handleNewAccountRequest=this.handleNewAccountRequest.bind(this),this.handleUpdatePasswordRequest=this.handleUpdatePasswordRequest.bind(this),this.handleUpdateAccountTagsRequest=this.handleUpdateAccountTagsRequest.bind(this),this.handleToggleIncognitoMode=this.handleToggleIncognitoMode.bind(this),this.handleSettings=this.handleSettings.bind(this),this.handleGlobalSettings=this.handleGlobalSettings.bind(this),this.handleShowArchive=this.handleShowArchive.bind(this),this.handleShowBlocked=this.handleShowBlocked.bind(this),this.handleToggleMessageSounds=this.handleToggleMessageSounds.bind(this),this.handleCredAdd=this.handleCredAdd.bind(this),this.handleCredDelete=this.handleCredDelete.bind(this),this.handleCredConfirm=this.handleCredConfirm.bind(this),this.initFCMessaging=this.initFCMessaging.bind(this),this.toggleFCMToken=this.toggleFCMToken.bind(this),this.handlePushMessage=this.handlePushMessage.bind(this),this.handleSidepanelCancel=this.handleSidepanelCancel.bind(this),this.handleStartTopicRequest=this.handleStartTopicRequest.bind(this),this.handleNewTopicCreated=this.handleNewTopicCreated.bind(this),this.handleTopicUpdateRequest=this.handleTopicUpdateRequest.bind(this),this.handleUnarchive=this.handleUnarchive.bind(this),this.handleChangePermissions=this.handleChangePermissions.bind(this),this.handleTagsUpdateRequest=this.handleTagsUpdateRequest.bind(this),this.handleLogout=this.handleLogout.bind(this),this.handleDeleteAccount=this.handleDeleteAccount.bind(this),this.handleDeleteTopicRequest=this.handleDeleteTopicRequest.bind(this),this.handleDeleteMessagesRequest=this.handleDeleteMessagesRequest.bind(this),this.handleLeaveUnsubRequest=this.handleLeaveUnsubRequest.bind(this),this.handleBlockTopicRequest=this.handleBlockTopicRequest.bind(this),this.handleReportTopic=this.handleReportTopic.bind(this),this.handleShowContextMenu=this.handleShowContextMenu.bind(this),this.defaultTopicContextMenu=this.defaultTopicContextMenu.bind(this),this.handleHideContextMenu=this.handleHideContextMenu.bind(this),this.handleShowAlert=this.handleShowAlert.bind(this),this.handleShowInfoView=this.handleShowInfoView.bind(this),this.handleMemberUpdateRequest=this.handleMemberUpdateRequest.bind(this),this.handleValidateCredentialsRequest=this.handleValidateCredentialsRequest.bind(this),this.handlePasswordResetRequest=this.handlePasswordResetRequest.bind(this),this.handleResetPassword=this.handleResetPassword.bind(this),this.handleContextMenuAction=this.handleContextMenuAction.bind(this),this.handleShowCountrySelector=this.handleShowCountrySelector.bind(this),this.handleShowForwardDialog=this.handleShowForwardDialog.bind(this),this.handleHideForwardDialog=this.handleHideForwardDialog.bind(this),this.handleStartVideoCall=this.handleStartVideoCall.bind(this),this.handleStartAudioCall=this.handleStartAudioCall.bind(this),this.handleInfoMessage=this.handleInfoMessage.bind(this),this.handleDataMessage=this.handleDataMessage.bind(this),this.handleCallClose=this.handleCallClose.bind(this),this.handleCallInvite=this.handleCallInvite.bind(this),this.handleCallRinging=this.handleCallRinging.bind(this),this.handleCallHangup=this.handleCallHangup.bind(this),this.handleCallSendOffer=this.handleCallSendOffer.bind(this),this.handleCallIceCandidate=this.handleCallIceCandidate.bind(this),this.handleCallSendAnswer=this.handleCallSendAnswer.bind(this),this.handleCallAccept=this.handleCallAccept.bind(this),this.sendMessageToTopic=this.sendMessageToTopic.bind(this),this.callTimeoutTimer=null}getBlankState(){const e=Hi.Z.getObject("settings")||{},t=!!Hi.Z.getObject("keep-logged-in");return{connected:!1,ready:!1,autoLogin:!1,transport:e.transport||null,serverAddress:e.serverAddress||qi(),secureConnection:void 0===e.secureConnection?ji():e.secureConnection,serverVersion:"no connection",messageSounds:!e.messageSoundsOff,incognitoMode:!1,desktopAlerts:t&&!!e.desktopAlerts,desktopAlertsEnabled:(ji()||"object"==typeof window.location&&"localhost"==window.location.hostname)&&void 0!==de&&"undefined"!=typeof navigator&&"undefined"!=typeof FIREBASE_INIT,firebaseToken:t?Hi.Z.getObject("firebase-token"):null,applicationVisible:!document.hidden,errorText:"",errorLevel:null,errorAction:void 0,errorActionText:null,sidePanelSelected:"login",sidePanelTitle:null,sidePanelAvatar:null,myTrustedBadges:[],loadSpinnerVisible:!1,login:"",password:"",persist:t,myUserId:null,liveConnection:navigator.onLine,topicSelected:"",topicSelectedOnline:!1,topicSelectedAcs:null,newTopicParams:null,loginDisabled:!1,displayMobile:window.innerWidth<=hs.yl,infoPanel:void 0,mobilePanel:"sidepanel",callTopic:void 0,callState:0,callAudioOnly:void 0,callShouldStart:!1,contextMenuVisible:!1,contextMenuBounds:null,contextMenuClickAt:null,contextMenuParams:null,contextMenuItems:[],forwardDialogVisible:!1,forwardMessage:null,alertVisible:!1,alertParams:{},chatList:[],searchResults:[],searchableContacts:[],reqCredMethod:void 0,credMethod:void 0,credCode:void 0,credToken:void 0,requestedTopic:void 0}}componentDidMount(){if(window.addEventListener("resize",this.handleResize),this.handleOnlineOn=e=>{this.handleOnline(!0)},window.addEventListener("online",this.handleOnlineOn),this.handleOnlineOff=e=>{this.handleOnline(!1)},window.addEventListener("offline",this.handleOnlineOff),window.addEventListener("hashchange",this.handleHashRoute),"function"==typeof BroadcastChannel){new BroadcastChannel("tinode-sw").addEventListener("message",this.handlePushMessage)}else console.warn("Your browser does not support BroadcastChannel. Some features will not be available");document.addEventListener("visibilitychange",this.handleVisibilityEvent),this.setState({viewportWidth:document.documentElement.clientWidth,viewportHeight:document.documentElement.clientHeight}),new Promise(((e,t)=>{this.tinode=Zi.tnSetup(this.state.serverAddress,ji(),this.state.transport,this.props.intl.locale,this.state.persist,e),this.tinode.onConnect=this.handleConnected,this.tinode.onDisconnect=this.handleDisconnect,this.tinode.onAutoreconnectIteration=this.handleAutoreconnectIteration,this.tinode.onInfoMessage=this.handleInfoMessage,this.tinode.onDataMessage=this.handleDataMessage})).then((e=>{this.state.desktopAlertsEnabled&&this.initFCMessaging().catch((e=>{})),this.resetContactList();const t=this.state.persist?Hi.Z.getObject("auth-token"):void 0;t&&(this.setState({autoLogin:!0}),t.expires=new Date(t.expires),this.tinode.setAuthToken(t),this.tinode.connect().catch((e=>{this.handleError(e.message,"err")}))),this.readTimer=null,this.readTimerCallback=null;const s=si.Z.parseUrlHash(window.location.hash);if(["cred","reset","register"].includes(s.path[0]))this.handleHashRoute();else{this.setState({requestedTopic:s.path[1]});const e=s.params&&s.params.cred_done?si.Z.addUrlParam("","cred_done",s.params.cred_done):"";si.Z.navigateTo(e)}}))}componentWillUnmount(){window.removeEventListener("resize",this.handleResize),window.removeEventListener("hashchange",this.handleHashRoute),window.removeEventListener("online",this.handleOnlineOn),window.removeEventListener("offline",this.handleOnlineOff),document.removeEventListener("visibilitychange",this.handleVisibilityEvent)}static tnSetup(e,t,s,a,i,n){const o=new cs.Tinode({appName:hs.iC,host:e,apiKey:hs.$h,transport:s,secure:t,persist:i},n);return o.setHumanLanguage(a),o.enableLogging(hs.JG,!0),o}handlePushMessage(e){this.tinode.oobNotification(e.data||{})}initFCMessaging(){const{formatMessage:e,locale:t}=this.props.intl,s=(t,s)=>{console.error(t,s),this.handleError(e(zi.push_init_failed),"err"),this.setState({firebaseToken:null}),Hi.Z.updateObject("settings",{desktopAlerts:!1})};try{return this.fcm=ns(de(FIREBASE_INIT,hs.iC)),navigator.serviceWorker.getRegistration("/service-worker.js").then((e=>e||navigator.serviceWorker.register("/service-worker.js").then((e=>(this.checkForAppUpdate(e),e))))).then((e=>((e.active||e.installing).postMessage(JSON.stringify({locale:t,version:Bi.l})),Zi.requestFCMToken(this.fcm,e)))).then((e=>{const t=Hi.Z.getObject("keep-logged-in");e!=this.state.firebaseToken&&(this.tinode.setDeviceToken(e),t&&Hi.Z.setObject("firebase-token",e)),this.setState({firebaseToken:e,desktopAlerts:!0}),t&&Hi.Z.updateObject("settings",{desktopAlerts:!0}),ls(this.fcm,(e=>{this.handlePushMessage(e)}))})).catch((e=>{throw s(e),e}))}catch(e){return s(e),Promise.reject(e)}}static requestFCMToken(e,t){return os(e,{serviceWorkerRegistration:t,vapidKey:FIREBASE_INIT.messagingVapidKey}).then((t=>{if(t)return t;if("undefined"!=typeof Notification)return Notification.requestPermission().then((t=>{if("granted"===t)return os(e,{serviceWorkerRegistration:reg,vapidKey:FIREBASE_INIT.messagingVapidKey}).then((e=>{if(e)return e;throw new Error("Failed to initialize notifications")}));throw new Error("No permission to send notifications: "+t)}));throw new Error("Notifications are not supported")}))}handleResize(){const e=document.documentElement.clientWidth<=hs.yl;this.setState({viewportWidth:document.documentElement.clientWidth,viewportHeight:document.documentElement.clientHeight}),this.state.displayMobile!=e&&this.setState({displayMobile:e})}checkForAppUpdate(e){e.onupdatefound=s=>{const i=e.installing;i.onstatechange=e=>{if("installed"==i.state&&navigator.serviceWorker.controller){const e=t().createElement(t().Fragment,null,t().createElement(a.FormattedMessage,{id:"update_available",defaultMessage:[{type:0,value:"Update available."}]})," ",t().createElement("a",{href:""},t().createElement(a.FormattedMessage,{id:"reload_update",defaultMessage:[{type:0,value:"Reload"}]})),".");this.handleError(e,"info")}}}}handleHashRoute(){const e=si.Z.parseUrlHash(window.location.hash),t={infoPanel:e.params.info,newTopicTabSelected:e.params.tab};if(e.path&&e.path.length>0){["register","settings","edit","notif","security","support","general","crop","cred","reset","newtpk","archive","blocked","contacts",""].includes(e.path[0])?t.sidePanelSelected=e.path[0]:console.warn("Unknown sidepanel view",e.path[0]);let s=e.path[1]||null;s!=this.state.topicSelected&&(cs.Tinode.topicType(s)?t.mobilePanel="topic-view":(s=null,t.mobilePanel="sidepanel"),Object.assign(t,{topicSelected:s,topicSelectedAcs:this.tinode.getTopicAccessMode(s)}))}else Object.assign(t,{sidePanelSelected:"",topicSelected:null});e.params.method&&(t.credMethod=e.params.method),e.params.code&&(t.credCode=e.params.code),e.params.token&&(t.credToken=e.params.token),e.params.cred_done&&Object.assign(t,Zi.stateForError(this.props.intl.formatMessage(zi.cred_confirmed_successfully),"info")),this.setState(t)}handleOnline(e){e?(this.handleError(),clearInterval(this.reconnectCountdown),this.tinode.reconnect()):this.handleError(this.props.intl.formatMessage(zi.no_connection),"warn"),this.setState({liveConnection:e})}handleVisibilityEvent(){this.setState({applicationVisible:!document.hidden})}static stateForError(e,t,s,a){return{errorText:e,errorLevel:t,errorAction:s,errorActionText:a,callShouldStart:!1}}handleError(e,t,s,a){this.setState(Zi.stateForError(e,t,s,a))}handleLoginRequest(e,t){this.setState({loginDisabled:!0,login:e,password:t,loadSpinnerVisible:!0,autoLogin:!0}),this.handleError("",null),this.tinode.isConnected()?this.doLogin(e,t,null,{meth:this.state.credMethod,resp:this.state.credCode}):this.tinode.connect().catch((e=>{this.setState({loginDisabled:!1,autoLogin:!1,loadSpinnerVisible:!1}),this.handleError(e.message,"err")})),this.state.desktopAlertsEnabled&&!this.state.firebaseToken&&this.initFCMessaging()}handlePersistenceChange(e){e?this.tinode.initStorage().then((e=>{Hi.Z.setObject("keep-logged-in",!0),this.setState({persist:!0})})):this.tinode.clearStorage().then((e=>{Hi.Z.setObject("keep-logged-in",!1),this.setState({persist:!1})}))}handleConnected(){clearInterval(this.reconnectCountdown),this.handleError();const e=this.tinode.getServerInfo();this.setState({serverVersion:e.ver+" "+(e.build?e.build:"none"),reqCredMethod:((e.reqCred||{}).auth||[])[0]||"email"}),this.state.autoLogin&&this.doLogin(this.state.login,this.state.password,null,{meth:this.state.credMethod,resp:this.state.credCode})}handleAutoreconnectIteration(e,t){if(clearInterval(this.reconnectCountdown),e<0)return void this.handleError();if(t)return void t.then((e=>{this.handleError()})).catch((e=>{this.handleError(e.message,"err")}));const{formatMessage:s}=this.props.intl;let a=e/1e3;a|=a,this.reconnectCountdown=setInterval((e=>{if(a<-10)return clearInterval(this.reconnectCountdown),void this.tinode.reconnect();const t=a>99?(0,ys.nH)(a):a;this.handleError(s(zi.reconnect_countdown,{seconds:t}),"warn",(e=>{clearInterval(this.reconnectCountdown),this.tinode.reconnect()}),s(zi.reconnect_now)),a-=1}),1e3)}handleDisconnect(e){this.setState({connected:!1,ready:!1,topicSelectedOnline:!1,errorText:e&&e.message?e.message:"Disconnected",errorLevel:e&&e.message?"err":"warn",loginDisabled:!1,contextMenuVisible:!1,forwardDialogVisible:!1,serverVersion:"no connection"})}doLogin(e,t,s,a){if(this.tinode.isAuthenticated())return void si.Z.navigateTo("");let i=s||(this.tinode.getAuthToken()||{}).token;if(!(e&&t||i))return si.Z.navigateTo(""),void this.setState({loginDisabled:!1});a=cs.Tinode.credential(a);let n,o=this.tinode.isConnected()?Promise.resolve():this.tinode.connect();e&&t?(i=null,this.setState({password:null}),n=o.then((s=>this.tinode.loginBasic(e,t,a)))):n=o.then((e=>this.tinode.loginToken(i,a))),n.then((e=>{e.code>=300&&"validate credentials"===e.text?(this.setState({loadSpinnerVisible:!1}),a&&this.handleError(this.props.intl.formatMessage(zi.code_doesnot_match),"warn"),Zi.navigateToCredentialsView(e.params)):this.handleLoginSuccessful()})).catch((e=>{const t=e.code>=500;this.setState({loginDisabled:!1,credMethod:void 0,credCode:void 0,loadSpinnerVisible:!1,autoLogin:t}),this.handleError(e.message,"err"),console.warn("Login failed",e),t||(i&&this.handleLogout(),si.Z.navigateTo(""))}))}static navigateToCredentialsView(e){const t=si.Z.parseUrlHash(window.location.hash);t.path[0]="cred",t.params.method=e.cred[0],t.params.token=e.token,si.Z.navigateTo(si.Z.composeUrlHash(t.path,t.params))}handleLoginSuccessful(){this.handleError(),Hi.Z.getObject("keep-logged-in")&&Hi.Z.setObject("auth-token",this.tinode.getAuthToken());const e=this.state.requestedTopic,t=this.tinode.getMeTopic();t.onMetaDesc=this.tnMeMetaDesc,t.onContactUpdate=this.tnMeContactUpdate,t.onSubsUpdated=this.tnMeSubsUpdated,this.setState({connected:!0,credMethod:void 0,credCode:void 0,credToken:void 0,myUserId:this.tinode.getCurrentUserID(),autoLogin:!0,requestedTopic:void 0}),t.subscribe(t.startMetaQuery().withLaterSub().withDesc().withTags().withCred().build()).catch((e=>{this.tinode.disconnect(),localStorage.removeItem("auth-token"),this.handleError(e.message,"err"),si.Z.navigateTo("")})).finally((e=>{this.setState({loadSpinnerVisible:!1})}));let s=si.Z.setUrlSidePanel(window.location.hash,"contacts");e&&(s=si.Z.setUrlTopic(s,e)),si.Z.navigateTo(s)}tnMeMetaDesc(e){if(e){if(e.public&&this.setState({sidePanelTitle:e.public.fn,sidePanelAvatar:(0,ks.PD)(e.public.photo)}),e.trusted){const t=[];for(const[s,a]of Object.entries(e.trusted))a&&t.push(s);this.setState({myTrustedBadges:t})}e.acs&&this.setState({incognitoMode:!e.acs.isPresencer()})}}tnMeContactUpdate(e,t){if("on"==e||"off"==e)this.resetContactList(),this.state.topicSelected==t.topic&&this.setState({topicSelectedOnline:"on"==e});else if("read"==e)this.resetContactList();else if("msg"==e){const e=this.tinode.getTopic(t.topic),s=e&&e.isArchived();t.unread>0&&this.state.messageSounds&&!s&&(document.hidden||this.state.topicSelected!=t.topic)&&Wi.play().catch((e=>{})),this.resetContactList()}else"recv"==e||("gone"==e||"unsub"==e?(this.state.topicSelected==t.topic&&this.handleTopicSelected(null),this.resetContactList()):"acs"==e?this.state.topicSelected==t.topic&&this.setState({topicSelectedAcs:t.acs}):"del"==e||"upd"==e||"call"==e||console.info("Unsupported (yet) presence update:",e,"in",t.topic))}tnMeSubsUpdated(e){this.resetContactList()}static prepareSearchableContacts(e,t){const s={};for(const t of e)cs.Tinode.isP2PTopicName(t.topic)&&(s[t.topic]={user:t.topic,updated:t.updated,public:t.public,private:t.private,acs:t.acs});for(const e of t)s[e.user]||(s[e.user]=e);return Object.values(s)}resetContactList(){const e={chatList:[]};this.state.ready||(e.ready=!0),this.tinode.getMeTopic().contacts((t=>{t.topic||t.user||(t.topic=t.name),e.chatList.push(t),this.state.topicSelected==t.topic&&(e.topicSelectedOnline=t.online,e.topicSelectedAcs=t.acs)}));const t=new Date(0);e.chatList.sort(((e,s)=>(e.touched||t).getTime()-(s.touched||t).getTime())),e.searchableContacts=Zi.prepareSearchableContacts(e.chatList,this.state.searchResults),this.setState(e)}tnInitFind(){const e=this.tinode.getFndTopic();e.onSubsUpdated=this.tnFndSubsUpdated,e.isSubscribed()?this.tnFndSubsUpdated():e.subscribe(e.startMetaQuery().withSub().build()).catch((e=>{this.handleError(e.message,"err")}))}tnFndSubsUpdated(){const e=[];this.tinode.getFndTopic().contacts((t=>{e.push(t)})),this.setState({searchResults:e,searchableContacts:Zi.prepareSearchableContacts(this.state.chatList,e)})}handleSearchContacts(e){const t=this.tinode.getFndTopic();t.setMeta({desc:{public:e}}).then((e=>t.getMeta(t.startMetaQuery().withSub().build()))).catch((e=>this.handleError(e.message,"err")))}handleTopicSelected(e){this.state.newTopicParams&&this.state.newTopicParams._topicName!=e&&this.setState({newTopicParams:null}),e?(this.setState({errorText:"",errorLevel:null,mobilePanel:"topic-view",infoPanel:void 0}),this.state.topicSelected!=e&&(this.setState({topicSelectedOnline:this.tinode.isTopicOnline(e),topicSelectedAcs:this.tinode.getTopicAccessMode(e),forwardMessage:null}),si.Z.navigateTo(si.Z.setUrlTopic("",e)))):(this.setState({errorText:"",errorLevel:null,mobilePanel:"sidepanel",topicSelectedOnline:!1,topicSelectedAcs:null,infoPanel:void 0,forwardMessage:null}),si.Z.navigateTo(si.Z.setUrlTopic("",null)))}handleHideMessagesView(){this.setState({mobilePanel:"sidepanel"}),si.Z.navigateTo(si.Z.setUrlTopic(window.location.hash,null))}handleSendMessage(e,t,s,a){const i=this.tinode.getTopic(this.state.topicSelected);return this.sendMessageToTopic(i,e,t,s,a)}sendMessageToTopic(e,t,s,a,i){(t=e.createMessage(t,!1))._uploader=a,i&&(t.head=Object.assign(t.head||{},i));const n=[];if(s&&n.push(s),!e.isSubscribed()){const s=e.subscribe().then((s=>{let a=[];e.queuedMessages((s=>{s._sending||s.seq==t.seq||(s.head&&s.head.webrtc?a.push(s.seq):e.isSubscribed()&&e.publishMessage(s))})),a.length>0&&e.delMessagesList(a,!0)}));n.push(s)}return e.publishDraft(t,Promise.all(n)).then((t=>(e.isArchived()&&e.archive(!1),t))).catch((e=>this.handleError(e.message,"err")))}handleNewChatInvitation(e,t){const s=this.tinode.getTopic(e);let a=null;switch(t){case"accept":const i=s.getAccessMode().getGiven();a=s.setMeta({sub:{mode:i}}),s.isP2PType()&&(a=a.then((t=>s.setMeta({sub:{user:e,mode:i}}))));break;case"delete":a=s.delTopic(!0);break;case"block":const n=s.getAccessMode().updateWant("-JP").getWant();a=s.setMeta({sub:{mode:n}}).then((e=>this.handleTopicSelected(null)));break;default:console.warn("Unknown invitation action",'"'+t+'""')}null!=a&&a.catch((e=>this.handleError(e.message,"err")))}handleNewAccount(){this.handleError(),si.Z.navigateTo(si.Z.setUrlSidePanel(window.location.hash,"register"))}handleNewAccountRequest(e,t,s,a,i){this.handleError(),this.tinode.connect(this.state.serverAddress).then((n=>{let o;return s&&s.photo&&s.photo.ref&&(o=[s.photo.ref]),this.tinode.createAccountBasic(e,t,{public:s,tags:i,cred:cs.Tinode.credential(a),attachments:o})})).then((e=>{e.code>=300&&"validate credentials"==e.text?Zi.navigateToCredentialsView(e.params):this.handleLoginSuccessful(this)})).catch((e=>{this.handleError(e.message,"err")}))}handleToggleIncognitoMode(e){this.setState({incognitoMode:null});const t=this.tinode.getMeTopic(),s=t.getAccessMode().updateWant(e?"-P":"+P").getWant();t.setMeta({sub:{mode:s}}).catch((t=>{this.setState({incognitoMode:!e}),this.handleError(t.message,"err")}))}handleUpdateAccountTagsRequest(e,t){this.tinode.getMeTopic().setMeta({tags:t}).catch((e=>this.handleError(e.message,"err")))}handleSettings(){this.handleError(),si.Z.navigateTo(si.Z.setUrlSidePanel(window.location.hash,this.state.myUserId?"edit":"settings"))}handleGlobalSettings(e){const t=e.serverAddress||this.state.serverAddress,s=e.transport||this.state.transport,a=void 0===e.secureConnection?this.state.secureConnection:e.secureConnection;this.tinode&&(this.tinode.clearStorage(),this.tinode.onDisconnect=void 0,this.tinode.disconnect()),this.tinode=Zi.tnSetup(t,a,s,this.props.intl.locale,Hi.Z.getObject("keep-logged-in")),this.tinode.onConnect=this.handleConnected,this.tinode.onDisconnect=this.handleDisconnect,this.tinode.onAutoreconnectIteration=this.handleAutoreconnectIteration,this.tinode.onInfoMessage=this.handleInfoMessage,this.tinode.onDataMessage=this.handleDataMessage,this.setState({serverAddress:t,transport:s,secureConnection:a}),Hi.Z.setObject("settings",{serverAddress:t,transport:s,secureConnection:a}),si.Z.navigateTo(si.Z.setUrlSidePanel(window.location.hash,""))}handleShowArchive(){si.Z.navigateTo(si.Z.setUrlSidePanel(window.location.hash,this.state.myUserId?"archive":""))}handleShowBlocked(){si.Z.navigateTo(si.Z.setUrlSidePanel(window.location.hash,this.state.myUserId?"blocked":""))}toggleFCMToken(e){e?(this.setState({desktopAlerts:null}),this.state.firebaseToken?(this.setState({desktopAlerts:!0}),Hi.Z.getObject("keep-logged-in")&&Hi.Z.updateObject("settings",{desktopAlerts:!0})):this.initFCMessaging()):this.state.firebaseToken&&this.fcm?rs(this.fcm).catch((e=>{console.error("Unable to delete token.",e)})).finally((e=>{Hi.Z.updateObject("settings",{desktopAlerts:!1}),localStorage.removeItem("firebase-token"),this.setState({desktopAlerts:!1,firebaseToken:null}),this.tinode.setDeviceToken(null)})):(this.setState({desktopAlerts:!1,firebaseToken:null}),Hi.Z.updateObject("settings",{desktopAlerts:!1}))}handleToggleMessageSounds(e){this.setState({messageSounds:e}),Hi.Z.updateObject("settings",{messageSoundsOff:!e})}handleCredAdd(e,t){this.tinode.getMeTopic().setMeta({cred:{meth:e,val:t}}).catch((e=>this.handleError(e.message,"err")))}handleCredDelete(e,t){this.tinode.getMeTopic().delCredential(e,t).catch((e=>this.handleError(e.message,"err")))}handleCredConfirm(e,t){Zi.navigateToCredentialsView({cred:[e]})}handleSidepanelCancel(){const e=si.Z.parseUrlHash(window.location.hash);let t="";["security","support","general","notif"].includes(e.path[0])?t="edit":"crop"==e.path[0]?t="general":"blocked"==e.path[0]?t="security":this.state.myUserId&&(t="contacts"),e.path[0]=t,e.params&&(delete e.params.code,delete e.params.method,delete e.params.tab,delete e.params.scheme,delete e.params.token),si.Z.navigateTo(si.Z.composeUrlHash(e.path,e.params)),this.setState({errorText:"",errorLevel:null})}basicNavigator(e){si.Z.navigateTo(si.Z.setUrlSidePanel(window.location.hash,e))}infoNavigator(e){si.Z.navigateTo(si.Z.setUrlInfoPanel(window.location.hash,e))}handleStartTopicRequest(e,t,s){if(e&&this.tinode.isTopicCached(e))return void this.handleTopicSelected(e);const a={};cs.Tinode.isP2PTopicName(e)?(a.sub={mode:hs.RK},a.desc={defacs:{auth:hs.RK}}):(e=e||this.tinode.newGroupTopicName(s),t&&(a.desc={public:t.public,private:{comment:t.private}},a.tags=t.tags)),a._topicName=e,this.setState({newTopicParams:a},(t=>{this.handleTopicSelected(e)}))}handleNewTopicCreated(e,t){let s={};this.state.callShouldStart&&(s={callState:Qs,callShouldStart:!1}),this.state.topicSelected==e&&e!=t&&(s.topicSelected=t),this.setState(s,(e=>{si.Z.navigateTo(si.Z.setUrlTopic("",t))}))}handleTopicUpdateRequest(e,t,s,a){this.handleError();const i=this.tinode.getTopic(e);if(i){const e={};let n;t&&(t.photo&&(t.photo.ref&&t.photo.ref!=cs.Tinode.DEL_CHAR?n=[t.photo.ref]:t.photo.data&&t.photo.data!=cs.Tinode.DEL_CHAR||(t.photo=cs.Tinode.DEL_CHAR)),e.public=t),"string"==typeof s&&(e.private=s===cs.Tinode.DEL_CHAR?cs.Tinode.DEL_CHAR:{comment:s}),a&&(e.defacs=a),i.setMeta({desc:e,attachments:n}).catch((e=>this.handleError(e.message,"err")))}}handleUnarchive(e){const t=this.tinode.getTopic(e);t&&t.archive(!1).catch((e=>this.handleError(e.message,"err")))}handleUpdatePasswordRequest(e){this.handleError(),e&&this.tinode.updateAccountBasic(null,this.tinode.getCurrentLogin(),e).catch((e=>this.handleError(e.message,"err")))}handleChangePermissions(e,t,s){const a=this.tinode.getTopic(e);if(a){const e=a.getAccessMode();s?(e.updateGiven(t),t=e.getGiven()):(e.updateWant(t),t=e.getWant()),a.setMeta({sub:{user:s,mode:t}}).catch((e=>this.handleError(e.message,"err")))}}handleTagsUpdateRequest(e,t){const s=this.tinode.getTopic(e);s&&s.setMeta({tags:t}).catch((e=>this.handleError(e.message,"err")))}handleLogout(){let e;(0,Ds.J_)(0),localStorage.removeItem("auth-token"),localStorage.removeItem("firebase-token"),localStorage.removeItem("settings"),this.state.firebaseToken&&rs(this.fcm),clearInterval(this.reconnectCountdown),this.tinode?(e=this.tinode.clearStorage(),this.tinode.onDisconnect=void 0,this.tinode.disconnect()):e=Promose.resolve(),this.setState(this.getBlankState()),e.then((e=>{this.tinode=Zi.tnSetup(this.state.serverAddress,ji(),this.state.transport,this.props.intl.locale,Hi.Z.getObject("keep-logged-in"),(e=>{this.tinode.onConnect=this.handleConnected,this.tinode.onDisconnect=this.handleDisconnect,this.tinode.onAutoreconnectIteration=this.handleAutoreconnectIteration,this.tinode.onInfoMessage=this.handleInfoMessage,this.tinode.onDataMessage=this.handleDataMessage,si.Z.navigateTo("")}))}))}handleDeleteAccount(){this.tinode.delCurrentUser(!0).then((e=>{this.handleLogout()}))}handleDeleteTopicRequest(e){const t=this.tinode.getTopic(e);t&&t.delTopic(!0).then((e=>{si.Z.navigateTo(si.Z.setUrlTopic(window.location.hash,""))})).catch((e=>{this.handleError(e.message,"err")}))}handleDeleteMessagesRequest(e){const t=this.tinode.getTopic(e);t&&t.delMessagesAll(!0).catch((e=>this.handleError(e.message,"err")))}handleLeaveUnsubRequest(e){const t=this.tinode.getTopic(e);t&&t.leave(!0).then((e=>{si.Z.navigateTo(si.Z.setUrlTopic(window.location.hash,""))})).catch((e=>{this.handleError(e.message,"err")}))}handleBlockTopicRequest(e){const t=this.tinode.getTopic(e);t&&t.updateMode(null,"-JP").then((e=>{si.Z.navigateTo(si.Z.setUrlTopic(window.location.hash,""))})).catch((e=>this.handleError(e.message,"err")))}handleReportTopic(e){const t=this.tinode.getTopic(e);t&&(this.tinode.report("report",e),t.updateMode(null,"-JP").then((e=>{si.Z.navigateTo(si.Z.setUrlTopic(window.location.hash,""))})).catch((e=>this.handleError(e.message,"err"))))}handleShowContextMenu(e,t){this.setState({contextMenuVisible:!0,contextMenuClickAt:{x:e.x,y:e.y},contextMenuParams:e,contextMenuItems:t||this.defaultTopicContextMenu(e.topicName),contextMenuBounds:this.selfRef.current.getBoundingClientRect()})}handleShowForwardDialog(e){"newtpk"==this.state.sidePanelSelected&&this.handleSidepanelCancel();const t="➦ "+e.userName,s="string"==typeof e.content?cs.Drafty.init(e.content):cs.Drafty.forwardedContent(e.content),a=cs.Drafty.preview(s,hs.vX,!0),i=cs.Drafty.append(cs.Drafty.appendLineBreak(cs.Drafty.mention(t,e.userFrom)),s),n=cs.Drafty.quote(t,e.userFrom,a),o={forwarded:e.topicName+":"+e.seq};this.setState({forwardDialogVisible:!0,forwardMessage:{head:o,msg:i,preview:n}})}defaultTopicContextMenu(e){const t=this.tinode.getTopic(e);if(t._deleted)return["topic_delete"];let s=!1,a=!1,i=!1,n=!1,o=!1,r=!1,l=!1;if(t){n=t.isSubscribed(),r=t.isArchived();const e=t.getAccessMode();e&&(s=e.isMuted(),a=!e.isJoiner(),i=!e.isJoiner("want"),o=e.isDeleter())}return l=!!this.tinode.getServerParam("iceServers"),[n?{title:this.props.intl.formatMessage(zi.menu_item_info),handler:this.handleShowInfoView}:null,n&&cs.Tinode.isP2PTopicName(e)&&l?{title:this.props.intl.formatMessage(zi.menu_item_audio_call),handler:this.handleStartAudioCall}:null,n&&cs.Tinode.isP2PTopicName(e)&&l?{title:this.props.intl.formatMessage(zi.menu_item_video_call),handler:this.handleStartVideoCall}:null,n?"messages_clear":null,n&&o?"messages_clear_hard":null,s?a?null:"topic_unmute":"topic_mute",i?"topic_unblock":"topic_block",r?"topic_restore":"topic_archive","topic_delete"]}handleHideContextMenu(){this.setState({contextMenuVisible:!1,contextMenuClickAt:null,contextMenuParams:null,contextMenuBounds:null})}handleHideForwardDialog(e){this.setState({forwardDialogVisible:!1,forwardMessage:e?this.state.forwardMessage:null})}handleContextMenuAction(e,t,s){"topic_archive"==e?t&&s.topicName&&s.topicName==this.state.topicSelected&&t.then((e=>{this.handleTopicSelected(null)})):"menu_item_forward"==e&&this.handleShowForwardDialog(s)}handleShowAlert(e,t,s,a,i,n){this.setState({alertVisible:!0,alertParams:{title:e,content:t,onConfirm:s,confirm:a,onReject:i,reject:n}})}handleShowInfoView(){si.Z.navigateTo(si.Z.addUrlParam(window.location.hash,"info","info")),this.setState({infoPanel:"info"})}handleMemberUpdateRequest(e,t,s){if(!e)return;const a=this.tinode.getTopic(e);a&&(t&&t.length>0&&t.forEach((e=>{a.invite(e,null).catch((e=>this.handleError(e.message,"err")))})),s&&s.length>0&&s.forEach((e=>{a.delSubscription(e).catch((e=>this.handleError(e.message,"err")))})))}handleValidateCredentialsRequest(e,t,s){this.tinode.isAuthenticated()?this.tinode.getMeTopic().setMeta({cred:{meth:e,resp:t}}).catch((e=>this.handleError(e.message,"err"))):(this.setState({credMethod:e,credCode:t,credToken:s}),this.doLogin(null,null,s,{meth:e,resp:t}))}handlePasswordResetRequest(e,t){return this.tinode.connect().then((s=>this.tinode.requestResetAuthSecret("basic",e,t))).catch((e=>{this.handleError(e.message,"err")}))}handleResetPassword(e,t){const s=(0,ks.DC)(t.secret);s&&t.scheme?this.tinode.connect().then((a=>this.tinode.updateAccountBasic(null,null,e,{scheme:t.scheme,secret:s}))).then((e=>si.Z.navigateTo(""))).catch((e=>{this.handleError(e.message,"err")})):this.handleError(this.props.intl.formatMessage(zi.invalid_security_token),"err")}handleShowCountrySelector(s,i,n){this.handleShowAlert("Select country",t().createElement(e.Suspense,{fallback:t().createElement("div",null,t().createElement(a.FormattedMessage,{id:"loading_note",defaultMessage:[{type:0,value:"Loading..."}]}))},t().createElement(Vi,{selected:s,onSubmit:(e,t)=>{this.setState({alertVisible:!1}),n(e,t)}})),null,null,(e=>{}),"Cancel")}handleStartVideoCall(){this.setState({callTopic:this.state.topicSelected,callState:Gs,callAudioOnly:!1})}handleStartAudioCall(){this.setState({callTopic:this.state.topicSelected,callState:Gs,callAudioOnly:!0})}handleCallInvite(e,t,s,a){switch(s){case Gs:const s={webrtc:Xs,aonly:!!a};this.handleSendMessage(cs.Drafty.videoCall(a),void 0,void 0,s).then((e=>{e.code<200||e.code>=300||!e.params||!e.params.seq?this.handleCallClose():this.setState({callSeq:e.params.seq})}));break;case Qs:const i=this.tinode.getTopic(e);if(!i)return;i.videoCall("accept",t)}}handleCallRinging(e,t){const s=this.tinode.getTopic(e);s&&s.videoCall("ringing",t)}handleCallHangup(e,t){const s=this.tinode.getTopic(e);s&&s.videoCall("hang-up",t)}handleCallSendOffer(e,t,s){const a=this.tinode.getTopic(e);a&&a.videoCall("offer",t,s)}handleCallIceCandidate(e,t,s){const a=this.tinode.getTopic(e);a&&a.videoCall("ice-candidate",t,s)}handleCallSendAnswer(e,t,s){const a=this.tinode.getTopic(e);a&&a.videoCall("answer",t,s)}handleCallClose(){this.callTimeoutTimer&&clearTimeout(this.callTimeoutTimer),this.setState({callTopic:void 0,callState:0,callAudioOnly:void 0})}handleCallAccept(e){const t=this.tinode.getTopic(e);t&&(t.isSubscribed()?(this.handleTopicSelected(this.state.callTopic),this.setState({callState:Qs})):this.setState({callShouldStart:!0},(e=>this.handleTopicSelected(this.state.callTopic))))}handleInfoMessage(e){if("call"==e.what)switch(e.event){case"accept":if(cs.Tinode.isMeTopicName(e.topic)&&this.tinode.isMe(e.from))return void this.setState({callTopic:null,callState:0,callSeq:null,callAudioOnly:void 0});e.topic==this.state.callTopic&&this.setState({callState:Qs});break;case"hang-up":this.handleCallClose()}}handleDataMessage(e){if(e.head&&e.head.webrtc&&e.head.webrtc==Xs){const t=this.tinode.getTopic(e.topic);if(t){const s=t.latestMsgVersion(e.seq)||e;s.head&&s.head.webrtc&&s.head.webrtc==Xs&&e.from!=this.state.myUserId&&(0==this.state.callState?this.setState({callTopic:e.topic,callState:2,callSeq:e.seq,callAudioOnly:!!s.head.aonly}):this.handleCallHangup(e.topic,e.seq))}else console.warn("Received vc data message from unknown topic",e.topic)}}render(){return t().createElement("div",{id:"app-container",ref:this.selfRef},this.state.contextMenuVisible?t().createElement(ms,{tinode:this.tinode,bounds:this.state.contextMenuBounds,clickAt:this.state.contextMenuClickAt,params:this.state.contextMenuParams,items:this.state.contextMenuItems,hide:this.handleHideContextMenu,onShowAlert:this.handleShowAlert,onAction:this.handleContextMenuAction,onTopicRemoved:e=>{e==this.state.topicSelected&&this.handleTopicSelected(null)},onError:this.handleError}):null,this.state.forwardDialogVisible?t().createElement(Ks,{tinode:this.tinode,contacts:this.state.chatList,topicSelected:this.state.topicSelected,myUserId:this.state.myUserId,hide:this.handleHideForwardDialog,onInitFind:this.tnInitFind,searchResults:this.state.searchResults,onSearchContacts:this.handleSearchContacts,onTopicSelected:this.handleStartTopicRequest}):null,this.state.callTopic&&2==this.state.callState?t().createElement(Js,{tinode:this.tinode,topic:this.state.callTopic,seq:this.state.callSeq,callState:this.state.callState,audioOnly:this.state.callAudioOnly,onClose:this.handleCallClose,onRinging:this.handleCallRinging,onAcceptCall:this.handleCallAccept,onReject:this.handleCallHangup}):null,this.state.alertVisible?t().createElement(ds,{title:this.state.alertParams.title,content:this.state.alertParams.content,onReject:this.state.alertParams.onReject?e=>this.setState({alertVisible:!1}):null,reject:this.state.alertParams.reject,onConfirm:this.state.alertParams.onConfirm?e=>{this.setState({alertVisible:!1}),this.state.alertParams.onConfirm()}:null,confirm:this.state.alertParams.confirm}):null,this.state.displayMobile&&"sidepanel"!=this.state.mobilePanel?null:t().createElement(Oi,{tinode:this.tinode,connected:this.state.connected,displayMobile:this.state.displayMobile,state:this.state.sidePanelSelected,title:this.state.sidePanelTitle,avatar:this.state.sidePanelAvatar,trustedBadges:this.state.myTrustedBadges,login:this.state.login,persist:this.state.persist,myUserId:this.state.myUserId,loginDisabled:this.state.loginDisabled,loadSpinnerVisible:this.state.loadSpinnerVisible,errorText:this.state.errorText,errorLevel:this.state.errorLevel,errorAction:this.state.errorAction,errorActionText:this.state.errorActionText,topicSelected:this.state.topicSelected,chatList:this.state.chatList,credMethod:this.state.credMethod,credCode:this.state.credCode,credToken:this.state.credToken,transport:this.state.transport,messageSounds:this.state.messageSounds,desktopAlerts:this.state.desktopAlerts,desktopAlertsEnabled:this.state.desktopAlertsEnabled,incognitoMode:this.state.incognitoMode,serverAddress:this.state.serverAddress,secureConnection:this.state.secureConnection,serverVersion:this.state.serverVersion,reqCredMethod:this.state.reqCredMethod,onGlobalSettings:this.handleGlobalSettings,onSignUp:this.handleNewAccount,onSettings:this.handleSettings,onNavigate:this.basicNavigator,onLoginRequest:this.handleLoginRequest,onPersistenceChange:this.handlePersistenceChange,onCreateAccount:this.handleNewAccountRequest,onUpdateAccountDesc:this.handleTopicUpdateRequest,onUpdatePassword:this.handleUpdatePasswordRequest,onUpdateAccountTags:this.handleUpdateAccountTagsRequest,onTogglePushNotifications:this.toggleFCMToken,onToggleMessageSounds:this.handleToggleMessageSounds,onToggleIncognitoMode:this.handleToggleIncognitoMode,onCredAdd:this.handleCredAdd,onCredDelete:this.handleCredDelete,onCredConfirm:this.handleCredConfirm,onTopicSelected:this.handleTopicSelected,onCreateTopic:this.handleStartTopicRequest,onLogout:this.handleLogout,onDeleteAccount:this.handleDeleteAccount,onShowAlert:this.handleShowAlert,onCancel:this.handleSidepanelCancel,onError:this.handleError,onValidateCredentials:this.handleValidateCredentialsRequest,onPasswordResetRequest:this.handlePasswordResetRequest,onResetPassword:this.handleResetPassword,onShowArchive:this.handleShowArchive,onShowBlocked:this.handleShowBlocked,onShowCountrySelector:this.handleShowCountrySelector,onInitFind:this.tnInitFind,searchResults:this.state.searchResults,onSearchContacts:this.handleSearchContacts,showContextMenu:this.handleShowContextMenu}),!this.state.displayMobile||"topic-view"==this.state.mobilePanel&&!this.state.infoPanel?t().createElement(li,{tinode:this.tinode,connected:this.state.connected,ready:this.state.ready,online:this.state.topicSelectedOnline,acs:this.state.topicSelectedAcs,displayMobile:this.state.displayMobile,viewportWidth:this.state.viewportWidth,viewportHeight:this.state.viewportHeight,topic:this.state.topicSelected,myUserId:this.state.myUserId,myUserName:this.state.sidePanelTitle,serverVersion:this.state.serverVersion,serverAddress:this.state.serverAddress,applicationVisible:this.state.applicationVisible,forwardMessage:this.state.forwardMessage,onCancelForwardMessage:this.handleHideForwardDialog,callTopic:this.state.callTopic,callSeq:this.state.callSeq,callState:this.state.callState,callAudioOnly:this.state.callAudioOnly,onCallHangup:this.handleCallHangup,onCallInvite:this.handleCallInvite,onCallSendOffer:this.handleCallSendOffer,onCallIceCandidate:this.handleCallIceCandidate,onCallSendAnswer:this.handleCallSendAnswer,errorText:this.state.errorText,errorLevel:this.state.errorLevel,errorAction:this.state.errorAction,errorActionText:this.state.errorActionText,newTopicParams:this.state.newTopicParams,onHideMessagesView:this.handleHideMessagesView,onError:this.handleError,onNewTopicCreated:this.handleNewTopicCreated,showContextMenu:this.handleShowContextMenu,onChangePermissions:this.handleChangePermissions,onNewChat:this.handleNewChatInvitation,sendMessage:this.handleSendMessage,onVideoCallClosed:this.handleCallClose}):null,this.state.infoPanel?t().createElement(Sa,{tinode:this.tinode,connected:this.state.connected,displayMobile:this.state.displayMobile,topic:this.state.topicSelected,searchableContacts:this.state.searchableContacts,myUserId:this.state.myUserId,panel:this.state.infoPanel,errorText:this.state.errorText,errorLevel:this.state.errorLevel,errorAction:this.state.errorAction,errorActionText:this.state.errorActionText,onNavigate:this.infoNavigator,onTopicDescUpdateRequest:this.handleTopicUpdateRequest,onShowAlert:this.handleShowAlert,onChangePermissions:this.handleChangePermissions,onMemberUpdateRequest:this.handleMemberUpdateRequest,onDeleteTopic:this.handleDeleteTopicRequest,onDeleteMessages:this.handleDeleteMessagesRequest,onLeaveTopic:this.handleLeaveUnsubRequest,onBlockTopic:this.handleBlockTopicRequest,onReportTopic:this.handleReportTopic,onAddMember:this.handleManageGroupMembers,onTopicTagsUpdateRequest:this.handleTagsUpdateRequest,onTopicUnArchive:this.handleUnarchive,onInitFind:this.tnInitFind,onError:this.handleError,showContextMenu:this.handleShowContextMenu}):null)}}const Ki=(0,a.injectIntl)(Zi);if("undefined"!=typeof FIREBASE_INIT&&FIREBASE_INIT&&FIREBASE_INIT.measurementId){const tn=document.getElementsByTagName("head")[0];let sn=document.createElement("script");function an(){dataLayer.push(arguments)}sn.src="https://www.googletagmanager.com/gtag/js?id="+FIREBASE_INIT.measurementId,sn.async=!0,tn.prepend(sn),window.dataLayer=window.dataLayer||[],an("js",new Date),an("config",FIREBASE_INIT.measurementId)}const $i={de:e=>o.e(92).then(o.t.bind(o,6092,19)),en:e=>o.e(514).then(o.t.bind(o,4514,19)),es:e=>o.e(932).then(o.t.bind(o,9932,19)),fr:e=>o.e(107).then(o.t.bind(o,107,19)),ko:e=>o.e(898).then(o.t.bind(o,898,19)),ro:e=>o.e(817).then(o.t.bind(o,4817,19)),ru:e=>o.e(734).then(o.t.bind(o,3734,19)),zh:e=>o.e(700).then(o.t.bind(o,5700,19)),"zh-TW":e=>o.e(226).then(o.t.bind(o,5226,19))},{params:Gi}=si.Z.parseUrlHash(window.location.hash),Qi=Gi&&Gi.hl||navigator.languages&&navigator.languages[0]||navigator.language||navigator.userLanguage||"en",Xi=Qi.replace("_","-"),Yi=Xi.split("-")[0].toLowerCase(),Ji=$i[Xi]?Qi:$i[Yi]?Yi:"en";document.getElementsByTagName("html")[0].setAttribute("lang",Ji);const en=(0,s.s)(document.getElementById("mountPoint"));$i[Ji]().then((e=>en.render(t().createElement(a.IntlProvider,{locale:Qi,messages:e,textComponent:t().Fragment},t().createElement(Ki,null)))))})()})();
//# sourceMappingURL=index.prod.js.map
\ No newline at end of file
diff --git a/umd/index.prod.js.map b/umd/index.prod.js.map
index 37fbbd5f..f8de8381 100644
--- a/umd/index.prod.js.map
+++ b/umd/index.prod.js.map
@@ -1 +1 @@
-{"version":3,"file":"index.prod.js","mappings":"uBACIA,EADAC,ECAAC,EACAC,E,mYCEG,MAAMC,EAAW,c,QAAgBC,GAAmB,QAG9CC,EAAU,mCAGVC,EAAc,CAACC,OAAQ,gBAAiBC,MAAO,kBAG/CC,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SAAUA,EAAUurE,cAAelrE,IAAAA,UACjEA,IAAAA,cAAC67D,GAAS,S","sources":["webpack://tinode-webapp/webpack/runtime/create fake namespace object","webpack://tinode-webapp/webpack/runtime/load script","webpack://tinode-webapp/./src/config.js","webpack://tinode-webapp/./src/lib/blob-helpers.js","webpack://tinode-webapp/./src/lib/local-storage.js","webpack://tinode-webapp/./src/lib/navigation.js","webpack://tinode-webapp/./src/lib/strformat.js","webpack://tinode-webapp/./src/lib/utils.js","webpack://tinode-webapp/./src/version.js","webpack://tinode-webapp/./src/widgets/audio-player.jsx","webpack://tinode-webapp/./src/widgets/cropper.jsx","webpack://tinode-webapp/./src/widgets/avatar-crop.jsx","webpack://tinode-webapp/./src/widgets/avatar-upload.jsx","webpack://tinode-webapp/./src/widgets/badge-list.jsx","webpack://tinode-webapp/./src/widgets/checkbox.jsx","webpack://tinode-webapp/./src/widgets/letter-tile.jsx","webpack://tinode-webapp/./src/widgets/load-spinner.jsx","webpack://tinode-webapp/./src/widgets/visible-password.jsx","webpack://tinode-webapp/./node_modules/react-dom/client.js","webpack://tinode-webapp/external var \"React\"","webpack://tinode-webapp/external var \"ReactDOM\"","webpack://tinode-webapp/external var \"ReactIntl\"","webpack://tinode-webapp/external var \"tinode\"","webpack://tinode-webapp/webpack/bootstrap","webpack://tinode-webapp/webpack/runtime/compat get default export","webpack://tinode-webapp/webpack/runtime/define property getters","webpack://tinode-webapp/webpack/runtime/ensure chunk","webpack://tinode-webapp/webpack/runtime/get javascript chunk filename","webpack://tinode-webapp/webpack/runtime/global","webpack://tinode-webapp/webpack/runtime/hasOwnProperty shorthand","webpack://tinode-webapp/webpack/runtime/make namespace object","webpack://tinode-webapp/webpack/runtime/publicPath","webpack://tinode-webapp/webpack/runtime/jsonp chunk loading","webpack://tinode-webapp/./node_modules/@firebase/util/dist/index.esm2017.js","webpack://tinode-webapp/./node_modules/@firebase/component/dist/esm/index.esm2017.js","webpack://tinode-webapp/./node_modules/@firebase/logger/dist/esm/index.esm2017.js","webpack://tinode-webapp/./node_modules/idb/build/wrap-idb-value.js","webpack://tinode-webapp/./node_modules/idb/build/index.js","webpack://tinode-webapp/./node_modules/@firebase/app/dist/esm/index.esm2017.js","webpack://tinode-webapp/./node_modules/firebase/app/dist/esm/index.esm.js","webpack://tinode-webapp/./node_modules/@firebase/installations/dist/esm/index.esm2017.js","webpack://tinode-webapp/./node_modules/@firebase/messaging/dist/esm/index.esm2017.js","webpack://tinode-webapp/./src/widgets/alert.jsx","webpack://tinode-webapp/./src/widgets/context-menu.jsx","webpack://tinode-webapp/./src/widgets/contact-badges.jsx","webpack://tinode-webapp/./src/widgets/unread-badge.jsx","webpack://tinode-webapp/./src/widgets/call-message.jsx","webpack://tinode-webapp/./src/widgets/call-status.jsx","webpack://tinode-webapp/./src/widgets/inline-video.jsx","webpack://tinode-webapp/./src/widgets/lazy-image.jsx","webpack://tinode-webapp/./src/widgets/file-progress.jsx","webpack://tinode-webapp/./src/widgets/uploading-image.jsx","webpack://tinode-webapp/./src/lib/formatters.js","webpack://tinode-webapp/./src/widgets/contact.jsx","webpack://tinode-webapp/./src/widgets/contact-action.jsx","webpack://tinode-webapp/./src/widgets/contact-list.jsx","webpack://tinode-webapp/./src/widgets/search-contacts.jsx","webpack://tinode-webapp/./src/widgets/forward-dialog.jsx","webpack://tinode-webapp/./src/constants.js","webpack://tinode-webapp/./src/widgets/call-incoming.jsx","webpack://tinode-webapp/./src/widgets/menu-cancel.jsx","webpack://tinode-webapp/./src/widgets/error-panel.jsx","webpack://tinode-webapp/./src/widgets/chip.jsx","webpack://tinode-webapp/./src/widgets/chip-input.jsx","webpack://tinode-webapp/./src/widgets/group-manager.jsx","webpack://tinode-webapp/./src/widgets/permissions-editor.jsx","webpack://tinode-webapp/./src/widgets/in-place-edit.jsx","webpack://tinode-webapp/./src/widgets/tag-manager.jsx","webpack://tinode-webapp/./src/widgets/topic-desc-edit.jsx","webpack://tinode-webapp/./src/views/topic-common-view.jsx","webpack://tinode-webapp/./src/widgets/topic-security.jsx","webpack://tinode-webapp/./src/views/info-view.jsx","webpack://tinode-webapp/./src/widgets/call-panel.jsx","webpack://tinode-webapp/./src/widgets/attachment.jsx","webpack://tinode-webapp/./src/widgets/received-marker.jsx","webpack://tinode-webapp/./src/widgets/chat-message.jsx","webpack://tinode-webapp/./src/widgets/send-message.jsx","webpack://tinode-webapp/./src/widgets/doc-preview.jsx","webpack://tinode-webapp/./src/widgets/group-subs.jsx","webpack://tinode-webapp/./src/widgets/image-preview.jsx","webpack://tinode-webapp/./src/widgets/invitation.jsx","webpack://tinode-webapp/./src/views/logo-view.jsx","webpack://tinode-webapp/./src/widgets/meta-message.jsx","webpack://tinode-webapp/./src/widgets/pinned-messages.jsx","webpack://tinode-webapp/./src/widgets/video-preview.jsx","webpack://tinode-webapp/./src/views/messages-view.jsx","webpack://tinode-webapp/./src/widgets/button-back.jsx","webpack://tinode-webapp/./src/widgets/menu-contacts.jsx","webpack://tinode-webapp/./src/widgets/menu-start.jsx","webpack://tinode-webapp/./src/widgets/side-navbar.jsx","webpack://tinode-webapp/./src/views/contacts-view.jsx","webpack://tinode-webapp/./src/views/acc-notifications-view.jsx","webpack://tinode-webapp/./src/views/acc-security-view.jsx","webpack://tinode-webapp/./src/views/acc-support-view.jsx","webpack://tinode-webapp/./src/views/login-view.jsx","webpack://tinode-webapp/./src/widgets/new-topic-by-id.jsx","webpack://tinode-webapp/./src/widgets/new-topic-group.jsx","webpack://tinode-webapp/./src/views/new-topic-view.jsx","webpack://tinode-webapp/./src/widgets/host-selector.jsx","webpack://tinode-webapp/./src/views/settings-view.jsx","webpack://tinode-webapp/./src/views/validation-view.jsx","webpack://tinode-webapp/./src/views/sidepanel-view.jsx","webpack://tinode-webapp/./src/lib/host-name.js","webpack://tinode-webapp/./src/views/tinode-web.jsx","webpack://tinode-webapp/./src/index.js"],"sourcesContent":["var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"tinode-webapp:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tscript.timeout = 120;\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","import { PACKAGE_VERSION } from './version.js';\n\n// Name of this application, used in the User-Agent.\nexport const APP_NAME = 'TinodeWeb/' + (PACKAGE_VERSION || '0.21');\n\n// API key. Use https://github.com/tinode/chat/tree/master/keygen to generate your own\nexport const API_KEY = 'AQEAAAABAAD_rAp4DJh05a1HAwFT3A6K';\n\n// The array of possible hosts to connect to.\nexport const KNOWN_HOSTS = {hosted: 'web.tinode.co', local: 'localhost:6060'};\n\n// Default host name and port to connect to.\nexport const DEFAULT_HOST = KNOWN_HOSTS.hosted;\n\n// Enable console logging.\nexport const LOGGING_ENABLED = true;\n\n// Minimum time between two keypress notifications, milliseconds.\nexport const KEYPRESS_DELAY = 3_000;\n// Delay before sending a read notification, milliseconds.\nexport const READ_DELAY = 1_500;\n\n// The default shortest allowed tag length. Matches the value on the server.\nexport const MIN_TAG_LENGTH = 2;\n// The default greatest allowed tag length. Matches the value on the server.\nexport const MAX_TAG_LENGTH = 96;\n// The default maximum number of tags allowed. Matches the value on the server.\nexport const MAX_TAG_COUNT = 16;\n\n// Access mode for P2P subscriptions initiated by the current user.\nexport const DEFAULT_P2P_ACCESS_MODE = 'JRWPS';\n// Access mode for new group topics created by the current user.\nexport const NEW_GRP_ACCESS_MODE = 'JRWPSAO';\n// Access mode for a channel.\nexport const CHANNEL_ACCESS_MODE = 'JR';\n\n// Access mode for no access.\nexport const NO_ACCESS_MODE = 'N';\n\n// Mediaquery breakpoint between desktop and mobile, in px. Should match the value\n// in @media (max-size: 640px) in base.css\nexport const MEDIA_BREAKPOINT = 640;\n// Size of css 'rem' unit in pixels. Default 1rem = 10pt = 13px.\nexport const REM_SIZE = 13;\n\n// Size of the avatar image: when image dimensions are greater or the image is not square, it's resized to\n// a square of this size or less.\nexport const AVATAR_SIZE = 384;\n\n// Maximum size of an avatar in bytes for sending in-band. Bigger avatars will be sent out of band (as uploads).\nexport const MAX_AVATAR_BYTES = 4096;\n\n// Size of the broken_image shown in MessagesView\nexport const BROKEN_IMAGE_SIZE = 32;\n\n// Size of video preview when dimensions are missing.\nexport const NO_DIMENSIONS_VIDEO = 128;\n\n// Number of chat messages to fetch in one call.\nexport const MESSAGES_PAGE = 24;\n\n// Default maximum in-band (included directly into the message) attachment size which fits into\n// a message of 256K in size. Used when the server-provided value is unavailable. The actual\n// binary size of the attachment should be smaller due to base64 encoding expansion and some overhead,\n// for instance 1024 bytes.\n// Increase this limit to a greater value in production, if desired. Also increase\n// max_message_size in the server config.\nexport const MAX_INBAND_ATTACHMENT_SIZE = 262_144;\n\n// Default absolute maximum attachment size to be used with the server = 8MB.\n// Used when the server-provided value is unavailable. Increase to something like 100MB in production.\nexport const MAX_EXTERN_ATTACHMENT_SIZE = 1 << 23;\n\n// Maximum allowed linear dimension (pixels) of an image sent inline. Larger images will be shrunk\n// to make the larger dimension fit under this size. You may want to adjust it to 1600 or\n// 2400 for production.\nexport const MAX_IMAGE_DIM = 1024;\n\n// Linear dimensions of image preview: shrink image under this size for previews.\nexport const IMAGE_PREVIEW_DIM = 64;\n\n// Linear dimensions of video screencapture: shrink image under this size for previews.\nexport const VIDEO_PREVIEW_DIM = 96;\n\n// Linear dimensions of image thumbnail: shrink image under this size for thumbnails in reply quote previews.\nexport const IMAGE_THUMBNAIL_DIM = 36;\n// Width of video thumbnail: allow it to be wider, but not taller. Use IMAGE_THUMBNAIL_DIM for height.\nexport const VIDEO_THUMBNAIL_WIDTH = 48;\n\n// Maximum number of online users to be shown in a topic title bar. Others will be\n// hidden under \"+X more\"\nexport const MAX_ONLINE_IN_TOPIC = 4;\n\n// Maximum length of user name, topic title, and private comment.\nexport const MAX_TITLE_LENGTH = 60;\n// Maximum length of topic description.\nexport const MAX_TOPIC_DESCRIPTION_LENGTH = 360;\n// Maximum length of user name when displaying a video call.\nexport const MAX_PEER_TITLE_LENGTH = 20;\n\n// Length of message previews in chat list, in characters.\nexport const MESSAGE_PREVIEW_LENGTH = 80;\n\n// Length of a quote in quoted reply (for outgoing messages).\nexport const QUOTED_REPLY_LENGTH = 30;\n// Length of a preview of a forwarded message.\nexport const FORWARDED_PREVIEW_LENGTH = 84;\n// Length of preview for a message being edited.\nexport const EDIT_PREVIEW_LENGTH = 48;\n\n// Minimum duration of an audio recording in milliseconds (2 sec).\nexport const MIN_DURATION = 2_000;\n// Maximum duration of an audio recording in milliseconds (10 min).\nexport const MAX_DURATION = 600_000;\n\n// Link for \"Contact Us\".\nexport const LINK_CONTACT_US = 'mailto:support@tinode.co';\n\n// Link to Privacy Policy.\nexport const LINK_PRIVACY_POLICY = 'https://tinode.co/privacy.html';\n\n// Link to Terms of Service.\nexport const LINK_TERMS_OF_SERVICE = 'https://tinode.co/terms.html';\n\n// When user starts a P2P topic, automatic subscription does not\n// happen until the first message. Setting this option to true enables\n// immediate subscription.\nexport const IMMEDIATE_P2P_SUBSCRIPTION = false;\n","// File and image helper functions.\n\n// Supported image MIME types and corresponding file extensions.\nexport const SUPPORTED_IMAGE_FORMATS = ['image/jpeg', 'image/gif', 'image/png', 'image/svg', 'image/svg+xml'];\nexport const MIME_EXTENSIONS = ['jpg', 'gif', 'png', 'svg', 'svg'];\n\n// Get an URL from a theCard photo: either create a data: URL or return reference URL.\nexport function makeImageUrl(photo) {\n if (photo && typeof photo == 'object') {\n if (photo.ref) {\n return photo.ref\n }\n if (photo.data && photo.type) {\n const mime = photo.type.startsWith('image/') ? photo.type : ('image/' + photo.type);\n return 'data:' + mime + ';base64,' + photo.data;\n }\n }\n return null;\n}\n\n// Calculate linear dimensions for scaling image down to fit under a certain size.\n// Returns an object which contains destination sizes, source sizes, and offsets\n// into source (when making square images).\nexport function fitImageSize(width, height, maxWidth, maxHeight, forceSquare) {\n // Sanitize input\n width = width | 0;\n height = height | 0;\n maxWidth = maxWidth | 0;\n maxHeight = maxHeight | 0;\n\n if (width <= 0 || height <= 0 || maxWidth <= 0 || maxHeight <= 0) {\n return null;\n }\n\n if (forceSquare) {\n maxWidth = maxHeight = Math.min(maxWidth, maxHeight);\n }\n\n const scale = Math.min(\n Math.min(width, maxWidth) / width,\n Math.min(height, maxHeight) / height\n );\n\n const size = {\n dstWidth: (width * scale) | 0,\n dstHeight: (height * scale) | 0,\n };\n\n if (forceSquare) {\n // Also calculate parameters for making the image square.\n size.dstWidth = size.dstHeight = Math.min(size.dstWidth, size.dstHeight);\n size.srcWidth = size.srcHeight = Math.min(width, height);\n size.xoffset = ((width - size.srcWidth) / 2) | 0;\n size.yoffset = ((height - size.srcWidth) / 2) | 0;\n } else {\n size.xoffset = size.yoffset = 0;\n size.srcWidth = width;\n size.srcHeight = height;\n }\n return size;\n}\n\n// Ensure file's extension matches mime content type\nexport function fileNameForMime(fname, mime) {\n const idx = SUPPORTED_IMAGE_FORMATS.indexOf(mime);\n if (idx < 0 || !fname) {\n // Unknown mime or empty name.\n return fname;\n }\n const ext = MIME_EXTENSIONS[idx];\n\n const at = fname.lastIndexOf('.');\n if (at >= 0) {\n fname = fname.substring(0, at);\n }\n return fname + '.' + ext;\n}\n\n// Scale uploaded image to fit under certain dimensions and byte size, optionally constraining to a square.\n// Returns a promise which is resolven on success or rejected on failure.\nexport function imageScaled(fileOrBlob, maxWidth, maxHeight, maxSize, forceSquare) {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.crossOrigin = 'Anonymous';\n img.onerror = function(err) {\n reject(new Error(\"Image format unrecognized\"));\n }\n img.onload = async function() {\n // Once the image is loaded, the URL is no longer needed.\n URL.revokeObjectURL(img.src);\n\n // Calculate the desired image dimensions.\n const dim = fitImageSize(img.width, img.height, maxWidth, maxHeight, forceSquare);\n if (!dim) {\n reject(new Error(\"Invalid image\"));\n return;\n }\n let canvas = document.createElement('canvas');\n canvas.width = dim.dstWidth;\n canvas.height = dim.dstHeight;\n let ctx = canvas.getContext('2d');\n ctx.imageSmoothingEnabled = true;\n ctx.drawImage(img, dim.xoffset, dim.yoffset, dim.srcWidth, dim.srcHeight,\n 0, 0, dim.dstWidth, dim.dstHeight);\n\n const mime = SUPPORTED_IMAGE_FORMATS.includes(fileOrBlob.type) ? fileOrBlob.type : 'image/jpeg';\n // Generate blob to check size of the image.\n let blob = await new Promise(resolve => canvas.toBlob(resolve, mime));\n if (!blob) {\n reject(new Error(\"Unsupported image format\"));\n return;\n }\n // Ensure the image is not too large. Shrink the image keeping the aspect ratio.\n // Do nothing if maxsize is <= 0.\n while (maxSize > 0 && blob.length > maxSize) {\n dim.dstWidth = (dim.dstWidth * 0.70710678118) | 0;\n dim.dstHeight = (dim.dstHeight * 0.70710678118) | 0;\n canvas.width = dim.dstWidth;\n canvas.height = dim.dstHeight;\n ctx = canvas.getContext('2d');\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.drawImage(img, dim.xoffset, dim.yoffset, dim.srcWidth, dim.srcHeight,\n 0, 0, dim.dstWidth, dim.dstHeight);\n blob = await new Promise(resolve => canvas.toBlob(resolve, mime));\n }\n\n canvas = null;\n resolve({mime: mime, blob: blob, width: dim.dstWidth, height: dim.dstHeight, name: fileNameForMime(fileOrBlob.name, mime)});\n };\n img.src = URL.createObjectURL(fileOrBlob);\n });\n}\n\n// Scale and crop image according to specified dimensions.\n// The coordinates are in unscaled image pixels, i.e. cut the rectangle first then scale it.\n// returns a promise.\nexport function imageCrop(mime, objURL, left, top, width, height, scale) {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.crossOrigin = 'Anonymous';\n img.onerror = _ => {\n reject(new Error(\"Image format unrecognized\"));\n };\n img.onload = _ => {\n // Once the image is loaded, the URL is no longer needed.\n URL.revokeObjectURL(img.src);\n\n let canvas = document.createElement('canvas');\n canvas.width = width * scale;\n canvas.height = height * scale;\n let ctx = canvas.getContext('2d');\n ctx.imageSmoothingEnabled = true;\n ctx.drawImage(img, left, top, width, height, 0, 0, canvas.width, canvas.height);\n\n mime = SUPPORTED_IMAGE_FORMATS.includes(mime) ? mime : 'image/jpeg';\n // Generate blob to check size of the image.\n canvas.toBlob((blob) => {\n // Allow GC.\n canvas = null;\n if (blob) {\n resolve({mime: mime, blob: blob, width: width, height: height});\n } else {\n reject(new Error(\"Unsupported image format\"));\n }\n }, mime);\n };\n img.src = objURL;\n });\n}\n\n// Convert file to base64 string.\nexport function fileToBase64(file) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = _ => {\n reject(reader.error);\n };\n reader.onload = _ => {\n resolve({mime: file.type, bits: reader.result.split(',')[1], name: file.name});\n };\n reader.readAsDataURL(file);\n });\n}\n\n// Convert Blob to base64 string. Returns a promise resolved with the base64 string and mime.\nexport function blobToBase64(blob) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = _ => {\n reject(reader.error);\n };\n reader.onload = _ => {\n resolve({mime: blob.type, bits: reader.result.split(',')[1]});\n };\n reader.readAsDataURL(blob);\n });\n}\n\n// File pasted from the clipboard. It's either an inline image or a file attachment.\nexport function filePasted(event, onImageSuccess, onAttachmentSuccess, onError) {\n const items = (event.clipboardData || event.originalEvent.clipboardData || {}).items;\n if (!items || !items.length) {\n return false;\n }\n\n for (let i in items) {\n const item = items[i];\n if (item.kind === 'file') {\n const file = item.getAsFile();\n if (!file) {\n console.error(\"Failed to get file object from pasted file item\", item.kind, item.type);\n onError(\"Failed to get file object from pasted file item\");\n continue;\n }\n if (file.type && file.type.split('/')[0] == 'image') {\n onImageSuccess(file);\n } else {\n onAttachmentSuccess(file);\n }\n // Indicate that the pasted data contains a file.\n return true;\n }\n }\n // No file found.\n return false;\n}\n\n// Get mime type from data URL header.\nexport function getMimeType(header) {\n const mime = /^data:(image\\/[-+a-z0-9.]+);base64/.exec(header);\n return (mime && mime.length > 1) ? mime[1] : null;\n}\n\n// Given length of a binary object in bytes, calculate the length after\n// base64 encoding.\nexport function base64EncodedLen(n) {\n return Math.floor((n + 2) / 3) * 4;\n}\n\n// Given length of a base64-encoded object, calculate decoded size of the\n// pbject in bytes.\nexport function base64DecodedLen(n) {\n return Math.floor(n / 4) * 3;\n}\n\n// Re-encode string to standard base64 encoding with padding.\n// The string may be base64-URL encoded without the padding.\nexport function base64ReEncode(str) {\n if (str) {\n str = str.replace(/-/g, '+').replace(/_/g, '/');\n try {\n str = btoa(atob(str));\n } catch(err) {\n console.error(\"Failed to base64 re-encode string.\", err);\n str = null;\n }\n }\n return str;\n}\n\n// Convert a base64 encoded string with the provided mime type into a Blob.\nexport function base64ToBlob(str, mime) {\n if (!str) {\n return null;\n }\n\n try {\n // Make blob.\n const bin = atob(str);\n const length = bin.length;\n const buf = new ArrayBuffer(length);\n const arr = new Uint8Array(buf);\n for (let i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n\n return new Blob([buf], { type: mime });\n } catch(err) {\n console.error(\"Failed to convert base64 to blob: \", err);\n }\n\n return null;\n}\n\nexport function intArrayToBase64(arr) {\n if (!Array.isArray(arr)) {\n return null;\n }\n try {\n let bin = '';\n new Uint8Array(arr).forEach(b => bin += String.fromCharCode(b));\n return window.btoa(bin);\n } catch (err) {}\n return null;\n}\n\nexport function base64ToIntArray(b64) {\n const arr = [];\n try {\n const bin = window.atob(b64);\n [...bin].forEach(c => {\n arr.push(c.charCodeAt(0));\n });\n return arr;\n } catch (err) {}\n return null;\n}\n","// Helper functions for storing values in localStorage.\n// By default localStorage can store only strings, not objects or other types.\n\nexport default class LocalStorageUtil {\n // Replace old object with the new one.\n static setObject(key, value) {\n localStorage.setItem(key, JSON.stringify(value));\n }\n\n // Get stored object.\n static getObject(key) {\n const value = localStorage.getItem(key);\n return value && JSON.parse(value);\n }\n\n // Partially or wholly update stored object.\n static updateObject(key, value) {\n const oldVal = this.getObject(key);\n this.setObject(key, Object.assign(oldVal || {}, value));\n }\n\n // Just a wrapper.\n static removeItem(key) {\n localStorage.removeItem(key);\n }\n}\n","// Utility class for hash navigation.\n\nexport default class HashNavigation {\n // Parse hash as in http://www.example.com/path#hash as if it were\n // path and arguments.\n static parseUrlHash(hash) {\n // Split path from args, path -> parts[0], args->path[1]\n const parts = hash.split('?', 2);\n const params = {};\n let path = [];\n if (parts[0]) {\n path = parts[0].replace('#', '').split('/');\n }\n if (parts[1]) {\n parts[1].split('&').forEach((arg) => {\n // Can't use split() because the value may contain '='.\n const eq = arg.indexOf('=');\n if (eq > 0) {\n params[arg.slice(0, eq)] = decodeURIComponent(arg.slice(eq + 1));\n }\n });\n }\n return {path: path, params: params};\n }\n\n static navigateTo(url) {\n window.location.hash = url;\n }\n\n static composeUrlHash(path, params) {\n let url = path.join('/');\n const args = [];\n for (const key in params) {\n if (params.hasOwnProperty(key)) {\n args.push(key + '=' + encodeURIComponent(params[key]));\n }\n }\n if (args.length > 0) {\n url += '?' + args.join('&');\n }\n return url;\n }\n\n static addUrlParam(hash, key, value) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.params[key] = value;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static removeUrlParam(hash, key) {\n const parsed = HashNavigation.parseUrlHash(hash);\n delete parsed.params[key];\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlSidePanel(hash, sidepanel) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.path[0] = sidepanel;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlInfoPanel(hash, infopanel) {\n const parsed = HashNavigation.parseUrlHash(hash);\n if (infopanel) {\n parsed.params.info = infopanel;\n } else {\n delete parsed.params.info;\n }\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlTopic(hash, topic) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.path[1] = topic;\n // Close InfoView on topic change.\n delete parsed.params.info;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n}\n","// Short representation of time in the past.\nexport function shortDateFormat(then, locale) {\n locale = locale || window.navigator.userLanguage || window.navigator.language;\n const now = new Date();\n if (then.getFullYear() == now.getFullYear()) {\n // Same year.\n if (then.getMonth() == now.getMonth() && then.getDate() == now.getDate()) {\n // Same month and day, show time only.\n return then.toLocaleTimeString(locale, {hour12: false, hour: '2-digit', minute: '2-digit'});\n }\n // Different month and/or day, show month day, time.\n return then.toLocaleDateString(locale,\n {hour12: false, month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'});\n }\n // Different year: just show the date.\n return then.toLocaleDateString(locale, {year: 'numeric', month: 'short', day: 'numeric'});\n}\n\n// Representation a date relative to now.\nexport function relativeDateFormat(then, locale) {\n locale = locale || window.navigator.userLanguage || window.navigator.language;\n const now = new Date();\n const thenDays = Math.floor((then.getTime() - then.getTimezoneOffset() * 60_000) / 86_400_000);\n const nowDays = Math.floor((now.getTime() - now.getTimezoneOffset() * 60_000) / 86_400_000);\n const diff = thenDays - nowDays;\n if (Math.abs(diff) < 2) {\n // Today or yesterday.\n return new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(diff, 'day')\n }\n // More than two days: just show the date.\n return new Intl.DateTimeFormat(locale).format(then);\n}\n\n// Convert seconds to [hours:]minutes:seconds, i.e. 156 sec -> 2:36, 3756 sec -> 1:02:36.\n// If fixedMins is true, then minutes are represented by at least two digits.\nexport function secondsToTime(seconds, fixedMin) {\n if (typeof seconds != 'number') {\n return '';\n }\n\n let min = (Math.floor(seconds / 60) | 0) % 60;\n let hours = Math.floor(seconds / 3600) | 0;\n\n if (fixedMin || hours > 0) {\n min = min < 10 ? `0${min}` : min;\n }\n let sec = (seconds | 0) % 60;\n sec = sec < 10 ? `0${sec}` : sec;\n if (hours == 0) {\n return `${min}:${sec}`;\n }\n return `${hours}:${min}:${sec}`;\n}\n\n// Convert a number of bytes to human-readable format.\nexport function bytesToHumanSize(bytes) {\n if (!bytes || bytes == 0) {\n return '0 Bytes';\n }\n\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];\n const bucket = Math.min(Math.floor(Math.log2(bytes) / 10) | 0, sizes.length-1);\n const count = bytes / Math.pow(1024, bucket);\n const round = bucket > 0 ? (count < 3 ? 2 : (count < 30 ? 1 : 0)) : 0;\n return count.toFixed(round) + ' ' + sizes[bucket];\n}\n\n// Shorten a file name to be under maxLength by clipping out the middle.\nexport function shortenFileName(filename, maxLength) {\n if (typeof filename != 'string') {\n return filename;\n }\n return filename.length > maxLength ?\n filename.slice(0, maxLength/2 - 1) + '…' + filename.slice(1 - maxLength/2) : filename;\n}\n\n// Get 32 bit integer hash value for a string. Ideally it should produce the same value\n// as Java's String#hash().\nfunction stringToColorHash(value) {\n let hash = 0;\n value = '' + value;\n for (let i = 0; i < value.length; i++) {\n hash = ((hash << 5) - hash) + value.charCodeAt(i);\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash;\n}\n\n// User avatar letter color id.\nexport function letterTileColorId(userId) {\n return Math.abs(stringToColorHash(userId)) % 16;\n}\n\n// Converts user or topic ID to a CSS color class. Ideally it should produce the same color value as Java version.\n// params:\n// - {string} id: user or topic ID\n// - {boolean} light: light or dark version of the color.\n// - {boolean} fg: foreground (text) or background color.\nexport function idToColorClass(id, light, fg) {\n return (light ? 'lt-' : 'dk-') + (fg ? 'fg-' : 'bg-') + letterTileColorId(id);\n}\n\n// Takes ISO Alpha-2 country code, like 'US' and converts it to a flag emoji.\nexport function flagEmoji(countryCode) {\n const codePoints = countryCode\n .toUpperCase()\n .split('')\n .map(char => 0x1F1A5 + char.charCodeAt());\n return String.fromCodePoint(...codePoints);\n}\n","// Odds and ends\n\nimport { Tinode } from 'tinode-sdk';\n\n// Make shortcut icon appear with a green dot + show unread count in title.\nexport function updateFavicon(count) {\n const oldIcon = document.getElementById('shortcut-icon');\n const head = document.head || document.getElementsByTagName('head')[0];\n const newIcon = document.createElement('link');\n newIcon.type = 'image/png';\n newIcon.id = 'shortcut-icon';\n newIcon.rel = 'shortcut icon';\n newIcon.href = 'img/logo32x32' + (count > 0 ? 'a' : '') + '.png';\n if (oldIcon) {\n head.removeChild(oldIcon);\n }\n head.appendChild(newIcon);\n\n document.title = (count > 0 ? '('+count+') ' : '') + 'Tinode';\n}\n\n// Create theCard which represents user's or topic's \"public\" info.\nexport function theCard(fn, imageUrl, imageMimeType, note) {\n let card = null;\n fn = fn && fn.trim();\n note = note && note.trim();\n\n if (fn) {\n card = {\n fn: fn\n };\n }\n\n if (typeof note == 'string') {\n card = card || {};\n card.note = note ? note : Tinode.DEL_CHAR;\n }\n\n if (imageUrl) {\n card = card || {};\n let mimeType = imageMimeType;\n // Is this a data URL \"data:[ field: the URL must be a relative URL or\n// have http:, https:, blob: or data: scheme.\n// In case of data: scheme, the URL must must be of the right MIME type such as 'data:{mimeMajor}/XXXX;base64,'.\nexport function sanitizeUrlForMime(url, mimeMajor) {\n if (!url) {\n return null;\n }\n\n const sanitizedUrl = sanitizeUrl(url);\n if (sanitizedUrl) {\n return sanitizedUrl;\n }\n\n // Is this a data: URL of the appropriate mime type?\n const re = new RegExp(`data:${mimeMajor}\\/[a-z0-9.-]+;base64,`, 'i');\n if (re.test(url.trim())) {\n return url;\n }\n\n return null;\n}\n\n// Given message's received status, return name and color of a delivery indicator icon.\nexport function deliveryMarker(received) {\n switch (received) {\n case Tinode.MESSAGE_STATUS_SENDING:\n return { name: 'access_time' }; // watch face\n case Tinode.MESSAGE_STATUS_FAILED:\n case Tinode.MESSAGE_STATUS_FATAL:\n return { name: 'warning', color: 'danger-color' }; // yellow icon /!\\\n case Tinode.MESSAGE_STATUS_SENT:\n return { name: 'done' }; // checkmark\n case Tinode.MESSAGE_STATUS_RECEIVED:\n return { name: 'done_all' }; // double checkmark\n case Tinode.MESSAGE_STATUS_READ:\n return { name: 'done_all', color: 'blue' }; // blue double checkmark\n }\n return null;\n}\n\n// Wraps a promise to make it cancelable.\n// The parameter can be either a promise or an error. If it's an error, the wrapped promise is\n// created in a rejected state.\nexport function cancelablePromise(promise) {\n let hasCanceled = false;\n\n const wrappedPromise = promise instanceof Error ?\n Promise.reject(promise) :\n new Promise((resolve, reject) => {\n promise.then(\n result => hasCanceled ? reject({isCanceled: true}) : resolve(result),\n error => hasCanceled ? reject({isCanceled: true}) : reject(error)\n );\n });\n\n return {\n promise: wrappedPromise,\n cancel() {\n hasCanceled = true;\n },\n };\n};\n\n// Clips string to the specified length.\nexport function clipStr(str, length) {\n return str && str.substring(0, length);\n}\n","// This is a generated file. Don't edit.\n\nexport const PACKAGE_VERSION = \"0.23.0-rc1\";\n","// Audio recorder widget.\n\nimport React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nimport { secondsToTime } from '../lib/strformat';\nimport { base64ToIntArray } from '../lib/blob-helpers';\n\n// Make canvas bigger than the element size to reduce blurring.\nconst CANVAS_UPSCALING = 2.0;\n// Thickness of a visualization bar.\nconst LINE_WIDTH = 3 * CANVAS_UPSCALING;\n// Spacing between two visualization bars.\nconst SPACING = 2 * CANVAS_UPSCALING;\n// Color of histogram bars.\nconst BAR_COLOR = '#888A';\nconst BAR_COLOR_DARK = '#666C';\nconst THUMB_COLOR = '#444E';\n// Minimum number of amplitude bars to draw.\nconst MIN_PREVIEW_LENGTH = 16;\n\nconst messages = defineMessages({\n icon_title_play: {\n id: 'icon_title_play',\n defaultMessage: 'Play recording',\n description: 'Icon tool tip for starting audio playback'\n }\n});\n\nclass AudioPlayer extends React.PureComponent {\n constructor(props) {\n super(props);\n\n let preview = base64ToIntArray(this.props.preview);\n if (!Array.isArray(preview) || preview.length < MIN_PREVIEW_LENGTH) {\n preview = null;\n }\n\n this.state = {\n canPlay: false,\n playing: false,\n currentTime: '0:00',\n duration: this.props.duration > 0 ? secondsToTime(this.props.duration / 1000) : '-:--',\n longMin: this.props.duration >= 600000,\n preview: preview\n };\n\n this.initAudio = this.initAudio.bind(this);\n this.initCanvas = this.initCanvas.bind(this);\n this.resampleBars = this.resampleBars.bind(this);\n this.visualize = this.visualize.bind(this);\n\n this.handlePlay = this.handlePlay.bind(this);\n this.handleSeek = this.handleSeek.bind(this);\n this.handleError = this.handleError.bind(this);\n\n this.audioPlayer = null;\n\n this.viewBuffer = [];\n this.canvasRef = React.createRef();\n }\n\n componentDidMount() {\n if (this.props.src) {\n this.initAudio();\n }\n\n this.initCanvas();\n }\n\n componentWillUnmount() {\n if (this.audioPlayer) {\n this.audioPlayer.onloadedmetadata = null;\n this.audioPlayer.ontimeupdate = null;\n this.audioPlayer.onended = null;\n this.audioPlayer.pause();\n this.audioPlayer = null;\n }\n }\n\n componentDidUpdate(prevProps) {\n if (this.props.src != prevProps.src) {\n this.initAudio();\n }\n\n if (this.props.preview != prevProps.preview) {\n let preview = base64ToIntArray(this.props.preview);\n if (!Array.isArray(preview) || preview.length < MIN_PREVIEW_LENGTH) {\n preview = null;\n }\n this.setState({preview: preview}, this.initCanvas);\n }\n }\n\n initAudio() {\n this.audioPlayer = new Audio(this.props.src);\n this.audioPlayer.onloadedmetadata = _ => this.setState({canPlay: true});\n this.audioPlayer.ontimeupdate = _ => this.setState({\n currentTime: secondsToTime(this.audioPlayer.currentTime, this.state.longMin)\n });\n this.audioPlayer.onended = _ => {\n this.audioPlayer.currentTime = 0;\n this.setState({playing: false, currentTime: secondsToTime(0, this.state.longMin)})\n }\n }\n\n initCanvas() {\n // Force canvas aspect ratio to match one of the element + upscale canvas to reduce blurring.\n this.canvasRef.current.width = this.canvasRef.current.offsetWidth * CANVAS_UPSCALING;\n this.canvasRef.current.height = this.canvasRef.current.offsetHeight * CANVAS_UPSCALING;\n\n this.canvasContext = this.canvasRef.current.getContext('2d');\n this.canvasContext.lineCap = 'round';\n\n this.viewBuffer = this.resampleBars(this.state.preview);\n this.visualize();\n }\n\n // Draw amplitude of sound.\n visualize() {\n if (!this.canvasRef.current) {\n return;\n }\n\n const width = this.effectiveWidth;\n const height = this.canvasRef.current.height;\n\n this.canvasContext.lineWidth = LINE_WIDTH;\n\n const drawFrame = _ => {\n if (!this.canvasRef.current || !this.audioPlayer) {\n // The component is unmounted.\n return;\n }\n\n this.canvasContext.clearRect(0, 0, this.canvasRef.current.width, height);\n\n if (this.viewBuffer) {\n if (this.state.playing) {\n window.requestAnimationFrame(drawFrame);\n }\n\n // Current playback position.\n const thumbAt = this.props.duration ?\n Math.max(0, Math.min(this.audioPlayer.currentTime * 1000 / this.props.duration, 1)) * (width - LINE_WIDTH * 2) : -1;\n\n // Draw amplitude bars.\n this.canvasContext.beginPath();\n this.canvasContext.strokeStyle = BAR_COLOR_DARK;\n for (let i = 0; i < this.viewBuffer.length; i++) {\n let x = 1 + i * (LINE_WIDTH + SPACING) + LINE_WIDTH * 0.5;\n let y = Math.max(this.viewBuffer[i] * height * 0.9, 1);\n\n const color = x < thumbAt ? BAR_COLOR_DARK : BAR_COLOR;\n if (this.canvasContext.strokeStyle != color) {\n this.canvasContext.stroke();\n this.canvasContext.beginPath();\n this.canvasContext.strokeStyle = color;\n }\n\n this.canvasContext.moveTo(x, (height - y) * 0.5);\n this.canvasContext.lineTo(x, (height + y) * 0.5);\n }\n // Actually draw the bars on canvas.\n this.canvasContext.stroke();\n\n // Draw thumb.\n if (this.props.duration) {\n this.canvasContext.beginPath();\n this.canvasContext.arc(thumbAt + LINE_WIDTH * 2, height * 0.5, LINE_WIDTH * 2, 0, 2 * Math.PI);\n this.canvasContext.fillStyle = THUMB_COLOR;\n this.canvasContext.fill();\n }\n }\n }\n\n drawFrame();\n }\n\n // Quick and dirty downsampling of the original preview bars into a smaller (or equal) number of bars we can display here.\n resampleBars(original) {\n const dstCount = ((this.canvasRef.current.width - SPACING) / (LINE_WIDTH + SPACING)) | 0;\n // Remove extra padding on the right due to fractional bar which is not drawn.\n this.effectiveWidth = dstCount * (LINE_WIDTH + SPACING) + SPACING;\n\n if (!Array.isArray(original) || original.length == 0) {\n return Array.apply(null, Array(dstCount)).map(_ => 0.01);\n }\n\n const factor = original.length / dstCount;\n let amps = [];\n let maxAmp = -1;\n for (let i=0; i
\n \n \n
:\n this.props.readOnly && this.props.uid ?\n
{e.target.onerror = null; e.target.src=\"../img/broken_image.png\"}} />;\n } else {\n avatar = null;\n }\n return avatar;\n }\n}\n","import React from 'react';\n\nexport default class LoadSpinner extends React.PureComponent {\n render() {\n const className = 'load-spinner-box' + (this.props.large ? ' large' : '')\n + (this.props.clear ? ' clear' : '') + (this.props.centered ? ' centered' : '');\n return (this.props.show ?\n
\n {menu}\n
\n );\n }\n}\n\nexport default injectIntl(ContextMenu);\n","import React from 'react';\n\nconst icon_mapping = {'muted': 'notifications_off', 'banned': 'block', 'staff': 'verified_user'};\n\n/* Contact's labels: [you], or icons [muted], [blocked] */\nexport default class ContactBadges extends React.PureComponent {\n render() {\n let badges = null;\n if (this.props.badges && this.props.badges.length > 0) {\n badges = [];\n this.props.badges.forEach(b => {\n const color = (b.color ? ' ' + b.color : '');\n if (b.icon) {\n badges.push({icon_mapping[b.icon] || b.icon});\n } else {\n badges.push({b.name});\n }\n });\n return <>{badges}>;\n }\n return null;\n }\n};\n","// The counter of unread messages in the topic.\nimport React from 'react';\n\nexport default class UnreadBadge extends React.PureComponent {\n render() {\n return (this.props.count > 0 ?\n {this.props.count > 9 ? \"9+\" : this.props.count}\n : null);\n }\n};\n","// Chat message describing a video or voice call.\n\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { secondsToTime } from '../lib/strformat.js';\n\nexport default class CallMessage extends React.PureComponent {\n render() {\n const isCallDropped = ['busy', 'declined', 'disconnected', 'missed'].includes(this.props.callState);\n const successClass = 'material-icons medium ' + (isCallDropped ? 'red' : 'green');\n const callIcon = this.props.incoming ?\n (isCallDropped ? 'call_missed' : 'call_received') :\n (isCallDropped ? 'call_missed_outgoing' : 'call_made');\n let duration;\n if (isCallDropped) {\n switch (this.props.callState) {\n case 'busy':\n duration =
}\n .\n el = UploadingImage;\n }\n\n return el;\n}\n\n// Additional processing of image data.\nfunction handleVideoData(el, data, attr) {\n if (!data) {\n attr.src = 'img/broken_video.png';\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n };\n return el;\n }\n attr.className = 'inline-image';\n const dim = fitImageSize(data.width, data.height,\n this.viewportWidth > 0 ? Math.min(this.viewportWidth - REM_SIZE * 6.5, REM_SIZE * 34.5) :\n REM_SIZE * 34.5, REM_SIZE * 24, false) ||\n {dstWidth: NO_DIMENSIONS_VIDEO, dstHeight: NO_DIMENSIONS_VIDEO};\n attr.style = {\n width: dim.dstWidth + 'px',\n height: dim.dstHeight + 'px',\n // Looks like a Chrome bug: broken image does not respect 'width' and 'height'.\n minWidth: dim.dstWidth + 'px',\n minHeight: dim.dstHeight + 'px'\n };\n if (!Drafty.isProcessing(data)) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'image'));\n attr.alt = data.name;\n if (data.ref || data.val) {\n attr.onClick = this.onVideoPreview;\n attr.loading = 'lazy';\n }\n el = InlineVideo;\n } else {\n // Use custom element instead of
.\n el = UploadingImage;\n }\n\n return el;\n}\n\n// Converts Drafty object into a one-line preview. 'this' is set by the caller.\n// 'this' must contain:\n// formatMessage: this.props.intl.formatMessage\n// messages: formatjs messages defined with defineMessages.\nexport function previewFormatter(style, data, values, key) {\n if (!style) {\n // Unformatted.\n return values;\n }\n\n let el = Drafty.tagName(style);\n const attr = { key: key };\n switch (style) {\n case 'AU':\n // Voicemail as '[mic] 0:00'.\n el = React.Fragment;\n values = [mic, ' ', secondsToTime(data.duration/1000)];\n break;\n case 'BR':\n // Replace new line with a space.\n el = React.Fragment;\n values = [' '];\n break;\n case 'HL':\n // Make highlight less prominent in preview.\n attr.className = 'highlight preview';\n break;\n case 'LN':\n case 'MN':\n // Disable links in previews.\n el = 'span';\n break;\n case 'IM':\n // Replace image with '[icon] Image'.\n el = React.Fragment;\n values = [photo, ' ', this.formatMessage(messages.drafty_image)];\n break;\n case 'BN':\n el = 'span';\n attr.className = 'flat-button faux';\n break;\n case 'FM':\n el = React.Fragment;\n values = [dashboard,\n this.formatMessage(messages.drafty_form)].concat(' ', values || []);\n break;\n case 'RW':\n el = React.Fragment;\n break;\n case 'EX':\n if (data) {\n if (data.mime == 'application/json') {\n // Ignore JSON attachments: they are form response payloads.\n return null;\n }\n // Clear payload.\n delete data.val;\n delete data.ref;\n }\n el = React.Fragment;\n values = [attachment, ' ', this.formatMessage(messages.drafty_attachment)];\n break;\n case 'VC':\n el = CallStatus;\n if (data) {\n attr.callState = data.state;\n attr.incoming = data.incoming;\n attr.duration = data.duration;\n }\n values = null;\n break;\n case 'QQ':\n case 'HD':\n el = null;\n values = null;\n break;\n case 'VD':\n // Replace image with '[icon] Video'.\n el = React.Fragment;\n values = [play_circle_outline, ' ', this.formatMessage(messages.drafty_video)];\n break;\n default:\n if (!el) {\n // Unknown element.\n el = React.Fragment;\n values = [extension, ' ', this.formatMessage(messages.drafty_unknown)];\n }\n break;\n }\n if (!el) {\n return values;\n }\n return React.createElement(el, attr, values);\n};\n\n// Converts Drafty object into a quoted reply; 'this' is set by the caller.\nfunction inlineImageAttr(attr, data) {\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n maxWidth: IMAGE_THUMBNAIL_DIM + 'px',\n maxHeight: IMAGE_THUMBNAIL_DIM + 'px',\n }\n attr.className = 'inline-image';\n attr.alt = this.formatMessage(messages.drafty_image);\n if (!data) {\n attr.src = 'img/broken_image.png';\n } else {\n attr.src = attr.src || 'img/broken_image.png';\n }\n attr.title = attr.alt;\n return attr;\n}\n\n// Converts Drafty object into a quoted reply; 'this' is set by the caller.\nfunction inlineVideoAttr(attr, data) {\n const dim = fitImageSize(data.width, data.height, VIDEO_THUMBNAIL_WIDTH, IMAGE_THUMBNAIL_DIM);\n attr.style = {\n width: dim.width + 'px',\n height: dim.height + 'px',\n maxWidth: VIDEO_THUMBNAIL_WIDTH + 'px',\n maxHeight: IMAGE_THUMBNAIL_DIM + 'px',\n }\n attr.className = 'inline-image';\n attr.alt = this.formatMessage(messages.drafty_video);\n attr.title = attr.alt;\n if (!data) {\n attr.src = 'img/broken_video.png';\n } else {\n attr.src = attr.src || 'img/broken_video.png';\n }\n return attr;\n}\n\n// Displays a portion of Drafty within 'QQ' quotes. 'this' is set by the caller.\n// 'this' must contain:\n// formatMessage: this.props.intl.formatMessage\n// messages: formatjs messages defined with defineMessages.\n// authorizeURL: this.props.tinode.authorizeURL\n// onQuoteClick: this.handleQuoteClick (optional)\nfunction quoteFormatter(style, data, values, key) {\n if (['BR', 'EX', 'IM', 'MN', 'VD'].includes(style)) {\n let el = Drafty.tagName(style);\n let attr = Drafty.attrValue(style, data) || {};\n attr.key = key;\n switch(style) {\n case 'BR':\n values = null;\n break;\n case 'IM':\n attr = inlineImageAttr.call(this, attr, data);\n values = [React.createElement('img', attr, null), ' ', attr.alt];\n el = React.Fragment;\n // Fragment attributes.\n attr = {key: key};\n break;\n case 'VD':\n attr = inlineVideoAttr.call(this, attr, data);\n values = [React.createElement('img', attr, null), ' ', attr.alt];\n el = React.Fragment;\n // Fragment attributes.\n attr = {key: key};\n break;\n case 'MN':\n el = 'span';\n attr.className = 'mention'\n if (data) {\n attr.className += ' ' + idToColorClass(data.val, false, true);\n }\n break;\n case 'EX':\n let fname;\n if (data) {\n if (data.mime == 'application/json') {\n // Ignore JSON attachments: they are form response payloads.\n return null;\n }\n fname = data.name;\n // Clear payload.\n delete data.val;\n delete data.ref;\n }\n el = React.Fragment;\n values = [attachment,\n shortenFileName(fname, 16) || this.formatMessage(messages.drafty_attachment)];\n break;\n }\n return React.createElement(el, attr, values);\n }\n return previewFormatter.call(this, style, data, values, key);\n}\n\n// Create image thumbnail suitable for inclusion in a quote.\nfunction quoteImageOrVideo(data, isVideo) {\n let promise;\n let bits, ref, mime;\n if (isVideo) {\n bits = data.preview;\n mime = data.premime || 'image/jpeg';\n ref = data.preref;\n } else {\n bits = data.val;\n mime = data.mime;\n ref = data.ref;\n }\n // Get the blob from the image data.\n if (bits) {\n const blob = base64ToBlob(bits, mime);\n if (!blob) {\n throw new Error(\"Invalid image\");\n }\n promise = Promise.resolve(blob);\n } else if (ref) {\n promise = fetch(this.authorizeURL(sanitizeUrlForMime(ref, 'image')))\n .then(evt => {\n if (evt.ok) {\n return evt.blob();\n } else {\n throw new Error(`Image fetch unsuccessful: ${evt.status} ${evt.statusText}`);\n }\n });\n } else {\n throw new Error(\"Missing image data\");\n }\n\n // Scale the blob.\n return promise\n .then(blob => {\n // If it's an image, cut the square from the center of the image and shrink it.\n // If it's a video, allow it to be rectantular.\n return imageScaled(blob, isVideo ? VIDEO_THUMBNAIL_WIDTH : IMAGE_THUMBNAIL_DIM, IMAGE_THUMBNAIL_DIM, -1, !isVideo)\n }).then(scaled => {\n if (isVideo) {\n data.premime = scaled.mime;\n } else {\n data.mime = scaled.mime;\n }\n data.size = scaled.blob.size;\n data.width = scaled.width;\n data.height = scaled.height;\n delete data.ref;\n delete data.preref;\n // Keeping the original file name, if provided: ex.data.name;\n\n data.src = URL.createObjectURL(scaled.blob);\n return blobToBase64(scaled.blob);\n }).then(b64 => {\n if (isVideo) {\n data.preview = b64.bits;\n } else {\n data.val = b64.bits;\n }\n return data;\n }).catch(err => {\n delete data.val;\n delete data.preview;\n delete data.src;\n data.width = IMAGE_THUMBNAIL_DIM;\n data.height = IMAGE_THUMBNAIL_DIM;\n // Rethrow.\n throw err;\n });\n}\n\n// Create a preview of a reply.\nexport function replyFormatter(style, data, values, key, stack) {\n if (style == 'IM' || style == 'VD') {\n const isImage = style == 'IM';\n const attr = isImage ? inlineImageAttr.call(this, {key: key}, data) :\n inlineVideoAttr.call(this, {key: key}, data);\n\n let loadedPromise;\n try {\n loadedPromise = cancelablePromise(quoteImageOrVideo.call(this, data, style == 'VD'));\n } catch (error) {\n console.warn(\"Failed to quote image:\", error.message);\n loadedPromise = cancelablePromise(error);\n }\n attr.whenDone = loadedPromise;\n values = [React.createElement(LazyImage, attr, null), ' ', attr.alt];\n return React.createElement(React.Fragment, {key: key}, values);\n } else if (style == 'QQ') {\n if (stack.includes('QQ')) {\n // Quote inside quote when forwarding a message.\n return React.createElement('span', {key: key},\n [format_quote, ' ']);\n }\n\n const attr = Drafty.attrValue('QQ', data) || {};\n attr.key = key;\n attr.className = 'reply-quote'\n return React.createElement(Drafty.tagName('QQ'), attr, values);\n }\n return quoteFormatter.call(this, style, data, values, key);\n}\n","// A single topic or user.\nimport React from 'react';\nimport { FormattedMessage, injectIntl } from 'react-intl';\n\nimport ContactBadges from './contact-badges.jsx';\nimport LetterTile from './letter-tile.jsx';\nimport UnreadBadge from './unread-badge.jsx';\n\nimport { Drafty } from 'tinode-sdk';\n\nimport { previewFormatter } from '../lib/formatters.js';\nimport { deliveryMarker } from '../lib/utils.js';\n\nclass Contact extends React.Component {\n constructor(props) {\n super(props);\n\n this.handleClick = this.handleClick.bind(this);\n this.handleContextClick = this.handleContextClick.bind(this);\n }\n\n handleClick(e) {\n e.preventDefault();\n e.stopPropagation();\n if (this.props.onSelected) {\n // Index this.props.index is used by GroupManager.\n this.props.onSelected(this.props.item, this.props.index);\n }\n }\n\n handleContextClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.showContextMenu({ topicName: this.props.item, y: e.pageY, x: e.pageX });\n }\n\n render() {\n let title = this.props.title;\n if (!title) {\n title =
: null}\n \n {contactNodes}\n
\n :\n null\n }\n \n \n );\n }\n\n return (\n {names[c]} \n {skip.indexOf(c) < 0 ?\n {this.props.compare ? \n : null}\n
: null}\n \n \n {this.props.compare ?\n
\n \n :\n null}\n \n {items}\n {this.props.modeTitle} \n {this.props.compareTitle} \n
\n
: null}\n
\n {messageNodes}\n
\n fixedMins is true, then minutes are represented by at least two digits.\nexport function secondsToTime(seconds, fixedMin) {\n if (typeof seconds != 'number') {\n return '';\n }\n\n let min = (Math.floor(seconds / 60) | 0) % 60;\n let hours = Math.floor(seconds / 3600) | 0;\n\n if (fixedMin || hours > 0) {\n min = min < 10 ? `0${min}` : min;\n }\n let sec = (seconds | 0) % 60;\n sec = sec < 10 ? `0${sec}` : sec;\n if (hours == 0) {\n return `${min}:${sec}`;\n }\n return `${hours}:${min}:${sec}`;\n}\n\n// Convert a number of bytes to human-readable format.\nexport function bytesToHumanSize(bytes) {\n if (!bytes || bytes == 0) {\n return '0 Bytes';\n }\n\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];\n const bucket = Math.min(Math.floor(Math.log2(bytes) / 10) | 0, sizes.length-1);\n const count = bytes / Math.pow(1024, bucket);\n const round = bucket > 0 ? (count < 3 ? 2 : (count < 30 ? 1 : 0)) : 0;\n return count.toFixed(round) + ' ' + sizes[bucket];\n}\n\n// Shorten a file name to be under maxLength by clipping out the middle.\nexport function shortenFileName(filename, maxLength) {\n if (typeof filename != 'string') {\n return filename;\n }\n return filename.length > maxLength ?\n filename.slice(0, maxLength/2 - 1) + '…' + filename.slice(1 - maxLength/2) : filename;\n}\n\n// Get 32 bit integer hash value for a string. Ideally it should produce the same value\n// as Java's String#hash().\nfunction stringToColorHash(value) {\n let hash = 0;\n value = '' + value;\n for (let i = 0; i < value.length; i++) {\n hash = ((hash << 5) - hash) + value.charCodeAt(i);\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash;\n}\n\n// User avatar letter color id.\nexport function letterTileColorId(userId) {\n return Math.abs(stringToColorHash(userId)) % 16;\n}\n\n// Converts user or topic ID to a CSS color class. Ideally it should produce the same color value as Java version.\n// params:\n// - {string} id: user or topic ID\n// - {boolean} light: light or dark version of the color.\n// - {boolean} fg: foreground (text) or background color.\nexport function idToColorClass(id, light, fg) {\n return (light ? 'lt-' : 'dk-') + (fg ? 'fg-' : 'bg-') + letterTileColorId(id);\n}\n\n// Takes ISO Alpha-2 country code, like 'US' and converts it to a flag emoji.\nexport function flagEmoji(countryCode) {\n const codePoints = countryCode\n .toUpperCase()\n .split('')\n .map(char => 0x1F1A5 + char.charCodeAt());\n return String.fromCodePoint(...codePoints);\n}\n","// Odds and ends\n\nimport { Tinode } from 'tinode-sdk';\n\n// Make shortcut icon appear with a green dot + show unread count in title.\nexport function updateFavicon(count) {\n const oldIcon = document.getElementById('shortcut-icon');\n const head = document.head || document.getElementsByTagName('head')[0];\n const newIcon = document.createElement('link');\n newIcon.type = 'image/png';\n newIcon.id = 'shortcut-icon';\n newIcon.rel = 'shortcut icon';\n newIcon.href = 'img/logo32x32' + (count > 0 ? 'a' : '') + '.png';\n if (oldIcon) {\n head.removeChild(oldIcon);\n }\n head.appendChild(newIcon);\n\n document.title = (count > 0 ? '('+count+') ' : '') + 'Tinode';\n}\n\n// Create theCard which represents user's or topic's \"public\" info.\nexport function theCard(fn, imageUrl, imageMimeType, note) {\n let card = null;\n fn = fn && fn.trim();\n note = note && note.trim();\n\n if (fn) {\n card = {\n fn: fn\n };\n }\n\n if (typeof note == 'string') {\n card = card || {};\n card.note = note ? note : Tinode.DEL_CHAR;\n }\n\n if (imageUrl) {\n card = card || {};\n let mimeType = imageMimeType;\n // Is this a data URL \"data:[ field: the URL must be a relative URL or\n// have http:, https:, blob: or data: scheme.\n// In case of data: scheme, the URL must must be of the right MIME type such as 'data:{mimeMajor}/XXXX;base64,'.\nexport function sanitizeUrlForMime(url, mimeMajor) {\n if (!url) {\n return null;\n }\n\n const sanitizedUrl = sanitizeUrl(url);\n if (sanitizedUrl) {\n return sanitizedUrl;\n }\n\n // Is this a data: URL of the appropriate mime type?\n const re = new RegExp(`data:${mimeMajor}\\/[a-z0-9.-]+;base64,`, 'i');\n if (re.test(url.trim())) {\n return url;\n }\n\n return null;\n}\n\n// Given message's received status, return name and color of a delivery indicator icon.\nexport function deliveryMarker(received) {\n switch (received) {\n case Tinode.MESSAGE_STATUS_SENDING:\n return { name: 'access_time' }; // watch face\n case Tinode.MESSAGE_STATUS_FAILED:\n case Tinode.MESSAGE_STATUS_FATAL:\n return { name: 'warning', color: 'danger-color' }; // yellow icon /!\\\n case Tinode.MESSAGE_STATUS_SENT:\n return { name: 'done' }; // checkmark\n case Tinode.MESSAGE_STATUS_RECEIVED:\n return { name: 'done_all' }; // double checkmark\n case Tinode.MESSAGE_STATUS_READ:\n return { name: 'done_all', color: 'blue' }; // blue double checkmark\n }\n return null;\n}\n\n// Wraps a promise to make it cancelable.\n// The parameter can be either a promise or an error. If it's an error, the wrapped promise is\n// created in a rejected state.\nexport function cancelablePromise(promise) {\n let hasCanceled = false;\n\n const wrappedPromise = promise instanceof Error ?\n Promise.reject(promise) :\n new Promise((resolve, reject) => {\n promise.then(\n result => hasCanceled ? reject({isCanceled: true}) : resolve(result),\n error => hasCanceled ? reject({isCanceled: true}) : reject(error)\n );\n });\n\n return {\n promise: wrappedPromise,\n cancel() {\n hasCanceled = true;\n },\n };\n};\n\n// Clips string to the specified length.\nexport function clipStr(str, length) {\n return str && str.substring(0, length);\n}\n","// This is a generated file. Don't edit.\n\nexport const PACKAGE_VERSION = \"0.23.0-rc1\";\n","// Audio recorder widget.\n\nimport React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nimport { secondsToTime } from '../lib/strformat';\nimport { base64ToIntArray } from '../lib/blob-helpers';\n\n// Make canvas bigger than the element size to reduce blurring.\nconst CANVAS_UPSCALING = 2.0;\n// Thickness of a visualization bar.\nconst LINE_WIDTH = 3 * CANVAS_UPSCALING;\n// Spacing between two visualization bars.\nconst SPACING = 2 * CANVAS_UPSCALING;\n// Color of histogram bars.\nconst BAR_COLOR = '#888A';\nconst BAR_COLOR_DARK = '#666C';\nconst THUMB_COLOR = '#444E';\n// Minimum number of amplitude bars to draw.\nconst MIN_PREVIEW_LENGTH = 16;\n\nconst messages = defineMessages({\n icon_title_play: {\n id: 'icon_title_play',\n defaultMessage: 'Play recording',\n description: 'Icon tool tip for starting audio playback'\n }\n});\n\nclass AudioPlayer extends React.PureComponent {\n constructor(props) {\n super(props);\n\n let preview = base64ToIntArray(this.props.preview);\n if (!Array.isArray(preview) || preview.length < MIN_PREVIEW_LENGTH) {\n preview = null;\n }\n\n this.state = {\n canPlay: false,\n playing: false,\n currentTime: '0:00',\n duration: this.props.duration > 0 ? secondsToTime(this.props.duration / 1000) : '-:--',\n longMin: this.props.duration >= 600000,\n preview: preview\n };\n\n this.initAudio = this.initAudio.bind(this);\n this.initCanvas = this.initCanvas.bind(this);\n this.resampleBars = this.resampleBars.bind(this);\n this.visualize = this.visualize.bind(this);\n\n this.handlePlay = this.handlePlay.bind(this);\n this.handleSeek = this.handleSeek.bind(this);\n this.handleError = this.handleError.bind(this);\n\n this.audioPlayer = null;\n\n this.viewBuffer = [];\n this.canvasRef = React.createRef();\n }\n\n componentDidMount() {\n if (this.props.src) {\n this.initAudio();\n }\n\n this.initCanvas();\n }\n\n componentWillUnmount() {\n if (this.audioPlayer) {\n this.audioPlayer.onloadedmetadata = null;\n this.audioPlayer.ontimeupdate = null;\n this.audioPlayer.onended = null;\n this.audioPlayer.pause();\n this.audioPlayer = null;\n }\n }\n\n componentDidUpdate(prevProps) {\n if (this.props.src != prevProps.src) {\n this.initAudio();\n }\n\n if (this.props.preview != prevProps.preview) {\n let preview = base64ToIntArray(this.props.preview);\n if (!Array.isArray(preview) || preview.length < MIN_PREVIEW_LENGTH) {\n preview = null;\n }\n this.setState({preview: preview}, this.initCanvas);\n }\n }\n\n initAudio() {\n this.audioPlayer = new Audio(this.props.src);\n this.audioPlayer.onloadedmetadata = _ => this.setState({canPlay: true});\n this.audioPlayer.ontimeupdate = _ => this.setState({\n currentTime: secondsToTime(this.audioPlayer.currentTime, this.state.longMin)\n });\n this.audioPlayer.onended = _ => {\n this.audioPlayer.currentTime = 0;\n this.setState({playing: false, currentTime: secondsToTime(0, this.state.longMin)})\n }\n }\n\n initCanvas() {\n // Force canvas aspect ratio to match one of the element + upscale canvas to reduce blurring.\n this.canvasRef.current.width = this.canvasRef.current.offsetWidth * CANVAS_UPSCALING;\n this.canvasRef.current.height = this.canvasRef.current.offsetHeight * CANVAS_UPSCALING;\n\n this.canvasContext = this.canvasRef.current.getContext('2d');\n this.canvasContext.lineCap = 'round';\n\n this.viewBuffer = this.resampleBars(this.state.preview);\n this.visualize();\n }\n\n // Draw amplitude of sound.\n visualize() {\n if (!this.canvasRef.current) {\n return;\n }\n\n const width = this.effectiveWidth;\n const height = this.canvasRef.current.height;\n\n this.canvasContext.lineWidth = LINE_WIDTH;\n\n const drawFrame = _ => {\n if (!this.canvasRef.current || !this.audioPlayer) {\n // The component is unmounted.\n return;\n }\n\n this.canvasContext.clearRect(0, 0, this.canvasRef.current.width, height);\n\n if (this.viewBuffer) {\n if (this.state.playing) {\n window.requestAnimationFrame(drawFrame);\n }\n\n // Current playback position.\n const thumbAt = this.props.duration ?\n Math.max(0, Math.min(this.audioPlayer.currentTime * 1000 / this.props.duration, 1)) * (width - LINE_WIDTH * 2) : -1;\n\n // Draw amplitude bars.\n this.canvasContext.beginPath();\n this.canvasContext.strokeStyle = BAR_COLOR_DARK;\n for (let i = 0; i < this.viewBuffer.length; i++) {\n let x = 1 + i * (LINE_WIDTH + SPACING) + LINE_WIDTH * 0.5;\n let y = Math.max(this.viewBuffer[i] * height * 0.9, 1);\n\n const color = x < thumbAt ? BAR_COLOR_DARK : BAR_COLOR;\n if (this.canvasContext.strokeStyle != color) {\n this.canvasContext.stroke();\n this.canvasContext.beginPath();\n this.canvasContext.strokeStyle = color;\n }\n\n this.canvasContext.moveTo(x, (height - y) * 0.5);\n this.canvasContext.lineTo(x, (height + y) * 0.5);\n }\n // Actually draw the bars on canvas.\n this.canvasContext.stroke();\n\n // Draw thumb.\n if (this.props.duration) {\n this.canvasContext.beginPath();\n this.canvasContext.arc(thumbAt + LINE_WIDTH * 2, height * 0.5, LINE_WIDTH * 2, 0, 2 * Math.PI);\n this.canvasContext.fillStyle = THUMB_COLOR;\n this.canvasContext.fill();\n }\n }\n }\n\n drawFrame();\n }\n\n // Quick and dirty downsampling of the original preview bars into a smaller (or equal) number of bars we can display here.\n resampleBars(original) {\n const dstCount = ((this.canvasRef.current.width - SPACING) / (LINE_WIDTH + SPACING)) | 0;\n // Remove extra padding on the right due to fractional bar which is not drawn.\n this.effectiveWidth = dstCount * (LINE_WIDTH + SPACING) + SPACING;\n\n if (!Array.isArray(original) || original.length == 0) {\n return Array.apply(null, Array(dstCount)).map(_ => 0.01);\n }\n\n const factor = original.length / dstCount;\n let amps = [];\n let maxAmp = -1;\n for (let i=0; i
\n \n \n
:\n this.props.readOnly && this.props.uid ?\n
{e.target.onerror = null; e.target.src=\"../img/broken_image.png\"}} />;\n } else {\n avatar = null;\n }\n return avatar;\n }\n}\n","import React from 'react';\n\nexport default class LoadSpinner extends React.PureComponent {\n render() {\n const className = 'load-spinner-box' + (this.props.large ? ' large' : '')\n + (this.props.clear ? ' clear' : '') + (this.props.centered ? ' centered' : '');\n return (this.props.show ?\n
\n {menu}\n
\n );\n }\n}\n\nexport default injectIntl(ContextMenu);\n","import React from 'react';\n\nconst icon_mapping = {'muted': 'notifications_off', 'banned': 'block', 'staff': 'verified_user'};\n\n/* Contact's labels: [you], or icons [muted], [blocked] */\nexport default class ContactBadges extends React.PureComponent {\n render() {\n let badges = null;\n if (this.props.badges && this.props.badges.length > 0) {\n badges = [];\n this.props.badges.forEach(b => {\n const color = (b.color ? ' ' + b.color : '');\n if (b.icon) {\n badges.push({icon_mapping[b.icon] || b.icon});\n } else {\n badges.push({b.name});\n }\n });\n return <>{badges}>;\n }\n return null;\n }\n};\n","// The counter of unread messages in the topic.\nimport React from 'react';\n\nexport default class UnreadBadge extends React.PureComponent {\n render() {\n return (this.props.count > 0 ?\n {this.props.count > 9 ? \"9+\" : this.props.count}\n : null);\n }\n};\n","// Chat message describing a video or voice call.\n\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { secondsToTime } from '../lib/strformat.js';\n\nexport default class CallMessage extends React.PureComponent {\n render() {\n const isCallDropped = ['busy', 'declined', 'disconnected', 'missed'].includes(this.props.callState);\n const successClass = 'material-icons medium ' + (isCallDropped ? 'red' : 'green');\n const callIcon = this.props.incoming ?\n (isCallDropped ? 'call_missed' : 'call_received') :\n (isCallDropped ? 'call_missed_outgoing' : 'call_made');\n let duration;\n if (isCallDropped) {\n switch (this.props.callState) {\n case 'busy':\n duration =
}\n .\n el = UploadingImage;\n }\n\n return el;\n}\n\n// Additional processing of image data.\nfunction handleVideoData(el, data, attr) {\n if (!data) {\n attr.src = 'img/broken_video.png';\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n };\n return el;\n }\n attr.className = 'inline-image';\n const dim = fitImageSize(data.width, data.height,\n this.viewportWidth > 0 ? Math.min(this.viewportWidth - REM_SIZE * 6.5, REM_SIZE * 34.5) :\n REM_SIZE * 34.5, REM_SIZE * 24, false) ||\n {dstWidth: NO_DIMENSIONS_VIDEO, dstHeight: NO_DIMENSIONS_VIDEO};\n attr.style = {\n width: dim.dstWidth + 'px',\n height: dim.dstHeight + 'px',\n // Looks like a Chrome bug: broken image does not respect 'width' and 'height'.\n minWidth: dim.dstWidth + 'px',\n minHeight: dim.dstHeight + 'px'\n };\n if (!Drafty.isProcessing(data)) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'image'));\n attr.alt = data.name;\n if (data.ref || data.val) {\n attr.onClick = this.onVideoPreview;\n attr.loading = 'lazy';\n }\n el = InlineVideo;\n } else {\n // Use custom element instead of
.\n el = UploadingImage;\n }\n\n return el;\n}\n\n// Converts Drafty object into a one-line preview. 'this' is set by the caller.\n// 'this' must contain:\n// formatMessage: this.props.intl.formatMessage\n// messages: formatjs messages defined with defineMessages.\nexport function previewFormatter(style, data, values, key) {\n if (!style) {\n // Unformatted.\n return values;\n }\n\n let el = Drafty.tagName(style);\n const attr = { key: key };\n switch (style) {\n case 'AU':\n // Voicemail as '[mic] 0:00'.\n el = React.Fragment;\n values = [mic, ' ', secondsToTime(data.duration/1000)];\n break;\n case 'BR':\n // Replace new line with a space.\n el = React.Fragment;\n values = [' '];\n break;\n case 'HL':\n // Make highlight less prominent in preview.\n attr.className = 'highlight preview';\n break;\n case 'LN':\n case 'MN':\n // Disable links in previews.\n el = 'span';\n break;\n case 'IM':\n // Replace image with '[icon] Image'.\n el = React.Fragment;\n values = [photo, ' ', this.formatMessage(messages.drafty_image)];\n break;\n case 'BN':\n el = 'span';\n attr.className = 'flat-button faux';\n break;\n case 'FM':\n el = React.Fragment;\n values = [dashboard,\n this.formatMessage(messages.drafty_form)].concat(' ', values || []);\n break;\n case 'RW':\n el = React.Fragment;\n break;\n case 'EX':\n if (data) {\n if (data.mime == 'application/json') {\n // Ignore JSON attachments: they are form response payloads.\n return null;\n }\n // Clear payload.\n delete data.val;\n delete data.ref;\n }\n el = React.Fragment;\n values = [attachment, ' ', this.formatMessage(messages.drafty_attachment)];\n break;\n case 'VC':\n el = CallStatus;\n if (data) {\n attr.callState = data.state;\n attr.incoming = data.incoming;\n attr.duration = data.duration;\n }\n values = null;\n break;\n case 'QQ':\n case 'HD':\n el = null;\n values = null;\n break;\n case 'VD':\n // Replace image with '[icon] Video'.\n el = React.Fragment;\n values = [play_circle_outline, ' ', this.formatMessage(messages.drafty_video)];\n break;\n default:\n if (!el) {\n // Unknown element.\n el = React.Fragment;\n values = [extension, ' ', this.formatMessage(messages.drafty_unknown)];\n }\n break;\n }\n if (!el) {\n return values;\n }\n return React.createElement(el, attr, values);\n};\n\n// Converts Drafty object into a quoted reply; 'this' is set by the caller.\nfunction inlineImageAttr(attr, data) {\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n maxWidth: IMAGE_THUMBNAIL_DIM + 'px',\n maxHeight: IMAGE_THUMBNAIL_DIM + 'px',\n }\n attr.className = 'inline-image';\n attr.alt = this.formatMessage(messages.drafty_image);\n if (!data) {\n attr.src = 'img/broken_image.png';\n } else {\n attr.src = attr.src || 'img/broken_image.png';\n }\n attr.title = attr.alt;\n return attr;\n}\n\n// Converts Drafty object into a quoted reply; 'this' is set by the caller.\nfunction inlineVideoAttr(attr, data) {\n const dim = fitImageSize(data.width, data.height, VIDEO_THUMBNAIL_WIDTH, IMAGE_THUMBNAIL_DIM);\n attr.style = {\n width: dim.width + 'px',\n height: dim.height + 'px',\n maxWidth: VIDEO_THUMBNAIL_WIDTH + 'px',\n maxHeight: IMAGE_THUMBNAIL_DIM + 'px',\n }\n attr.className = 'inline-image';\n attr.alt = this.formatMessage(messages.drafty_video);\n attr.title = attr.alt;\n if (!data) {\n attr.src = 'img/broken_video.png';\n } else {\n attr.src = attr.src || 'img/broken_video.png';\n }\n return attr;\n}\n\n// Displays a portion of Drafty within 'QQ' quotes. 'this' is set by the caller.\n// 'this' must contain:\n// formatMessage: this.props.intl.formatMessage\n// messages: formatjs messages defined with defineMessages.\n// authorizeURL: this.props.tinode.authorizeURL\n// onQuoteClick: this.handleQuoteClick (optional)\nfunction quoteFormatter(style, data, values, key) {\n if (['BR', 'EX', 'IM', 'MN', 'VD'].includes(style)) {\n let el = Drafty.tagName(style);\n let attr = Drafty.attrValue(style, data) || {};\n attr.key = key;\n switch(style) {\n case 'BR':\n values = null;\n break;\n case 'IM':\n attr = inlineImageAttr.call(this, attr, data);\n values = [React.createElement('img', attr, null), ' ', attr.alt];\n el = React.Fragment;\n // Fragment attributes.\n attr = {key: key};\n break;\n case 'VD':\n attr = inlineVideoAttr.call(this, attr, data);\n values = [React.createElement('img', attr, null), ' ', attr.alt];\n el = React.Fragment;\n // Fragment attributes.\n attr = {key: key};\n break;\n case 'MN':\n el = 'span';\n attr.className = 'mention'\n if (data) {\n attr.className += ' ' + idToColorClass(data.val, false, true);\n }\n break;\n case 'EX':\n let fname;\n if (data) {\n if (data.mime == 'application/json') {\n // Ignore JSON attachments: they are form response payloads.\n return null;\n }\n fname = data.name;\n // Clear payload.\n delete data.val;\n delete data.ref;\n }\n el = React.Fragment;\n values = [attachment,\n shortenFileName(fname, 16) || this.formatMessage(messages.drafty_attachment)];\n break;\n }\n return React.createElement(el, attr, values);\n }\n return previewFormatter.call(this, style, data, values, key);\n}\n\n// Create image thumbnail suitable for inclusion in a quote.\nfunction quoteImageOrVideo(data, isVideo) {\n let promise;\n let bits, ref, mime;\n if (isVideo) {\n bits = data.preview;\n mime = data.premime || 'image/jpeg';\n ref = data.preref;\n } else {\n bits = data.val;\n mime = data.mime;\n ref = data.ref;\n }\n // Get the blob from the image data.\n if (bits) {\n const blob = base64ToBlob(bits, mime);\n if (!blob) {\n throw new Error(\"Invalid image\");\n }\n promise = Promise.resolve(blob);\n } else if (ref) {\n promise = fetch(this.authorizeURL(sanitizeUrlForMime(ref, 'image')))\n .then(evt => {\n if (evt.ok) {\n return evt.blob();\n } else {\n throw new Error(`Image fetch unsuccessful: ${evt.status} ${evt.statusText}`);\n }\n });\n } else {\n throw new Error(\"Missing image data\");\n }\n\n // Scale the blob.\n return promise\n .then(blob => {\n // If it's an image, cut the square from the center of the image and shrink it.\n // If it's a video, allow it to be rectantular.\n return imageScaled(blob, isVideo ? VIDEO_THUMBNAIL_WIDTH : IMAGE_THUMBNAIL_DIM, IMAGE_THUMBNAIL_DIM, -1, !isVideo)\n }).then(scaled => {\n if (isVideo) {\n data.premime = scaled.mime;\n } else {\n data.mime = scaled.mime;\n }\n data.size = scaled.blob.size;\n data.width = scaled.width;\n data.height = scaled.height;\n delete data.ref;\n delete data.preref;\n // Keeping the original file name, if provided: ex.data.name;\n\n data.src = URL.createObjectURL(scaled.blob);\n return blobToBase64(scaled.blob);\n }).then(b64 => {\n if (isVideo) {\n data.preview = b64.bits;\n } else {\n data.val = b64.bits;\n }\n return data;\n }).catch(err => {\n delete data.val;\n delete data.preview;\n delete data.src;\n data.width = IMAGE_THUMBNAIL_DIM;\n data.height = IMAGE_THUMBNAIL_DIM;\n // Rethrow.\n throw err;\n });\n}\n\n// Create a preview of a reply.\nexport function replyFormatter(style, data, values, key, stack) {\n if (style == 'IM' || style == 'VD') {\n const isImage = style == 'IM';\n const attr = isImage ? inlineImageAttr.call(this, {key: key}, data) :\n inlineVideoAttr.call(this, {key: key}, data);\n\n let loadedPromise;\n try {\n loadedPromise = cancelablePromise(quoteImageOrVideo.call(this, data, style == 'VD'));\n } catch (error) {\n console.warn(\"Failed to quote image:\", error.message);\n loadedPromise = cancelablePromise(error);\n }\n attr.whenDone = loadedPromise;\n values = [React.createElement(LazyImage, attr, null), ' ', attr.alt];\n return React.createElement(React.Fragment, {key: key}, values);\n } else if (style == 'QQ') {\n if (stack.includes('QQ')) {\n // Quote inside quote when forwarding a message.\n return React.createElement('span', {key: key},\n [format_quote, ' ']);\n }\n\n const attr = Drafty.attrValue('QQ', data) || {};\n attr.key = key;\n attr.className = 'reply-quote'\n return React.createElement(Drafty.tagName('QQ'), attr, values);\n }\n return quoteFormatter.call(this, style, data, values, key);\n}\n","// A single topic or user.\nimport React from 'react';\nimport { FormattedMessage, injectIntl } from 'react-intl';\n\nimport ContactBadges from './contact-badges.jsx';\nimport LetterTile from './letter-tile.jsx';\nimport UnreadBadge from './unread-badge.jsx';\n\nimport { Drafty } from 'tinode-sdk';\n\nimport { previewFormatter } from '../lib/formatters.js';\nimport { deliveryMarker } from '../lib/utils.js';\n\nclass Contact extends React.Component {\n constructor(props) {\n super(props);\n\n this.handleClick = this.handleClick.bind(this);\n this.handleContextClick = this.handleContextClick.bind(this);\n }\n\n handleClick(e) {\n e.preventDefault();\n e.stopPropagation();\n if (this.props.onSelected) {\n // Index this.props.index is used by GroupManager.\n this.props.onSelected(this.props.item, this.props.index);\n }\n }\n\n handleContextClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.showContextMenu({ topicName: this.props.item, y: e.pageY, x: e.pageX });\n }\n\n render() {\n let title = this.props.title;\n if (!title) {\n title =
: null}\n \n {contactNodes}\n
\n :\n null\n }\n \n \n );\n }\n\n return (\n {names[c]} \n {skip.indexOf(c) < 0 ?\n {this.props.compare ? \n : null}\n
: null}\n \n \n {this.props.compare ?\n
\n \n :\n null}\n \n {items}\n {this.props.modeTitle} \n {this.props.compareTitle} \n
\n
: null}\n
\n {messageNodes}\n
\n '+' or '-' then the bits to add or remove, e.g. '+R-W' or '-PS'.\n * - a new value of access mode\n *\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {number} val - access mode value to update.\n * @param {string} upd - update to apply to val.\n * @returns {number} - updated access mode.\n */\n static update(val, upd) {\n if (!upd || typeof upd != 'string') {\n return val;\n }\n\n let action = upd.charAt(0);\n if (action == '+' || action == '-') {\n let val0 = val;\n // Split delta-string like '+ABC-DEF+Z' into an array of parts including + and -.\n const parts = upd.split(/([-+])/);\n // Starting iteration from 1 because String.split() creates an array with the first empty element.\n // Iterating by 2 because we parse pairs +/- then data.\n for (let i = 1; i < parts.length - 1; i += 2) {\n action = parts[i];\n const m0 = AccessMode.decode(parts[i + 1]);\n if (m0 == AccessMode._INVALID) {\n return val;\n }\n if (m0 == null) {\n continue;\n }\n if (action === '+') {\n val0 |= m0;\n } else if (action === '-') {\n val0 &= ~m0;\n }\n }\n val = val0;\n } else {\n // The string is an explicit new value 'ABC' rather than delta.\n const val0 = AccessMode.decode(upd);\n if (val0 != AccessMode._INVALID) {\n val = val0;\n }\n }\n\n return val;\n }\n /**\n * Bits present in a1 but missing in a2.\n *\n * @static\n * @memberof Tinode\n *\n * @param {number | string} a1 - access mode to subtract from.\n * @param {number | string} a2 - access mode to subtract.\n * @returns {number} access mode with bits present in a1 but missing in a2.\n */\n static diff(a1, a2) {\n a1 = AccessMode.decode(a1);\n a2 = AccessMode.decode(a2);\n\n if (a1 == AccessMode._INVALID || a2 == AccessMode._INVALID) {\n return AccessMode._INVALID;\n }\n return a1 & ~a2;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Custom formatter\n */\n toString() {\n return '{\"mode\": \"' + AccessMode.encode(this.mode) +\n '\", \"given\": \"' + AccessMode.encode(this.given) +\n '\", \"want\": \"' + AccessMode.encode(this.want) + '\"}';\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Converts numeric values to strings.\n */\n jsonHelper() {\n return {\n mode: AccessMode.encode(this.mode),\n given: AccessMode.encode(this.given),\n want: AccessMode.encode(this.want)\n };\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign value to 'mode'.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} m - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setMode(m) {\n this.mode = AccessMode.decode(m);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update mode value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateMode(u) {\n this.mode = AccessMode.update(this.mode, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get mode value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - mode value.\n */\n getMode() {\n return AccessMode.encode(this.mode);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign given value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} g - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setGiven(g) {\n this.given = AccessMode.decode(g);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'given' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateGiven(u) {\n this.given = AccessMode.update(this.given, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'given' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - given value.\n */\n getGiven() {\n return AccessMode.encode(this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} w - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setWant(w) {\n this.want = AccessMode.decode(w);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateWant(u) {\n this.want = AccessMode.update(this.want, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'want' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - want value.\n */\n getWant() {\n return AccessMode.encode(this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'want' but missing in 'given'.\n * Inverse of {@link Tinode.AccessMode#getExcessive}\n *\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in want but missing in given.\n */\n getMissing() {\n return AccessMode.encode(this.want & ~this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'given' but missing in 'want'.\n * Inverse of {@link Tinode.AccessMode#getMissing}\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in given but missing in want.\n */\n getExcessive() {\n return AccessMode.encode(this.given & ~this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want', 'give', and 'mode' values.\n * @memberof Tinode.AccessMode\n *\n * @param {AccessMode} val - new access mode value.\n * @returns {AccessMode} - this AccessMode.\n */\n updateAll(val) {\n if (val) {\n this.updateGiven(val.given);\n this.updateWant(val.want);\n this.mode = this.given & this.want;\n }\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Owner (O) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isOwner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._OWNER);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isPresencer(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._PRES);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is NOT set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isMuted(side) {\n return !this.isPresencer(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Join (J) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isJoiner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._JOIN);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Reader (R) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isReader(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._READ);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Writer (W) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isWriter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._WRITE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Approver (A) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isApprover(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._APPROVE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O) or Approver (A) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isAdmin(side) {\n return this.isOwner(side) || this.isApprover(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O), Approver (A), or Sharer (S) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isSharer(side) {\n return this.isAdmin(side) || AccessMode.#checkFlag(this, side, AccessMode._SHARE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Deleter (D) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isDeleter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._DELETE);\n }\n}\n\nAccessMode._NONE = 0x00;\nAccessMode._JOIN = 0x01;\nAccessMode._READ = 0x02;\nAccessMode._WRITE = 0x04;\nAccessMode._PRES = 0x08;\nAccessMode._APPROVE = 0x10;\nAccessMode._SHARE = 0x20;\nAccessMode._DELETE = 0x40;\nAccessMode._OWNER = 0x80;\n\nAccessMode._BITMASK = AccessMode._JOIN | AccessMode._READ | AccessMode._WRITE | AccessMode._PRES |\n AccessMode._APPROVE | AccessMode._SHARE | AccessMode._DELETE | AccessMode._OWNER;\nAccessMode._INVALID = 0x100000;\n","/**\n * @file In-memory sorted cache of objects.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n/**\n * In-memory sorted cache of objects.\n *\n * @class CBuffer\n * @memberof Tinode\n * @protected\n *\n * @param {function} compare custom comparator of objects. Takes two parameters a and b;\n * returns -1 if a < b, 0 if a == b, 1 otherwise.\n * @param {boolean} unique enforce element uniqueness: when true replace existing element with a new\n * one on conflict; when false keep both elements.\n */\nexport default class CBuffer {\n #comparator = undefined;\n #unique = false;\n buffer = [];\n\n constructor(compare_, unique_) {\n this.#comparator = compare_ || ((a, b) => {\n return a === b ? 0 : a < b ? -1 : 1;\n });\n this.#unique = unique_;\n }\n\n #findNearest(elem, arr, exact) {\n let start = 0;\n let end = arr.length - 1;\n let pivot = 0;\n let diff = 0;\n let found = false;\n\n while (start <= end) {\n pivot = (start + end) / 2 | 0;\n diff = this.#comparator(arr[pivot], elem);\n if (diff < 0) {\n start = pivot + 1;\n } else if (diff > 0) {\n end = pivot - 1;\n } else {\n found = true;\n break;\n }\n }\n if (found) {\n return {\n idx: pivot,\n exact: true\n };\n }\n if (exact) {\n return {\n idx: -1\n };\n }\n // Not exact - insertion point\n return {\n idx: diff < 0 ? pivot + 1 : pivot\n };\n }\n\n // Insert element into a sorted array.\n #insertSorted(elem, arr) {\n const found = this.#findNearest(elem, arr, false);\n const count = (found.exact && this.#unique) ? 1 : 0;\n arr.splice(found.idx, count, elem);\n return arr;\n }\n\n /**\n * Get an element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to fetch from.\n * @returns {Object} Element at the given position or undefined.\n */\n getAt(at) {\n return this.buffer[at];\n }\n\n /**\n * Convenience method for getting the element from the end of the buffer.\n * @memberof Tinode.CBuffer#\n * @param {number} at - position to fetch from, counting from the end;\n * undefined or null mean \"last\".\n * @returns {Object} The last element in the buffer or undefined if buffer is empty.\n */\n getLast(at) {\n at |= 0;\n return this.buffer.length > at ? this.buffer[this.buffer.length - 1 - at] : undefined;\n }\n\n /**\n * Insert new element(s) to the buffer at the correct position according to the sort method.\n * Variadic: takes one or more arguments. If an array is passed as a single argument, its\n * elements are inserted individually.\n * @memberof Tinode.CBuffer#\n *\n * @param {...Object|Array} - One or more objects to insert.\n */\n put() {\n let insert;\n // inspect arguments: if array, insert its elements, if one or more non-array arguments, insert them one by one\n if (arguments.length == 1 && Array.isArray(arguments[0])) {\n insert = arguments[0];\n } else {\n insert = arguments;\n }\n for (let idx in insert) {\n this.#insertSorted(insert[idx], this.buffer);\n }\n }\n\n /**\n * Remove element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to delete at.\n * @returns {Object} Element at the given position or undefined.\n */\n delAt(at) {\n at |= 0;\n let r = this.buffer.splice(at, 1);\n if (r && r.length > 0) {\n return r[0];\n }\n return undefined;\n }\n\n /**\n * Remove elements between two positions.\n * @memberof Tinode.CBuffer#\n * @param {number} since - Position to delete from (inclusive).\n * @param {number} before - Position to delete to (exclusive).\n *\n * @returns {Array} array of removed elements (could be zero length).\n */\n delRange(since, before) {\n return this.buffer.splice(since, before - since);\n }\n\n /**\n * Return the number of elements the buffer holds.\n * @memberof Tinode.CBuffer#\n * @return {number} Number of elements in the buffer.\n */\n length() {\n return this.buffer.length;\n }\n\n /**\n * Reset the buffer discarding all elements\n * @memberof Tinode.CBuffer#\n */\n reset() {\n this.buffer = [];\n }\n\n /**\n * Callback for iterating contents of buffer. See {@link Tinode.CBuffer#forEach}.\n * @callback ForEachCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {Object} prev - Previous element of the buffer.\n * @param {Object} next - Next element of the buffer.\n * @param {number} index - Index of the current element.\n */\n\n /**\n * Apply given callback to all elements of the buffer.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.ForEachCallbackType} callback - Function to call for each element.\n * @param {number} startIdx - Optional index to start iterating from (inclusive), default: 0.\n * @param {number} beforeIdx - Optional index to stop iterating before (exclusive), default: length of the buffer.\n * @param {Object} context - calling context (i.e. value of this in callback)\n */\n forEach(callback, startIdx, beforeIdx, context) {\n startIdx = Math.max(0, startIdx | 0);\n beforeIdx = Math.min(beforeIdx || this.buffer.length, this.buffer.length);\n\n for (let i = startIdx; i < beforeIdx; i++) {\n callback.call(context, this.buffer[i],\n (i > startIdx ? this.buffer[i - 1] : undefined),\n (i < beforeIdx - 1 ? this.buffer[i + 1] : undefined), i);\n }\n }\n\n /**\n * Find element in buffer using buffer's comparison function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Object} elem - element to find.\n * @param {boolean=} nearest - when true and exact match is not found, return the nearest element (insertion point).\n * @returns {number} index of the element in the buffer or -1.\n */\n find(elem, nearest) {\n const {\n idx\n } = this.#findNearest(elem, this.buffer, !nearest);\n return idx;\n }\n\n /**\n * Callback for filtering the buffer. See {@link Tinode.CBuffer#filter}.\n * @callback FilterCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {number} index - Index of the current element.\n * @returns {boolen} true to keep the element, false to remove.\n */\n\n /**\n * Remove all elements that do not pass the test implemented by the provided callback function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.FilterCallbackType} callback - Function to call for each element.\n * @param {Object} context - calling context (i.e. value of this in the callback)\n */\n filter(callback, context) {\n let count = 0;\n for (let i = 0; i < this.buffer.length; i++) {\n if (callback.call(context, this.buffer[i], i)) {\n this.buffer[count] = this.buffer[i];\n count++;\n }\n }\n\n this.buffer.splice(count);\n }\n\n /**\n * Check if buffer is empty.\n * @returns {boolean} true if the buffer is empty, false otherwise.\n */\n isEmpty() {\n return this.buffer.length == 0;\n }\n}\n","/**\n * @file Throwable error with numeric error code.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nexport default class CommError extends Error {\n constructor(message, code) {\n super(`${message} (${code})`);\n this.name = 'CommError';\n this.code = code;\n }\n}\n","/**\n * @file Global constants and configuration parameters.\n *\n * @copyright 2015-2023 Tinode LLC\n */\n'use strict';\n\nimport {\n PACKAGE_VERSION\n} from '../version.js';\n\n// Global constants\nexport const PROTOCOL_VERSION = '0'; // Major component of the version, e.g. '0' in '0.17.1'.\nexport const VERSION = PACKAGE_VERSION || '0.21';\nexport const LIBRARY = 'tinodejs/' + VERSION;\n\n// Topic name prefixes.\nexport const TOPIC_NEW = 'new';\nexport const TOPIC_NEW_CHAN = 'nch';\nexport const TOPIC_ME = 'me';\nexport const TOPIC_FND = 'fnd';\nexport const TOPIC_SYS = 'sys';\nexport const TOPIC_CHAN = 'chn';\nexport const TOPIC_GRP = 'grp';\nexport const TOPIC_P2P = 'p2p';\nexport const USER_NEW = 'new';\n\n// Starting value of a locally-generated seqId used for pending messages.\nexport const LOCAL_SEQID = 0xFFFFFFF;\n\n// Status codes.\nexport const MESSAGE_STATUS_NONE = 0; // Status not assigned.\nexport const MESSAGE_STATUS_QUEUED = 10; // Local ID assigned, in progress to be sent.\nexport const MESSAGE_STATUS_SENDING = 20; // Transmission started.\nexport const MESSAGE_STATUS_FAILED = 30; // At least one attempt was made to send the message.\nexport const MESSAGE_STATUS_FATAL = 40; // Message sending failed and it should not be retried.\nexport const MESSAGE_STATUS_SENT = 50; // Delivered to the server.\nexport const MESSAGE_STATUS_RECEIVED = 60; // Received by the client.\nexport const MESSAGE_STATUS_READ = 70; // Read by the user.\nexport const MESSAGE_STATUS_TO_ME = 80; // The message is received from another user.\n\n// Reject unresolved futures after this many milliseconds.\nexport const EXPIRE_PROMISES_TIMEOUT = 5_000;\n// Periodicity of garbage collection of unresolved futures.\nexport const EXPIRE_PROMISES_PERIOD = 1_000;\n\n// Delay before acknowledging that a message was recived.\nexport const RECV_TIMEOUT = 100;\n\n// Default number of messages to pull into memory from persistent cache.\nexport const DEFAULT_MESSAGES_PAGE = 24;\n\n// Unicode DEL character indicating data was deleted.\nexport const DEL_CHAR = '\\u2421';\n\n// Maximum number of pinnned messages;\nexport const MAX_PINNED_COUNT = 5;\n","/**\n * @file Abstraction layer for websocket and long polling connections.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n jsonParseHelper\n} from './utils.js';\n\nlet WebSocketProvider;\nlet XHRProvider;\n\n// Error code to return in case of a network problem.\nconst NETWORK_ERROR = 503;\nconst NETWORK_ERROR_TEXT = \"Connection failed\";\n\n// Error code to return when user disconnected from server.\nconst NETWORK_USER = 418;\nconst NETWORK_USER_TEXT = \"Disconnected by client\";\n\n// Settings for exponential backoff\nconst _BOFF_BASE = 2000; // 2000 milliseconds, minimum delay between reconnects\nconst _BOFF_MAX_ITER = 10; // Maximum delay between reconnects 2^10 * 2000 ~ 34 minutes\nconst _BOFF_JITTER = 0.3; // Add random delay\n\n// Helper function for creating an endpoint URL.\nfunction makeBaseUrl(host, protocol, version, apiKey) {\n let url = null;\n\n if (['http', 'https', 'ws', 'wss'].includes(protocol)) {\n url = `${protocol}://${host}`;\n if (url.charAt(url.length - 1) !== '/') {\n url += '/';\n }\n url += 'v' + version + '/channels';\n if (['http', 'https'].includes(protocol)) {\n // Long polling endpoint ends with \"lp\", i.e.\n // '/v0/channels/lp' vs just '/v0/channels' for ws\n url += '/lp';\n }\n url += '?apikey=' + apiKey;\n }\n return url;\n}\n\n/**\n * An abstraction for a websocket or a long polling connection.\n *\n * @class Connection\n * @memberof Tinode\n\n * @param {Object} config - configuration parameters.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - Network transport to use, either \"ws\"/\"wss\" for websocket or\n * lp for long polling.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} version_ - Major value of the protocol version, e.g. '0' in '0.17.1'.\n * @param {boolean} autoreconnect_ - If connection is lost, try to reconnect automatically.\n */\nexport default class Connection {\n // Logger, does nothing by default.\n static #log = _ => {};\n\n #boffTimer = null;\n #boffIteration = 0;\n #boffClosed = false; // Indicator if the socket was manually closed - don't autoreconnect if true.\n\n // Websocket.\n #socket = null;\n\n host;\n secure;\n apiKey;\n\n version;\n autoreconnect;\n\n initialized;\n\n // (config.host, config.apiKey, config.transport, config.secure), PROTOCOL_VERSION, true\n constructor(config, version_, autoreconnect_) {\n this.host = config.host;\n this.secure = config.secure;\n this.apiKey = config.apiKey;\n\n this.version = version_;\n this.autoreconnect = autoreconnect_;\n\n if (config.transport === 'lp') {\n // explicit request to use long polling\n this.#init_lp();\n this.initialized = 'lp';\n } else if (config.transport === 'ws') {\n // explicit request to use web socket\n // if websockets are not available, horrible things will happen\n this.#init_ws();\n this.initialized = 'ws';\n }\n\n if (!this.initialized) {\n // Invalid or undefined network transport.\n Connection.#log(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n throw new Error(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n }\n }\n\n /**\n * To use Connection in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n * @memberof Connection\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n }\n\n /**\n * Assign a non-default logger.\n * @static\n * @memberof Connection\n * @param {function} l variadic logging function.\n */\n static set logger(l) {\n Connection.#log = l;\n }\n\n /**\n * Initiate a new connection\n * @memberof Tinode.Connection#\n * @param {string} host_ Host name to connect to; if null the old host name will be used.\n * @param {boolean} force Force new connection even if one already exists.\n * @return {Promise} Promise resolved/rejected when the connection call completes, resolution is called without\n * parameters, rejection passes the {Error} as parameter.\n */\n connect(host_, force) {\n return Promise.reject(null);\n }\n\n /**\n * Try to restore a network connection, also reset backoff.\n * @memberof Tinode.Connection#\n *\n * @param {boolean} force - reconnect even if there is a live connection already.\n */\n reconnect(force) {}\n\n /**\n * Terminate the network connection\n * @memberof Tinode.Connection#\n */\n disconnect() {}\n\n /**\n * Send a string to the server.\n * @memberof Tinode.Connection#\n *\n * @param {string} msg - String to send.\n * @throws Throws an exception if the underlying connection is not live.\n */\n sendText(msg) {}\n\n /**\n * Check if connection is alive.\n * @memberof Tinode.Connection#\n * @returns {boolean} true if connection is live, false otherwise.\n */\n isConnected() {\n return false;\n }\n\n /**\n * Get the name of the current network transport.\n * @memberof Tinode.Connection#\n * @returns {string} name of the transport such as \"ws\" or \"lp\".\n */\n transport() {\n return this.initialized;\n }\n\n /**\n * Send network probe to check if connection is indeed live.\n * @memberof Tinode.Connection#\n */\n probe() {\n this.sendText('1');\n }\n\n /**\n * Reset autoreconnect counter to zero.\n * @memberof Tinode.Connection#\n */\n backoffReset() {\n this.#boffReset();\n }\n\n // Backoff implementation - reconnect after a timeout.\n #boffReconnect() {\n // Clear timer\n clearTimeout(this.#boffTimer);\n // Calculate when to fire the reconnect attempt\n const timeout = _BOFF_BASE * (Math.pow(2, this.#boffIteration) * (1.0 + _BOFF_JITTER * Math.random()));\n // Update iteration counter for future use\n this.#boffIteration = (this.#boffIteration >= _BOFF_MAX_ITER ? this.#boffIteration : this.#boffIteration + 1);\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(timeout);\n }\n\n this.#boffTimer = setTimeout(_ => {\n Connection.#log(`Reconnecting, iter=${this.#boffIteration}, timeout=${timeout}`);\n // Maybe the socket was closed while we waited for the timer?\n if (!this.#boffClosed) {\n const prom = this.connect();\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(0, prom);\n } else {\n // Suppress error if it's not used.\n prom.catch(_ => {\n /* do nothing */\n });\n }\n } else if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(-1);\n }\n }, timeout);\n }\n\n // Terminate auto-reconnect process.\n #boffStop() {\n clearTimeout(this.#boffTimer);\n this.#boffTimer = null;\n }\n\n // Reset auto-reconnect iteration counter.\n #boffReset() {\n this.#boffIteration = 0;\n }\n\n // Initialization for long polling.\n #init_lp() {\n const XDR_UNSENT = 0; // Client has been created. open() not called yet.\n const XDR_OPENED = 1; // open() has been called.\n const XDR_HEADERS_RECEIVED = 2; // send() has been called, and headers and status are available.\n const XDR_LOADING = 3; // Downloading; responseText holds partial data.\n const XDR_DONE = 4; // The operation is complete.\n\n // Fully composed endpoint URL, with API key & SID\n let _lpURL = null;\n\n let _poller = null;\n let _sender = null;\n\n let lp_sender = (url_) => {\n const sender = new XHRProvider();\n sender.onreadystatechange = (evt) => {\n if (sender.readyState == XDR_DONE && sender.status >= 400) {\n // Some sort of error response\n throw new CommError(\"LP sender failed\", sender.status);\n }\n };\n\n sender.open('POST', url_, true);\n return sender;\n }\n\n let lp_poller = (url_, resolve, reject) => {\n let poller = new XHRProvider();\n let promiseCompleted = false;\n\n poller.onreadystatechange = evt => {\n if (poller.readyState == XDR_DONE) {\n if (poller.status == 201) { // 201 == HTTP.Created, get SID\n let pkt = JSON.parse(poller.responseText, jsonParseHelper);\n _lpURL = url_ + '&sid=' + pkt.ctrl.params.sid;\n poller = lp_poller(_lpURL);\n poller.send(null);\n if (this.onOpen) {\n this.onOpen();\n }\n\n if (resolve) {\n promiseCompleted = true;\n resolve();\n }\n\n if (this.autoreconnect) {\n this.#boffStop();\n }\n } else if (poller.status > 0 && poller.status < 400) { // 0 = network error; 400 = HTTP.BadRequest\n if (this.onMessage) {\n this.onMessage(poller.responseText);\n }\n poller = lp_poller(_lpURL);\n poller.send(null);\n } else {\n // Don't throw an error here, gracefully handle server errors\n if (reject && !promiseCompleted) {\n promiseCompleted = true;\n reject(poller.responseText);\n }\n if (this.onMessage && poller.responseText) {\n this.onMessage(poller.responseText);\n }\n if (this.onDisconnect) {\n const code = poller.status || (this.#boffClosed ? NETWORK_USER : NETWORK_ERROR);\n const text = poller.responseText || (this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT);\n this.onDisconnect(new CommError(text, code), code);\n }\n\n // Polling has stopped. Indicate it by setting poller to null.\n poller = null;\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n }\n }\n };\n // Using POST to avoid caching response by service worker.\n poller.open('POST', url_, true);\n return poller;\n }\n\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (_poller) {\n if (!force) {\n return Promise.resolve();\n }\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'https' : 'http', this.version, this.apiKey);\n Connection.#log(\"LP connecting to:\", url);\n _poller = lp_poller(url, resolve, reject);\n _poller.send(null);\n }).catch(err => {\n Connection.#log(\"LP connection failed:\", err);\n });\n };\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (_sender) {\n _sender.onreadystatechange = undefined;\n _sender.abort();\n _sender = null;\n }\n if (_poller) {\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (this.onDisconnect) {\n this.onDisconnect(new CommError(NETWORK_USER_TEXT, NETWORK_USER), NETWORK_USER);\n }\n // Ensure it's reconstructed\n _lpURL = null;\n };\n\n this.sendText = (msg) => {\n _sender = lp_sender(_lpURL);\n if (_sender && (_sender.readyState == XDR_OPENED)) { // 1 == OPENED\n _sender.send(msg);\n } else {\n throw new Error(\"Long poller failed to connect\");\n }\n };\n\n this.isConnected = _ => {\n return (_poller && true);\n };\n }\n\n // Initialization for Websocket\n #init_ws() {\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (this.#socket) {\n if (!force && this.#socket.readyState == this.#socket.OPEN) {\n return Promise.resolve();\n }\n this.#socket.close();\n this.#socket = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'wss' : 'ws', this.version, this.apiKey);\n\n Connection.#log(\"WS connecting to: \", url);\n\n // It throws when the server is not accessible but the exception cannot be caught:\n // https://stackoverflow.com/questions/31002592/javascript-doesnt-catch-error-in-websocket-instantiation/31003057\n const conn = new WebSocketProvider(url);\n\n conn.onerror = err => {\n reject(err);\n };\n\n conn.onopen = _ => {\n if (this.autoreconnect) {\n this.#boffStop();\n }\n\n if (this.onOpen) {\n this.onOpen();\n }\n\n resolve();\n };\n\n conn.onclose = _ => {\n this.#socket = null;\n\n if (this.onDisconnect) {\n const code = this.#boffClosed ? NETWORK_USER : NETWORK_ERROR;\n this.onDisconnect(new CommError(this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT, code), code);\n }\n\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n };\n\n conn.onmessage = evt => {\n if (this.onMessage) {\n this.onMessage(evt.data);\n }\n };\n\n this.#socket = conn;\n });\n }\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (!this.#socket) {\n return;\n }\n this.#socket.close();\n this.#socket = null;\n };\n\n this.sendText = msg => {\n if (this.#socket && (this.#socket.readyState == this.#socket.OPEN)) {\n this.#socket.send(msg);\n } else {\n throw new Error(\"Websocket is not connected\");\n }\n };\n\n this.isConnected = _ => {\n return (this.#socket && (this.#socket.readyState == this.#socket.OPEN));\n };\n }\n\n // Callbacks:\n\n /**\n * A callback to pass incoming messages to. See {@link Tinode.Connection#onMessage}.\n * @callback Tinode.Connection.OnMessage\n * @memberof Tinode.Connection\n * @param {string} message - Message to process.\n */\n onMessage = undefined;\n\n /**\n * A callback for reporting a dropped connection.\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onDisconnect = undefined;\n\n /**\n * A callback called when the connection is ready to be used for sending. For websockets it's socket open,\n * for long polling it's readyState=1 (OPENED)\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onOpen = undefined;\n\n /**\n * A callback to notify of reconnection attempts. See {@link Tinode.Connection#onAutoreconnectIteration}.\n * @memberof Tinode.Connection\n * @callback AutoreconnectIterationType\n * @param {string} timeout - time till the next reconnect attempt in milliseconds. -1 means reconnect was skipped.\n * @param {Promise} promise resolved or rejected when the reconnect attemp completes.\n *\n */\n /**\n * A callback to inform when the next attampt to reconnect will happen and to receive connection promise.\n * @memberof Tinode.Connection#\n * @type {Tinode.Connection.AutoreconnectIterationType}\n */\n onAutoreconnectIteration = undefined;\n}\n\nConnection.NETWORK_ERROR = NETWORK_ERROR;\nConnection.NETWORK_ERROR_TEXT = NETWORK_ERROR_TEXT;\nConnection.NETWORK_USER = NETWORK_USER;\nConnection.NETWORK_USER_TEXT = NETWORK_USER_TEXT;\n","/**\n * @file Helper methods for dealing with IndexedDB cache of messages, users, and topics.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nimport {\n clipRange\n} from './utils.js';\n\nconst DB_VERSION = 3;\nconst DB_NAME = 'tinode-web';\n\nlet IDBProvider;\n\nexport default class DB {\n #onError = _ => {};\n #logger = _ => {};\n\n // Instance of IndexDB.\n db = null;\n // Indicator that the cache is disabled.\n disabled = false;\n\n constructor(onError, logger) {\n this.#onError = onError || this.#onError;\n this.#logger = logger || this.#logger;\n }\n\n #mapObjects(source, callback, context) {\n if (!this.db) {\n return disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction([source]);\n trx.onerror = event => {\n this.#logger('PCache', 'mapObjects', source, event.target.error);\n reject(event.target.error);\n };\n trx.objectStore(source).getAll().onsuccess = event => {\n if (callback) {\n event.target.result.forEach(topic => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n /**\n * Initialize persistent cache: open or create/upgrade if needed.\n * @returns {Promise} promise to be resolved/rejected when the DB is initialized.\n */\n initDatabase() {\n return new Promise((resolve, reject) => {\n // Open the database and initialize callbacks.\n const req = IDBProvider.open(DB_NAME, DB_VERSION);\n req.onsuccess = event => {\n this.db = event.target.result;\n this.disabled = false;\n resolve(this.db);\n };\n req.onerror = event => {\n this.#logger('PCache', \"failed to initialize\", event);\n reject(event.target.error);\n this.#onError(event.target.error);\n };\n req.onupgradeneeded = event => {\n this.db = event.target.result;\n\n this.db.onerror = event => {\n this.#logger('PCache', \"failed to create storage\", event);\n this.#onError(event.target.error);\n };\n\n // Individual object stores.\n // Object store (table) for topics. The primary key is topic name.\n this.db.createObjectStore('topic', {\n keyPath: 'name'\n });\n\n // Users object store. UID is the primary key.\n this.db.createObjectStore('user', {\n keyPath: 'uid'\n });\n\n // Subscriptions object store topic <-> user. Topic name + UID is the primary key.\n this.db.createObjectStore('subscription', {\n keyPath: ['topic', 'uid']\n });\n\n // Messages object store. The primary key is topic name + seq.\n this.db.createObjectStore('message', {\n keyPath: ['topic', 'seq']\n });\n\n // Records of deleted message ranges. The primary key is topic name + low seq.\n const dellog = this.db.createObjectStore('dellog', {\n keyPath: ['topic', 'low', 'hi']\n });\n dellog.createIndex('topic_clear', ['topic', 'clear'], {\n unique: false\n });\n };\n });\n }\n\n /**\n * Delete persistent cache.\n */\n deleteDatabase() {\n // Close connection, otherwise operations will fail with 'onblocked'.\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n return new Promise((resolve, reject) => {\n const req = IDBProvider.deleteDatabase(DB_NAME);\n req.onblocked = _ => {\n if (this.db) {\n this.db.close();\n }\n const err = new Error(\"blocked\");\n this.#logger('PCache', 'deleteDatabase', err);\n reject(err);\n };\n req.onsuccess = _ => {\n this.db = null;\n this.disabled = true;\n resolve(true);\n };\n req.onerror = event => {\n this.#logger('PCache', 'deleteDatabase', event.target.error);\n reject(event.target.error);\n };\n });\n }\n\n /**\n * Check if persistent cache is ready for use.\n * @memberOf DB\n * @returns {boolean} true if cache is ready, false otherwise.\n */\n isReady() {\n return !!this.db;\n }\n\n // Topics.\n\n /**\n * Save to cache or update topic in persistent cache.\n * @memberOf DB\n * @param {Topic} topic - topic to be added or updated.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updTopic(topic) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updTopic', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(topic.name);\n req.onsuccess = _ => {\n trx.objectStore('topic').put(DB.#serializeTopic(req.result, topic));\n trx.commit();\n };\n });\n }\n\n /**\n * Mark or unmark topic as deleted.\n * @memberOf DB\n * @param {string} name - name of the topic to mark or unmark.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n markTopicAsDeleted(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'markTopicAsDeleted', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(name);\n req.onsuccess = event => {\n const topic = event.target.result;\n topic._deleted = true;\n trx.objectStore('topic').put(topic);\n trx.commit();\n };\n });\n }\n\n /**\n * Remove topic from persistent cache.\n * @memberOf DB\n * @param {string} name - name of the topic to remove from database.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remTopic(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic', 'subscription', 'message'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remTopic', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('topic').delete(IDBKeyRange.only(name));\n trx.objectStore('subscription').delete(IDBKeyRange.bound([name, '-'], [name, '~']));\n trx.objectStore('message').delete(IDBKeyRange.bound([name, 0], [name, Number.MAX_SAFE_INTEGER]));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored topic.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapTopics(callback, context) {\n return this.#mapObjects('topic', callback, context);\n }\n\n /**\n * Copy data from serialized object to topic.\n * @memberOf DB\n * @param {Topic} topic - target to deserialize to.\n * @param {Object} src - serialized data to copy from.\n */\n deserializeTopic(topic, src) {\n DB.#deserializeTopic(topic, src);\n }\n\n // Users.\n /**\n * Add or update user object in the persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to save or update.\n * @param {Object} pub - user's public information.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updUser(uid, pub) {\n if (arguments.length < 2 || pub === undefined) {\n // No point inupdating user with invalid data.\n return;\n }\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').put({\n uid: uid,\n public: pub\n });\n trx.commit();\n });\n }\n\n /**\n * Remove user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to remove from the cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').delete(IDBKeyRange.only(uid));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored user.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapUsers(callback, context) {\n return this.#mapObjects('user', callback, context);\n }\n\n /**\n * Read a single user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to fetch from cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n getUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user']);\n trx.oncomplete = event => {\n const user = event.target.result;\n resolve({\n user: user.uid,\n public: user.public\n });\n };\n trx.onerror = event => {\n this.#logger('PCache', 'getUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').get(uid);\n });\n }\n\n // Subscriptions.\n /**\n * Add or update subscription in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {string} uid - ID of the subscribed user.\n * @param {Object} sub - subscription to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updSubscription(topicName, uid, sub) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updSubscription', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').get([topicName, uid]).onsuccess = (event) => {\n trx.objectStore('subscription').put(DB.#serializeSubscription(event.target.result, topicName, uid, sub));\n trx.commit();\n };\n });\n }\n\n /**\n * Execute a callback for each cached subscription in a given topic.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the subscriptions.\n * @param {function} callback - function to call for each subscription.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapSubscriptions(topicName, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription']);\n trx.onerror = (event) => {\n this.#logger('PCache', 'mapSubscriptions', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').getAll(IDBKeyRange.bound([topicName, '-'], [topicName, '~'])).onsuccess = (event) => {\n if (callback) {\n event.target.result.forEach((topic) => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n // Messages.\n\n /**\n * Save message to persistent cache.\n * @memberOf DB\n * @param {Object} msg - message to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n addMessage(msg) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'addMessage', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').add(DB.#serializeMessage(null, msg));\n trx.commit();\n });\n }\n\n /**\n * Update delivery status of a message stored in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} seq - ID of the message to update\n * @param {number} status - new delivery status of the message.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updMessageStatus(topicName, seq, status) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updMessageStatus', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('message').get(IDBKeyRange.only([topicName, seq]));\n req.onsuccess = event => {\n const src = req.result || event.target.result;\n if (!src || src._status == status) {\n trx.commit();\n return;\n }\n trx.objectStore('message').put(DB.#serializeMessage(src, {\n topic: topicName,\n seq: seq,\n _status: status\n }));\n trx.commit();\n };\n });\n }\n\n /**\n * Remove one or more messages from persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} from - id of the message to remove or lower boundary when removing range (inclusive).\n * @param {number=} to - upper boundary (exclusive) when removing a range of messages.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remMessages(topicName, from, to) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n if (!from && !to) {\n from = 0;\n to = Number.MAX_SAFE_INTEGER;\n }\n const range = to > 0 ? IDBKeyRange.bound([topicName, from], [topicName, to], false, true) :\n IDBKeyRange.only([topicName, from]);\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remMessages', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').delete(range);\n trx.commit();\n });\n }\n\n /**\n * Retrieve messages from persistent store.\n * @memberOf DB\n * @param {string} topicName - name of the topic to retrieve messages from.\n * @param {function} callback to call for each retrieved message.\n * @param {GetDataType} query - parameters of the message range to retrieve.\n *\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n readMessages(topicName, query, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n\n const trx = this.db.transaction(['message']);\n let result = [];\n\n // Handle individual message ranges.\n if (Array.isArray(query.ranges)) {\n return new Promise((resolve, reject) => {\n trx.onerror = event => {\n this.#logger('PCache', 'readMessages', event.target.error);\n reject(event.target.error);\n };\n\n let count = 0;\n query.ranges.forEach(range => {\n const key = range.hi ? IDBKeyRange.bound([topicName, range.low], [topicName, range.hi], false, true) :\n IDBKeyRange.only([topicName, range.low]);\n trx.objectStore('message').getAll(key).onsuccess = event => {\n const msgs = event.target.result;\n if (msgs) {\n if (callback) {\n callback.call(context, msgs);\n }\n if (Array.isArray(msgs)) {\n result = result.concat(msgs);\n } else {\n result.push(msgs);\n }\n }\n count++;\n if (count == query.ranges.length) {\n resolve(result);\n }\n };\n });\n });\n }\n\n return new Promise((resolve, reject) => {\n query = query || {};\n const since = query.since > 0 ? query.since : 0;\n const before = query.before > 0 ? query.before : Number.MAX_SAFE_INTEGER;\n const limit = query.limit | 0;\n\n trx.onerror = event => {\n this.#logger('PCache', 'readMessages', event.target.error);\n reject(event.target.error);\n };\n\n const range = IDBKeyRange.bound([topicName, since], [topicName, before], false, true);\n // Iterate in descending order.\n trx.objectStore('message').openCursor(range, 'prev')\n .onsuccess = event => {\n const cursor = event.target.result;\n if (cursor) {\n if (callback) {\n callback.call(context, cursor.value);\n }\n result.push(cursor.value);\n if (limit <= 0 || result.length < limit) {\n cursor.continue();\n } else {\n resolve(result);\n }\n } else {\n resolve(result);\n }\n };\n });\n }\n\n // Delete log\n\n /**\n * Add records of deleted messages.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} delId - id of the deletion transaction.\n * @param {Array.require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IDBProvider = idbProvider;\n }\n}\n","/**\n * @copyright 2015-2022 Tinode LLC.\n * @summary Minimally rich text representation and formatting for Tinode.\n * @license Apache 2.0\n *\n * @file Basic parser and formatter for very simple text markup. Mostly targeted at\n * mobile use cases similar to Telegram, WhatsApp, and FB Messenger.\n *\n * \n *
\n * Also supports forms and buttons.\n *\n * Nested formatting is supported, e.g. *abc _def_* -> abc def\n * URLs, @mentions, and #hashtags are extracted and converted into links.\n * Forms and buttons can be added procedurally.\n * JSON data representation is inspired by Draft.js raw formatting.\n *\n *\n * @example\n * Text:\n * abc\n * this is *bold*, `code` and _italic_, ~strike~\n * combined *bold and _italic_*\n * an url: https://www.example.com/abc#fragment and another _www.tinode.co_\n * this is a @mention and a #hashtag in a string\n * second #hashtag\n *
\n *\n * Sample JSON representation of the text above:\n * {\n * \"txt\": \"this is bold, code and italic, strike combined bold and italic an url: https://www.example.com/abc#fragment \" +\n * \"and another www.tinode.co this is a @mention and a #hashtag in a string second #hashtag\",\n * \"fmt\": [\n * { \"at\":8, \"len\":4,\"tp\":\"ST\" },{ \"at\":14, \"len\":4, \"tp\":\"CO\" },{ \"at\":23, \"len\":6, \"tp\":\"EM\"},\n * { \"at\":31, \"len\":6, \"tp\":\"DL\" },{ \"tp\":\"BR\", \"len\":1, \"at\":37 },{ \"at\":56, \"len\":6, \"tp\":\"EM\" },\n * { \"at\":47, \"len\":15, \"tp\":\"ST\" },{ \"tp\":\"BR\", \"len\":1, \"at\":62 },{ \"at\":120, \"len\":13, \"tp\":\"EM\" },\n * { \"at\":71, \"len\":36, \"key\":0 },{ \"at\":120, \"len\":13, \"key\":1 },{ \"tp\":\"BR\", \"len\":1, \"at\":133 },\n * { \"at\":144, \"len\":8, \"key\":2 },{ \"at\":159, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":179 },\n * { \"at\":187, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":195 }\n * ],\n * \"ent\": [\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"https://www.example.com/abc#fragment\" } },\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"http://www.tinode.co\" } },\n * { \"tp\":\"MN\", \"data\":{ \"val\":\"mention\" } },\n * { \"tp\":\"HT\", \"data\":{ \"val\":\"hashtag\" } }\n * ]\n * }\n */\n\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nconst MAX_FORM_ELEMENTS = 8;\nconst MAX_PREVIEW_ATTACHMENTS = 3;\nconst MAX_PREVIEW_DATA_SIZE = 64;\nconst JSON_MIME_TYPE = 'application/json';\nconst DRAFTY_MIME_TYPE = 'text/x-drafty';\nconst ALLOWED_ENT_FIELDS = ['act', 'height', 'duration', 'incoming', 'mime', 'name', 'premime', 'preref', 'preview',\n 'ref', 'size', 'state', 'url', 'val', 'width'\n];\n\n// Regular expressions for parsing inline formats. Javascript does not support lookbehind,\n// so it's a bit messy.\nconst INLINE_STYLES = [\n // Strong = bold, *bold text*\n {\n name: 'ST',\n start: /(?:^|[\\W_])(\\*)[^\\s*]/,\n end: /[^\\s*](\\*)(?=$|[\\W_])/\n },\n // Emphesized = italic, _italic text_\n {\n name: 'EM',\n start: /(?:^|\\W)(_)[^\\s_]/,\n end: /[^\\s_](_)(?=$|\\W)/\n },\n // Deleted, ~strike this though~\n {\n name: 'DL',\n start: /(?:^|[\\W_])(~)[^\\s~]/,\n end: /[^\\s~](~)(?=$|[\\W_])/\n },\n // Code block `this is monospace`\n {\n name: 'CO',\n start: /(?:^|\\W)(`)[^`]/,\n end: /[^`](`)(?=$|\\W)/\n }\n];\n\n// Relative weights of formatting spans. Greater index in array means greater weight.\nconst FMT_WEIGHT = ['QQ'];\n\n// RegExps for entity extraction (RF = reference)\nconst ENTITY_TYPES = [\n // URLs\n {\n name: 'LN',\n dataName: 'url',\n pack: function(val) {\n // Check if the protocol is specified, if not use http\n if (!/^[a-z]+:\\/\\//i.test(val)) {\n val = 'http://' + val;\n }\n return {\n url: val\n };\n },\n re: /(?:(?:https?|ftp):\\/\\/|www\\.|ftp\\.)[-A-Z0-9+&@#\\/%=~_|$?!:,.]*[A-Z0-9+&@#\\/%=~_|$]/ig\n },\n // Mentions @user (must be 2 or more characters)\n {\n name: 'MN',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B@([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n },\n // Hashtags #hashtag, like metion 2 or more characters.\n {\n name: 'HT',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B#([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n }\n];\n\n// HTML tag name suggestions\nconst FORMAT_TAGS = {\n AU: {\n html_tag: 'audio',\n md_tag: undefined,\n isVoid: false\n },\n BN: {\n html_tag: 'button',\n md_tag: undefined,\n isVoid: false\n },\n BR: {\n html_tag: 'br',\n md_tag: '\\n',\n isVoid: true\n },\n CO: {\n html_tag: 'tt',\n md_tag: '`',\n isVoid: false\n },\n DL: {\n html_tag: 'del',\n md_tag: '~',\n isVoid: false\n },\n EM: {\n html_tag: 'i',\n md_tag: '_',\n isVoid: false\n },\n EX: {\n html_tag: '',\n md_tag: undefined,\n isVoid: true\n },\n FM: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n HD: {\n html_tag: '',\n md_tag: undefined,\n isVoid: false\n },\n HL: {\n html_tag: 'span',\n md_tag: undefined,\n isVoid: false\n },\n HT: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n IM: {\n html_tag: 'img',\n md_tag: undefined,\n isVoid: false\n },\n LN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n MN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n RW: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false,\n },\n QQ: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n ST: {\n html_tag: 'b',\n md_tag: '*',\n isVoid: false\n },\n VC: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n VD: {\n html_tag: 'video',\n md_tag: undefined,\n isVoid: false\n }\n};\n\n// Convert base64-encoded string into Blob.\nfunction base64toObjectUrl(b64, contentType, logger) {\n if (!b64) {\n return null;\n }\n\n try {\n const bin = atob(b64);\n const length = bin.length;\n const buf = new ArrayBuffer(length);\n const arr = new Uint8Array(buf);\n for (let i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n\n return URL.createObjectURL(new Blob([buf], {\n type: contentType\n }));\n } catch (err) {\n if (logger) {\n logger(\"Drafty: failed to convert object.\", err.message);\n }\n }\n\n return null;\n}\n\nfunction base64toDataUrl(b64, contentType) {\n if (!b64) {\n return null;\n }\n contentType = contentType || 'image/jpeg';\n return 'data:' + contentType + ';base64,' + b64;\n}\n\n// Helpers for converting Drafty to HTML.\nconst DECORATORS = {\n // Visial styles\n ST: {\n open: _ => '',\n close: _ => ''\n },\n EM: {\n open: _ => '',\n close: _ => ''\n },\n DL: {\n open: _ => '',\n close: _ => ''\n },\n CO: {\n open: _ => '',\n close: _ => ''\n },\n // Line break\n BR: {\n open: _ => '
',\n close: _ => ''\n },\n // Hidden element\n HD: {\n open: _ => '',\n close: _ => ''\n },\n // Highlighted element.\n HL: {\n open: _ => '',\n close: _ => ''\n },\n // Link (URL)\n LN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n href: data.url,\n target: '_blank'\n } : null;\n },\n },\n // Mention\n MN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Hashtag\n HT: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Button\n BN: {\n open: _ => '',\n props: (data) => {\n return data ? {\n 'data-act': data.act,\n 'data-val': data.val,\n 'data-name': data.name,\n 'data-ref': data.ref\n } : null;\n },\n },\n // Audio recording\n AU: {\n open: (data) => {\n const url = data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger);\n return '',\n props: (data) => {\n if (!data) return null;\n return {\n // Embedded data or external link.\n src: data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-duration': data.duration,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n // Image\n IM: {\n open: data => {\n // Don't use data.ref for preview: it's a security risk.\n const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime);\n const previewUrl = base64toObjectUrl(data.val, data.mime, Drafty.logger);\n const downloadUrl = data.ref || previewUrl;\n return (data.name ? '' : '') +\n '';\n },\n close: data => {\n return (data.name ? '' : '');\n },\n props: data => {\n if (!data) return null;\n return {\n // Temporary preview, or permanent preview, or external link.\n src: base64toDataUrl(data._tempPreview, data.mime) ||\n data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n title: data.name,\n alt: data.name,\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n },\n },\n // Form - structured layout of elements.\n FM: {\n open: _ => '
';\n },\n close: _ => '',\n props: data => {\n if (!data) return null;\n const poster = data.preref || base64toObjectUrl(data.preview, data.premime || 'image/jpeg', Drafty.logger);\n return {\n // Embedded data or external link.\n src: poster,\n 'data-src': data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-preview': poster,\n 'data-duration': data.duration | 0,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n};\n\n/**\n * The main object which performs all the formatting actions.\n * @class Drafty\n * @constructor\n */\nconst Drafty = function() {\n this.txt = '';\n this.fmt = [];\n this.ent = [];\n}\n\n/**\n * Initialize Drafty document to a plain text string.\n *\n * @param {string} plainText - string to use as Drafty content.\n *\n * @returns new Drafty document or null is plainText is not a string or undefined.\n */\nDrafty.init = function(plainText) {\n if (typeof plainText == 'undefined') {\n plainText = '';\n } else if (typeof plainText != 'string') {\n return null;\n }\n\n return {\n txt: plainText\n };\n}\n\n/**\n * Parse plain text into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} content - plain-text content to parse.\n * @return {Drafty} parsed document or null if the source is not plain text.\n */\nDrafty.parse = function(content) {\n // Make sure we are parsing strings only.\n if (typeof content != 'string') {\n return null;\n }\n\n // Split text into lines. It makes further processing easier.\n const lines = content.split(/\\r?\\n/);\n\n // Holds entities referenced from text\n const entityMap = [];\n const entityIndex = {};\n\n // Processing lines one by one, hold intermediate result in blx.\n const blx = [];\n lines.forEach((line) => {\n let spans = [];\n let entities;\n\n // Find formatted spans in the string.\n // Try to match each style.\n INLINE_STYLES.forEach((tag) => {\n // Each style could be matched multiple times.\n spans = spans.concat(spannify(line, tag.start, tag.end, tag.name));\n });\n\n let block;\n if (spans.length == 0) {\n block = {\n txt: line\n };\n } else {\n // Sort spans by style occurence early -> late, then by length: first long then short.\n spans.sort((a, b) => {\n const diff = a.at - b.at;\n return diff != 0 ? diff : b.end - a.end;\n });\n\n // Convert an array of possibly overlapping spans into a tree.\n spans = toSpanTree(spans);\n\n // Build a tree representation of the entire string, not\n // just the formatted parts.\n const chunks = chunkify(line, 0, line.length, spans);\n\n const drafty = draftify(chunks, 0);\n\n block = {\n txt: drafty.txt,\n fmt: drafty.fmt\n };\n }\n\n // Extract entities from the cleaned up string.\n entities = extractEntities(block.txt);\n if (entities.length > 0) {\n const ranges = [];\n for (let i in entities) {\n // {offset: match['index'], unique: match[0], len: match[0].length, data: ent.packer(), type: ent.name}\n const entity = entities[i];\n let index = entityIndex[entity.unique];\n if (!index) {\n index = entityMap.length;\n entityIndex[entity.unique] = index;\n entityMap.push({\n tp: entity.type,\n data: entity.data\n });\n }\n ranges.push({\n at: entity.offset,\n len: entity.len,\n key: index\n });\n }\n block.ent = ranges;\n }\n\n blx.push(block);\n });\n\n const result = {\n txt: ''\n };\n\n // Merge lines and save line breaks as BR inline formatting.\n if (blx.length > 0) {\n result.txt = blx[0].txt;\n result.fmt = (blx[0].fmt || []).concat(blx[0].ent || []);\n\n for (let i = 1; i < blx.length; i++) {\n const block = blx[i];\n const offset = result.txt.length + 1;\n\n result.fmt.push({\n tp: 'BR',\n len: 1,\n at: offset - 1\n });\n\n result.txt += ' ' + block.txt;\n if (block.fmt) {\n result.fmt = result.fmt.concat(block.fmt.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n if (block.ent) {\n result.fmt = result.fmt.concat(block.ent.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n }\n\n if (result.fmt.length == 0) {\n delete result.fmt;\n }\n\n if (entityMap.length > 0) {\n result.ent = entityMap;\n }\n }\n return result;\n}\n\n/**\n * Append one Drafty document to another.\n *\n * @param {Drafty} first - Drafty document to append to.\n * @param {Drafty|string} second - Drafty document or string being appended.\n *\n * @return {Drafty} first document with the second appended to it.\n */\nDrafty.append = function(first, second) {\n if (!first) {\n return second;\n }\n if (!second) {\n return first;\n }\n\n first.txt = first.txt || '';\n const len = first.txt.length;\n\n if (typeof second == 'string') {\n first.txt += second;\n } else if (second.txt) {\n first.txt += second.txt;\n }\n\n if (Array.isArray(second.fmt)) {\n first.fmt = first.fmt || [];\n if (Array.isArray(second.ent)) {\n first.ent = first.ent || [];\n }\n second.fmt.forEach(src => {\n const fmt = {\n at: (src.at | 0) + len,\n len: src.len | 0\n };\n // Special case for the outside of the normal rendering flow styles.\n if (src.at == -1) {\n fmt.at = -1;\n fmt.len = 0;\n }\n if (src.tp) {\n fmt.tp = src.tp;\n } else {\n fmt.key = first.ent.length;\n first.ent.push(second.ent[src.key || 0]);\n }\n first.fmt.push(fmt);\n });\n }\n\n return first;\n}\n\n/**\n * Description of an image to attach.\n * @typedef {Object} ImageDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the image, e.g. \"image/png\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded image content. Could be null/undefined.\n * @property {string} preview - base64-encoded thumbnail of the image.\n * @property {integer} width - width of the image.\n * @property {integer} height - height of the image.\n * @property {string} filename - file name suggestion for downloading the image.\n * @property {integer} size - size of the image in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded image preview used during upload process; not serializable.\n * @property {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {integer} at - index where the object is inserted. The length of the image is always 1.\n * @param {ImageDesc} imageDesc - object with image paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertImage = function(content, at, imageDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'IM',\n data: {\n mime: imageDesc.mime,\n ref: imageDesc.refurl,\n val: imageDesc.bits || imageDesc.preview,\n width: imageDesc.width,\n height: imageDesc.height,\n name: imageDesc.filename,\n size: imageDesc.size | 0,\n }\n };\n\n if (imageDesc.urlPromise) {\n ex.data._tempPreview = imageDesc._tempPreview;\n ex.data._processing = true;\n imageDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Description of a video to attach.\n * @typedef {Object} VideoDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the video, e.g. \"video/mpeg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - in-band base64-encoded image data. Could be null/undefined.\n * @property {string} preview - base64-encoded screencapture from the video. Could be null/undefined.\n * @property {string} preref - reference to screencapture from the video. Could be null/undefined.\n * @property {integer} width - width of the video.\n * @property {integer} height - height of the video.\n * @property {integer} duration - duration of the video.\n * @property {string} filename - file name suggestion for downloading the video.\n * @property {integer} size - size of the video in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded screencapture used during upload process; not serializable.\n * @property {Promise} urlPromise - array of two promises, which return URLs of video and preview uploads correspondingly\n * (either could be null).\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add video to.\n * @param {integer} at - index where the object is inserted. The length of the video is always 1.\n * @param {VideoDesc} videoDesc - object with video paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertVideo = function(content, at, videoDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'VD',\n data: {\n mime: videoDesc.mime,\n ref: videoDesc.refurl,\n val: videoDesc.bits,\n preref: videoDesc.preref,\n preview: videoDesc.preview,\n width: videoDesc.width,\n height: videoDesc.height,\n duration: videoDesc.duration | 0,\n name: videoDesc.filename,\n size: videoDesc.size | 0,\n }\n };\n\n if (videoDesc.urlPromise) {\n ex.data._tempPreview = videoDesc._tempPreview;\n ex.data._processing = true;\n videoDesc.urlPromise.then(\n urls => {\n ex.data.ref = urls[0];\n ex.data.preref = urls[1];\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Description of an audio recording to attach.\n * @typedef {Object} AudioDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the audio, e.g. \"audio/ogg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded audio content. Could be null/undefined.\n * @property {integer} duration - duration of the record in milliseconds.\n * @property {string} preview - base64 encoded short array of amplitude values 0..100.\n * @property {string} filename - file name suggestion for downloading the audio.\n * @property {integer} size - size of the recording in bytes. Treat is as an untrusted hint.\n * @property {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert audio recording into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add audio record to.\n * @param {integer} at - index where the object is inserted. The length of the record is always 1.\n * @param {AudioDesc} audioDesc - object with the audio paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertAudio = function(content, at, audioDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'AU',\n data: {\n mime: audioDesc.mime,\n val: audioDesc.bits,\n duration: audioDesc.duration | 0,\n preview: audioDesc.preview,\n name: audioDesc.filename,\n size: audioDesc.size | 0,\n ref: audioDesc.refurl\n }\n };\n\n if (audioDesc.urlPromise) {\n ex.data._processing = true;\n audioDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Create a (self-contained) video call Drafty document.\n * @memberof Drafty\n * @static\n * @param {boolean} audioOnly
true if the call is initially audio-only.\n * @returns Video Call drafty document.\n */\nDrafty.videoCall = function(audioOnly) {\n const content = {\n txt: ' ',\n fmt: [{\n at: 0,\n len: 1,\n key: 0\n }],\n ent: [{\n tp: 'VC',\n data: {\n aonly: audioOnly\n },\n }]\n };\n return content;\n}\n\n/**\n * Update video call (VC) entity with the new status and duration.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - VC document to update.\n * @param {object} params - new video call parameters.\n * @param {string} params.state - state of video call.\n * @param {number} params.duration - duration of the video call in milliseconds.\n *\n * @returns the same document with update applied.\n */\nDrafty.updateVideoCall = function(content, params) {\n // The video element could be just a format or a format + entity.\n // Must ensure it's the latter first.\n const fmt = ((content || {}).fmt || [])[0];\n if (!fmt) {\n // Unrecognized content.\n return content;\n }\n\n let ent;\n if (fmt.tp == 'VC') {\n // Just a format, convert to format + entity.\n delete fmt.tp;\n fmt.key = 0;\n ent = {\n tp: 'VC'\n };\n content.ent = [ent];\n } else {\n ent = (content.ent || [])[fmt.key | 0];\n if (!ent || ent.tp != 'VC') {\n // Not a VC entity.\n return content;\n }\n }\n ent.data = ent.data || {};\n Object.assign(ent.data, params);\n return content;\n}\n\n/**\n * Create a quote to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} header - Quote header (title, etc.).\n * @param {string} uid - UID of the author to mention.\n * @param {Drafty} body - Body of the quoted message.\n *\n * @returns Reply quote Drafty doc with the quote formatting.\n */\nDrafty.quote = function(header, uid, body) {\n const quote = Drafty.append(Drafty.appendLineBreak(Drafty.mention(header, uid)), body);\n\n // Wrap into a quote.\n quote.fmt.push({\n at: 0,\n len: quote.txt.length,\n tp: 'QQ'\n });\n\n return quote;\n}\n\n/**\n * Create a Drafty document with a mention.\n *\n * @param {string} name - mentioned name.\n * @param {string} uid - mentioned user ID.\n *\n * @returns {Drafty} document with the mention.\n */\nDrafty.mention = function(name, uid) {\n return {\n txt: name || '',\n fmt: [{\n at: 0,\n len: (name || '').length,\n key: 0\n }],\n ent: [{\n tp: 'MN',\n data: {\n val: uid\n }\n }]\n };\n}\n\n/**\n * Append a link to a Drafty document.\n *\n * @param {Drafty} content - Drafty document to append link to.\n * @param {Object} linkData - Link info in format {txt: 'ankor text', url: 'http://...'}.\n *\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLink = function(content, linkData) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: content.txt.length,\n len: linkData.txt.length,\n key: content.ent.length\n });\n content.txt += linkData.txt;\n\n const ex = {\n tp: 'LN',\n data: {\n url: linkData.url\n }\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Append image to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {ImageDesc} imageDesc - object with image paramenets.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendImage = function(content, imageDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertImage(content, content.txt.length - 1, imageDesc);\n}\n\n/**\n * Append audio recodring to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add recording to.\n * @param {AudioDesc} audioDesc - object with audio data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendAudio = function(content, audioDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertAudio(content, content.txt.length - 1, audioDesc);\n}\n\n/**\n * Description of a file to attach.\n * @typedef {Object} AttachmentDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the attachment, e.g. \"application/octet-stream\"\n * @property {string} data - base64-encoded in-band content of small attachments. Could be null/undefined.\n * @property {string} filename - file name suggestion for downloading the attachment.\n * @property {integer} size - size of the file in bytes. Treat is as an untrusted hint.\n * @property {string} refurl - reference to the out-of-band content. Could be null/undefined.\n * @property {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Attach file to Drafty content. Either as a blob or as a reference.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to attach file to.\n * @param {AttachmentDesc} object - containing attachment description and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.attachFile = function(content, attachmentDesc) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'EX',\n data: {\n mime: attachmentDesc.mime,\n val: attachmentDesc.data,\n name: attachmentDesc.filename,\n ref: attachmentDesc.refurl,\n size: attachmentDesc.size | 0\n }\n }\n if (attachmentDesc.urlPromise) {\n ex.data._processing = true;\n attachmentDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n /* catch the error, otherwise it will appear in the console. */\n ex.data._processing = undefined;\n }\n );\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Wraps drafty document into a simple formatting style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - document or string to wrap into a style.\n * @param {string} style - two-letter style to wrap into.\n * @param {number} at - index where the style starts, default 0.\n * @param {number} len - length of the form content, default all of it.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapInto = function(content, style, at, len) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at || 0,\n len: len || content.txt.length,\n tp: style,\n });\n\n return content;\n}\n\n/**\n * Wraps content into an interactive form.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - to wrap into a form.\n * @param {number} at - index where the forms starts.\n * @param {number} len - length of the form content.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapAsForm = function(content, at, len) {\n return Drafty.wrapInto(content, 'FM', at, len);\n}\n\n/**\n * Insert clickable button into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {number} at - location where the button is inserted.\n * @param {number} len - the length of the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertButton = function(content, at, len, name, actionType, actionValue, refUrl) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n\n if (!content || !content.txt || content.txt.length < at + len) {\n return null;\n }\n\n if (len <= 0 || ['url', 'pub'].indexOf(actionType) == -1) {\n return null;\n }\n // Ensure refUrl is a string.\n if (actionType == 'url' && !refUrl) {\n return null;\n }\n refUrl = '' + refUrl;\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: len,\n key: content.ent.length\n });\n content.ent.push({\n tp: 'BN',\n data: {\n act: actionType,\n val: actionValue,\n ref: refUrl,\n name: name\n }\n });\n\n return content;\n}\n\n/**\n * Append clickable button to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {string} title - the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendButton = function(content, title, name, actionType, actionValue, refUrl) {\n content = content || {\n txt: ''\n };\n const at = content.txt.length;\n content.txt += title;\n return Drafty.insertButton(content, at, title.length, name, actionType, actionValue, refUrl);\n}\n\n/**\n * Attach a generic JS object. The object is attached as a json string.\n * Intended for representing a form response.\n *\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to attach file to.\n * @param {Object} data - data to convert to json string and attach.\n * @returns {Drafty} the same document as content.\n */\nDrafty.attachJSON = function(content, data) {\n content = content || {\n txt: ''\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n content.ent.push({\n tp: 'EX',\n data: {\n mime: JSON_MIME_TYPE,\n val: data\n }\n });\n\n return content;\n}\n/**\n * Append line break to a Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to append linebreak to.\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLineBreak = function(content) {\n content = content || {\n txt: ''\n };\n content.fmt = content.fmt || [];\n content.fmt.push({\n at: content.txt.length,\n len: 1,\n tp: 'BR'\n });\n content.txt += ' ';\n\n return content;\n}\n/**\n * Given Drafty document, convert it to HTML.\n * No attempt is made to strip pre-existing html markup.\n * This is potentially unsafe because content.txt may contain malicious HTML\n * markup.\n * @memberof Tinode.Drafty\n * @static\n *\n * @param {Drafty} doc - document to convert.\n *\n * @returns {string} HTML-representation of content.\n */\nDrafty.UNSAFE_toHTML = function(doc) {\n const tree = draftyToTree(doc);\n const htmlFormatter = function(type, data, values) {\n const tag = DECORATORS[type];\n let result = values ? values.join('') : '';\n if (tag) {\n result = tag.open(data) + result + tag.close(data);\n }\n return result;\n };\n return treeBottomUp(tree, htmlFormatter, 0);\n}\n\n/**\n * Callback for applying custom formatting to a Drafty document.\n * Called once for each style span.\n * @memberof Drafty\n * @static\n *\n * @callback Formatter\n * @param {string} style - style code such as \"ST\" or \"IM\".\n * @param {Object} data - entity's data.\n * @param {Object} values - possibly styled subspans contained in this style span.\n * @param {number} index - index of the element guaranteed to be unique.\n */\n\n/**\n * Convert Drafty document to a representation suitable for display.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|Object} content - Drafty document to transform.\n * @param {Formatter} formatter - callback which formats individual elements.\n * @param {Object} context - context provided to formatter as this.\n *\n * @return {Object} transformed object\n */\nDrafty.format = function(original, formatter, context) {\n return treeBottomUp(draftyToTree(original), formatter, 0, [], context);\n}\n\n/**\n * Shorten Drafty document making the drafty text no longer than the limit.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characrets to shorten to.\n * @param {boolean} light - remove heavy data from entities.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.shorten = function(original, limit, light) {\n let tree = draftyToTree(original);\n tree = shortenTree(tree, limit, '…');\n if (tree && light) {\n tree = lightEntity(tree);\n }\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Transform Drafty doc for forwarding: strip leading @mention and any leading line breaks or whitespace.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.forwardedContent = function(original) {\n let tree = draftyToTree(original);\n const rmMention = function(node) {\n if (node.type == 'MN') {\n if (!node.parent || !node.parent.type) {\n return null;\n }\n }\n return node;\n }\n // Strip leading mention.\n tree = treeTopDown(tree, rmMention);\n // Remove leading whitespace.\n tree = lTrim(tree);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Prepare Drafty doc for wrapping into QQ as a reply:\n * - Replace forwarding mention with symbol '➦' and remove data (UID).\n * - Remove quoted text completely.\n * - Replace line breaks with spaces.\n * - Strip entities of heavy content.\n * - Move attachments to the end of the document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.replyContent = function(original, limit) {\n const convMNnQQnBR = function(node) {\n if (node.type == 'QQ') {\n return null;\n } else if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n delete node.data;\n }\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.type;\n delete node.children;\n }\n return node;\n }\n\n let tree = draftyToTree(original);\n if (!tree) {\n return original;\n }\n\n // Strip leading mention.\n tree = treeTopDown(tree, convMNnQQnBR);\n // Move attachments to the end of the doc.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n // Shorten the doc.\n tree = shortenTree(tree, limit, '…');\n // Strip heavy elements except IM.data['val'] and VD.data['preview'] (have to keep them to generate previews later).\n const filter = node => {\n switch (node.type) {\n case 'IM':\n return ['val'];\n case 'VD':\n return ['preview'];\n }\n return null;\n };\n tree = lightEntity(tree, filter);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n\n/**\n * Generate drafty preview:\n * - Shorten the document.\n * - Strip all heavy entity data leaving just inline styles and entity references.\n * - Replace line breaks with spaces.\n * - Replace content of QQ with a space.\n * - Replace forwarding mention with symbol '➦'.\n * move all attachments to the end of the document and make them visible.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @param {boolean} forwarding - this a forwarding message preview.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.preview = function(original, limit, forwarding) {\n let tree = draftyToTree(original);\n\n // Move attachments to the end.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n\n // Convert leading mention to '➦' and replace QQ and BR with a space ' '.\n const convMNnQQnBR = function(node) {\n if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n }\n } else if (node.type == 'QQ') {\n node.text = ' ';\n delete node.children;\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.children;\n delete node.type;\n }\n return node;\n }\n tree = treeTopDown(tree, convMNnQQnBR);\n\n tree = shortenTree(tree, limit, '…');\n if (forwarding) {\n // Keep some IM and VD data for preview.\n const filter = {\n IM: ['val'],\n VD: ['preview']\n };\n tree = lightEntity(tree, node => {\n return filter[node.type];\n });\n } else {\n tree = lightEntity(tree);\n }\n\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Given Drafty document, convert it to plain text.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text.\n * @returns {string} plain-text representation of the drafty document.\n */\nDrafty.toPlainText = function(content) {\n return typeof content == 'string' ? content : content.txt;\n}\n\n/**\n * Check if the document has no markup and no entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for presence of markup.\n * @returns true is content is plain text, false otherwise.\n */\nDrafty.isPlainText = function(content) {\n return typeof content == 'string' || !(content.fmt || content.ent);\n}\n\n/**\n * Convert document to plain text with markdown. All elements which cannot\n * be represented in markdown are stripped.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text with markdown.\n */\nDrafty.toMarkdown = function(content) {\n let tree = draftyToTree(content);\n const mdFormatter = function(type, _, values) {\n const def = FORMAT_TAGS[type];\n let result = (values ? values.join('') : '');\n if (def) {\n if (def.isVoid) {\n result = def.md_tag || '';\n } else if (def.md_tag) {\n result = def.md_tag + result + def.md_tag;\n }\n }\n return result;\n };\n return treeBottomUp(tree, mdFormatter, 0);\n}\n\n/**\n * Checks if the object represets is a valid Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for validity.\n * @returns true is content is valid, false otherwise.\n */\nDrafty.isValid = function(content) {\n if (!content) {\n return false;\n }\n\n const {\n txt,\n fmt,\n ent\n } = content;\n\n if (!txt && txt !== '' && !fmt && !ent) {\n return false;\n }\n\n const txt_type = typeof txt;\n if (txt_type != 'string' && txt_type != 'undefined' && txt !== null) {\n return false;\n }\n\n if (typeof fmt != 'undefined' && !Array.isArray(fmt) && fmt !== null) {\n return false;\n }\n\n if (typeof ent != 'undefined' && !Array.isArray(ent) && ent !== null) {\n return false;\n }\n return true;\n}\n\n/**\n * Check if the drafty document has attachments: style EX and outside of normal rendering flow,\n * i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for attachments.\n * @returns true if there are attachments.\n */\nDrafty.hasAttachments = function(content) {\n if (!Array.isArray(content.fmt)) {\n return false;\n }\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n return ent && ent.tp == 'EX' && ent.data;\n }\n }\n return false;\n}\n\n/**\n * Callback for enumerating entities in a Drafty document.\n * Called once for each entity.\n * @memberof Drafty\n * @static\n *\n * @callback EntityCallback\n * @param {Object} data entity data.\n * @param {string} entity type.\n * @param {number} index entity's index in `content.ent`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate attachments: style EX and outside of normal rendering flow, i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to process for attachments.\n * @param {EntityCallback} callback - callback to call for each attachment.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.attachments = function(content, callback, context) {\n if (!Array.isArray(content.fmt)) {\n return;\n }\n let count = 0;\n for (let i in content.ent) {\n let fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n if (ent && ent.tp == 'EX' && ent.data) {\n if (callback.call(context, ent.data, count++, 'EX')) {\n break;\n }\n }\n }\n };\n}\n\n/**\n * Check if the drafty document has entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for entities.\n * @returns true if there are entities.\n */\nDrafty.hasEntities = function(content) {\n return content.ent && content.ent.length > 0;\n}\n\n/**\n * Enumerate entities. Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @param {EntityCallback} callback - callback to call for each entity.\n * @param {Object} context - value of \"this\" for callback.\n *\n */\nDrafty.entities = function(content, callback, context) {\n if (content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n if (content.ent[i]) {\n if (callback.call(context, content.ent[i].data, i, content.ent[i].tp)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Callback for enumerating styles (inline formats) in a Drafty document.\n * Called once for each style.\n * @memberof Drafty\n * @static\n *\n * @callback StyleCallback\n * @param {string} tp - format type.\n * @param {number} at - starting position of the format in text.\n * @param {number} len - extent of the format in characters.\n * @param {number} key - index of the entity if format is a reference.\n * @param {number} index - style's index in `content.fmt`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate styles (inline formats). Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with styles (formats) to enumerate.\n * @param {StyleCallback} callback - callback to call for each format.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.styles = function(content, callback, context) {\n if (content.fmt && content.fmt.length > 0) {\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt) {\n if (callback.call(context, fmt.tp, fmt.at, fmt.len, fmt.key, i)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Remove unrecognized fields from entity data\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @returns content.\n */\nDrafty.sanitizeEntities = function(content) {\n if (content && content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n const ent = content.ent[i];\n if (ent && ent.data) {\n const data = copyEntData(ent.data);\n if (data) {\n content.ent[i].data = data;\n } else {\n delete content.ent[i].data;\n }\n }\n }\n }\n return content;\n}\n\n/**\n * Given the entity, get URL which can be used for downloading\n * entity data.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the URl from.\n * @returns {string} URL to download entity data or null.\n */\nDrafty.getDownloadUrl = function(entData) {\n let url = null;\n if (entData.mime != JSON_MIME_TYPE && entData.val) {\n url = base64toObjectUrl(entData.val, entData.mime, Drafty.logger);\n } else if (typeof entData.ref == 'string') {\n url = entData.ref;\n }\n return url;\n}\n\n/**\n * Check if the entity data is not ready for sending, such as being uploaded to the server.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n * @returns {boolean} true if upload is in progress, false otherwise.\n */\nDrafty.isProcessing = function(entData) {\n return !!entData._processing;\n}\n\n/**\n * Given the entity, get URL which can be used for previewing\n * the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n *\n * @returns {string} url for previewing or null if no such url is available.\n */\nDrafty.getPreviewUrl = function(entData) {\n return entData.val ? base64toObjectUrl(entData.val, entData.mime, Drafty.logger) : null;\n}\n\n/**\n * Get approximate size of the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the size for.\n * @returns {number} size of entity data in bytes.\n */\nDrafty.getEntitySize = function(entData) {\n // Either size hint or length of value. The value is base64 encoded,\n // the actual object size is smaller than the encoded length.\n return entData.size ? entData.size : entData.val ? (entData.val.length * 0.75) | 0 : 0;\n}\n\n/**\n * Get entity mime type.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the type for.\n * @returns {string} mime type of entity.\n */\nDrafty.getEntityMimeType = function(entData) {\n return entData.mime || 'text/plain';\n}\n\n/**\n * Get HTML tag for a given two-letter style name.\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style, like ST or LN.\n *\n * @returns {string} HTML tag name if style is found, {code: undefined} if style is falsish or not found.\n */\nDrafty.tagName = function(style) {\n return FORMAT_TAGS[style] && FORMAT_TAGS[style].html_tag;\n}\n\n/**\n * For a given data bundle generate an object with HTML attributes,\n * for instance, given {url: \"http://www.example.com/\"} return\n * {href: \"http://www.example.com/\"}\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style to generate attributes for.\n * @param {Object} data - data bundle to convert to attributes\n *\n * @returns {Object} object with HTML attributes.\n */\nDrafty.attrValue = function(style, data) {\n if (data && DECORATORS[style]) {\n return DECORATORS[style].props(data);\n }\n\n return undefined;\n}\n\n/**\n * Drafty MIME type.\n * @memberof Drafty\n * @static\n *\n * @returns {string} content-Type \"text/x-drafty\".\n */\nDrafty.getContentType = function() {\n return DRAFTY_MIME_TYPE;\n}\n\n// =================\n// Utility methods.\n// =================\n\n// Take a string and defined earlier style spans, re-compose them into a tree where each leaf is\n// a same-style (including unstyled) string. I.e. 'hello *bold _italic_* and ~more~ world' ->\n// ('hello ', (b: 'bold ', (i: 'italic')), ' and ', (s: 'more'), ' world');\n//\n// This is needed in order to clear markup, i.e. 'hello *world*' -> 'hello world' and convert\n// ranges from markup-ed offsets to plain text offsets.\nfunction chunkify(line, start, end, spans) {\n const chunks = [];\n\n if (spans.length == 0) {\n return [];\n }\n\n for (let i in spans) {\n // Get the next chunk from the queue\n const span = spans[i];\n\n // Grab the initial unstyled chunk\n if (span.at > start) {\n chunks.push({\n txt: line.slice(start, span.at)\n });\n }\n\n // Grab the styled chunk. It may include subchunks.\n const chunk = {\n tp: span.tp\n };\n const chld = chunkify(line, span.at + 1, span.end, span.children);\n if (chld.length > 0) {\n chunk.children = chld;\n } else {\n chunk.txt = span.txt;\n }\n chunks.push(chunk);\n start = span.end + 1; // '+1' is to skip the formatting character\n }\n\n // Grab the remaining unstyled chunk, after the last span\n if (start < end) {\n chunks.push({\n txt: line.slice(start, end)\n });\n }\n\n return chunks;\n}\n\n// Detect starts and ends of formatting spans. Unformatted spans are\n// ignored at this stage.\nfunction spannify(original, re_start, re_end, type) {\n const result = [];\n let index = 0;\n let line = original.slice(0); // make a copy;\n\n while (line.length > 0) {\n // match[0]; // match, like '*abc*'\n // match[1]; // match captured in parenthesis, like 'abc'\n // match['index']; // offset where the match started.\n\n // Find the opening token.\n const start = re_start.exec(line);\n if (start == null) {\n break;\n }\n\n // Because javascript RegExp does not support lookbehind, the actual offset may not point\n // at the markup character. Find it in the matched string.\n let start_offset = start['index'] + start[0].lastIndexOf(start[1]);\n // Clip the processed part of the string.\n line = line.slice(start_offset + 1);\n // start_offset is an offset within the clipped string. Convert to original index.\n start_offset += index;\n // Index now point to the beginning of 'line' within the 'original' string.\n index = start_offset + 1;\n\n // Find the matching closing token.\n const end = re_end ? re_end.exec(line) : null;\n if (end == null) {\n break;\n }\n let end_offset = end['index'] + end[0].indexOf(end[1]);\n // Clip the processed part of the string.\n line = line.slice(end_offset + 1);\n // Update offsets\n end_offset += index;\n // Index now points to the beginning of 'line' within the 'original' string.\n index = end_offset + 1;\n\n result.push({\n txt: original.slice(start_offset + 1, end_offset),\n children: [],\n at: start_offset,\n end: end_offset,\n tp: type\n });\n }\n\n return result;\n}\n\n// Convert linear array or spans into a tree representation.\n// Keep standalone and nested spans, throw away partially overlapping spans.\nfunction toSpanTree(spans) {\n if (spans.length == 0) {\n return [];\n }\n\n const tree = [spans[0]];\n let last = spans[0];\n for (let i = 1; i < spans.length; i++) {\n // Keep spans which start after the end of the previous span or those which\n // are complete within the previous span.\n if (spans[i].at > last.end) {\n // Span is completely outside of the previous span.\n tree.push(spans[i]);\n last = spans[i];\n } else if (spans[i].end <= last.end) {\n // Span is fully inside of the previous span. Push to subnode.\n last.children.push(spans[i]);\n }\n // Span could partially overlap, ignoring it as invalid.\n }\n\n // Recursively rearrange the subnodes.\n for (let i in tree) {\n tree[i].children = toSpanTree(tree[i].children);\n }\n\n return tree;\n}\n\n// Convert drafty document to a tree.\nfunction draftyToTree(doc) {\n if (!doc) {\n return null;\n }\n\n doc = (typeof doc == 'string') ? {\n txt: doc\n } : doc;\n let {\n txt,\n fmt,\n ent\n } = doc;\n\n txt = txt || '';\n if (!Array.isArray(ent)) {\n ent = [];\n }\n\n if (!Array.isArray(fmt) || fmt.length == 0) {\n if (ent.length == 0) {\n return {\n text: txt\n };\n }\n\n // Handle special case when all values in fmt are 0 and fmt therefore is skipped.\n fmt = [{\n at: 0,\n len: 0,\n key: 0\n }];\n }\n\n // Sanitize spans.\n const spans = [];\n const attachments = [];\n fmt.forEach((span) => {\n if (!span || typeof span != 'object') {\n return;\n }\n\n if (!['undefined', 'number'].includes(typeof span.at)) {\n // Present, but non-numeric 'at'.\n return;\n }\n if (!['undefined', 'number'].includes(typeof span.len)) {\n // Present, but non-numeric 'len'.\n return;\n }\n let at = span.at | 0;\n let len = span.len | 0;\n if (len < 0) {\n // Invalid span length.\n return;\n }\n\n let key = span.key || 0;\n if (ent.length > 0 && (typeof key != 'number' || key < 0 || key >= ent.length)) {\n // Invalid key value.\n return;\n }\n\n if (at <= -1) {\n // Attachment. Store attachments separately.\n attachments.push({\n start: -1,\n end: 0,\n key: key\n });\n return;\n } else if (at + len > txt.length) {\n // Span is out of bounds.\n return;\n }\n\n if (!span.tp) {\n if (ent.length > 0 && (typeof ent[key] == 'object')) {\n spans.push({\n start: at,\n end: at + len,\n key: key\n });\n }\n } else {\n spans.push({\n type: span.tp,\n start: at,\n end: at + len\n });\n }\n });\n\n // Sort spans first by start index (asc) then by length (desc), then by weight.\n spans.sort((a, b) => {\n let diff = a.start - b.start;\n if (diff != 0) {\n return diff;\n }\n diff = b.end - a.end;\n if (diff != 0) {\n return diff;\n }\n return FMT_WEIGHT.indexOf(b.type) - FMT_WEIGHT.indexOf(a.type);\n });\n\n // Move attachments to the end of the list.\n if (attachments.length > 0) {\n spans.push(...attachments);\n }\n\n spans.forEach((span) => {\n if (ent.length > 0 && !span.type && ent[span.key] && typeof ent[span.key] == 'object') {\n span.type = ent[span.key].tp;\n span.data = ent[span.key].data;\n }\n\n // Is type still undefined? Hide the invalid element!\n if (!span.type) {\n span.type = 'HD';\n }\n });\n\n let tree = spansToTree({}, txt, 0, txt.length, spans);\n\n // Flatten tree nodes.\n const flatten = function(node) {\n if (Array.isArray(node.children) && node.children.length == 1) {\n // Unwrap.\n const child = node.children[0];\n if (!node.type) {\n const parent = node.parent;\n node = child;\n node.parent = parent;\n } else if (!child.type && !child.children) {\n node.text = child.text;\n delete node.children;\n }\n }\n return node;\n }\n tree = treeTopDown(tree, flatten);\n\n return tree;\n}\n\n// Add tree node to a parent tree.\nfunction addNode(parent, n) {\n if (!n) {\n return parent;\n }\n\n if (!parent.children) {\n parent.children = [];\n }\n\n // If text is present, move it to a subnode.\n if (parent.text) {\n parent.children.push({\n text: parent.text,\n parent: parent\n });\n delete parent.text;\n }\n\n n.parent = parent;\n parent.children.push(n);\n\n return parent;\n}\n\n// Returns a tree of nodes.\nfunction spansToTree(parent, text, start, end, spans) {\n if (!spans || spans.length == 0) {\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n return parent;\n }\n\n // Process subspans.\n for (let i = 0; i < spans.length; i++) {\n const span = spans[i];\n if (span.start < 0 && span.type == 'EX') {\n addNode(parent, {\n type: span.type,\n data: span.data,\n key: span.key,\n att: true\n });\n continue;\n }\n\n // Add un-styled range before the styled span starts.\n if (start < span.start) {\n addNode(parent, {\n text: text.substring(start, span.start)\n });\n start = span.start;\n }\n\n // Get all spans which are within the current span.\n const subspans = [];\n while (i < spans.length - 1) {\n const inner = spans[i + 1];\n if (inner.start < 0) {\n // Attachments are in the end. Stop.\n break;\n } else if (inner.start < span.end) {\n if (inner.end <= span.end) {\n const tag = FORMAT_TAGS[inner.tp] || {};\n if (inner.start < inner.end || tag.isVoid) {\n // Valid subspan: completely within the current span and\n // either non-zero length or zero length is acceptable.\n subspans.push(inner);\n }\n }\n i++;\n // Overlapping subspans are ignored.\n } else {\n // Past the end of the current span. Stop.\n break;\n }\n }\n\n addNode(parent, spansToTree({\n type: span.type,\n data: span.data,\n key: span.key\n }, text, start, span.end, subspans));\n start = span.end;\n }\n\n // Add the last unformatted range.\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n\n return parent;\n}\n\n// Append a tree to a Drafty doc.\nfunction treeToDrafty(doc, tree, keymap) {\n if (!tree) {\n return doc;\n }\n\n doc.txt = doc.txt || '';\n\n // Checkpoint to measure length of the current tree node.\n const start = doc.txt.length;\n\n if (tree.text) {\n doc.txt += tree.text;\n } else if (Array.isArray(tree.children)) {\n tree.children.forEach((c) => {\n treeToDrafty(doc, c, keymap);\n });\n }\n\n if (tree.type) {\n const len = doc.txt.length - start;\n doc.fmt = doc.fmt || [];\n if (Object.keys(tree.data || {}).length > 0) {\n doc.ent = doc.ent || [];\n const newKey = (typeof keymap[tree.key] == 'undefined') ? doc.ent.length : keymap[tree.key];\n keymap[tree.key] = newKey;\n doc.ent[newKey] = {\n tp: tree.type,\n data: tree.data\n };\n if (tree.att) {\n // Attachment.\n doc.fmt.push({\n at: -1,\n len: 0,\n key: newKey\n });\n } else {\n doc.fmt.push({\n at: start,\n len: len,\n key: newKey\n });\n }\n } else {\n doc.fmt.push({\n tp: tree.type,\n at: start,\n len: len\n });\n }\n }\n return doc;\n}\n\n// Traverse the tree top down transforming the nodes: apply transformer to every tree node.\nfunction treeTopDown(src, transformer, context) {\n if (!src) {\n return null;\n }\n\n let dst = transformer.call(context, src);\n if (!dst || !dst.children) {\n return dst;\n }\n\n const children = [];\n for (let i in dst.children) {\n let n = dst.children[i];\n if (n) {\n n = treeTopDown(n, transformer, context);\n if (n) {\n children.push(n);\n }\n }\n }\n\n if (children.length == 0) {\n dst.children = null;\n } else {\n dst.children = children;\n }\n\n return dst;\n}\n\n// Traverse the tree bottom-up: apply formatter to every node.\n// The formatter must maintain its state through context.\nfunction treeBottomUp(src, formatter, index, stack, context) {\n if (!src) {\n return null;\n }\n\n if (stack && src.type) {\n stack.push(src.type);\n }\n\n let values = [];\n for (let i in src.children) {\n const n = treeBottomUp(src.children[i], formatter, i, stack, context);\n if (n) {\n values.push(n);\n }\n }\n if (values.length == 0) {\n if (src.text) {\n values = [src.text];\n } else {\n values = null;\n }\n }\n\n if (stack && src.type) {\n stack.pop();\n }\n\n return formatter.call(context, src.type, src.data, values, index, stack);\n}\n\n// Clip tree to the provided limit.\nfunction shortenTree(tree, limit, tail) {\n if (!tree) {\n return null;\n }\n\n if (tail) {\n limit -= tail.length;\n }\n\n const shortener = function(node) {\n if (limit <= -1) {\n // Limit -1 means the doc was already clipped.\n return null;\n }\n\n if (node.att) {\n // Attachments are unchanged.\n return node;\n }\n if (limit == 0) {\n node.text = tail;\n limit = -1;\n } else if (node.text) {\n const len = node.text.length;\n if (len > limit) {\n node.text = node.text.substring(0, limit) + tail;\n limit = -1;\n } else {\n limit -= len;\n }\n }\n return node;\n }\n\n return treeTopDown(tree, shortener);\n}\n\n// Strip heavy entities from a tree.\nfunction lightEntity(tree, allow) {\n const lightCopy = node => {\n const data = copyEntData(node.data, true, allow ? allow(node) : null);\n if (data) {\n node.data = data;\n } else {\n delete node.data;\n }\n return node;\n }\n return treeTopDown(tree, lightCopy);\n}\n\n// Remove spaces and breaks on the left.\nfunction lTrim(tree) {\n if (tree.type == 'BR') {\n tree = null;\n } else if (tree.text) {\n if (!tree.type) {\n tree.text = tree.text.trimStart();\n if (!tree.text) {\n tree = null;\n }\n }\n } else if (!tree.type && tree.children && tree.children.length > 0) {\n const c = lTrim(tree.children[0]);\n if (c) {\n tree.children[0] = c;\n } else {\n tree.children.shift();\n if (!tree.type && tree.children.length == 0) {\n tree = null;\n }\n }\n }\n return tree;\n}\n\n// Move attachments to the end. Attachments must be at the top level, no need to traverse the tree.\nfunction attachmentsToEnd(tree, limit) {\n if (!tree) {\n return null;\n }\n\n if (tree.att) {\n tree.text = ' ';\n delete tree.att;\n delete tree.children;\n } else if (tree.children) {\n const attachments = [];\n const children = [];\n for (let i in tree.children) {\n const c = tree.children[i];\n if (c.att) {\n if (attachments.length == limit) {\n // Too many attachments to preview;\n continue;\n }\n if (c.data['mime'] == JSON_MIME_TYPE) {\n // JSON attachments are not shown in preview.\n continue;\n }\n\n delete c.att;\n delete c.children;\n c.text = ' ';\n attachments.push(c);\n } else {\n children.push(c);\n }\n }\n tree.children = children.concat(attachments);\n }\n return tree;\n}\n\n// Get a list of entities from a text.\nfunction extractEntities(line) {\n let match;\n let extracted = [];\n ENTITY_TYPES.forEach((entity) => {\n while ((match = entity.re.exec(line)) !== null) {\n extracted.push({\n offset: match['index'],\n len: match[0].length,\n unique: match[0],\n data: entity.pack(match[0]),\n type: entity.name\n });\n }\n });\n\n if (extracted.length == 0) {\n return extracted;\n }\n\n // Remove entities detected inside other entities, like #hashtag in a URL.\n extracted.sort((a, b) => {\n return a.offset - b.offset;\n });\n\n let idx = -1;\n extracted = extracted.filter((el) => {\n const result = (el.offset > idx);\n idx = el.offset + el.len;\n return result;\n });\n\n return extracted;\n}\n\n// Convert the chunks into format suitable for serialization.\nfunction draftify(chunks, startAt) {\n let plain = '';\n let ranges = [];\n for (let i in chunks) {\n const chunk = chunks[i];\n if (!chunk.txt) {\n const drafty = draftify(chunk.children, plain.length + startAt);\n chunk.txt = drafty.txt;\n ranges = ranges.concat(drafty.fmt);\n }\n\n if (chunk.tp) {\n ranges.push({\n at: plain.length + startAt,\n len: chunk.txt.length,\n tp: chunk.tp\n });\n }\n\n plain += chunk.txt;\n }\n return {\n txt: plain,\n fmt: ranges\n };\n}\n\n// Create a copy of entity data with (light=false) or without (light=true) the large payload.\n// The array 'allow' contains a list of fields exempt from stripping.\nfunction copyEntData(data, light, allow) {\n if (data && Object.entries(data).length > 0) {\n allow = allow || [];\n const dc = {};\n ALLOWED_ENT_FIELDS.forEach(key => {\n if (data[key]) {\n if (light && !allow.includes(key) &&\n (typeof data[key] == 'string' || Array.isArray(data[key])) &&\n data[key].length > MAX_PREVIEW_DATA_SIZE) {\n return;\n }\n if (typeof data[key] == 'object') {\n return;\n }\n dc[key] = data[key];\n }\n });\n\n if (Object.entries(dc).length != 0) {\n return dc;\n }\n }\n return null;\n}\n\nif (typeof module != 'undefined') {\n module.exports = Drafty;\n}\n","/**\n * @file Definition of 'fnd' topic.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport * as Const from './config.js';\nimport Topic from './topic.js';\nimport {\n mergeToCache\n} from './utils.js';\n\n\n/**\n * Special case of {@link Tinode.Topic} for searching for contacts and group topics\n * @extends Tinode.Topic\n *\n */\nexport default class TopicFnd extends Topic {\n // List of users and topics uid or topic_name -> Contact object)\n _contacts = {};\n\n /**\n * Create TopicFnd.\n *\n * @param {TopicFnd.Callbacks} callbacks - Callbacks to receive various events.\n */\n constructor(callbacks) {\n super(Const.TOPIC_FND, callbacks);\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = Object.getOwnPropertyNames(this._contacts).length;\n // Reset contact list.\n this._contacts = {};\n for (let idx in subs) {\n let sub = subs[idx];\n const indexBy = sub.topic ? sub.topic : sub.user;\n\n sub = mergeToCache(this._contacts, indexBy, sub);\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(sub);\n }\n }\n\n if (updateCount > 0 && this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._contacts));\n }\n }\n\n /**\n * Publishing to TopicFnd is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicFnd#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'fnd' is not supported\"));\n }\n\n /**\n * setMeta to TopicFnd resets contact list in addition to sending the message.\n * @memberof Tinode.TopicFnd#\n * @param {Tinode.SetParams} params parameters to update.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n setMeta(params) {\n return Object.getPrototypeOf(TopicFnd.prototype).setMeta.call(this, params).then(_ => {\n if (Object.keys(this._contacts).length > 0) {\n this._contacts = {};\n if (this.onSubsUpdated) {\n this.onSubsUpdated([]);\n }\n }\n });\n }\n\n /**\n * Iterate over found contacts. If callback is undefined, use {@link this.onMetaSub}.\n * @function\n * @memberof Tinode.TopicFnd#\n * @param {TopicFnd.ContactCallback} callback - Callback to call for each contact.\n * @param {Object} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._contacts) {\n cb.call(context, this._contacts[idx], idx, this._contacts);\n }\n }\n }\n}\n","/**\n * @file Utilities for uploading and downloading files.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n isUrlRelative,\n jsonParseHelper\n} from './utils.js';\n\nlet XHRProvider;\n\nfunction addURLParam(relUrl, key, value) {\n const url = new URL(relUrl, window.location.origin);\n url.searchParams.append(key, value);\n return url.toString().substring(window.location.origin.length);\n}\n\n/**\n * @class LargeFileHelper - utilities for uploading and downloading files out of band.\n * Don't instantiate this class directly. Use {Tinode.getLargeFileHelper} instead.\n * @memberof Tinode\n *\n * @param {Tinode} tinode - the main Tinode object.\n * @param {string} version - protocol version, i.e. '0'.\n */\nexport default class LargeFileHelper {\n constructor(tinode, version) {\n this._tinode = tinode;\n this._version = version;\n\n this._apiKey = tinode._apiKey;\n this._authToken = tinode.getAuthToken();\n\n // Ongoing requests.\n this.xhr = [];\n }\n\n /**\n * Start uploading the file to an endpoint at baseUrl.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} baseUrl base URL of upload server.\n * @param {File|Blob} data data to upload.\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure) {\n let url = `/v${this._version}/file/u/`;\n if (baseUrl) {\n let base = baseUrl;\n if (base.endsWith('/')) {\n // Removing trailing slash.\n base = base.slice(0, -1);\n }\n if (base.startsWith('http://') || base.startsWith('https://')) {\n url = base + url;\n } else {\n throw new Error(`Invalid base URL '${baseUrl}'`);\n }\n }\n\n const instance = this;\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n xhr.open('POST', url, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n if (this._authToken) {\n xhr.setRequestHeader('X-Tinode-Auth', `Token ${this._authToken.token}`);\n }\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n xhr.upload.onprogress = e => {\n if (e.lengthComputable) {\n if (onProgress) {\n onProgress(e.loaded / e.total);\n }\n if (this.onProgress) {\n this.onProgress(e.loaded / e.total);\n }\n }\n };\n\n xhr.onload = function() {\n let pkt;\n try {\n pkt = JSON.parse(this.response, jsonParseHelper);\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.response);\n pkt = {\n ctrl: {\n code: this.status,\n text: this.statusText\n }\n };\n }\n\n if (this.status >= 200 && this.status < 300) {\n if (toResolve) {\n toResolve(pkt.ctrl.params.url);\n }\n if (onSuccess) {\n onSuccess(pkt.ctrl);\n }\n } else if (this.status >= 400) {\n if (toReject) {\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n }\n if (onFailure) {\n onFailure(pkt.ctrl);\n }\n } else {\n instance._tinode.logger(\"ERROR: Unexpected server response status\", this.status, this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(e || new Error(\"failed\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n xhr.onabort = function(e) {\n if (toReject) {\n toReject(new Error(\"upload cancelled by user\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n try {\n const form = new FormData();\n form.append('file', data);\n form.set('id', this._tinode.getNextUniqueId());\n if (avatarFor) {\n form.set('topic', avatarFor);\n }\n xhr.send(form);\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onFailure) {\n onFailure(null);\n }\n }\n\n return result;\n }\n /**\n * Start uploading the file to default endpoint.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {File|Blob} data to upload\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n upload(data, avatarFor, onProgress, onSuccess, onFailure) {\n const baseUrl = (this._tinode._secure ? 'https://' : 'http://') + this._tinode._host;\n return this.uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure);\n }\n /**\n * Download the file from a given URL using GET request. This method works with the Tinode server only.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} relativeUrl - URL to download the file from. Must be relative url, i.e. must not contain the host.\n * @param {string=} filename - file name to use for the downloaded file.\n *\n * @returns {Promise} resolved/rejected when the download is completed/failed.\n */\n download(relativeUrl, filename, mimetype, onProgress, onError) {\n if (!isUrlRelative(relativeUrl)) {\n // As a security measure refuse to download from an absolute URL.\n if (onError) {\n onError(`The URL '${relativeUrl}' must be relative, not absolute`);\n }\n return;\n }\n if (!this._authToken) {\n if (onError) {\n onError(\"Must authenticate first\");\n }\n return;\n }\n const instance = this;\n\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n // Add '&asatt=1' to URL to request 'Content-Disposition: attachment' response header.\n relativeUrl = addURLParam(relativeUrl, 'asatt', '1');\n\n // Get data as blob (stored by the browser as a temporary file).\n xhr.open('GET', relativeUrl, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n xhr.setRequestHeader('X-Tinode-Auth', 'Token ' + this._authToken.token);\n xhr.responseType = 'blob';\n\n xhr.onprogress = function(e) {\n if (onProgress) {\n // Passing e.loaded instead of e.loaded/e.total because e.total\n // is always 0 with gzip compression enabled by the server.\n onProgress(e.loaded);\n }\n };\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n // The blob needs to be saved as file. There is no known way to\n // save the blob as file other than to fake a click on an .\n xhr.onload = function() {\n if (this.status == 200) {\n const link = document.createElement('a');\n // URL.createObjectURL is not available in non-browser environment. This call will fail.\n link.href = window.URL.createObjectURL(new Blob([this.response], {\n type: mimetype\n }));\n link.style.display = 'none';\n link.setAttribute('download', filename);\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n window.URL.revokeObjectURL(link.href);\n if (toResolve) {\n toResolve();\n }\n } else if (this.status >= 400 && toReject) {\n // The this.responseText is undefined, must use this.response which is a blob.\n // Need to convert this.response to JSON. The blob can only be accessed by the\n // FileReader.\n const reader = new FileReader();\n reader.onload = function() {\n try {\n const pkt = JSON.parse(this.result, jsonParseHelper);\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.result);\n toReject(err);\n }\n };\n reader.readAsText(this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(new Error(\"failed\"));\n }\n if (onError) {\n onError(e);\n }\n };\n\n xhr.onabort = function() {\n if (toReject) {\n toReject(null);\n }\n };\n\n try {\n xhr.send();\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onError) {\n onError(err);\n }\n }\n\n return result;\n }\n /**\n * Try to cancel all ongoing uploads or downloads.\n * @memberof Tinode.LargeFileHelper#\n */\n cancel() {\n this.xhr.forEach(req => {\n if (req.readyState < 4) {\n req.abort();\n }\n });\n }\n /**\n * To use LargeFileHelper in a non browser context, supply XMLHttpRequest provider.\n * @static\n * @memberof LargeFileHelper\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProvider(xhrProvider) {\n XHRProvider = xhrProvider;\n }\n}\n","/**\n * @file Definition of 'me' topic.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport * as Const from './config.js';\nimport Topic from './topic.js';\nimport {\n mergeObj\n} from './utils.js';\n\n/**\n * @class TopicMe - special case of {@link Tinode.Topic} for\n * managing data of the current user, including contact list.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicMe.Callbacks} callbacks - Callbacks to receive various events.\n */\nexport default class TopicMe extends Topic {\n onContactUpdate;\n\n constructor(callbacks) {\n super(Const.TOPIC_ME, callbacks);\n\n // me-specific callbacks\n if (callbacks) {\n this.onContactUpdate = callbacks.onContactUpdate;\n }\n }\n\n // Override the original Topic._processMetaDesc.\n _processMetaDesc(desc) {\n // Check if online contacts need to be turned off because P permission was removed.\n const turnOff = (desc.acs && !desc.acs.isPresencer()) && (this.acs && this.acs.isPresencer());\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n this._tinode._db.updTopic(this);\n // Update current user's record in the global cache.\n this._updateCachedUser(this._tinode._myUID, desc);\n\n // 'P' permission was removed. All topics are offline now.\n if (turnOff) {\n this._tinode.mapTopics((cont) => {\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n this._refreshContact('off', cont);\n }\n });\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = 0;\n subs.forEach((sub) => {\n const topicName = sub.topic;\n // Don't show 'me' and 'fnd' topics in the list of contacts.\n if (topicName == Const.TOPIC_FND || topicName == Const.TOPIC_ME) {\n return;\n }\n sub.online = !!sub.online;\n\n let cont = null;\n if (sub.deleted) {\n cont = sub;\n this._tinode.cacheRemTopic(topicName);\n this._tinode._db.remTopic(topicName);\n } else {\n // Ensure the values are defined and are integers.\n if (typeof sub.seq != 'undefined') {\n sub.seq = sub.seq | 0;\n sub.recv = sub.recv | 0;\n sub.read = sub.read | 0;\n sub.unread = sub.seq - sub.read;\n }\n\n const topic = this._tinode.getTopic(topicName);\n if (topic._new) {\n delete topic._new;\n }\n\n cont = mergeObj(topic, sub);\n this._tinode._db.updTopic(cont);\n\n if (Topic.isP2PTopicName(topicName)) {\n this._cachePutUser(topicName, cont);\n this._tinode._db.updUser(topicName, cont.public);\n }\n // Notify topic of the update if it's an external update.\n if (!sub._noForwarding && topic) {\n sub._noForwarding = true;\n topic._processMetaDesc(sub);\n }\n }\n\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(cont);\n }\n });\n\n if (this.onSubsUpdated && updateCount > 0) {\n const keys = [];\n subs.forEach((s) => {\n keys.push(s.topic);\n });\n this.onSubsUpdated(keys, updateCount);\n }\n }\n\n // Called by Tinode when meta.sub is recived.\n _processMetaCreds(creds, upd) {\n if (creds.length == 1 && creds[0] == Const.DEL_CHAR) {\n creds = [];\n }\n if (upd) {\n creds.forEach((cr) => {\n if (cr.val) {\n // Adding a credential.\n let idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && el.val == cr.val;\n });\n if (idx < 0) {\n // Not found.\n if (!cr.done) {\n // Unconfirmed credential replaces previous unconfirmed credential of the same method.\n idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n // Remove previous unconfirmed credential.\n this._credentials.splice(idx, 1);\n }\n }\n this._credentials.push(cr);\n } else {\n // Found. Maybe change 'done' status.\n this._credentials[idx].done = cr.done;\n }\n } else if (cr.resp) {\n // Handle credential confirmation.\n const idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n this._credentials[idx].done = true;\n }\n }\n });\n } else {\n this._credentials = creds;\n }\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n }\n\n // Process presence change message\n _routePres(pres) {\n if (pres.what == 'term') {\n // The 'me' topic itself is detached. Mark as unsubscribed.\n this._resetSub();\n return;\n }\n\n if (pres.what == 'upd' && pres.src == Const.TOPIC_ME) {\n // Update to me's description. Request updated value.\n this.getMeta(this.startMetaQuery().withDesc().build());\n return;\n }\n\n const cont = this._tinode.cacheGetTopic(pres.src);\n if (cont) {\n switch (pres.what) {\n case 'on': // topic came online\n cont.online = true;\n break;\n case 'off': // topic went offline\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n }\n break;\n case 'msg': // new message received\n cont._updateReceived(pres.seq, pres.act);\n break;\n case 'upd': // desc updated\n // Request updated subscription.\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n break;\n case 'acs': // access mode changed\n if (cont.acs) {\n cont.acs.updateAll(pres.dacs);\n } else {\n cont.acs = new AccessMode().updateAll(pres.dacs);\n }\n cont.touched = new Date();\n break;\n case 'ua':\n // user agent changed.\n cont.seen = {\n when: new Date(),\n ua: pres.ua\n };\n break;\n case 'recv':\n // user's other session marked some messges as received.\n pres.seq = pres.seq | 0;\n cont.recv = cont.recv ? Math.max(cont.recv, pres.seq) : pres.seq;\n break;\n case 'read':\n // user's other session marked some messages as read.\n pres.seq = pres.seq | 0;\n cont.read = cont.read ? Math.max(cont.read, pres.seq) : pres.seq;\n cont.recv = cont.recv ? Math.max(cont.read, cont.recv) : cont.recv;\n cont.unread = cont.seq - cont.read;\n break;\n case 'gone':\n // topic deleted or unsubscribed from.\n if (!cont._deleted) {\n cont._deleted = true;\n cont._attached = false;\n this._tinode._db.markTopicAsDeleted(pres.src);\n } else {\n this._tinode._db.remTopic(pres.src);\n }\n break;\n case 'del':\n // Update topic.del value.\n break;\n default:\n this._tinode.logger(\"INFO: Unsupported presence update in 'me'\", pres.what);\n }\n\n this._refreshContact(pres.what, cont);\n } else {\n if (pres.what == 'acs') {\n // New subscriptions and deleted/banned subscriptions have full\n // access mode (no + or - in the dacs string). Changes to known subscriptions are sent as\n // deltas, but they should not happen here.\n const acs = new AccessMode(pres.dacs);\n if (!acs || acs.mode == AccessMode._INVALID) {\n this._tinode.logger(\"ERROR: Invalid access mode update\", pres.src, pres.dacs);\n return;\n } else if (acs.mode == AccessMode._NONE) {\n this._tinode.logger(\"WARNING: Removing non-existent subscription\", pres.src, pres.dacs);\n return;\n } else {\n // New subscription. Send request for the full description.\n // Using .withOneSub (not .withLaterOneSub) to make sure IfModifiedSince is not set.\n this.getMeta(this.startMetaQuery().withOneSub(undefined, pres.src).build());\n // Create a dummy entry to catch online status update.\n const dummy = this._tinode.getTopic(pres.src);\n dummy.topic = pres.src;\n dummy.online = false;\n dummy.acs = acs;\n this._tinode._db.updTopic(dummy);\n }\n } else if (pres.what == 'tags') {\n this.getMeta(this.startMetaQuery().withTags().build());\n }\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n\n // Contact is updated, execute callbacks.\n _refreshContact(what, cont) {\n if (this.onContactUpdate) {\n this.onContactUpdate(what, cont);\n }\n }\n\n /**\n * Publishing to TopicMe is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicMe#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'me' is not supported\"));\n }\n\n /**\n * Delete validation credential.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} topic - Name of the topic to delete\n * @param {string} user - User ID to remove.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete credential in inactive 'me' topic\"));\n }\n // Send {del} message, return promise\n return this._tinode.delCredential(method, value).then(ctrl => {\n // Remove deleted credential from the cache.\n const index = this._credentials.findIndex((el) => {\n return el.meth == method && el.val == value;\n });\n if (index > -1) {\n this._credentials.splice(index, 1);\n }\n // Notify listeners\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n return ctrl;\n });\n }\n\n /**\n * @callback contactFilter\n * @param {Object} contact to check for inclusion.\n * @returns {boolean} true if contact should be processed, false to exclude it.\n */\n /**\n * Iterate over cached contacts.\n *\n * @function\n * @memberof Tinode.TopicMe#\n * @param {TopicMe.ContactCallback} callback - Callback to call for each contact.\n * @param {contactFilter=} filter - Optionally filter contacts; include all if filter is false-ish, otherwise\n * include those for which filter returns true-ish.\n * @param {Object=} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, filter, context) {\n this._tinode.mapTopics((c, idx) => {\n if (c.isCommType() && (!filter || filter(c))) {\n callback.call(context, c, idx);\n }\n });\n }\n\n /**\n * Get a contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get, either a UID (for p2p topics) or a topic name.\n * @returns {Tinode.Contact} - Contact or `undefined`.\n */\n getContact(name) {\n return this._tinode.cacheGetTopic(name);\n }\n\n /**\n * Get access mode of a given contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get access mode for, either a UID (for p2p topics)\n * or a topic name; if missing, access mode for the 'me' topic itself.\n * @returns {string} - access mode, such as `RWP`.\n */\n getAccessMode(name) {\n if (name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont ? cont.acs : null;\n }\n return this.acs;\n }\n\n /**\n * Check if contact is archived, i.e. contact.private.arch == true.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to check archived status, either a UID (for p2p topics) or a topic name.\n * @returns {boolean} - true if contact is archived, false otherwise.\n */\n isArchived(name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont && cont.private && !!cont.private.arch;\n }\n\n /**\n * @typedef Tinode.Credential\n * @memberof Tinode\n * @type Object\n * @property {string} meth - validation method such as 'email' or 'tel'.\n * @property {string} val - credential value, i.e. 'jdoe@example.com' or '+17025551234'\n * @property {boolean} done - true if credential is validated.\n */\n /**\n * Get the user's credentials: email, phone, etc.\n * @memberof Tinode.TopicMe#\n *\n * @returns {Tinode.Credential[]} - array of credentials.\n */\n getCredentials() {\n return this._credentials;\n }\n}\n","/**\n * @file Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport {\n listToRanges,\n normalizeRanges\n} from './utils';\n\n/**\n * Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @class MetaGetBuilder\n * @memberof Tinode\n *\n * @param {Tinode.Topic} parent topic which instantiated this builder.\n */\nexport default class MetaGetBuilder {\n constructor(parent) {\n this.topic = parent;\n this.what = {};\n }\n\n // Get timestamp of the most recent desc update.\n #get_desc_ims() {\n return this.topic.updated;\n }\n\n // Get timestamp of the most recent subs update.\n #get_subs_ims() {\n if (this.topic.isP2PType()) {\n return this.#get_desc_ims();\n }\n return this.topic._lastSubsUpdate;\n }\n /**\n * Add query parameters to fetch messages within explicit limits.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - messages newer than this (inclusive);\n * @param {number=} before - older than this (exclusive)\n * @param {number=} limit - number of messages to fetch\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withData(since, before, limit) {\n this.what['data'] = {\n since: since,\n before: before,\n limit: limit\n };\n return this;\n }\n /**\n * Add query parameters to fetch messages newer than the latest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of messages to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterData(limit) {\n return this.withData(this.topic._maxSeq > 0 ? this.topic._maxSeq + 1 : undefined, undefined, limit);\n }\n /**\n * Add query parameters to fetch messages within ID ranges.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Array.this object.\n */\n withDataRanges(ranges, limit) {\n this.what['data'] = {\n ranges: normalizeRanges(ranges, this.topic._maxSeq),\n limit: limit\n };\n return this;\n }\n /**\n * Add query parameters to fetch messages by an array of IDs.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number[]} list - array of seq IDs to fetch.\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDataList(list) {\n return this.withDataRanges(listToRanges(list));\n }\n /**\n * Add query parameters to fetch messages older than the earliest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of messages to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withEarlierData(limit) {\n return this.withData(undefined, this.topic._minSeq > 0 ? this.topic._minSeq : undefined, limit);\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the given timestamp.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch messages newer than this timestamp.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDesc(ims) {\n this.what['desc'] = {\n ims: ims\n };\n return this;\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDesc() {\n return this.withDesc(this.#get_desc_ims());\n }\n /**\n * Add query parameters to fetch subscriptions.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {number=} limit - maximum number of subscriptions to fetch.\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withSub(ims, limit, userOrTopic) {\n const opts = {\n ims: ims,\n limit: limit\n };\n if (this.topic.getType() == 'me') {\n opts.topic = userOrTopic;\n } else {\n opts.user = userOrTopic;\n }\n this.what['sub'] = opts;\n return this;\n }\n /**\n * Add query parameters to fetch a single subscription.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withOneSub(ims, userOrTopic) {\n return this.withSub(ims, undefined, userOrTopic);\n }\n /**\n * Add query parameters to fetch a single subscription if it's been updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterOneSub(userOrTopic) {\n return this.withOneSub(this.topic._lastSubsUpdate, userOrTopic);\n }\n /**\n * Add query parameters to fetch subscriptions updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of subscriptions to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterSub(limit) {\n return this.withSub(this.#get_subs_ims(), limit);\n }\n /**\n * Add query parameters to fetch topic tags.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withTags() {\n this.what['tags'] = true;\n return this;\n }\n /**\n * Add query parameters to fetch user's credentials. 'me' topic only.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withCred() {\n if (this.topic.getType() == 'me') {\n this.what['cred'] = true;\n } else {\n this.topic._tinode.logger(\"ERROR: Invalid topic type for MetaGetBuilder:withCreds\", this.topic.getType());\n }\n return this;\n }\n /**\n * Add query parameters to fetch topic tags.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withAux() {\n this.what['aux'] = true;\n return this;\n }\n /**\n * Add query parameters to fetch deleted messages within explicit limits. Any/all parameters can be null.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - ids of messages deleted since this 'del' id (inclusive)\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDel(since, limit) {\n if (since || limit) {\n this.what['del'] = {\n since: since,\n limit: limit\n };\n }\n return this;\n }\n /**\n * Add query parameters to fetch messages deleted after the saved 'del' id.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDel(limit) {\n // Specify 'since' only if we have already received some messages. If\n // we have no locally cached messages then we don't care if any messages were deleted.\n return this.withDel(this.topic._maxSeq > 0 ? this.topic._maxDel + 1 : undefined, limit);\n }\n\n /**\n * Extract subquery: get an object that contains specified subquery.\n * @memberof Tinode.MetaGetBuilder#\n * @param {string} what - subquery to return: one of 'data', 'sub', 'desc', 'tags', 'cred', 'del'.\n * @returns {Object} requested subquery or undefined.\n */\n extract(what) {\n return this.what[what];\n }\n\n /**\n * Construct parameters.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.GetQuery} Get query\n */\n build() {\n const what = [];\n let params = {};\n ['data', 'sub', 'desc', 'tags', 'cred', 'aux', 'del'].forEach((key) => {\n if (this.what.hasOwnProperty(key)) {\n what.push(key);\n if (Object.getOwnPropertyNames(this.what[key]).length > 0) {\n params[key] = this.what[key];\n }\n }\n });\n if (what.length > 0) {\n params.what = what.join(' ');\n } else {\n params = undefined;\n }\n return params;\n }\n}\n","/**\n * @file Topic management.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport CBuffer from './cbuffer.js';\nimport CommError from './comm-error.js';\nimport * as Const from './config.js';\nimport Drafty from './drafty.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport {\n listToRanges,\n mergeObj,\n mergeToCache,\n normalizeArray,\n normalizeRanges\n} from './utils.js';\n\n/**\n * Topic is a class representing a logical communication channel.\n */\nexport default class Topic {\n /**\n * @callback onData\n * @param {Data} data - Data packet\n */\n\n /**\n * Create topic.\n * @param {string} name - Name of the topic to create.\n * @param {Object=} callbacks - Object with various event callbacks.\n * @param {onData} callbacks.onData - Callback which receives a {data} message.\n * @param {callback} callbacks.onMeta - Callback which receives a {meta} message.\n * @param {callback} callbacks.onPres - Callback which receives a {pres} message.\n * @param {callback} callbacks.onInfo - Callback which receives an {info} message.\n * @param {callback} callbacks.onMetaDesc - Callback which receives changes to topic desctioption {@link desc}.\n * @param {callback} callbacks.onMetaSub - Called for a single subscription record change.\n * @param {callback} callbacks.onSubsUpdated - Called after a batch of subscription changes have been recieved and cached.\n * @param {callback} callbacks.onDeleteTopic - Called after the topic is deleted.\n * @param {callback} callbacls.onAllMessagesReceived - Called when all requested {data} messages have been recived.\n */\n constructor(name, callbacks) {\n // Parent Tinode object.\n this._tinode = null;\n\n // Server-provided data, locally immutable.\n // topic name\n this.name = name;\n // Timestamp when the topic was created.\n this.created = null;\n // Timestamp when the topic was last updated.\n this.updated = null;\n // Timestamp of the last messages\n this.touched = new Date(0);\n // Access mode, see AccessMode\n this.acs = new AccessMode(null);\n // Per-topic private data (accessible by current user only).\n this.private = null;\n // Per-topic public data (accessible by all users).\n this.public = null;\n // Per-topic system-provided data (accessible by all users).\n this.trusted = null;\n\n // Locally cached data\n // Subscribed users, for tracking read/recv/msg notifications.\n this._users = {};\n\n // Current value of locally issued seqId, used for pending messages.\n this._queuedSeqId = Const.LOCAL_SEQID;\n\n // The maximum known {data.seq} value.\n this._maxSeq = 0;\n // The minimum known {data.seq} value.\n this._minSeq = 0;\n // Indicator that the last request for earlier messages returned 0.\n this._noEarlierMsgs = false;\n // The maximum known deletion ID.\n this._maxDel = 0;\n // Timer object used to send 'recv' notifications.\n this._recvNotificationTimer = null;\n\n // User discovery tags\n this._tags = [];\n // Credentials such as email or phone number.\n this._credentials = [];\n // Auxiliary data\n this._aux = {};\n\n // Message versions cache (e.g. for edited messages).\n // Keys: original message seq ID.\n // Values: CBuffers containing newer versions of the original message\n // ordered by seq id.\n this._messageVersions = {};\n // Message cache, sorted by message seq values, from old to new.\n this._messages = new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n // Boolean, true if the topic is currently live\n this._attached = false;\n // Timestap of the most recently updated subscription.\n this._lastSubsUpdate = new Date(0);\n // Topic created but not yet synced with the server. Used only during initialization.\n this._new = true;\n // The topic is deleted at the server, this is a local copy.\n this._deleted = false;\n\n // Timer used to trgger {leave} request after a delay.\n this._delayedLeaveTimer = null;\n\n // Callbacks\n if (callbacks) {\n this.onData = callbacks.onData;\n this.onMeta = callbacks.onMeta;\n this.onPres = callbacks.onPres;\n this.onInfo = callbacks.onInfo;\n // A single desc update;\n this.onMetaDesc = callbacks.onMetaDesc;\n // A single subscription record;\n this.onMetaSub = callbacks.onMetaSub;\n // All subscription records received;\n this.onSubsUpdated = callbacks.onSubsUpdated;\n this.onTagsUpdated = callbacks.onTagsUpdated;\n this.onCredsUpdated = callbacks.onCredsUpdated;\n this.onAuxUpdated = callbacks.onAuxUpdated;\n this.onDeleteTopic = callbacks.onDeleteTopic;\n this.onAllMessagesReceived = callbacks.onAllMessagesReceived;\n }\n }\n\n // Static methods.\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n *\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n const types = {\n 'me': Const.TOPIC_ME,\n 'fnd': Const.TOPIC_FND,\n 'grp': Const.TOPIC_GRP,\n 'new': Const.TOPIC_GRP,\n 'nch': Const.TOPIC_GRP,\n 'chn': Const.TOPIC_GRP,\n 'usr': Const.TOPIC_P2P,\n 'sys': Const.TOPIC_SYS\n };\n return types[(typeof name == 'string') ? name.substring(0, 3) : 'xxx'];\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_ME;\n }\n\n /**\n * Check if the given topic name is a name of a group topic.\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_GRP;\n }\n\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_P2P;\n }\n\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isP2PTopicName(name) || Topic.isGroupTopicName(name);\n }\n\n /**\n * Check if the topic name is a name of a new topic.\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_NEW || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n /**\n * Check if the topic name is a name of a channel.\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_CHAN || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n // Returns true if pub is meant to replace another message (e.g. original message was edited).\n static #isReplacementMsg(pub) {\n return pub.head && pub.head.replace;\n }\n\n /**\n * Check if the topic is subscribed.\n * @returns {boolean} True is topic is attached/subscribed, false otherwise.\n */\n isSubscribed() {\n return this._attached;\n }\n\n /**\n * Request topic to subscribe. Wrapper for {@link Tinode#subscribe}.\n *\n * @param {Tinode.GetQuery=} getParams - get query parameters.\n * @param {Tinode.SetParams=} setParams - set parameters.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n subscribe(getParams, setParams) {\n // Clear request to leave topic.\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = null;\n\n // If the topic is already subscribed, return resolved promise\n if (this._attached) {\n return Promise.resolve(this);\n }\n\n // If the topic is deleted, reject subscription requests.\n if (this._deleted) {\n return Promise.reject(new Error(\"Conversation deleted\"));\n }\n\n // Send subscribe message, handle async response.\n // If topic name is explicitly provided, use it. If no name, then it's a new group topic,\n // use \"new\".\n return this._tinode.subscribe(this.name || Const.TOPIC_NEW, getParams, setParams).then(ctrl => {\n if (ctrl.code >= 300) {\n // Do nothing if subscription status has not changed.\n return ctrl;\n }\n\n this._attached = true;\n this._deleted = false;\n this.acs = (ctrl.params && ctrl.params.acs) ? ctrl.params.acs : this.acs;\n\n // Set topic name for new topics and add it to cache.\n if (this._new) {\n delete this._new;\n\n if (this.name != ctrl.topic) {\n // Name may change new123456 -> grpAbCdEf. Remove from cache under the old name.\n this._cacheDelSelf();\n this.name = ctrl.topic;\n }\n this._cachePutSelf();\n\n this.created = ctrl.ts;\n this.updated = ctrl.ts;\n\n if (this.name != Const.TOPIC_ME && this.name != Const.TOPIC_FND) {\n // Add the new topic to the list of contacts maintained by the 'me' topic.\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (setParams && setParams.desc) {\n setParams.desc._noForwarding = true;\n this._processMetaDesc(setParams.desc);\n }\n }\n return ctrl;\n });\n }\n\n /**\n * Create a draft of a message without sending it to the server.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Content to wrap in a draft.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * session. Otherwise the server will send a copy of the message to sender.\n *\n * @returns {Object} message draft.\n */\n createMessage(data, noEcho) {\n return this._tinode.createMessage(this.name, data, noEcho);\n }\n\n /**\n * Immediately publish data to topic. Wrapper for {@link Tinode#publish}.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Message to publish, either plain string or a Drafty object.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publish(data, noEcho) {\n return this.publishMessage(this.createMessage(data, noEcho));\n }\n\n /**\n * Publish message created by {@link Tinode.Topic#createMessage}.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - {data} object to publish. Must be created by {@link Tinode.Topic#createMessage}\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publishMessage(pub) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot publish on inactive topic\"));\n }\n if (this._sending) {\n return Promise.reject(new Error(\"The message is already being sent\"));\n }\n\n // Send data.\n pub._sending = true;\n pub._failed = false;\n\n // Extract refereces to attachments and out of band image records.\n let attachments = null;\n if (Drafty.hasEntities(pub.content)) {\n attachments = [];\n Drafty.entities(pub.content, data => {\n if (data) {\n if (data.ref) {\n attachments.push(data.ref);\n }\n if (data.preref) {\n attachments.push(data.preref);\n }\n }\n });\n if (attachments.length == 0) {\n attachments = null;\n }\n }\n\n return this._tinode.publishMessage(pub, attachments).then(ctrl => {\n pub._sending = false;\n pub.ts = ctrl.ts;\n this.swapMessageId(pub, ctrl.params.seq);\n this._maybeUpdateMessageVersionsCache(pub);\n this._routeData(pub);\n return ctrl;\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message rejected by the server\", err);\n pub._sending = false;\n pub._failed = true;\n if (this.onData) {\n this.onData();\n }\n });\n }\n\n /**\n * Add message to local message cache, send to the server when the promise is resolved.\n * If promise is null or undefined, the message will be sent immediately.\n * The message is sent when the\n * The message should be created by {@link Tinode.Topic#createMessage}.\n * This is probably not the final API.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - Message to use as a draft.\n * @param {Promise} prom - Message will be sent when this promise is resolved, discarded if rejected.\n *\n * @returns {Promise} derived promise.\n */\n publishDraft(pub, prom) {\n const seq = pub.seq || this._getQueuedSeqId();\n if (!pub._noForwarding) {\n // The 'seq', 'ts', and 'from' are added to mimic {data}. They are removed later\n // before the message is sent.\n pub._noForwarding = true;\n pub.seq = seq;\n pub.ts = new Date();\n pub.from = this._tinode.getCurrentUserID();\n\n // Don't need an echo message because the message is added to local cache right away.\n pub.noecho = true;\n // Add to cache.\n this._messages.put(pub);\n this._tinode._db.addMessage(pub);\n\n if (this.onData) {\n this.onData(pub);\n }\n }\n // If promise is provided, send the queued message when it's resolved.\n // If no promise is provided, create a resolved one and send immediately.\n return (prom || Promise.resolve())\n .then(_ => {\n if (pub._cancelled) {\n return {\n code: 300,\n text: \"cancelled\"\n };\n }\n return this.publishMessage(pub);\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message draft rejected\", err);\n pub._sending = false;\n pub._failed = true;\n pub._fatal = err instanceof CommError ? (err.code >= 400 && err.code < 500) : false;\n if (this.onData) {\n this.onData();\n }\n // Rethrow to let caller know that the operation failed.\n throw err;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean=} unsub - If true, unsubscribe, otherwise just leave.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n leave(unsub) {\n // It's possible to unsubscribe (unsub==true) from inactive topic.\n if (!this._attached && !unsub) {\n return Promise.reject(new Error(\"Cannot leave inactive topic\"));\n }\n\n // Send a 'leave' message, handle async response\n return this._tinode.leave(this.name, unsub).then(ctrl => {\n this._resetSub();\n if (unsub) {\n this._gone();\n }\n return ctrl;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe after a delay. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} unsub - If true, unsubscribe, otherwise just leave.\n * @param {number} delay - time in milliseconds to delay leave request.\n */\n leaveDelayed(unsub, delay) {\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = setTimeout(_ => {\n this._delayedLeaveTimer = null;\n this.leave(unsub)\n }, delay);\n }\n\n /**\n * Request topic metadata from the local cache or from the server.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.GetQuery} request parameters\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n getMeta(params) {\n // Send {get} message, return promise.\n return this._tinode.getMeta(this.name, params);\n }\n\n /**\n * Request more messages from the server. The goal is to load continous range of messages\n * covering at least between 'min' and 'max' + one full page forward (newer = true) or backwards\n * (newer=false).\n * @memberof Tinode.Topic#\n *\n * @param {number} limit number of messages to get.\n * @param {Array.null means to use default.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n invite(uid, mode) {\n return this.setMeta({\n sub: {\n user: uid,\n mode: mode\n }\n });\n }\n /**\n * Archive or un-archive the topic. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} arch - true to archive the topic, false otherwise.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n archive(arch) {\n if (this.private && (!this.private.arch == !arch)) {\n return Promise.resolve(arch);\n }\n return this.setMeta({\n desc: {\n private: {\n arch: arch ? true : Const.DEL_CHAR\n }\n }\n });\n }\n /**\n * Set message as pinned or unpinned by adding it to aux.pins array. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - seq ID of the message to pin or un-pin.\n * @param {boolean} pin - true to pin the message, false to un-pin.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n pinMessage(seq, pin) {\n let pinned = this.aux('pins');\n if (!Array.isArray(pinned)) {\n pinned = [];\n }\n let changed = false;\n if (pin) {\n if (!pinned.includes(seq)) {\n changed = true;\n if (pinned.length == Const.MAX_PINNED_COUNT) {\n pinned.shift();\n }\n pinned.push(seq);\n }\n } else {\n if (pinned.includes(seq)) {\n changed = true;\n pinned = pinned.filter(id => id != seq);\n if (pinned.length == 0) {\n pinned = Const.DEL_CHAR;\n }\n }\n }\n if (changed) {\n return this.setMeta({\n aux: {\n pins: pinned\n }\n });\n }\n return Promise.resolve();\n }\n /**\n * Delete messages. Hard-deleting messages requires Owner permission.\n * Wrapper for {@link Tinode#delMessages}.\n * @memberof Tinode.Topic#\n *\n * @param {Array.recv, read.\n * @param {number} seq - ID or the message read or received.\n */\n note(what, seq) {\n if (!this._attached) {\n // Cannot sending {note} on an inactive topic\".\n return;\n }\n\n // Update local cache with the new count.\n const user = this._users[this._tinode.getCurrentUserID()];\n let update = false;\n if (user) {\n // Self-subscription is found.\n if (!user[what] || user[what] < seq) {\n user[what] = seq;\n update = true;\n }\n } else {\n // Self-subscription is not found.\n update = (this[what] | 0) < seq;\n }\n\n if (update) {\n // Send notification to the server.\n this._tinode.note(this.name, what, seq);\n // Update locally cached contact with the new count.\n this._updateReadRecv(what, seq);\n\n if (this.acs != null && !this.acs.isMuted()) {\n const me = this._tinode.getMeTopic();\n // Sent a notification to 'me' listeners.\n me._refreshContact(what, this);\n }\n }\n }\n\n /**\n * Send a 'recv' receipt. Wrapper for {@link Tinode#noteRecv}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge.\n */\n noteRecv(seq) {\n this.note('recv', seq);\n }\n /**\n * Send a 'read' receipt. Wrapper for {@link Tinode#noteRead}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge or 0/undefined to acknowledge the latest messages.\n */\n noteRead(seq) {\n seq = seq || this._maxSeq;\n if (seq > 0) {\n this.note('read', seq);\n }\n }\n /**\n * Send a key-press notification. Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n */\n noteKeyPress() {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name);\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n /**\n * Send a notification than a video or audio message is . Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n * @param audioOnly - true if the recording is audio-only, false if it's a video recording.\n */\n noteRecording(audioOnly) {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name, audioOnly ? 'kpa' : 'kpv');\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n\n /**\n * Send a {note what='call'}. Wrapper for {@link Tinode#videoCall}.\n * @memberof Tinode#\n *\n * @param {string} evt - Call event.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(evt, seq, payload) {\n if (!this._attached && !['ringing', 'hang-up'].includes(evt)) {\n // Cannot {call} on an inactive topic\".\n return;\n }\n return this._tinode.videoCall(this.name, seq, evt, payload);\n }\n\n // Update cached read/recv/unread counts.\n _updateReadRecv(what, seq, ts) {\n let oldVal, doUpdate = false;\n\n seq = seq | 0;\n this.seq = this.seq | 0;\n this.read = this.read | 0;\n this.recv = this.recv | 0;\n switch (what) {\n case 'recv':\n oldVal = this.recv;\n this.recv = Math.max(this.recv, seq);\n doUpdate = (oldVal != this.recv);\n break;\n case 'read':\n oldVal = this.read;\n this.read = Math.max(this.read, seq);\n doUpdate = (oldVal != this.read);\n break;\n case 'msg':\n oldVal = this.seq;\n this.seq = Math.max(this.seq, seq);\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = (oldVal != this.seq);\n break;\n }\n\n // Sanity checks.\n if (this.recv < this.read) {\n this.recv = this.read;\n doUpdate = true;\n }\n if (this.seq < this.recv) {\n this.seq = this.recv;\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = true;\n }\n this.unread = this.seq - this.read;\n return doUpdate;\n }\n /**\n * Get user description from global cache. The user does not need to be a\n * subscriber of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - ID of the user to fetch.\n * @return {Object} user description or undefined.\n */\n userDesc(uid) {\n // TODO: handle asynchronous requests\n const user = this._cacheGetUser(uid);\n if (user) {\n return user; // Promise.resolve(user)\n }\n }\n /**\n * Get description of the p2p peer from subscription cache.\n * @memberof Tinode.Topic#\n *\n * @return {Object} peer's description or undefined.\n */\n p2pPeerDesc() {\n if (!this.isP2PType()) {\n return undefined;\n }\n return this._users[this.name];\n }\n /**\n * Iterate over cached subscribers. If callback is undefined, use this.onMetaSub.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive subscribers one by one.\n * @param {Object=} context - Value of `this` inside the `callback`.\n */\n subscribers(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._users) {\n cb.call(context, this._users[idx], idx, this._users);\n }\n }\n }\n /**\n * Get a copy of cached tags.\n * @memberof Tinode.Topic#\n *\n * @return {Array.key or undefined.\n */\n aux(key) {\n return this._aux[key];\n }\n /**\n * Get cached subscription for the given user ID.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - id of the user to query for\n * @return user description or undefined.\n */\n subscriber(uid) {\n return this._users[uid];\n }\n /**\n * Iterate over versions of a message: call callback for each version (excluding original).\n * If callback is undefined, does nothing.\n * @memberof Tinode.Topic#\n *\n * @param {number} origSeq - seq ID of the original message.\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messageVersions(origSeq, callback, context) {\n if (!callback) {\n // No callback? We are done then.\n return;\n }\n const versions = this._messageVersions[origSeq];\n if (!versions) {\n return;\n }\n versions.forEach(callback, undefined, undefined, context);\n }\n /**\n * Iterate over cached messages: call callback for each message in the range [sinceIdx, beforeIdx).\n * If callback is undefined, use this.onData.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {number} sinceId - Optional seqId to start iterating from (inclusive).\n * @param {number} beforeId - Optional seqId to stop iterating before it is reached (exclusive).\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messages(callback, sinceId, beforeId, context) {\n const cb = (callback || this.onData);\n if (cb) {\n const startIdx = typeof sinceId == 'number' ? this._messages.find({\n seq: sinceId\n }, true) : undefined;\n const beforeIdx = typeof beforeId == 'number' ? this._messages.find({\n seq: beforeId\n }, true) : undefined;\n if (startIdx != -1 && beforeIdx != -1) {\n // Step 1. Filter out all replacement messages and\n // save displayable messages in a temporary buffer.\n let msgs = [];\n this._messages.forEach((msg, unused1, unused2, i) => {\n if (Topic.#isReplacementMsg(msg)) {\n // Skip replacements.\n return;\n }\n if (msg._deleted) {\n // Skip deleted ranges.\n return;\n }\n // In case the massage was edited, replace timestamp of the version with the original's timestamp.\n const latest = this.latestMsgVersion(msg.seq) || msg;\n if (!latest._origTs) {\n latest._origTs = latest.ts;\n latest._origSeq = latest.seq;\n latest.ts = msg.ts;\n latest.seq = msg.seq;\n }\n msgs.push({\n data: latest,\n idx: i\n });\n }, startIdx, beforeIdx, {});\n // Step 2. Loop over displayble messages invoking cb on each of them.\n msgs.forEach((val, i) => {\n cb.call(context, val.data,\n (i > 0 ? msgs[i - 1].data : undefined),\n (i < msgs.length - 1 ? msgs[i + 1].data : undefined), val.idx);\n });\n }\n }\n }\n /**\n * Get the message from cache by literal seq (does not resolve message edits).\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message seqId to search for.\n * @returns {Object} the message with the given seq or undefined, if no such message is found.\n */\n findMessage(seq) {\n const idx = this._messages.find({\n seq: seq\n });\n if (idx >= 0) {\n return this._messages.getAt(idx);\n }\n return undefined;\n }\n /**\n * Get the most recent message from cache. This method counts all messages, including deleted ranges.\n * @memberof Tinode.Topic#\n *\n * @returns {Object} the most recent cached message or undefined, if no messages are cached.\n */\n latestMessage() {\n return this._messages.getLast();\n }\n /**\n * Get the latest version for message.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - original seq ID of the message.\n * @returns {Object} the latest version of the message or null if message not found.\n */\n latestMsgVersion(seq) {\n const versions = this._messageVersions[seq];\n return versions ? versions.getLast() : null;\n }\n /**\n * Get the maximum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest seq ID in cache.\n */\n maxMsgSeq() {\n return this._maxSeq;\n }\n /**\n * Get the minimum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the smallest seq ID in cache or 0.\n */\n minMsgSeq() {\n return this._minSeq;\n }\n /**\n * Get the maximum deletion ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest deletion ID.\n */\n maxClearId() {\n return this._maxDel;\n }\n /**\n * Get the number of messages in the cache.\n * @memberof Tinode.Topic#\n *\n * @returns {number} count of cached messages.\n */\n messageCount() {\n return this._messages.length();\n }\n /**\n * Iterate over cached unsent messages. Wraps {@link Tinode.Topic#messages}.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of this inside the callback.\n */\n queuedMessages(callback, context) {\n if (!callback) {\n throw new Error(\"Callback must be provided\");\n }\n this.messages(callback, Const.LOCAL_SEQID, undefined, context);\n }\n /**\n * Get the number of topic subscribers who marked this message as either recv or read\n * Current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {string} what - what action to consider: received \"recv\" or read \"read\".\n * @param {number} seq - ID or the message read or received.\n *\n * @returns {number} the number of subscribers who marked the message with the given ID as read or received.\n */\n msgReceiptCount(what, seq) {\n let count = 0;\n if (seq > 0) {\n const me = this._tinode.getCurrentUserID();\n for (let idx in this._users) {\n const user = this._users[idx];\n if (user.user !== me && user[what] >= seq) {\n count++;\n }\n }\n }\n return count;\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as read.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message id to check.\n * @returns {number} number of subscribers who claim to have received the message.\n */\n msgReadCount(seq) {\n return this.msgReceiptCount('read', seq);\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as received.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - Message id to check.\n * @returns {number} Number of subscribers who claim to have received the message.\n */\n msgRecvCount(seq) {\n return this.msgReceiptCount('recv', seq);\n }\n /**\n * Check if cached message IDs indicate that the server may have more messages.\n * @memberof Tinode.Topic#\n *\n * @param {number} min - smallest seq ID loaded range.\n * @param {number} max - greatest seq ID in loaded range.\n * @param {boolean} newer - if true, check for newer messages only.\n * @returns {Array.true if message was cancelled, false otherwise.\n */\n cancelSend(seqId) {\n const idx = this._messages.find({\n seq: seqId\n });\n if (idx >= 0) {\n const msg = this._messages.getAt(idx);\n const status = this.msgStatus(msg);\n if (status == Const.MESSAGE_STATUS_QUEUED ||\n status == Const.MESSAGE_STATUS_FAILED ||\n status == Const.MESSAGE_STATUS_FATAL) {\n this._tinode._db.remMessages(this.name, seqId);\n msg._cancelled = true;\n this._messages.delAt(idx);\n if (this.onData) {\n // Calling with no parameters to indicate the message was deleted.\n this.onData();\n }\n return true;\n }\n }\n return false;\n }\n /**\n * Get type of the topic: me, p2p, grp, fnd...\n * @memberof Tinode.Topic#\n *\n * @returns {string} One of 'me', 'p2p', 'grp', 'fnd', 'sys' or undefined.\n */\n getType() {\n return Topic.topicType(this.name);\n }\n /**\n * Get current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.AccessMode} - user's access mode\n */\n getAccessMode() {\n return this.acs;\n }\n /**\n * Set current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @param {AccessMode | Object} acs - access mode to set.\n */\n setAccessMode(acs) {\n return this.acs = new AccessMode(acs);\n }\n /**\n * Get topic's default access mode.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.DefAcs} - access mode, such as {auth: `RWP`, anon: `N`}.\n */\n getDefaultAccess() {\n return this.defacs;\n }\n /**\n * Initialize new meta {@link Tinode.GetQuery} builder. The query is attched to the current topic.\n * It will not work correctly if used with a different topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.MetaGetBuilder} query attached to the current topic.\n */\n startMetaQuery() {\n return new MetaGetBuilder(this);\n }\n /**\n * Check if topic is archived, i.e. private.arch == true.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is archived, false otherwise.\n */\n isArchived() {\n return this.private && !!this.private.arch;\n }\n /**\n * Check if topic is a 'me' topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a 'me' topic, false otherwise.\n */\n isMeType() {\n return Topic.isMeTopicName(this.name);\n }\n /**\n * Check if topic is a channel.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a channel, false otherwise.\n */\n isChannelType() {\n return Topic.isChannelTopicName(this.name);\n }\n /**\n * Check if topic is a group topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a group, false otherwise.\n */\n isGroupType() {\n return Topic.isGroupTopicName(this.name);\n }\n /**\n * Check if topic is a p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p topic, false otherwise.\n */\n isP2PType() {\n return Topic.isP2PTopicName(this.name);\n }\n /**\n * Check if topic is a communication topic, i.e. a group or p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p or group topic, false otherwise.\n */\n isCommType() {\n return Topic.isCommTopicName(this.name);\n }\n /**\n * Get status (queued, sent, received etc) of a given message in the context\n * of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {Message} msg - message to check for status.\n * @param {boolean} upd - update chached message status.\n *\n * @returns message status constant.\n */\n msgStatus(msg, upd) {\n let status = Const.MESSAGE_STATUS_NONE;\n if (this._tinode.isMe(msg.from)) {\n if (msg._sending) {\n status = Const.MESSAGE_STATUS_SENDING;\n } else if (msg._fatal || msg._cancelled) {\n status = Const.MESSAGE_STATUS_FATAL;\n } else if (msg._failed) {\n status = Const.MESSAGE_STATUS_FAILED;\n } else if (msg.seq >= Const.LOCAL_SEQID) {\n status = Const.MESSAGE_STATUS_QUEUED;\n } else if (this.msgReadCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_READ;\n } else if (this.msgRecvCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_RECEIVED;\n } else if (msg.seq > 0) {\n status = Const.MESSAGE_STATUS_SENT;\n }\n } else {\n status = Const.MESSAGE_STATUS_TO_ME;\n }\n\n if (upd && msg._status != status) {\n msg._status = status;\n this._tinode._db.updMessageStatus(this.name, msg.seq, status);\n }\n\n return status;\n }\n\n // If msg is a replacement for another message, save the msg in the message versions cache\n // as a newer version for the message it's supposed to replace.\n _maybeUpdateMessageVersionsCache(msg) {\n if (!Topic.#isReplacementMsg(msg)) {\n // Check if this message is the original in the chain of edits and if so\n // ensure all version have the same sender.\n if (this._messageVersions[msg.seq]) {\n // Remove versions with different 'from'.\n this._messageVersions[msg.seq].filter(version => version.from == msg.from);\n if (this._messageVersions[msg.seq].isEmpty()) {\n delete this._messageVersions[msg.seq];\n }\n }\n return;\n }\n\n const targetSeq = parseInt(msg.head.replace.split(':')[1]);\n if (targetSeq > msg.seq) {\n // Substitutes are supposed to have higher seq ids.\n return;\n }\n const targetMsg = this.findMessage(targetSeq);\n if (targetMsg && targetMsg.from != msg.from) {\n // Substitute cannot change the sender.\n return;\n }\n const versions = this._messageVersions[targetSeq] || new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n versions.put(msg);\n this._messageVersions[targetSeq] = versions;\n }\n\n // Process data message\n _routeData(data) {\n if (data.content) {\n if (!this.touched || this.touched < data.ts) {\n this.touched = data.ts;\n this._tinode._db.updTopic(this);\n }\n }\n\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n this.msgStatus(data, true);\n // Ackn receiving the message.\n clearTimeout(this._recvNotificationTimer);\n this._recvNotificationTimer = setTimeout(_ => {\n this._recvNotificationTimer = null;\n this.noteRecv(this._maxSeq);\n }, Const.RECV_TIMEOUT);\n }\n\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n\n const outgoing = ((!this.isChannelType() && !data.from) || this._tinode.isMe(data.from));\n\n if (data.head && data.head.webrtc && data.head.mime == Drafty.getContentType() && data.content) {\n // Rewrite VC body with info from the headers.\n data.content = Drafty.updateVideoCall(data.content, {\n state: data.head.webrtc,\n duration: data.head['webrtc-duration'],\n incoming: !outgoing,\n });\n }\n\n if (!data._noForwarding) {\n this._messages.put(data);\n this._tinode._db.addMessage(data);\n this._maybeUpdateMessageVersionsCache(data);\n }\n\n if (this.onData) {\n this.onData(data);\n }\n\n // Update locally cached contact with the new message count.\n const what = outgoing ? 'read' : 'msg';\n this._updateReadRecv(what, data.seq, data.ts);\n // Notify 'me' listeners of the change.\n this._tinode.getMeTopic()._refreshContact(what, this);\n }\n\n // Process metadata message\n _routeMeta(meta) {\n if (meta.desc) {\n this._processMetaDesc(meta.desc);\n }\n if (meta.sub && meta.sub.length > 0) {\n this._processMetaSub(meta.sub);\n }\n if (meta.del) {\n this._processDelMessages(meta.del.clear, meta.del.delseq);\n }\n if (meta.tags) {\n this._processMetaTags(meta.tags);\n }\n if (meta.cred) {\n this._processMetaCreds(meta.cred);\n }\n if (meta.aux) {\n this._processMetaAux(meta.aux);\n }\n if (this.onMeta) {\n this.onMeta(meta);\n }\n }\n // Process presence change message\n _routePres(pres) {\n let user, uid;\n switch (pres.what) {\n case 'del':\n // Delete cached messages.\n this._processDelMessages(pres.clear, pres.delseq);\n break;\n case 'on':\n case 'off':\n // Update online status of a subscription.\n user = this._users[pres.src];\n if (user) {\n user.online = pres.what == 'on';\n } else {\n this._tinode.logger(\"WARNING: Presence update for an unknown user\", this.name, pres.src);\n }\n break;\n case 'term':\n // Attachment to topic is terminated probably due to cluster rehashing.\n this._resetSub();\n break;\n case 'upd':\n // A topic subscriber has updated his description.\n // Issue {get sub} only if the current user has no p2p topics with the updated user (p2p name is not in cache).\n // Otherwise 'me' will issue a {get desc} request.\n if (pres.src && !this._tinode.isTopicCached(pres.src)) {\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n }\n break;\n case 'aux':\n // Auxiliary data updated.\n this.getMeta(this.startMetaQuery().withAux().build());\n break;\n case 'acs':\n uid = pres.src || this._tinode.getCurrentUserID();\n user = this._users[uid];\n if (!user) {\n // Update for an unknown user: notification of a new subscription.\n const acs = new AccessMode().updateAll(pres.dacs);\n if (acs && acs.mode != AccessMode._NONE) {\n user = this._cacheGetUser(uid);\n if (!user) {\n user = {\n user: uid,\n acs: acs\n };\n this.getMeta(this.startMetaQuery().withOneSub(undefined, uid).build());\n } else {\n user.acs = acs;\n }\n user.updated = new Date();\n this._processMetaSub([user]);\n }\n } else {\n // Known user\n user.acs.updateAll(pres.dacs);\n // Update user's access mode.\n this._processMetaSub([{\n user: uid,\n updated: new Date(),\n acs: user.acs\n }]);\n }\n break;\n default:\n this._tinode.logger(\"INFO: Ignored presence update\", pres.what);\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n // Process {info} message\n _routeInfo(info) {\n switch (info.what) {\n case 'recv':\n case 'read':\n const user = this._users[info.from];\n if (user) {\n user[info.what] = info.seq;\n if (user.recv < user.read) {\n user.recv = user.read;\n }\n }\n const msg = this.latestMessage();\n if (msg) {\n this.msgStatus(msg, true);\n }\n\n // If this is an update from the current user, update the cache with the new count.\n if (this._tinode.isMe(info.from)) {\n this._updateReadRecv(info.what, info.seq);\n }\n\n // Notify 'me' listener of the status change.\n this._tinode.getMeTopic()._refreshContact(info.what, this);\n break;\n case 'kp':\n // Do nothing.\n break;\n case 'call':\n // Do nothing here.\n break;\n default:\n this._tinode.logger(\"INFO: Ignored info update\", info.what);\n }\n\n if (this.onInfo) {\n this.onInfo(info);\n }\n }\n // Called by Tinode when meta.desc packet is received.\n // Called by 'me' topic on contact update (desc._noForwarding is true).\n _processMetaDesc(desc) {\n if (this.isP2PType()) {\n // Synthetic desc may include defacs for p2p topics which is useless.\n // Remove it.\n delete desc.defacs;\n\n // Update to p2p desc is the same as user update. Update cached user.\n this._tinode._db.updUser(this.name, desc.public);\n }\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n // Update persistent cache.\n this._tinode._db.updTopic(this);\n\n // Notify 'me' listener, if available:\n if (this.name !== Const.TOPIC_ME && !desc._noForwarding) {\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n // Called by Tinode when meta.sub is recived or in response to received\n // {ctrl} after setMeta-sub.\n _processMetaSub(subs) {\n for (let idx in subs) {\n const sub = subs[idx];\n\n // Fill defaults.\n sub.online = !!sub.online;\n // Update timestamp of the most recent subscription update.\n this._lastSubsUpdate = new Date(Math.max(this._lastSubsUpdate, sub.updated));\n\n let user = null;\n if (!sub.deleted) {\n // If this is a change to user's own permissions, update them in topic too.\n // Desc will update 'me' topic.\n if (this._tinode.isMe(sub.user) && sub.acs) {\n this._processMetaDesc({\n updated: sub.updated,\n touched: sub.touched,\n acs: sub.acs\n });\n }\n user = this._updateCachedUser(sub.user, sub);\n } else {\n // Subscription is deleted, remove it from topic (but leave in Users cache)\n delete this._users[sub.user];\n user = sub;\n }\n\n if (this.onMetaSub) {\n this.onMetaSub(user);\n }\n }\n\n if (this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._users));\n }\n }\n // Called by Tinode when meta.tags is recived.\n _processMetaTags(tags) {\n if (tags == Const.DEL_CHAR || (tags.length == 1 && tags[0] == Const.DEL_CHAR)) {\n tags = [];\n }\n this._tags = tags;\n this._tinode._db.updTopic(this);\n if (this.onTagsUpdated) {\n this.onTagsUpdated(tags);\n }\n }\n // Do nothing for topics other than 'me'\n _processMetaCreds(creds) {}\n\n // Called by Tinode when meta.aux is recived.\n _processMetaAux(aux) {\n aux = (!aux || aux == Const.DEL_CHAR) ? {} : aux;\n this._aux = mergeObj(this._aux, aux);\n this._tinode._db.updTopic(this);\n if (this.onAuxUpdated) {\n this.onAuxUpdated(this._aux);\n }\n }\n\n // Delete cached messages and update cached transaction IDs\n _processDelMessages(clear, delseq) {\n this._maxDel = Math.max(clear, this._maxDel);\n this.clear = Math.max(clear, this.clear);\n let count = 0;\n if (Array.isArray(delseq)) {\n delseq.forEach(range => {\n if (!range.hi) {\n count++;\n this.flushMessage(range.low);\n } else {\n count += range.hi - range.low;\n this.flushMessageRange(range.low, range.hi);\n }\n });\n\n this._tinode._db.addDelLog(this.name, clear, delseq);\n }\n\n if (count > 0) {\n if (this.onData) {\n this.onData();\n }\n }\n }\n // Topic is informed that the entire response to {get what=data} has been received.\n _allMessagesReceived(count) {\n\n if (this.onAllMessagesReceived) {\n this.onAllMessagesReceived(count);\n }\n }\n // Reset subscribed state\n _resetSub() {\n this._attached = false;\n }\n // This topic is either deleted or unsubscribed from.\n _gone() {\n this._messages.reset();\n this._tinode._db.remMessages(this.name);\n this._users = {};\n this.acs = new AccessMode(null);\n this.private = null;\n this.public = null;\n this.trusted = null;\n this._maxSeq = 0;\n this._minSeq = 0;\n this._attached = false;\n\n const me = this._tinode.getMeTopic();\n if (me) {\n me._routePres({\n _noForwarding: true,\n what: 'gone',\n topic: Const.TOPIC_ME,\n src: this.name\n });\n }\n if (this.onDeleteTopic) {\n this.onDeleteTopic();\n }\n }\n // Update global user cache and local subscribers cache.\n // Don't call this method for non-subscribers.\n _updateCachedUser(uid, obj) {\n // Fetch user object from the global cache.\n // This is a clone of the stored object\n let cached = this._cacheGetUser(uid);\n cached = mergeObj(cached || {}, obj);\n // Save to global cache\n this._cachePutUser(uid, cached);\n // Save to the list of topic subsribers.\n return mergeToCache(this._users, uid, cached);\n }\n // Get local seqId for a queued message.\n _getQueuedSeqId() {\n return this._queuedSeqId++;\n }\n\n // Load most recent messages from persistent cache.\n _loadMessages(db, query) {\n query = query || {};\n query.limit = query.limit || Const.DEFAULT_MESSAGES_PAGE;\n\n // Count of message loaded from DB.\n let count = 0;\n return db.readMessages(this.name, query)\n .then(msgs => {\n msgs.forEach(data => {\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n }\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n this._messages.put(data);\n this._maybeUpdateMessageVersionsCache(data);\n });\n count = msgs.length;\n })\n .then(_ => db.readDelLog(this.name, query))\n .then(dellog => {\n return dellog.forEach(rec => {\n this._messages.put({\n seq: rec.low,\n low: rec.low,\n hi: rec.hi,\n _deleted: true\n });\n });\n })\n .then(_ => {\n // DEBUG\n return count;\n });\n }\n\n // Push or {pres}: message received.\n _updateReceived(seq, act) {\n this.touched = new Date();\n this.seq = seq | 0;\n // Check if message is sent by the current user. If so it's been read already.\n if (!act || this._tinode.isMe(act)) {\n this.read = this.read ? Math.max(this.read, this.seq) : this.seq;\n this.recv = this.recv ? Math.max(this.read, this.recv) : this.read;\n }\n this.unread = this.seq - (this.read | 0);\n this._tinode._db.updTopic(this);\n }\n}\n","/**\n * @file Utilities used in multiple places.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport {\n DEL_CHAR,\n LOCAL_SEQID\n} from './config.js';\n\n// Attempt to convert date and AccessMode strings to objects.\nexport function jsonParseHelper(key, val) {\n // Try to convert string timestamps with optional milliseconds to Date,\n // e.g. 2015-09-02T01:45:43[.123]Z\n if (typeof val == 'string' && val.length >= 20 && val.length <= 24 && ['ts', 'touched', 'updated', 'created', 'when', 'deleted', 'expires'].includes(key)) {\n const date = new Date(val);\n if (!isNaN(date)) {\n return date;\n }\n } else if (key === 'acs' && typeof val === 'object') {\n return new AccessMode(val);\n }\n return val;\n}\n\n// Checks if URL is a relative url, i.e. has no 'scheme://', including the case of missing scheme '//'.\n// The scheme is expected to be RFC-compliant, e.g. [a-z][a-z0-9+.-]*\n// example.html - ok\n// https:example.com - not ok.\n// http:/example.com - not ok.\n// ' ↲ https://example.com' - not ok. (↲ means carriage return)\nexport function isUrlRelative(url) {\n return url && !/^\\s*([a-z][a-z0-9+.-]*:|\\/\\/)/im.test(url);\n}\n\nfunction isValidDate(d) {\n return (d instanceof Date) && !isNaN(d) && (d.getTime() != 0);\n}\n\n// RFC3339 formater of Date\nexport function rfc3339DateString(d) {\n if (!isValidDate(d)) {\n return undefined;\n }\n\n const pad = function(val, sp) {\n sp = sp || 2;\n return '0'.repeat(sp - ('' + val).length) + val;\n };\n\n const millis = d.getUTCMilliseconds();\n return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) +\n 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) +\n (millis ? '.' + pad(millis, 3) : '') + 'Z';\n}\n\n// Recursively merge src's own properties to dst.\n// Ignore properties where ignore[property] is true.\n// Array and Date objects are shallow-copied.\nexport function mergeObj(dst, src, ignore) {\n if (typeof src != 'object') {\n if (src === undefined) {\n return dst;\n }\n if (src === DEL_CHAR) {\n return undefined;\n }\n return src;\n }\n // JS is crazy: typeof null is 'object'.\n if (src === null) {\n return src;\n }\n\n // Handle Date\n if (src instanceof Date && !isNaN(src)) {\n return (!dst || !(dst instanceof Date) || isNaN(dst) || dst < src) ? src : dst;\n }\n\n // Access mode\n if (src instanceof AccessMode) {\n return new AccessMode(src);\n }\n\n // Handle Array\n if (src instanceof Array) {\n return src;\n }\n\n if (!dst || dst === DEL_CHAR) {\n dst = src.constructor();\n }\n\n for (let prop in src) {\n if (src.hasOwnProperty(prop) && (!ignore || !ignore[prop]) && (prop != '_noForwarding')) {\n try {\n dst[prop] = mergeObj(dst[prop], src[prop]);\n } catch (err) {\n // FIXME: probably need to log something here.\n }\n }\n }\n return dst;\n}\n\n// Update object stored in a cache. Returns updated value.\nexport function mergeToCache(cache, key, newval, ignore) {\n cache[key] = mergeObj(cache[key], newval, ignore);\n return cache[key];\n}\n\n// Strips all values from an object of they evaluate to false or if their name starts with '_'.\n// Used on all outgoing object before serialization to string.\nexport function simplify(obj) {\n Object.keys(obj).forEach((key) => {\n if (key[0] == '_') {\n // Strip fields like \"obj._key\".\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (Array.isArray(obj[key]) && obj[key].length == 0) {\n // Strip empty arrays.\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (obj[key] instanceof Date) {\n // Strip invalid or zero date.\n if (!isValidDate(obj[key])) {\n delete obj[key];\n }\n } else if (typeof obj[key] == 'object') {\n simplify(obj[key]);\n // Strip empty objects.\n if (Object.getOwnPropertyNames(obj[key]).length == 0) {\n delete obj[key];\n }\n }\n });\n return obj;\n};\n\n\n// Trim whitespace, strip empty and duplicate elements elements.\n// If the result is an empty array, add a single element \"\\u2421\" (Unicode Del character).\nexport function normalizeArray(arr) {\n let out = [];\n if (Array.isArray(arr)) {\n // Trim, throw away very short and empty tags.\n for (let i = 0, l = arr.length; i < l; i++) {\n let t = arr[i];\n if (t) {\n t = t.trim().toLowerCase();\n if (t.length > 1) {\n out.push(t);\n }\n }\n }\n out.sort().filter((item, pos, ary) => {\n return !pos || item != ary[pos - 1];\n });\n }\n if (out.length == 0) {\n // Add single tag with a Unicode Del character, otherwise an ampty array\n // is ambiguos. The Del tag will be stripped by the server.\n out.push(DEL_CHAR);\n }\n return out;\n}\n\n// Convert input to valid ranges of IDs.\nexport function normalizeRanges(ranges, maxSeq) {\n if (!Array.isArray(ranges)) {\n return [];\n }\n\n // Sort ranges in accending order by low, then descending by hi.\n ranges.sort((r1, r2) => {\n if (r1.low < r2.low) {\n return true;\n }\n if (r1.low == r2.low) {\n return !r2.hi || (r1.hi >= r2.hi);\n }\n return false;\n });\n\n // Remove pending messages from ranges possibly clipping some ranges.\n return ranges.reduce((out, r) => {\n if (r.low < LOCAL_SEQID && r.low > 0) {\n if (!r.hi || r.hi < LOCAL_SEQID) {\n out.push(r);\n } else {\n // Clip hi to max allowed value.\n out.push({\n low: r.low,\n hi: maxSeq + 1\n });\n }\n }\n return out;\n }, []);\n}\n\n// Convert array of IDs to array of ranges.\nexport function listToRanges(list) {\n // Sort the list in ascending order\n list.sort((a, b) => a - b);\n // Convert the array of IDs to ranges.\n return list.reduce((out, id) => {\n if (out.length == 0) {\n // First element.\n out.push({\n low: id\n });\n } else {\n let prev = out[out.length - 1];\n if ((!prev.hi && (id != prev.low + 1)) || (id > prev.hi)) {\n // New range.\n out.push({\n low: id\n });\n } else {\n // Expand existing range.\n prev.hi = prev.hi ? Math.max(prev.hi, id + 1) : id + 1;\n }\n }\n return out;\n }, []);\n}\n\n// Cuts 'clip' range out of the 'src' range.\n// Returns an array with 0, 1 or 2 elements.\nexport function clipRange(src, clip) {\n if (clip.hi < src.low || clip.low >= src.hi) {\n // Clip is completely outside of src, no intersection.\n return [src];\n }\n\n if (clip.low <= src.low) {\n if (clip.hi >= src.hi) {\n // The source range is completely inside the clipping range.\n return [];\n }\n // Partial clipping at the top.\n return [{\n low: src.low,\n hi: clip.hi\n }];\n }\n\n // Range on the lower end.\n const result = [{\n low: src.low,\n hi: clip.low\n }];\n if (clip.hi < src.hi) {\n // Maybe a range on the higher end, if clip is completely inside the source.\n result.push({\n low: clip.hi,\n hi: src.hi\n });\n }\n\n return result;\n}\n","export const PACKAGE_VERSION = \"0.23.0-rc1\";\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * @module tinode-sdk\n *\n * @copyright 2015-2022 Tinode LLC.\n * @summary Javascript bindings for Tinode.\n * @license Apache 2.0\n * @version 0.20\n *\n * See https://github.com/tinode/webapp for real-life usage.\n *\n * @example\n * \n * \n * \n *\n * \n * ...\n * \n * \n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nimport AccessMode from './access-mode.js';\nimport * as Const from './config.js';\nimport CommError from './comm-error.js';\nimport Connection from './connection.js';\nimport DBCache from './db.js';\nimport Drafty from './drafty.js';\nimport LargeFileHelper from './large-file.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport Topic from './topic.js';\nimport TopicFnd from './fnd-topic.js';\nimport TopicMe from './me-topic.js';\n\nimport {\n isUrlRelative,\n jsonParseHelper,\n mergeObj,\n rfc3339DateString,\n simplify\n} from './utils.js';\n\n// Re-export AccessMode\nexport {\n AccessMode\n};\n\nlet WebSocketProvider;\nif (typeof WebSocket != 'undefined') {\n WebSocketProvider = WebSocket;\n}\n\nlet XHRProvider;\nif (typeof XMLHttpRequest != 'undefined') {\n XHRProvider = XMLHttpRequest;\n}\n\nlet IndexedDBProvider;\nif (typeof indexedDB != 'undefined') {\n IndexedDBProvider = indexedDB;\n}\n\n// Re-export Drafty.\nexport {\n Drafty\n}\n\ninitForNonBrowserApp();\n\n// Utility functions\n\n// Polyfill for non-browser context, e.g. NodeJs.\nfunction initForNonBrowserApp() {\n // Tinode requirement in native mode because react native doesn't provide Base64 method\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\n if (typeof btoa == 'undefined') {\n global.btoa = function(input = '') {\n let str = input;\n let output = '';\n\n for (let block = 0, charCode, i = 0, map = chars; str.charAt(i | 0) || (map = '=', i % 1); output += map.charAt(63 & block >> 8 - i % 1 * 8)) {\n\n charCode = str.charCodeAt(i += 3 / 4);\n\n if (charCode > 0xFF) {\n throw new Error(\"'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.\");\n }\n block = block << 8 | charCode;\n }\n\n return output;\n };\n }\n\n if (typeof atob == 'undefined') {\n global.atob = function(input = '') {\n let str = input.replace(/=+$/, '');\n let output = '';\n\n if (str.length % 4 == 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (let bc = 0, bs = 0, buffer, i = 0; buffer = str.charAt(i++);\n\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n }\n\n if (typeof window == 'undefined') {\n global.window = {\n WebSocket: WebSocketProvider,\n XMLHttpRequest: XHRProvider,\n indexedDB: IndexedDBProvider,\n URL: {\n createObjectURL: function() {\n throw new Error(\"Unable to use URL.createObjectURL in a non-browser application\");\n }\n }\n }\n }\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n DBCache.setDatabaseProvider(IndexedDBProvider);\n}\n\n// Detect find most useful network transport.\nfunction detectTransport() {\n if (typeof window == 'object') {\n if (window['WebSocket']) {\n return 'ws';\n } else if (window['XMLHttpRequest']) {\n // The browser or node has no websockets, using long polling.\n return 'lp';\n }\n }\n return null;\n}\n\n// btoa replacement. Stock btoa fails on on non-Latin1 strings.\nfunction b64EncodeUnicode(str) {\n // The encodeURIComponent percent-encodes UTF-8 string,\n // then the percent encoding is converted into raw bytes which\n // can be fed into btoa.\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,\n function toSolidBytes(match, p1) {\n return String.fromCharCode('0x' + p1);\n }));\n}\n\n// JSON stringify helper - pre-processor for JSON.stringify\nfunction jsonBuildHelper(key, val) {\n if (val instanceof Date) {\n // Convert javascript Date objects to rfc3339 strings\n val = rfc3339DateString(val);\n } else if (val instanceof AccessMode) {\n val = val.jsonHelper();\n } else if (val === undefined || val === null || val === false ||\n (Array.isArray(val) && val.length == 0) ||\n ((typeof val == 'object') && (Object.keys(val).length == 0))) {\n // strip out empty elements while serializing objects to JSON\n return undefined;\n }\n\n return val;\n};\n\n// Trims very long strings (encoded images) to make logged packets more readable.\nfunction jsonLoggerHelper(key, val) {\n if (typeof val == 'string' && val.length > 128) {\n return '<' + val.length + ', bytes: ' + val.substring(0, 12) + '...' + val.substring(val.length - 12) + '>';\n }\n return jsonBuildHelper(key, val);\n};\n\n// Parse browser user agent to extract browser name and version.\nfunction getBrowserInfo(ua, product) {\n ua = ua || '';\n let reactnative = '';\n // Check if this is a ReactNative app.\n if (/reactnative/i.test(product)) {\n reactnative = 'ReactNative; ';\n }\n let result;\n // Remove useless string.\n ua = ua.replace(' (KHTML, like Gecko)', '');\n // Test for WebKit-based browser.\n let m = ua.match(/(AppleWebKit\\/[.\\d]+)/i);\n if (m) {\n // List of common strings, from more useful to less useful.\n // All unknown strings get the highest (-1) priority.\n const priority = ['edg', 'chrome', 'safari', 'mobile', 'version'];\n let tmp = ua.substr(m.index + m[0].length).split(' ');\n let tokens = [];\n let version; // 1.0 in Version/1.0 or undefined;\n // Split string like 'Name/0.0.0' into ['Name', '0.0.0', 3] where the last element is the priority.\n for (let i = 0; i < tmp.length; i++) {\n let m2 = /([\\w.]+)[\\/]([\\.\\d]+)/.exec(tmp[i]);\n if (m2) {\n // Unknown values are highest priority (-1).\n tokens.push([m2[1], m2[2], priority.findIndex((e) => {\n return m2[1].toLowerCase().startsWith(e);\n })]);\n if (m2[1] == 'Version') {\n version = m2[2];\n }\n }\n }\n // Sort by priority: more interesting is earlier than less interesting.\n tokens.sort((a, b) => {\n return a[2] - b[2];\n });\n if (tokens.length > 0) {\n // Return the least common browser string and version.\n if (tokens[0][0].toLowerCase().startsWith('edg')) {\n tokens[0][0] = 'Edge';\n } else if (tokens[0][0] == 'OPR') {\n tokens[0][0] = 'Opera';\n } else if (tokens[0][0] == 'Safari' && version) {\n tokens[0][1] = version;\n }\n result = tokens[0][0] + '/' + tokens[0][1];\n } else {\n // Failed to ID the browser. Return the webkit version.\n result = m[1];\n }\n } else if (/firefox/i.test(ua)) {\n m = /Firefox\\/([.\\d]+)/g.exec(ua);\n if (m) {\n result = 'Firefox/' + m[1];\n } else {\n result = 'Firefox/?';\n }\n } else {\n // Neither AppleWebKit nor Firefox. Try the last resort.\n m = /([\\w.]+)\\/([.\\d]+)/.exec(ua);\n if (m) {\n result = m[1] + '/' + m[2];\n } else {\n m = ua.split(' ');\n result = m[0];\n }\n }\n\n // Shorten the version to one dot 'a.bb.ccc.d -> a.bb' at most.\n m = result.split('/');\n if (m.length > 1) {\n const v = m[1].split('.');\n const minor = v[1] ? '.' + v[1].substr(0, 2) : '';\n result = `${m[0]}/${v[0]}${minor}`;\n }\n return reactnative + result;\n}\n\n/**\n * The main class for interacting with Tinode server.\n */\nexport class Tinode {\n _host;\n _secure;\n\n _appName;\n\n // API Key.\n _apiKey;\n\n // Name and version of the browser.\n _browser = '';\n _platform;\n // Hardware\n _hwos = 'undefined';\n _humanLanguage = 'xx';\n\n // Logging to console enabled\n _loggingEnabled = false;\n // When logging, trip long strings (base64-encoded images) for readability\n _trimLongStrings = false;\n // UID of the currently authenticated user.\n _myUID = null;\n // Status of connection: authenticated or not.\n _authenticated = false;\n // Login used in the last successful basic authentication\n _login = null;\n // Token which can be used for login instead of login/password.\n _authToken = null;\n // Counter of received packets\n _inPacketCount = 0;\n // Counter for generating unique message IDs\n _messageId = Math.floor((Math.random() * 0xFFFF) + 0xFFFF);\n // Information about the server, if connected\n _serverInfo = null;\n // Push notification token. Called deviceToken for consistency with the Android SDK.\n _deviceToken = null;\n\n // Cache of pending promises by message id.\n _pendingPromises = {};\n // The Timeout object returned by the reject expired promises setInterval.\n _expirePromises = null;\n\n // Websocket or long polling connection.\n _connection = null;\n\n // Use indexDB for caching topics and messages.\n _persist = false;\n // IndexedDB wrapper object.\n _db = null;\n\n // Tinode's cache of objects\n _cache = {};\n\n /**\n * Create Tinode object.\n *\n * @param {Object} config - configuration parameters.\n * @param {string} config.appName - Name of the calling application to be reported in the User Agent.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - See {@link Tinode.Connection#transport}.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} config.platform - Optional platform identifier, one of \"ios\", \"web\", \"android\".\n * @param {boolen} config.persist - Use IndexedDB persistent storage.\n * @param {function} onComplete - callback to call when initialization is completed.\n */\n constructor(config, onComplete) {\n this._host = config.host;\n this._secure = config.secure;\n\n // Client-provided application name, format null if no valid credentials were given.\n */\n static credential(meth, val, params, resp) {\n if (typeof meth == 'object') {\n ({\n val,\n params,\n resp,\n meth\n } = meth);\n }\n if (meth && (val || resp)) {\n return [{\n 'meth': meth,\n 'val': val,\n 'resp': resp,\n 'params': params\n }];\n }\n return null;\n }\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n return Topic.topicType(name);\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.isMeTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a group topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.isGroupTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.isP2PTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isCommTopicName(name);\n }\n /**\n * Check if the topic name is a name of a new topic.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return Topic.isNewGroupTopicName(name);\n }\n /**\n * Check if the topic name is a name of a channel.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return Topic.isChannelTopicName(name);\n }\n /**\n * Get information about the current version of this Tinode client library.\n * @returns {string} semantic version of the library, e.g. \"0.15.5-rc1\".\n */\n static getVersion() {\n return Const.VERSION;\n }\n /**\n * To use Tinode in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n *\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n }\n /**\n * To use Tinode in a non browser context, supply indexedDB provider.\n * @static\n *\n * @param idbProvider indexedDB provider, e.g. for nodeJS , require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IndexedDBProvider = idbProvider;\n\n DBCache.setDatabaseProvider(IndexedDBProvider);\n }\n /**\n * Return information about the current name and version of this Tinode library.\n * @static\n *\n * @returns {string} the name of the library and it's version.\n */\n static getLibrary() {\n return Const.LIBRARY;\n }\n /**\n * Check if the given string represents NULL value as defined by Tinode ('\\u2421').\n * @param {string} str - string to check for NULL value.\n * @returns {boolean} true if string represents NULL value, false otherwise.\n */\n static isNullValue(str) {\n return str === Const.DEL_CHAR;\n }\n\n // Instance methods.\n\n // Generates unique message IDs\n getNextUniqueId() {\n return (this._messageId != 0) ? '' + this._messageId++ : undefined;\n };\n\n /**\n * Connect to the server.\n *\n * @param {string} host_ - name of the host to connect to.\n * @return {Promise} Promise resolved/rejected when the connection call completes:\n * resolve() is called without parameters, reject() receives the\n * Error as a single parameter.\n */\n connect(host_) {\n return this._connection.connect(host_);\n }\n\n /**\n * Attempt to reconnect to the server immediately.\n *\n * @param {string} force - if true, reconnect even if there is a connection already.\n */\n reconnect(force) {\n this._connection.reconnect(force);\n }\n\n /**\n * Disconnect from the server.\n */\n disconnect() {\n this._connection.disconnect();\n }\n\n /**\n * Clear persistent cache: remove IndexedDB.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n clearStorage() {\n if (this._db.isReady()) {\n return this._db.deleteDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Initialize persistent cache: create IndexedDB cache.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n initStorage() {\n if (!this._db.isReady()) {\n return this._db.initDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Send a network probe message to make sure the connection is alive.\n */\n networkProbe() {\n this._connection.probe();\n }\n\n /**\n * Check for live connection to server.\n *\n * @returns {boolean} true if there is a live connection, false otherwise.\n */\n isConnected() {\n return this._connection.isConnected();\n }\n\n /**\n * Check if connection is authenticated (last login was successful).\n *\n * @returns {boolean} true if authenticated, false otherwise.\n */\n isAuthenticated() {\n return this._authenticated;\n }\n\n /**\n * Add API key and auth token to the relative URL making it usable for getting data\n * from the server in a simple HTTP GET request.\n *\n * @param {string} URL - URL to wrap.\n * @returns {string} URL with appended API key and token, if valid token is present.\n */\n authorizeURL(url) {\n if (typeof url != 'string') {\n return url;\n }\n\n if (isUrlRelative(url)) {\n // Fake base to make the relative URL parseable.\n const base = 'scheme://host/';\n const parsed = new URL(url, base);\n if (this._apiKey) {\n parsed.searchParams.append('apikey', this._apiKey);\n }\n if (this._authToken && this._authToken.token) {\n parsed.searchParams.append('auth', 'token');\n parsed.searchParams.append('secret', this._authToken.token);\n }\n // Convert back to string and strip fake base URL except for the root slash.\n url = parsed.toString().substring(base.length - 1);\n }\n return url;\n }\n\n /**\n * @typedef AccountParams\n * @type {Object}\n * @property {DefAcs=} defacs - Default access parameters for user's me topic.\n * @property {Object=} public - Public application-defined data exposed on me topic.\n * @property {Object=} private - Private application-defined data accessible on me topic.\n * @property {Object=} trusted - Trusted user data which can be set by a root user only.\n * @property {Array.me for authenticated users.\n * @property {string=} anon - Access mode for me for anonymous users.\n */\n\n /**\n * Create or update an account.\n *\n * @param {string} uid - User id to update\n * @param {string} scheme - Authentication scheme; \"basic\" and \"anonymous\" are the currently supported schemes.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n account(uid, scheme, secret, login, params) {\n const pkt = this.#initPacket('acc');\n pkt.acc.user = uid;\n pkt.acc.scheme = scheme;\n pkt.acc.secret = secret;\n // Log in to the new account using selected scheme\n pkt.acc.login = login;\n\n if (params) {\n pkt.acc.desc.defacs = params.defacs;\n pkt.acc.desc.public = params.public;\n pkt.acc.desc.private = params.private;\n pkt.acc.desc.trusted = params.trusted;\n\n pkt.acc.tags = params.tags;\n pkt.acc.cred = params.cred;\n\n pkt.acc.tmpscheme = params.scheme;\n pkt.acc.tmpsecret = params.secret;\n\n if (Array.isArray(params.attachments) && params.attachments.length > 0) {\n pkt.extra = {\n attachments: params.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n }\n\n return this.#send(pkt, pkt.acc.id);\n }\n\n /**\n * Create a new user. Wrapper for {@link Tinode#account}.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccount(scheme, secret, login, params) {\n let promise = this.account(Const.USER_NEW, scheme, secret, login, params);\n if (login) {\n promise = promise.then(ctrl => this.#loginSuccessful(ctrl));\n }\n return promise;\n }\n\n /**\n * Create user with 'basic' authentication scheme and immediately\n * use it for authentication. Wrapper for {@link Tinode#account}.\n *\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccountBasic(username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.createAccount('basic',\n b64EncodeUnicode(username + ':' + password), true, params);\n }\n\n /**\n * Update user's credentials for 'basic' authentication scheme. Wrapper for {@link Tinode#account}.\n *\n * @param {string} uid - User ID to update.\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n updateAccountBasic(uid, username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.account(uid, 'basic',\n b64EncodeUnicode(username + ':' + password), false, params);\n }\n\n /**\n * Send handshake to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n hello() {\n const pkt = this.#initPacket('hi');\n\n return this.#send(pkt, pkt.hi.id)\n .then(ctrl => {\n // Reset backoff counter on successful connection.\n this._connection.backoffReset();\n\n // Server response contains server protocol version, build, constraints,\n // session ID for long polling. Save them.\n if (ctrl.params) {\n this._serverInfo = ctrl.params;\n }\n\n if (this.onConnect) {\n this.onConnect();\n }\n\n return ctrl;\n }).catch(err => {\n this._connection.reconnect(true);\n\n if (this.onDisconnect) {\n this.onDisconnect(err);\n }\n });\n }\n\n /**\n * Set or refresh the push notifications/device token. If the client is connected,\n * the deviceToken can be sent to the server.\n *\n * @param {string} dt - token obtained from the provider or false,\n * null or undefined to clear the token.\n *\n * @returns true if attempt was made to send the update to the server.\n */\n setDeviceToken(dt) {\n let sent = false;\n // Convert any falsish value to null.\n dt = dt || null;\n if (dt != this._deviceToken) {\n this._deviceToken = dt;\n if (this.isConnected() && this.isAuthenticated()) {\n this.#send({\n 'hi': {\n 'dev': dt || Tinode.DEL_CHAR\n }\n });\n sent = true;\n }\n }\n return sent;\n }\n\n /**\n * @typedef Credential\n * @type {Object}\n * @property {string} meth - validation method.\n * @property {string} val - value to validate (e.g. email or phone number).\n * @property {string} resp - validation response.\n * @property {Object} params - validation parameters.\n */\n /**\n * Authenticate current session.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n login(scheme, secret, cred) {\n const pkt = this.#initPacket('login');\n pkt.login.scheme = scheme;\n pkt.login.secret = secret;\n pkt.login.cred = cred;\n\n return this.#send(pkt, pkt.login.id)\n .then(ctrl => this.#loginSuccessful(ctrl));\n }\n\n /**\n * Wrapper for {@link Tinode#login} with basic authentication\n *\n * @param {string} uname - User name.\n * @param {string} password - Password.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginBasic(uname, password, cred) {\n return this.login('basic', b64EncodeUnicode(uname + ':' + password), cred)\n .then(ctrl => {\n this._login = uname;\n return ctrl;\n });\n }\n\n /**\n * Wrapper for {@link Tinode#login} with token authentication\n *\n * @param {string} token - Token received in response to earlier login.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginToken(token, cred) {\n return this.login('token', token, cred);\n }\n\n /**\n * Send a request for resetting an authentication secret.\n *\n * @param {string} scheme - authentication scheme to reset.\n * @param {string} method - method to use for resetting the secret, such as \"email\" or \"tel\".\n * @param {string} value - value of the credential to use, a specific email address or a phone number.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving the server reply.\n */\n requestResetAuthSecret(scheme, method, value) {\n return this.login('reset', b64EncodeUnicode(scheme + ':' + method + ':' + value));\n }\n\n /**\n * @typedef AuthToken\n * @type {Object}\n * @property {string} token - Token value.\n * @property {Date} expires - Token expiration time.\n */\n /**\n * Get stored authentication token.\n *\n * @returns {AuthToken} authentication token.\n */\n getAuthToken() {\n if (this._authToken && (this._authToken.expires.getTime() > Date.now())) {\n return this._authToken;\n } else {\n this._authToken = null;\n }\n return null;\n }\n\n /**\n * Application may provide a saved authentication token.\n *\n * @param {AuthToken} token - authentication token.\n */\n setAuthToken(token) {\n this._authToken = token;\n }\n\n /**\n * @typedef SetParams\n * @type {Object}\n * @property {SetDesc=} desc - Topic initialization parameters when creating a new topic or a new subscription.\n * @property {SetSub=} sub - Subscription initialization parameters.\n * @property {Array.true, detach and unsubscribe, otherwise just detach.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n leave(topic, unsub) {\n const pkt = this.#initPacket('leave', topic);\n pkt.leave.unsub = unsub;\n\n return this.#send(pkt, pkt.leave.id);\n }\n\n /**\n * Create message draft without sending it to the server.\n *\n * @param {string} topic - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Object} new message which can be sent to the server or otherwise used.\n */\n createMessage(topic, content, noEcho) {\n const pkt = this.#initPacket('pub', topic);\n\n let dft = typeof content == 'string' ? Drafty.parse(content) : content;\n if (dft && !Drafty.isPlainText(dft)) {\n pkt.pub.head = {\n mime: Drafty.getContentType()\n };\n content = dft;\n }\n pkt.pub.noecho = noEcho;\n pkt.pub.content = content;\n\n return pkt.pub;\n }\n\n /**\n * Publish {data} message to topic.\n *\n * @param {string} topicName - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n publish(topicName, content, noEcho) {\n return this.publishMessage(\n this.createMessage(topicName, content, noEcho)\n );\n }\n\n /**\n * Publish message to topic. The message should be created by {@link Tinode#createMessage}.\n *\n * @param {Object} pub - Message to publish.\n * @param {Array.'me' topic.\n *\n * @param {string} method - validation method such as 'email' or 'tel'.\n * @param {string} value - validation value, i.e. 'alice@example.com'.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n const pkt = this.#initPacket('del', Const.TOPIC_ME);\n pkt.del.what = 'cred';\n pkt.del.cred = {\n meth: method,\n val: value\n };\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Request to delete account of the current user.\n *\n * @param {boolean} hard - hard-delete user.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCurrentUser(hard) {\n const pkt = this.#initPacket('del', null);\n pkt.del.what = 'user';\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id).then(_ => {\n this._myUID = null;\n });\n }\n\n /**\n * Notify server that a message or messages were read or received. Does NOT return promise.\n *\n * @param {string} topicName - Name of the topic where the mesage is being aknowledged.\n * @param {string} what - Action being aknowledged, either \"read\" or \"recv\".\n * @param {number} seq - Maximum id of the message being acknowledged.\n */\n note(topicName, what, seq) {\n if (seq <= 0 || seq >= Const.LOCAL_SEQID) {\n throw new Error(`Invalid message id ${seq}`);\n }\n\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = what;\n pkt.note.seq = seq;\n this.#send(pkt);\n }\n\n /**\n * Broadcast a key-press notification to topic subscribers. Used to show\n * typing notifications \"user X is typing...\".\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {string=} type - notification to send, default is 'kp'.\n */\n noteKeyPress(topicName, type) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = type || 'kp';\n this.#send(pkt);\n }\n\n /**\n * Send a video call notification to topic subscribers (including dialing,\n * hangup, etc.).\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} evt - Call event.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(topicName, seq, evt, payload) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.seq = seq;\n pkt.note.what = 'call';\n pkt.note.event = evt;\n pkt.note.payload = payload;\n this.#send(pkt, pkt.note.id);\n }\n\n /**\n * Get a named topic, either pull it from cache or create a new instance.\n * There is a single instance of topic for each name.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested or newly created topic or undefined if topic name is invalid.\n */\n getTopic(topicName) {\n let topic = this.#cacheGet('topic', topicName);\n if (!topic && topicName) {\n if (topicName == Const.TOPIC_ME) {\n topic = new TopicMe();\n } else if (topicName == Const.TOPIC_FND) {\n topic = new TopicFnd();\n } else {\n topic = new Topic(topicName);\n }\n // Cache management.\n this.#attachCacheToTopic(topic);\n topic._cachePutSelf();\n // Don't save to DB here: a record will be added when the topic is subscribed.\n }\n return topic;\n }\n\n /**\n * Get a named topic from cache.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested topic or undefined if topic is not found in cache.\n */\n cacheGetTopic(topicName) {\n return this.#cacheGet('topic', topicName);\n }\n\n /**\n * Remove named topic from cache.\n *\n * @param {string} topicName - Name of the topic to remove from cache.\n */\n cacheRemTopic(topicName) {\n this.#cacheDel('topic', topicName);\n }\n\n /**\n * Iterate over cached topics.\n *\n * @param {Function} func - callback to call for each topic.\n * @param {Object} context - 'this' inside the 'func'.\n */\n mapTopics(func, context) {\n this.#cacheMap('topic', func, context);\n }\n\n /**\n * Check if named topic is already present in cache.\n *\n * @param {string} topicName - Name of the topic to check.\n * @returns {boolean} true if topic is found in cache, false otherwise.\n */\n isTopicCached(topicName) {\n return !!this.#cacheGet('topic', topicName);\n }\n\n /**\n * Generate unique name like 'new123456' suitable for creating a new group topic.\n *\n * @param {boolean} isChan - if the topic is channel-enabled.\n * @returns {string} name which can be used for creating a new group topic.\n */\n newGroupTopicName(isChan) {\n return (isChan ? Const.TOPIC_NEW_CHAN : Const.TOPIC_NEW) + this.getNextUniqueId();\n }\n\n /**\n * Instantiate 'me' topic or get it from cache.\n *\n * @returns {TopicMe} Instance of 'me' topic.\n */\n getMeTopic() {\n return this.getTopic(Const.TOPIC_ME);\n }\n\n /**\n * Instantiate 'fnd' (find) topic or get it from cache.\n *\n * @returns {Topic} Instance of 'fnd' topic.\n */\n getFndTopic() {\n return this.getTopic(Const.TOPIC_FND);\n }\n\n /**\n * Create a new {@link LargeFileHelper} instance\n *\n * @returns {LargeFileHelper} instance of a {@link Tinode.LargeFileHelper}.\n */\n getLargeFileHelper() {\n return new LargeFileHelper(this, Const.PROTOCOL_VERSION);\n }\n\n /**\n * Get the UID of the the current authenticated user.\n *\n * @returns {string} UID of the current user or undefined if the session is not yet\n * authenticated or if there is no session.\n */\n getCurrentUserID() {\n return this._myUID;\n }\n\n /**\n * Check if the given user ID is equal to the current user's UID.\n *\n * @param {string} uid - UID to check.\n *\n * @returns {boolean} true if the given UID belongs to the current logged in user.\n */\n isMe(uid) {\n return this._myUID === uid;\n }\n\n /**\n * Get login used for last successful authentication.\n *\n * @returns {string} login last used successfully or undefined.\n */\n getCurrentLogin() {\n return this._login;\n }\n\n /**\n * Return information about the server: protocol version and build timestamp.\n *\n * @returns {Object} build and version of the server or null if there is no connection or\n * if the first server response has not been received yet.\n */\n getServerInfo() {\n return this._serverInfo;\n }\n\n /**\n * Report a topic for abuse. Wrapper for {@link Tinode#publish}.\n *\n * @param {string} action - the only supported action is 'report'.\n * @param {string} target - name of the topic being reported.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n report(action, target) {\n return this.publish(Const.TOPIC_SYS, Drafty.attachJSON(null, {\n 'action': action,\n 'target': target\n }));\n }\n\n /**\n * Return server-provided configuration value.\n *\n * @param {string} name of the value to return.\n * @param {Object} defaultValue to return in case the parameter is not set or not found.\n *\n * @returns {Object} named value.\n */\n getServerParam(name, defaultValue) {\n return this._serverInfo && this._serverInfo[name] || defaultValue;\n }\n\n /**\n * Toggle console logging. Logging is off by default.\n *\n * @param {boolean} enabled - Set to true to enable logging to console.\n * @param {boolean} trimLongStrings - Set to true to trim long strings.\n */\n enableLogging(enabled, trimLongStrings) {\n this._loggingEnabled = enabled;\n this._trimLongStrings = enabled && trimLongStrings;\n }\n\n /**\n * Set UI language to report to the server. Must be called before 'hi' is sent, otherwise it will not be used.\n *\n * @param {string} hl - human (UI) language, like \"en_US\" or \"zh-Hans\".\n */\n setHumanLanguage(hl) {\n if (hl) {\n this._humanLanguage = hl;\n }\n }\n\n /**\n * Check if given topic is online.\n *\n * @param {string} name of the topic to test.\n * @returns {boolean} true if topic is online, false otherwise.\n */\n isTopicOnline(name) {\n const topic = this.#cacheGet('topic', name);\n return topic && topic.online;\n }\n\n /**\n * Get access mode for the given contact.\n *\n * @param {string} name of the topic to query.\n * @returns {AccessMode} access mode if topic is found, null otherwise.\n */\n getTopicAccessMode(name) {\n const topic = this.#cacheGet('topic', name);\n return topic ? topic.acs : null;\n }\n\n /**\n * Include message ID into all subsequest messages to server instructin it to send aknowledgemens.\n * Required for promises to function. Default is \"on\".\n *\n * @param {boolean} status - Turn aknowledgemens on or off.\n * @deprecated\n */\n wantAkn(status) {\n if (status) {\n this._messageId = Math.floor((Math.random() * 0xFFFFFF) + 0xFFFFFF);\n } else {\n this._messageId = 0;\n }\n }\n\n // Callbacks:\n /**\n * Callback to report when the websocket is opened. The callback has no parameters.\n *\n * @type {onWebsocketOpen}\n */\n onWebsocketOpen = undefined;\n\n /**\n * @typedef ServerParams\n *\n * @type {Object}\n * @property {string} ver - Server version\n * @property {string} build - Server build\n * @property {string=} sid - Session ID, long polling connections only.\n */\n\n /**\n * @callback onConnect\n * @param {number} code - Result code\n * @param {string} text - Text epxplaining the completion, i.e \"OK\" or an error message.\n * @param {ServerParams} params - Parameters returned by the server.\n */\n /**\n * Callback to report when connection with Tinode server is established.\n * @type {onConnect}\n */\n onConnect = undefined;\n\n /**\n * Callback to report when connection is lost. The callback has no parameters.\n * @type {onDisconnect}\n */\n onDisconnect = undefined;\n\n /**\n * @callback onLogin\n * @param {number} code - NUmeric completion code, same as HTTP status codes.\n * @param {string} text - Explanation of the completion code.\n */\n /**\n * Callback to report login completion.\n * @type {onLogin}\n */\n onLogin = undefined;\n\n /**\n * Callback to receive {ctrl} (control) messages.\n * @type {onCtrlMessage}\n */\n onCtrlMessage = undefined;\n\n /**\n * Callback to recieve {data} (content) messages.\n * @type {onDataMessage}\n */\n onDataMessage = undefined;\n\n /**\n * Callback to receive {pres} (presence) messages.\n * @type {onPresMessage}\n */\n onPresMessage = undefined;\n\n /**\n * Callback to receive all messages as objects.\n * @type {onMessage}\n */\n onMessage = undefined;\n\n /**\n * Callback to receive all messages as unparsed text.\n * @type {onRawMessage}\n */\n onRawMessage = undefined;\n\n /**\n * Callback to receive server responses to network probes. See {@link Tinode#networkProbe}\n * @type {onNetworkProbe}\n */\n onNetworkProbe = undefined;\n\n /**\n * Callback to be notified when exponential backoff is iterating.\n * @type {onAutoreconnectIteration}\n */\n onAutoreconnectIteration = undefined;\n};\n\n// Exported constants\nTinode.MESSAGE_STATUS_NONE = Const.MESSAGE_STATUS_NONE;\nTinode.MESSAGE_STATUS_QUEUED = Const.MESSAGE_STATUS_QUEUED;\nTinode.MESSAGE_STATUS_SENDING = Const.MESSAGE_STATUS_SENDING;\nTinode.MESSAGE_STATUS_FAILED = Const.MESSAGE_STATUS_FAILED;\nTinode.MESSAGE_STATUS_FATAL = Const.MESSAGE_STATUS_FATAL;\nTinode.MESSAGE_STATUS_SENT = Const.MESSAGE_STATUS_SENT;\nTinode.MESSAGE_STATUS_RECEIVED = Const.MESSAGE_STATUS_RECEIVED;\nTinode.MESSAGE_STATUS_READ = Const.MESSAGE_STATUS_READ;\nTinode.MESSAGE_STATUS_TO_ME = Const.MESSAGE_STATUS_TO_ME;\n\n// Unicode [del] symbol.\nTinode.DEL_CHAR = Const.DEL_CHAR;\n\n// Names of keys to server-provided configuration limits.\nTinode.MAX_MESSAGE_SIZE = 'maxMessageSize';\nTinode.MAX_SUBSCRIBER_COUNT = 'maxSubscriberCount';\nTinode.MAX_TAG_COUNT = 'maxTagCount';\nTinode.MAX_FILE_UPLOAD_SIZE = 'maxFileUploadSize';\nTinode.REQ_CRED_VALIDATORS = 'reqCred';\n"],"names":["AccessMode","constructor","acs","given","decode","want","mode","checkFlag","#checkFlag","val","side","flag","includes","Error","str","_BITMASK","_NONE","bitmask","_JOIN","_READ","_WRITE","_PRES","_APPROVE","_SHARE","_DELETE","_OWNER","m0","i","length","bit","charAt","toUpperCase","encode","_INVALID","res","update","upd","action","val0","parts","split","diff","a1","a2","toString","jsonHelper","setMode","m","updateMode","u","getMode","setGiven","g","updateGiven","getGiven","setWant","w","updateWant","getWant","getMissing","getExcessive","updateAll","isOwner","isPresencer","isMuted","isJoiner","isReader","isWriter","isApprover","isAdmin","isSharer","isDeleter","CBuffer","comparator","undefined","unique","buffer","compare_","unique_","a","b","findNearest","#findNearest","elem","arr","exact","start","end","pivot","found","idx","insertSorted","#insertSorted","count","splice","getAt","at","getLast","put","insert","arguments","Array","isArray","delAt","r","delRange","since","before","reset","forEach","callback","startIdx","beforeIdx","context","Math","max","min","call","find","nearest","filter","isEmpty","CommError","message","code","name","PACKAGE_VERSION","PROTOCOL_VERSION","VERSION","LIBRARY","TOPIC_NEW","TOPIC_NEW_CHAN","TOPIC_ME","TOPIC_FND","TOPIC_SYS","TOPIC_CHAN","TOPIC_GRP","TOPIC_P2P","USER_NEW","LOCAL_SEQID","MESSAGE_STATUS_NONE","MESSAGE_STATUS_QUEUED","MESSAGE_STATUS_SENDING","MESSAGE_STATUS_FAILED","MESSAGE_STATUS_FATAL","MESSAGE_STATUS_SENT","MESSAGE_STATUS_RECEIVED","MESSAGE_STATUS_READ","MESSAGE_STATUS_TO_ME","EXPIRE_PROMISES_TIMEOUT","EXPIRE_PROMISES_PERIOD","RECV_TIMEOUT","DEFAULT_MESSAGES_PAGE","DEL_CHAR","MAX_PINNED_COUNT","jsonParseHelper","WebSocketProvider","XHRProvider","NETWORK_ERROR","NETWORK_ERROR_TEXT","NETWORK_USER","NETWORK_USER_TEXT","_BOFF_BASE","_BOFF_MAX_ITER","_BOFF_JITTER","makeBaseUrl","host","protocol","version","apiKey","url","Connection","log","_","boffTimer","boffIteration","boffClosed","socket","secure","autoreconnect","initialized","config","version_","autoreconnect_","transport","init_lp","init_ws","setNetworkProviders","wsProvider","xhrProvider","logger","l","connect","host_","force","Promise","reject","reconnect","disconnect","sendText","msg","isConnected","probe","backoffReset","boffReset","boffReconnect","#boffReconnect","clearTimeout","timeout","pow","random","onAutoreconnectIteration","setTimeout","prom","catch","boffStop","#boffStop","#boffReset","#init_lp","XDR_UNSENT","XDR_OPENED","XDR_HEADERS_RECEIVED","XDR_LOADING","XDR_DONE","_lpURL","_poller","_sender","lp_sender","url_","sender","onreadystatechange","evt","readyState","status","open","lp_poller","resolve","poller","promiseCompleted","pkt","JSON","parse","responseText","ctrl","params","sid","send","onOpen","onMessage","onDisconnect","text","abort","err","#init_ws","OPEN","close","conn","onerror","onopen","onclose","onmessage","data","clipRange","DB_VERSION","DB_NAME","IDBProvider","DB","onError","db","disabled","mapObjects","#mapObjects","source","trx","transaction","event","target","error","objectStore","getAll","onsuccess","result","topic","initDatabase","req","onupgradeneeded","createObjectStore","keyPath","dellog","createIndex","deleteDatabase","onblocked","isReady","updTopic","oncomplete","get","serializeTopic","commit","markTopicAsDeleted","_deleted","remTopic","delete","IDBKeyRange","only","bound","Number","MAX_SAFE_INTEGER","mapTopics","deserializeTopic","src","updUser","uid","pub","public","remUser","mapUsers","getUser","user","updSubscription","topicName","sub","serializeSubscription","mapSubscriptions","addMessage","add","serializeMessage","updMessageStatus","seq","_status","remMessages","from","to","range","readMessages","query","ranges","key","hi","low","msgs","concat","push","limit","openCursor","cursor","value","continue","addDelLog","delId","clear","readDelLog","maxDelId","index","topic_fields","#deserializeTopic","f","hasOwnProperty","tags","_tags","setAccessMode","read","unread","#serializeTopic","dst","getAccessMode","#serializeSubscription","fields","#serializeMessage","setDatabaseProvider","idbProvider","MAX_FORM_ELEMENTS","MAX_PREVIEW_ATTACHMENTS","MAX_PREVIEW_DATA_SIZE","JSON_MIME_TYPE","DRAFTY_MIME_TYPE","ALLOWED_ENT_FIELDS","INLINE_STYLES","FMT_WEIGHT","ENTITY_TYPES","dataName","pack","test","re","slice","FORMAT_TAGS","AU","html_tag","md_tag","isVoid","BN","BR","CO","DL","EM","EX","FM","HD","HL","HT","IM","LN","MN","RW","QQ","ST","VC","VD","base64toObjectUrl","b64","contentType","bin","atob","buf","ArrayBuffer","Uint8Array","charCodeAt","URL","createObjectURL","Blob","type","base64toDataUrl","DECORATORS","props","href","id","act","ref","mime","Drafty","duration","size","tmpPreviewUrl","_tempPreview","previewUrl","downloadUrl","width","height","title","alt","state","preview","premime","poster","preref","txt","fmt","ent","init","plainText","content","lines","entityMap","entityIndex","blx","line","spans","entities","tag","spannify","block","sort","toSpanTree","chunks","chunkify","drafty","draftify","extractEntities","entity","tp","offset","len","map","s","append","first","second","insertImage","imageDesc","ex","refurl","bits","filename","urlPromise","_processing","then","insertVideo","videoDesc","urls","insertAudio","audioDesc","videoCall","audioOnly","aonly","updateVideoCall","Object","assign","quote","header","body","appendLineBreak","mention","appendLink","linkData","appendImage","appendAudio","attachFile","attachmentDesc","wrapInto","style","wrapAsForm","insertButton","actionType","actionValue","refUrl","indexOf","appendButton","attachJSON","UNSAFE_toHTML","doc","tree","draftyToTree","htmlFormatter","values","join","treeBottomUp","format","original","formatter","shorten","light","shortenTree","lightEntity","treeToDrafty","forwardedContent","rmMention","node","parent","treeTopDown","lTrim","replyContent","convMNnQQnBR","startsWith","children","attachmentsToEnd","forwarding","toPlainText","isPlainText","toMarkdown","mdFormatter","def","isValid","txt_type","hasAttachments","attachments","hasEntities","styles","sanitizeEntities","copyEntData","getDownloadUrl","entData","isProcessing","getPreviewUrl","getEntitySize","getEntityMimeType","tagName","attrValue","getContentType","span","chunk","chld","re_start","re_end","exec","start_offset","lastIndexOf","end_offset","last","spansToTree","flatten","child","addNode","n","substring","att","subspans","inner","keymap","c","keys","newKey","transformer","stack","pop","tail","shortener","allow","lightCopy","trimStart","shift","match","extracted","el","startAt","plain","entries","dc","module","exports","Const","Topic","mergeToCache","TopicFnd","_contacts","callbacks","_processMetaSub","subs","updateCount","getOwnPropertyNames","indexBy","onMetaSub","onSubsUpdated","publish","setMeta","getPrototypeOf","prototype","contacts","cb","isUrlRelative","addURLParam","relUrl","window","location","origin","searchParams","LargeFileHelper","tinode","_tinode","_version","_apiKey","_authToken","getAuthToken","xhr","uploadWithBaseUrl","baseUrl","avatarFor","onProgress","onSuccess","onFailure","base","endsWith","instance","setRequestHeader","token","toResolve","toReject","upload","onprogress","e","lengthComputable","loaded","total","onload","response","statusText","onabort","form","FormData","set","getNextUniqueId","_secure","_host","download","relativeUrl","mimetype","responseType","link","document","createElement","display","setAttribute","appendChild","click","removeChild","revokeObjectURL","reader","FileReader","readAsText","cancel","setNetworkProvider","mergeObj","TopicMe","onContactUpdate","_processMetaDesc","desc","turnOff","_db","_updateCachedUser","_myUID","cont","online","seen","when","Date","_refreshContact","onMetaDesc","deleted","cacheRemTopic","recv","getTopic","_new","isP2PTopicName","_cachePutUser","_noForwarding","_processMetaCreds","creds","cr","_credentials","findIndex","meth","done","resp","onCredsUpdated","_routePres","pres","what","_resetSub","getMeta","startMetaQuery","withDesc","build","cacheGetTopic","_updateReceived","withLaterOneSub","dacs","touched","ua","_attached","withOneSub","dummy","withTags","onPres","delCredential","method","isCommType","getContact","isArchived","private","arch","getCredentials","listToRanges","normalizeRanges","MetaGetBuilder","get_desc_ims","#get_desc_ims","updated","get_subs_ims","#get_subs_ims","isP2PType","_lastSubsUpdate","withData","withLaterData","_maxSeq","withDataRanges","withDataList","list","withEarlierData","_minSeq","ims","withLaterDesc","withSub","userOrTopic","opts","getType","withLaterSub","withCred","withAux","withDel","withLaterDel","_maxDel","extract","normalizeArray","created","trusted","_users","_queuedSeqId","_noEarlierMsgs","_recvNotificationTimer","_aux","_messageVersions","_messages","_delayedLeaveTimer","onData","onMeta","onInfo","onTagsUpdated","onAuxUpdated","onDeleteTopic","onAllMessagesReceived","topicType","types","isMeTopicName","isGroupTopicName","isCommTopicName","isNewGroupTopicName","isChannelTopicName","isReplacementMsg","#isReplacementMsg","head","replace","isSubscribed","subscribe","getParams","setParams","_cacheDelSelf","_cachePutSelf","ts","me","getMeTopic","createMessage","noEcho","publishMessage","_sending","_failed","swapMessageId","_maybeUpdateMessageVersionsCache","_routeData","publishDraft","_getQueuedSeqId","getCurrentUserID","noecho","_cancelled","_fatal","leave","unsub","_gone","leaveDelayed","delay","getMessagesPage","gaps","newer","_loadMessages","msgHasMoreMessages","getPinnedMessages","pins","aux","remains","_processMetaTags","cred","_processMetaAux","subscriber","am","invite","archive","pinMessage","pin","pinned","changed","delMessages","hard","tosend","del","flushMessageRange","flushMessage","delMessagesAll","hardDel","_all","delMessagesList","delMessagesEdits","messageVersions","delTopic","delSubscription","note","_updateReadRecv","noteRecv","noteRead","noteKeyPress","noteRecording","payload","oldVal","doUpdate","userDesc","_cacheGetUser","p2pPeerDesc","subscribers","origSeq","versions","messages","sinceId","beforeId","unused1","unused2","latest","latestMsgVersion","_origTs","_origSeq","findMessage","latestMessage","maxMsgSeq","minMsgSeq","maxClearId","messageCount","queuedMessages","msgReceiptCount","msgReadCount","msgRecvCount","maxSeq","gap","prev","p","expected","isNewMessage","seqId","fromId","untilId","newSeqId","numMessages","cancelSend","msgStatus","getDefaultAccess","defacs","isMeType","isChannelType","isGroupType","isMe","targetSeq","parseInt","targetMsg","outgoing","webrtc","incoming","_routeMeta","meta","_processDelMessages","delseq","isTopicCached","_routeInfo","info","_allMessagesReceived","obj","cached","rec","date","isNaN","isValidDate","d","getTime","rfc3339DateString","pad","sp","repeat","millis","getUTCMilliseconds","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","ignore","prop","cache","newval","simplify","out","t","trim","toLowerCase","item","pos","ary","r1","r2","reduce","clip","DBCache","WebSocket","XMLHttpRequest","IndexedDBProvider","indexedDB","initForNonBrowserApp","chars","btoa","global","input","output","charCode","bc","bs","String","fromCharCode","detectTransport","b64EncodeUnicode","encodeURIComponent","toSolidBytes","p1","jsonBuildHelper","jsonLoggerHelper","getBrowserInfo","product","reactnative","priority","tmp","substr","tokens","m2","v","minor","Tinode","_appName","_browser","_platform","_hwos","_humanLanguage","_loggingEnabled","_trimLongStrings","_authenticated","_login","_inPacketCount","_messageId","floor","_serverInfo","_deviceToken","_pendingPromises","_expirePromises","_connection","_persist","_cache","onComplete","appName","platform","navigator","userAgent","language","dispatchMessage","connectionOpen","disconnected","promise","persist","cacheGet","attachCacheToTopic","cachePut","all","dateString","_len","args","_key","console","makePromise","#makePromise","execPromise","#execPromise","onOK","errorText","#send","stringify","#dispatchMessage","onRawMessage","onNetworkProbe","onCtrlMessage","onMetaMessage","onDataMessage","onPresMessage","onInfoMessage","#connectionOpen","setInterval","expires","hello","#disconnected","clearInterval","cacheMap","getUserAgent","#getUserAgent","initPacket","#initPacket","#cachePut","#cacheGet","cacheDel","#cacheDel","#cacheMap","func","#attachCacheToTopic","_cacheDelUser","loginSuccessful","#loginSuccessful","onLogin","credential","getVersion","getLibrary","isNullValue","clearStorage","initStorage","networkProbe","isAuthenticated","authorizeURL","parsed","account","scheme","secret","login","acc","tmpscheme","tmpsecret","extra","createAccount","createAccountBasic","username","password","updateAccountBasic","onConnect","setDeviceToken","dt","sent","loginBasic","uname","loginToken","requestResetAuthSecret","now","setAuthToken","dft","oobNotification","xfrom","finally","modeGiven","modeWant","delCurrentUser","newGroupTopicName","isChan","getFndTopic","getLargeFileHelper","getCurrentLogin","getServerInfo","report","getServerParam","defaultValue","enableLogging","enabled","trimLongStrings","setHumanLanguage","hl","isTopicOnline","getTopicAccessMode","wantAkn","onWebsocketOpen","MAX_MESSAGE_SIZE","MAX_SUBSCRIBER_COUNT","MAX_TAG_COUNT","MAX_FILE_UPLOAD_SIZE","REQ_CRED_VALIDATORS"],"sourceRoot":""}
\ No newline at end of file
+{"version":3,"file":"tinode.dev.js","mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;;;;;;;;;;;;;;ACLa;AAcE,MAAMA,UAAU,CAAC;EAC9BC,WAAWA,CAACC,GAAG,EAAE;IACf,IAAIA,GAAG,EAAE;MACP,IAAI,CAACC,KAAK,GAAG,OAAOD,GAAG,CAACC,KAAK,IAAI,QAAQ,GAAGD,GAAG,CAACC,KAAK,GAAGH,UAAU,CAACI,MAAM,CAACF,GAAG,CAACC,KAAK,CAAC;MACpF,IAAI,CAACE,IAAI,GAAG,OAAOH,GAAG,CAACG,IAAI,IAAI,QAAQ,GAAGH,GAAG,CAACG,IAAI,GAAGL,UAAU,CAACI,MAAM,CAACF,GAAG,CAACG,IAAI,CAAC;MAChF,IAAI,CAACC,IAAI,GAAGJ,GAAG,CAACI,IAAI,GAAI,OAAOJ,GAAG,CAACI,IAAI,IAAI,QAAQ,GAAGJ,GAAG,CAACI,IAAI,GAAGN,UAAU,CAACI,MAAM,CAACF,GAAG,CAACI,IAAI,CAAC,GACzF,IAAI,CAACH,KAAK,GAAG,IAAI,CAACE,IAAK;IAC5B;EACF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oB,GAAG,oBAAoB;AAClDzI,MAAM,CAAC0I,aAAa,GAAG,aAAa;AACpC1I,MAAM,CAAC2I,oBAAoB,GAAG,mBAAmB;AACjD3I,MAAM,CAAC4I,mBAAmB,GAAG,SAAS,C","sources":["webpack://tinode/webpack/universalModuleDefinition","webpack://tinode/./src/access-mode.js","webpack://tinode/./src/cbuffer.js","webpack://tinode/./src/comm-error.js","webpack://tinode/./src/config.js","webpack://tinode/./src/connection.js","webpack://tinode/./src/db.js","webpack://tinode/./src/drafty.js","webpack://tinode/./src/fnd-topic.js","webpack://tinode/./src/large-file.js","webpack://tinode/./src/me-topic.js","webpack://tinode/./src/meta-builder.js","webpack://tinode/./src/topic.js","webpack://tinode/./src/utils.js","webpack://tinode/./version.js","webpack://tinode/webpack/bootstrap","webpack://tinode/webpack/runtime/compat get default export","webpack://tinode/webpack/runtime/define property getters","webpack://tinode/webpack/runtime/global","webpack://tinode/webpack/runtime/hasOwnProperty shorthand","webpack://tinode/webpack/runtime/make namespace object","webpack://tinode/./src/tinode.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"tinode\"] = factory();\n\telse\n\t\troot[\"tinode\"] = factory();\n})(this, () => {\nreturn ","/**\n * @file Access control model.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\n/**\n * Helper class for handling access mode.\n *\n * @class AccessMode\n * @memberof Tinode\n *\n * @param {AccessMode|Object=} acs - AccessMode to copy or access mode object received from the server.\n */\nexport default class AccessMode {\n constructor(acs) {\n if (acs) {\n this.given = typeof acs.given == 'number' ? acs.given : AccessMode.decode(acs.given);\n this.want = typeof acs.want == 'number' ? acs.want : AccessMode.decode(acs.want);\n this.mode = acs.mode ? (typeof acs.mode == 'number' ? acs.mode : AccessMode.decode(acs.mode)) :\n (this.given & this.want);\n }\n }\n\n static #checkFlag(val, side, flag) {\n side = side || 'mode';\n if (['given', 'want', 'mode'].includes(side)) {\n return ((val[side] & flag) != 0);\n }\n throw new Error(`Invalid AccessMode component '${side}'`);\n }\n /**\n * Parse string into an access mode value.\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {string | Number} mode - either a String representation of the access mode to parse or a set of bits to assign.\n * @returns {number} - Access mode as a numeric value.\n */\n static decode(str) {\n if (!str) {\n return null;\n } else if (typeof str == 'number') {\n return str & AccessMode._BITMASK;\n } else if (str === 'N' || str === 'n') {\n return AccessMode._NONE;\n }\n\n const bitmask = {\n 'J': AccessMode._JOIN,\n 'R': AccessMode._READ,\n 'W': AccessMode._WRITE,\n 'P': AccessMode._PRES,\n 'A': AccessMode._APPROVE,\n 'S': AccessMode._SHARE,\n 'D': AccessMode._DELETE,\n 'O': AccessMode._OWNER\n };\n\n let m0 = AccessMode._NONE;\n\n for (let i = 0; i < str.length; i++) {\n const bit = bitmask[str.charAt(i).toUpperCase()];\n if (!bit) {\n // Unrecognized bit, skip.\n continue;\n }\n m0 |= bit;\n }\n return m0;\n }\n /**\n * Convert numeric representation of the access mode into a string.\n *\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {number} val - access mode value to convert to a string.\n * @returns {string} - Access mode as a string.\n */\n static encode(val) {\n if (val === null || val === AccessMode._INVALID) {\n return null;\n } else if (val === AccessMode._NONE) {\n return 'N';\n }\n\n const bitmask = ['J', 'R', 'W', 'P', 'A', 'S', 'D', 'O'];\n let res = '';\n for (let i = 0; i < bitmask.length; i++) {\n if ((val & (1 << i)) != 0) {\n res = res + bitmask[i];\n }\n }\n return res;\n }\n /**\n * Update numeric representation of access mode with the new value. The value\n * is one of the following:\n * - a string starting with '+' or '-' then the bits to add or remove, e.g. '+R-W' or '-PS'.\n * - a new value of access mode\n *\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {number} val - access mode value to update.\n * @param {string} upd - update to apply to val.\n * @returns {number} - updated access mode.\n */\n static update(val, upd) {\n if (!upd || typeof upd != 'string') {\n return val;\n }\n\n let action = upd.charAt(0);\n if (action == '+' || action == '-') {\n let val0 = val;\n // Split delta-string like '+ABC-DEF+Z' into an array of parts including + and -.\n const parts = upd.split(/([-+])/);\n // Starting iteration from 1 because String.split() creates an array with the first empty element.\n // Iterating by 2 because we parse pairs +/- then data.\n for (let i = 1; i < parts.length - 1; i += 2) {\n action = parts[i];\n const m0 = AccessMode.decode(parts[i + 1]);\n if (m0 == AccessMode._INVALID) {\n return val;\n }\n if (m0 == null) {\n continue;\n }\n if (action === '+') {\n val0 |= m0;\n } else if (action === '-') {\n val0 &= ~m0;\n }\n }\n val = val0;\n } else {\n // The string is an explicit new value 'ABC' rather than delta.\n const val0 = AccessMode.decode(upd);\n if (val0 != AccessMode._INVALID) {\n val = val0;\n }\n }\n\n return val;\n }\n /**\n * Bits present in a1 but missing in a2.\n *\n * @static\n * @memberof Tinode\n *\n * @param {number | string} a1 - access mode to subtract from.\n * @param {number | string} a2 - access mode to subtract.\n * @returns {number} access mode with bits present in a1 but missing in a2.\n */\n static diff(a1, a2) {\n a1 = AccessMode.decode(a1);\n a2 = AccessMode.decode(a2);\n\n if (a1 == AccessMode._INVALID || a2 == AccessMode._INVALID) {\n return AccessMode._INVALID;\n }\n return a1 & ~a2;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Custom formatter\n */\n toString() {\n return '{\"mode\": \"' + AccessMode.encode(this.mode) +\n '\", \"given\": \"' + AccessMode.encode(this.given) +\n '\", \"want\": \"' + AccessMode.encode(this.want) + '\"}';\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Converts numeric values to strings.\n */\n jsonHelper() {\n return {\n mode: AccessMode.encode(this.mode),\n given: AccessMode.encode(this.given),\n want: AccessMode.encode(this.want)\n };\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign value to 'mode'.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} m - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setMode(m) {\n this.mode = AccessMode.decode(m);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update mode value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateMode(u) {\n this.mode = AccessMode.update(this.mode, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get mode value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - mode value.\n */\n getMode() {\n return AccessMode.encode(this.mode);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign given value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} g - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setGiven(g) {\n this.given = AccessMode.decode(g);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'given' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateGiven(u) {\n this.given = AccessMode.update(this.given, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'given' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - given value.\n */\n getGiven() {\n return AccessMode.encode(this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} w - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setWant(w) {\n this.want = AccessMode.decode(w);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateWant(u) {\n this.want = AccessMode.update(this.want, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'want' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - want value.\n */\n getWant() {\n return AccessMode.encode(this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'want' but missing in 'given'.\n * Inverse of {@link Tinode.AccessMode#getExcessive}\n *\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in want but missing in given.\n */\n getMissing() {\n return AccessMode.encode(this.want & ~this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'given' but missing in 'want'.\n * Inverse of {@link Tinode.AccessMode#getMissing}\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in given but missing in want.\n */\n getExcessive() {\n return AccessMode.encode(this.given & ~this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want', 'give', and 'mode' values.\n * @memberof Tinode.AccessMode\n *\n * @param {AccessMode} val - new access mode value.\n * @returns {AccessMode} - this AccessMode.\n */\n updateAll(val) {\n if (val) {\n this.updateGiven(val.given);\n this.updateWant(val.want);\n this.mode = this.given & this.want;\n }\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Owner (O) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isOwner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._OWNER);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isPresencer(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._PRES);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is NOT set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isMuted(side) {\n return !this.isPresencer(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Join (J) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isJoiner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._JOIN);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Reader (R) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isReader(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._READ);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Writer (W) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isWriter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._WRITE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Approver (A) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isApprover(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._APPROVE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O) or Approver (A) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isAdmin(side) {\n return this.isOwner(side) || this.isApprover(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O), Approver (A), or Sharer (S) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isSharer(side) {\n return this.isAdmin(side) || AccessMode.#checkFlag(this, side, AccessMode._SHARE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Deleter (D) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isDeleter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._DELETE);\n }\n}\n\nAccessMode._NONE = 0x00;\nAccessMode._JOIN = 0x01;\nAccessMode._READ = 0x02;\nAccessMode._WRITE = 0x04;\nAccessMode._PRES = 0x08;\nAccessMode._APPROVE = 0x10;\nAccessMode._SHARE = 0x20;\nAccessMode._DELETE = 0x40;\nAccessMode._OWNER = 0x80;\n\nAccessMode._BITMASK = AccessMode._JOIN | AccessMode._READ | AccessMode._WRITE | AccessMode._PRES |\n AccessMode._APPROVE | AccessMode._SHARE | AccessMode._DELETE | AccessMode._OWNER;\nAccessMode._INVALID = 0x100000;\n","/**\n * @file In-memory sorted cache of objects.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n/**\n * In-memory sorted cache of objects.\n *\n * @class CBuffer\n * @memberof Tinode\n * @protected\n *\n * @param {function} compare custom comparator of objects. Takes two parameters a and b;\n * returns -1 if a < b, 0 if a == b, 1 otherwise.\n * @param {boolean} unique enforce element uniqueness: when true replace existing element with a new\n * one on conflict; when false keep both elements.\n */\nexport default class CBuffer {\n #comparator = undefined;\n #unique = false;\n buffer = [];\n\n constructor(compare_, unique_) {\n this.#comparator = compare_ || ((a, b) => {\n return a === b ? 0 : a < b ? -1 : 1;\n });\n this.#unique = unique_;\n }\n\n #findNearest(elem, arr, exact) {\n let start = 0;\n let end = arr.length - 1;\n let pivot = 0;\n let diff = 0;\n let found = false;\n\n while (start <= end) {\n pivot = (start + end) / 2 | 0;\n diff = this.#comparator(arr[pivot], elem);\n if (diff < 0) {\n start = pivot + 1;\n } else if (diff > 0) {\n end = pivot - 1;\n } else {\n found = true;\n break;\n }\n }\n if (found) {\n return {\n idx: pivot,\n exact: true\n };\n }\n if (exact) {\n return {\n idx: -1\n };\n }\n // Not exact - insertion point\n return {\n idx: diff < 0 ? pivot + 1 : pivot\n };\n }\n\n // Insert element into a sorted array.\n #insertSorted(elem, arr) {\n const found = this.#findNearest(elem, arr, false);\n const count = (found.exact && this.#unique) ? 1 : 0;\n arr.splice(found.idx, count, elem);\n return arr;\n }\n\n /**\n * Get an element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to fetch from.\n * @returns {Object} Element at the given position or undefined.\n */\n getAt(at) {\n return this.buffer[at];\n }\n\n /**\n * Convenience method for getting the element from the end of the buffer.\n * @memberof Tinode.CBuffer#\n * @param {number} at - position to fetch from, counting from the end;\n * undefined or null mean \"last\".\n * @returns {Object} The last element in the buffer or undefined if buffer is empty.\n */\n getLast(at) {\n at |= 0;\n return this.buffer.length > at ? this.buffer[this.buffer.length - 1 - at] : undefined;\n }\n\n /**\n * Insert new element(s) to the buffer at the correct position according to the sort method.\n * Variadic: takes one or more arguments. If an array is passed as a single argument, its\n * elements are inserted individually.\n * @memberof Tinode.CBuffer#\n *\n * @param {...Object|Array} - One or more objects to insert.\n */\n put() {\n let insert;\n // inspect arguments: if array, insert its elements, if one or more non-array arguments, insert them one by one\n if (arguments.length == 1 && Array.isArray(arguments[0])) {\n insert = arguments[0];\n } else {\n insert = arguments;\n }\n for (let idx in insert) {\n this.#insertSorted(insert[idx], this.buffer);\n }\n }\n\n /**\n * Remove element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to delete at.\n * @returns {Object} Element at the given position or undefined.\n */\n delAt(at) {\n at |= 0;\n let r = this.buffer.splice(at, 1);\n if (r && r.length > 0) {\n return r[0];\n }\n return undefined;\n }\n\n /**\n * Remove elements between two positions.\n * @memberof Tinode.CBuffer#\n * @param {number} since - Position to delete from (inclusive).\n * @param {number} before - Position to delete to (exclusive).\n *\n * @returns {Array} array of removed elements (could be zero length).\n */\n delRange(since, before) {\n return this.buffer.splice(since, before - since);\n }\n\n /**\n * Return the number of elements the buffer holds.\n * @memberof Tinode.CBuffer#\n * @return {number} Number of elements in the buffer.\n */\n length() {\n return this.buffer.length;\n }\n\n /**\n * Reset the buffer discarding all elements\n * @memberof Tinode.CBuffer#\n */\n reset() {\n this.buffer = [];\n }\n\n /**\n * Callback for iterating contents of buffer. See {@link Tinode.CBuffer#forEach}.\n * @callback ForEachCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {Object} prev - Previous element of the buffer.\n * @param {Object} next - Next element of the buffer.\n * @param {number} index - Index of the current element.\n */\n\n /**\n * Apply given callback to all elements of the buffer.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.ForEachCallbackType} callback - Function to call for each element.\n * @param {number} startIdx - Optional index to start iterating from (inclusive), default: 0.\n * @param {number} beforeIdx - Optional index to stop iterating before (exclusive), default: length of the buffer.\n * @param {Object} context - calling context (i.e. value of this in callback)\n */\n forEach(callback, startIdx, beforeIdx, context) {\n startIdx = Math.max(0, startIdx | 0);\n beforeIdx = Math.min(beforeIdx || this.buffer.length, this.buffer.length);\n\n for (let i = startIdx; i < beforeIdx; i++) {\n callback.call(context, this.buffer[i],\n (i > startIdx ? this.buffer[i - 1] : undefined),\n (i < beforeIdx - 1 ? this.buffer[i + 1] : undefined), i);\n }\n }\n\n /**\n * Find element in buffer using buffer's comparison function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Object} elem - element to find.\n * @param {boolean=} nearest - when true and exact match is not found, return the nearest element (insertion point).\n * @returns {number} index of the element in the buffer or -1.\n */\n find(elem, nearest) {\n const {\n idx\n } = this.#findNearest(elem, this.buffer, !nearest);\n return idx;\n }\n\n /**\n * Callback for filtering the buffer. See {@link Tinode.CBuffer#filter}.\n * @callback FilterCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {number} index - Index of the current element.\n * @returns {boolen} true to keep the element, false to remove.\n */\n\n /**\n * Remove all elements that do not pass the test implemented by the provided callback function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.FilterCallbackType} callback - Function to call for each element.\n * @param {Object} context - calling context (i.e. value of this in the callback)\n */\n filter(callback, context) {\n let count = 0;\n for (let i = 0; i < this.buffer.length; i++) {\n if (callback.call(context, this.buffer[i], i)) {\n this.buffer[count] = this.buffer[i];\n count++;\n }\n }\n\n this.buffer.splice(count);\n }\n\n /**\n * Check if buffer is empty.\n * @returns {boolean} true if the buffer is empty, false otherwise.\n */\n isEmpty() {\n return this.buffer.length == 0;\n }\n}\n","/**\n * @file Throwable error with numeric error code.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nexport default class CommError extends Error {\n constructor(message, code) {\n super(`${message} (${code})`);\n this.name = 'CommError';\n this.code = code;\n }\n}\n","/**\n * @file Global constants and configuration parameters.\n *\n * @copyright 2015-2023 Tinode LLC\n */\n'use strict';\n\nimport {\n PACKAGE_VERSION\n} from '../version.js';\n\n// Global constants\nexport const PROTOCOL_VERSION = '0'; // Major component of the version, e.g. '0' in '0.17.1'.\nexport const VERSION = PACKAGE_VERSION || '0.21';\nexport const LIBRARY = 'tinodejs/' + VERSION;\n\n// Topic name prefixes.\nexport const TOPIC_NEW = 'new';\nexport const TOPIC_NEW_CHAN = 'nch';\nexport const TOPIC_ME = 'me';\nexport const TOPIC_FND = 'fnd';\nexport const TOPIC_SYS = 'sys';\nexport const TOPIC_CHAN = 'chn';\nexport const TOPIC_GRP = 'grp';\nexport const TOPIC_P2P = 'p2p';\nexport const USER_NEW = 'new';\n\n// Starting value of a locally-generated seqId used for pending messages.\nexport const LOCAL_SEQID = 0xFFFFFFF;\n\n// Status codes.\nexport const MESSAGE_STATUS_NONE = 0; // Status not assigned.\nexport const MESSAGE_STATUS_QUEUED = 10; // Local ID assigned, in progress to be sent.\nexport const MESSAGE_STATUS_SENDING = 20; // Transmission started.\nexport const MESSAGE_STATUS_FAILED = 30; // At least one attempt was made to send the message.\nexport const MESSAGE_STATUS_FATAL = 40; // Message sending failed and it should not be retried.\nexport const MESSAGE_STATUS_SENT = 50; // Delivered to the server.\nexport const MESSAGE_STATUS_RECEIVED = 60; // Received by the client.\nexport const MESSAGE_STATUS_READ = 70; // Read by the user.\nexport const MESSAGE_STATUS_TO_ME = 80; // The message is received from another user.\n\n// Reject unresolved futures after this many milliseconds.\nexport const EXPIRE_PROMISES_TIMEOUT = 5_000;\n// Periodicity of garbage collection of unresolved futures.\nexport const EXPIRE_PROMISES_PERIOD = 1_000;\n\n// Delay before acknowledging that a message was recived.\nexport const RECV_TIMEOUT = 100;\n\n// Default number of messages to pull into memory from persistent cache.\nexport const DEFAULT_MESSAGES_PAGE = 24;\n\n// Unicode DEL character indicating data was deleted.\nexport const DEL_CHAR = '\\u2421';\n\n// Maximum number of pinnned messages;\nexport const MAX_PINNED_COUNT = 5;\n","/**\n * @file Abstraction layer for websocket and long polling connections.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n jsonParseHelper\n} from './utils.js';\n\nlet WebSocketProvider;\nlet XHRProvider;\n\n// Error code to return in case of a network problem.\nconst NETWORK_ERROR = 503;\nconst NETWORK_ERROR_TEXT = \"Connection failed\";\n\n// Error code to return when user disconnected from server.\nconst NETWORK_USER = 418;\nconst NETWORK_USER_TEXT = \"Disconnected by client\";\n\n// Settings for exponential backoff\nconst _BOFF_BASE = 2000; // 2000 milliseconds, minimum delay between reconnects\nconst _BOFF_MAX_ITER = 10; // Maximum delay between reconnects 2^10 * 2000 ~ 34 minutes\nconst _BOFF_JITTER = 0.3; // Add random delay\n\n// Helper function for creating an endpoint URL.\nfunction makeBaseUrl(host, protocol, version, apiKey) {\n let url = null;\n\n if (['http', 'https', 'ws', 'wss'].includes(protocol)) {\n url = `${protocol}://${host}`;\n if (url.charAt(url.length - 1) !== '/') {\n url += '/';\n }\n url += 'v' + version + '/channels';\n if (['http', 'https'].includes(protocol)) {\n // Long polling endpoint ends with \"lp\", i.e.\n // '/v0/channels/lp' vs just '/v0/channels' for ws\n url += '/lp';\n }\n url += '?apikey=' + apiKey;\n }\n return url;\n}\n\n/**\n * An abstraction for a websocket or a long polling connection.\n *\n * @class Connection\n * @memberof Tinode\n\n * @param {Object} config - configuration parameters.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - Network transport to use, either \"ws\"/\"wss\" for websocket or\n * lp for long polling.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} version_ - Major value of the protocol version, e.g. '0' in '0.17.1'.\n * @param {boolean} autoreconnect_ - If connection is lost, try to reconnect automatically.\n */\nexport default class Connection {\n // Logger, does nothing by default.\n static #log = _ => {};\n\n #boffTimer = null;\n #boffIteration = 0;\n #boffClosed = false; // Indicator if the socket was manually closed - don't autoreconnect if true.\n\n // Websocket.\n #socket = null;\n\n host;\n secure;\n apiKey;\n\n version;\n autoreconnect;\n\n initialized;\n\n // (config.host, config.apiKey, config.transport, config.secure), PROTOCOL_VERSION, true\n constructor(config, version_, autoreconnect_) {\n this.host = config.host;\n this.secure = config.secure;\n this.apiKey = config.apiKey;\n\n this.version = version_;\n this.autoreconnect = autoreconnect_;\n\n if (config.transport === 'lp') {\n // explicit request to use long polling\n this.#init_lp();\n this.initialized = 'lp';\n } else if (config.transport === 'ws') {\n // explicit request to use web socket\n // if websockets are not available, horrible things will happen\n this.#init_ws();\n this.initialized = 'ws';\n }\n\n if (!this.initialized) {\n // Invalid or undefined network transport.\n Connection.#log(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n throw new Error(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n }\n }\n\n /**\n * To use Connection in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n * @memberof Connection\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n }\n\n /**\n * Assign a non-default logger.\n * @static\n * @memberof Connection\n * @param {function} l variadic logging function.\n */\n static set logger(l) {\n Connection.#log = l;\n }\n\n /**\n * Initiate a new connection\n * @memberof Tinode.Connection#\n * @param {string} host_ Host name to connect to; if null the old host name will be used.\n * @param {boolean} force Force new connection even if one already exists.\n * @return {Promise} Promise resolved/rejected when the connection call completes, resolution is called without\n * parameters, rejection passes the {Error} as parameter.\n */\n connect(host_, force) {\n return Promise.reject(null);\n }\n\n /**\n * Try to restore a network connection, also reset backoff.\n * @memberof Tinode.Connection#\n *\n * @param {boolean} force - reconnect even if there is a live connection already.\n */\n reconnect(force) {}\n\n /**\n * Terminate the network connection\n * @memberof Tinode.Connection#\n */\n disconnect() {}\n\n /**\n * Send a string to the server.\n * @memberof Tinode.Connection#\n *\n * @param {string} msg - String to send.\n * @throws Throws an exception if the underlying connection is not live.\n */\n sendText(msg) {}\n\n /**\n * Check if connection is alive.\n * @memberof Tinode.Connection#\n * @returns {boolean} true if connection is live, false otherwise.\n */\n isConnected() {\n return false;\n }\n\n /**\n * Get the name of the current network transport.\n * @memberof Tinode.Connection#\n * @returns {string} name of the transport such as \"ws\" or \"lp\".\n */\n transport() {\n return this.initialized;\n }\n\n /**\n * Send network probe to check if connection is indeed live.\n * @memberof Tinode.Connection#\n */\n probe() {\n this.sendText('1');\n }\n\n /**\n * Reset autoreconnect counter to zero.\n * @memberof Tinode.Connection#\n */\n backoffReset() {\n this.#boffReset();\n }\n\n // Backoff implementation - reconnect after a timeout.\n #boffReconnect() {\n // Clear timer\n clearTimeout(this.#boffTimer);\n // Calculate when to fire the reconnect attempt\n const timeout = _BOFF_BASE * (Math.pow(2, this.#boffIteration) * (1.0 + _BOFF_JITTER * Math.random()));\n // Update iteration counter for future use\n this.#boffIteration = (this.#boffIteration >= _BOFF_MAX_ITER ? this.#boffIteration : this.#boffIteration + 1);\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(timeout);\n }\n\n this.#boffTimer = setTimeout(_ => {\n Connection.#log(`Reconnecting, iter=${this.#boffIteration}, timeout=${timeout}`);\n // Maybe the socket was closed while we waited for the timer?\n if (!this.#boffClosed) {\n const prom = this.connect();\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(0, prom);\n } else {\n // Suppress error if it's not used.\n prom.catch(_ => {\n /* do nothing */\n });\n }\n } else if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(-1);\n }\n }, timeout);\n }\n\n // Terminate auto-reconnect process.\n #boffStop() {\n clearTimeout(this.#boffTimer);\n this.#boffTimer = null;\n }\n\n // Reset auto-reconnect iteration counter.\n #boffReset() {\n this.#boffIteration = 0;\n }\n\n // Initialization for long polling.\n #init_lp() {\n const XDR_UNSENT = 0; // Client has been created. open() not called yet.\n const XDR_OPENED = 1; // open() has been called.\n const XDR_HEADERS_RECEIVED = 2; // send() has been called, and headers and status are available.\n const XDR_LOADING = 3; // Downloading; responseText holds partial data.\n const XDR_DONE = 4; // The operation is complete.\n\n // Fully composed endpoint URL, with API key & SID\n let _lpURL = null;\n\n let _poller = null;\n let _sender = null;\n\n let lp_sender = (url_) => {\n const sender = new XHRProvider();\n sender.onreadystatechange = (evt) => {\n if (sender.readyState == XDR_DONE && sender.status >= 400) {\n // Some sort of error response\n throw new CommError(\"LP sender failed\", sender.status);\n }\n };\n\n sender.open('POST', url_, true);\n return sender;\n }\n\n let lp_poller = (url_, resolve, reject) => {\n let poller = new XHRProvider();\n let promiseCompleted = false;\n\n poller.onreadystatechange = evt => {\n if (poller.readyState == XDR_DONE) {\n if (poller.status == 201) { // 201 == HTTP.Created, get SID\n let pkt = JSON.parse(poller.responseText, jsonParseHelper);\n _lpURL = url_ + '&sid=' + pkt.ctrl.params.sid;\n poller = lp_poller(_lpURL);\n poller.send(null);\n if (this.onOpen) {\n this.onOpen();\n }\n\n if (resolve) {\n promiseCompleted = true;\n resolve();\n }\n\n if (this.autoreconnect) {\n this.#boffStop();\n }\n } else if (poller.status > 0 && poller.status < 400) { // 0 = network error; 400 = HTTP.BadRequest\n if (this.onMessage) {\n this.onMessage(poller.responseText);\n }\n poller = lp_poller(_lpURL);\n poller.send(null);\n } else {\n // Don't throw an error here, gracefully handle server errors\n if (reject && !promiseCompleted) {\n promiseCompleted = true;\n reject(poller.responseText);\n }\n if (this.onMessage && poller.responseText) {\n this.onMessage(poller.responseText);\n }\n if (this.onDisconnect) {\n const code = poller.status || (this.#boffClosed ? NETWORK_USER : NETWORK_ERROR);\n const text = poller.responseText || (this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT);\n this.onDisconnect(new CommError(text, code), code);\n }\n\n // Polling has stopped. Indicate it by setting poller to null.\n poller = null;\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n }\n }\n };\n // Using POST to avoid caching response by service worker.\n poller.open('POST', url_, true);\n return poller;\n }\n\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (_poller) {\n if (!force) {\n return Promise.resolve();\n }\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'https' : 'http', this.version, this.apiKey);\n Connection.#log(\"LP connecting to:\", url);\n _poller = lp_poller(url, resolve, reject);\n _poller.send(null);\n }).catch(err => {\n Connection.#log(\"LP connection failed:\", err);\n });\n };\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (_sender) {\n _sender.onreadystatechange = undefined;\n _sender.abort();\n _sender = null;\n }\n if (_poller) {\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (this.onDisconnect) {\n this.onDisconnect(new CommError(NETWORK_USER_TEXT, NETWORK_USER), NETWORK_USER);\n }\n // Ensure it's reconstructed\n _lpURL = null;\n };\n\n this.sendText = (msg) => {\n _sender = lp_sender(_lpURL);\n if (_sender && (_sender.readyState == XDR_OPENED)) { // 1 == OPENED\n _sender.send(msg);\n } else {\n throw new Error(\"Long poller failed to connect\");\n }\n };\n\n this.isConnected = _ => {\n return (_poller && true);\n };\n }\n\n // Initialization for Websocket\n #init_ws() {\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (this.#socket) {\n if (!force && this.#socket.readyState == this.#socket.OPEN) {\n return Promise.resolve();\n }\n this.#socket.close();\n this.#socket = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'wss' : 'ws', this.version, this.apiKey);\n\n Connection.#log(\"WS connecting to: \", url);\n\n // It throws when the server is not accessible but the exception cannot be caught:\n // https://stackoverflow.com/questions/31002592/javascript-doesnt-catch-error-in-websocket-instantiation/31003057\n const conn = new WebSocketProvider(url);\n\n conn.onerror = err => {\n reject(err);\n };\n\n conn.onopen = _ => {\n if (this.autoreconnect) {\n this.#boffStop();\n }\n\n if (this.onOpen) {\n this.onOpen();\n }\n\n resolve();\n };\n\n conn.onclose = _ => {\n this.#socket = null;\n\n if (this.onDisconnect) {\n const code = this.#boffClosed ? NETWORK_USER : NETWORK_ERROR;\n this.onDisconnect(new CommError(this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT, code), code);\n }\n\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n };\n\n conn.onmessage = evt => {\n if (this.onMessage) {\n this.onMessage(evt.data);\n }\n };\n\n this.#socket = conn;\n });\n }\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (!this.#socket) {\n return;\n }\n this.#socket.close();\n this.#socket = null;\n };\n\n this.sendText = msg => {\n if (this.#socket && (this.#socket.readyState == this.#socket.OPEN)) {\n this.#socket.send(msg);\n } else {\n throw new Error(\"Websocket is not connected\");\n }\n };\n\n this.isConnected = _ => {\n return (this.#socket && (this.#socket.readyState == this.#socket.OPEN));\n };\n }\n\n // Callbacks:\n\n /**\n * A callback to pass incoming messages to. See {@link Tinode.Connection#onMessage}.\n * @callback Tinode.Connection.OnMessage\n * @memberof Tinode.Connection\n * @param {string} message - Message to process.\n */\n onMessage = undefined;\n\n /**\n * A callback for reporting a dropped connection.\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onDisconnect = undefined;\n\n /**\n * A callback called when the connection is ready to be used for sending. For websockets it's socket open,\n * for long polling it's readyState=1 (OPENED)\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onOpen = undefined;\n\n /**\n * A callback to notify of reconnection attempts. See {@link Tinode.Connection#onAutoreconnectIteration}.\n * @memberof Tinode.Connection\n * @callback AutoreconnectIterationType\n * @param {string} timeout - time till the next reconnect attempt in milliseconds. -1 means reconnect was skipped.\n * @param {Promise} promise resolved or rejected when the reconnect attemp completes.\n *\n */\n /**\n * A callback to inform when the next attampt to reconnect will happen and to receive connection promise.\n * @memberof Tinode.Connection#\n * @type {Tinode.Connection.AutoreconnectIterationType}\n */\n onAutoreconnectIteration = undefined;\n}\n\nConnection.NETWORK_ERROR = NETWORK_ERROR;\nConnection.NETWORK_ERROR_TEXT = NETWORK_ERROR_TEXT;\nConnection.NETWORK_USER = NETWORK_USER;\nConnection.NETWORK_USER_TEXT = NETWORK_USER_TEXT;\n","/**\n * @file Helper methods for dealing with IndexedDB cache of messages, users, and topics.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nimport {\n clipRange\n} from './utils.js';\n\nconst DB_VERSION = 3;\nconst DB_NAME = 'tinode-web';\n\nlet IDBProvider;\n\nexport default class DB {\n #onError = _ => {};\n #logger = _ => {};\n\n // Instance of IndexDB.\n db = null;\n // Indicator that the cache is disabled.\n disabled = false;\n\n constructor(onError, logger) {\n this.#onError = onError || this.#onError;\n this.#logger = logger || this.#logger;\n }\n\n #mapObjects(source, callback, context) {\n if (!this.db) {\n return disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction([source]);\n trx.onerror = event => {\n this.#logger('PCache', 'mapObjects', source, event.target.error);\n reject(event.target.error);\n };\n trx.objectStore(source).getAll().onsuccess = event => {\n if (callback) {\n event.target.result.forEach(topic => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n /**\n * Initialize persistent cache: open or create/upgrade if needed.\n * @returns {Promise} promise to be resolved/rejected when the DB is initialized.\n */\n initDatabase() {\n return new Promise((resolve, reject) => {\n // Open the database and initialize callbacks.\n const req = IDBProvider.open(DB_NAME, DB_VERSION);\n req.onsuccess = event => {\n this.db = event.target.result;\n this.disabled = false;\n resolve(this.db);\n };\n req.onerror = event => {\n this.#logger('PCache', \"failed to initialize\", event);\n reject(event.target.error);\n this.#onError(event.target.error);\n };\n req.onupgradeneeded = event => {\n this.db = event.target.result;\n\n this.db.onerror = event => {\n this.#logger('PCache', \"failed to create storage\", event);\n this.#onError(event.target.error);\n };\n\n // Individual object stores.\n // Object store (table) for topics. The primary key is topic name.\n this.db.createObjectStore('topic', {\n keyPath: 'name'\n });\n\n // Users object store. UID is the primary key.\n this.db.createObjectStore('user', {\n keyPath: 'uid'\n });\n\n // Subscriptions object store topic <-> user. Topic name + UID is the primary key.\n this.db.createObjectStore('subscription', {\n keyPath: ['topic', 'uid']\n });\n\n // Messages object store. The primary key is topic name + seq.\n this.db.createObjectStore('message', {\n keyPath: ['topic', 'seq']\n });\n\n // Records of deleted message ranges. The primary key is topic name + low seq.\n const dellog = this.db.createObjectStore('dellog', {\n keyPath: ['topic', 'low', 'hi']\n });\n dellog.createIndex('topic_clear', ['topic', 'clear'], {\n unique: false\n });\n };\n });\n }\n\n /**\n * Delete persistent cache.\n */\n deleteDatabase() {\n // Close connection, otherwise operations will fail with 'onblocked'.\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n return new Promise((resolve, reject) => {\n const req = IDBProvider.deleteDatabase(DB_NAME);\n req.onblocked = _ => {\n if (this.db) {\n this.db.close();\n }\n const err = new Error(\"blocked\");\n this.#logger('PCache', 'deleteDatabase', err);\n reject(err);\n };\n req.onsuccess = _ => {\n this.db = null;\n this.disabled = true;\n resolve(true);\n };\n req.onerror = event => {\n this.#logger('PCache', 'deleteDatabase', event.target.error);\n reject(event.target.error);\n };\n });\n }\n\n /**\n * Check if persistent cache is ready for use.\n * @memberOf DB\n * @returns {boolean} true if cache is ready, false otherwise.\n */\n isReady() {\n return !!this.db;\n }\n\n // Topics.\n\n /**\n * Save to cache or update topic in persistent cache.\n * @memberOf DB\n * @param {Topic} topic - topic to be added or updated.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updTopic(topic) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updTopic', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(topic.name);\n req.onsuccess = _ => {\n trx.objectStore('topic').put(DB.#serializeTopic(req.result, topic));\n trx.commit();\n };\n });\n }\n\n /**\n * Mark or unmark topic as deleted.\n * @memberOf DB\n * @param {string} name - name of the topic to mark or unmark.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n markTopicAsDeleted(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'markTopicAsDeleted', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(name);\n req.onsuccess = event => {\n const topic = event.target.result;\n topic._deleted = true;\n trx.objectStore('topic').put(topic);\n trx.commit();\n };\n });\n }\n\n /**\n * Remove topic from persistent cache.\n * @memberOf DB\n * @param {string} name - name of the topic to remove from database.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remTopic(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic', 'subscription', 'message'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remTopic', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('topic').delete(IDBKeyRange.only(name));\n trx.objectStore('subscription').delete(IDBKeyRange.bound([name, '-'], [name, '~']));\n trx.objectStore('message').delete(IDBKeyRange.bound([name, 0], [name, Number.MAX_SAFE_INTEGER]));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored topic.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapTopics(callback, context) {\n return this.#mapObjects('topic', callback, context);\n }\n\n /**\n * Copy data from serialized object to topic.\n * @memberOf DB\n * @param {Topic} topic - target to deserialize to.\n * @param {Object} src - serialized data to copy from.\n */\n deserializeTopic(topic, src) {\n DB.#deserializeTopic(topic, src);\n }\n\n // Users.\n /**\n * Add or update user object in the persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to save or update.\n * @param {Object} pub - user's public information.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updUser(uid, pub) {\n if (arguments.length < 2 || pub === undefined) {\n // No point inupdating user with invalid data.\n return;\n }\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').put({\n uid: uid,\n public: pub\n });\n trx.commit();\n });\n }\n\n /**\n * Remove user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to remove from the cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').delete(IDBKeyRange.only(uid));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored user.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapUsers(callback, context) {\n return this.#mapObjects('user', callback, context);\n }\n\n /**\n * Read a single user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to fetch from cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n getUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user']);\n trx.oncomplete = event => {\n const user = event.target.result;\n resolve({\n user: user.uid,\n public: user.public\n });\n };\n trx.onerror = event => {\n this.#logger('PCache', 'getUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').get(uid);\n });\n }\n\n // Subscriptions.\n /**\n * Add or update subscription in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {string} uid - ID of the subscribed user.\n * @param {Object} sub - subscription to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updSubscription(topicName, uid, sub) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updSubscription', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').get([topicName, uid]).onsuccess = (event) => {\n trx.objectStore('subscription').put(DB.#serializeSubscription(event.target.result, topicName, uid, sub));\n trx.commit();\n };\n });\n }\n\n /**\n * Execute a callback for each cached subscription in a given topic.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the subscriptions.\n * @param {function} callback - function to call for each subscription.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapSubscriptions(topicName, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription']);\n trx.onerror = (event) => {\n this.#logger('PCache', 'mapSubscriptions', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').getAll(IDBKeyRange.bound([topicName, '-'], [topicName, '~'])).onsuccess = (event) => {\n if (callback) {\n event.target.result.forEach((topic) => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n // Messages.\n\n /**\n * Save message to persistent cache.\n * @memberOf DB\n * @param {Object} msg - message to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n addMessage(msg) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'addMessage', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').add(DB.#serializeMessage(null, msg));\n trx.commit();\n });\n }\n\n /**\n * Update delivery status of a message stored in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} seq - ID of the message to update\n * @param {number} status - new delivery status of the message.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updMessageStatus(topicName, seq, status) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updMessageStatus', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('message').get(IDBKeyRange.only([topicName, seq]));\n req.onsuccess = event => {\n const src = req.result || event.target.result;\n if (!src || src._status == status) {\n trx.commit();\n return;\n }\n trx.objectStore('message').put(DB.#serializeMessage(src, {\n topic: topicName,\n seq: seq,\n _status: status\n }));\n trx.commit();\n };\n });\n }\n\n /**\n * Remove one or more messages from persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} from - id of the message to remove or lower boundary when removing range (inclusive).\n * @param {number=} to - upper boundary (exclusive) when removing a range of messages.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remMessages(topicName, from, to) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n if (!from && !to) {\n from = 0;\n to = Number.MAX_SAFE_INTEGER;\n }\n const range = to > 0 ? IDBKeyRange.bound([topicName, from], [topicName, to], false, true) :\n IDBKeyRange.only([topicName, from]);\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remMessages', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').delete(range);\n trx.commit();\n });\n }\n\n /**\n * Retrieve messages from persistent store.\n * @memberOf DB\n * @param {string} topicName - name of the topic to retrieve messages from.\n * @param {function} callback to call for each retrieved message.\n * @param {GetDataType} query - parameters of the message range to retrieve.\n *\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n readMessages(topicName, query, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n\n const trx = this.db.transaction(['message']);\n let result = [];\n\n // Handle individual message ranges.\n if (Array.isArray(query.ranges)) {\n return new Promise((resolve, reject) => {\n trx.onerror = event => {\n this.#logger('PCache', 'readMessages', event.target.error);\n reject(event.target.error);\n };\n\n let count = 0;\n query.ranges.forEach(range => {\n const key = range.hi ? IDBKeyRange.bound([topicName, range.low], [topicName, range.hi], false, true) :\n IDBKeyRange.only([topicName, range.low]);\n trx.objectStore('message').getAll(key).onsuccess = event => {\n const msgs = event.target.result;\n if (msgs) {\n if (callback) {\n callback.call(context, msgs);\n }\n if (Array.isArray(msgs)) {\n result = result.concat(msgs);\n } else {\n result.push(msgs);\n }\n }\n count++;\n if (count == query.ranges.length) {\n resolve(result);\n }\n };\n });\n });\n }\n\n return new Promise((resolve, reject) => {\n query = query || {};\n const since = query.since > 0 ? query.since : 0;\n const before = query.before > 0 ? query.before : Number.MAX_SAFE_INTEGER;\n const limit = query.limit | 0;\n\n trx.onerror = event => {\n this.#logger('PCache', 'readMessages', event.target.error);\n reject(event.target.error);\n };\n\n const range = IDBKeyRange.bound([topicName, since], [topicName, before], false, true);\n // Iterate in descending order.\n trx.objectStore('message').openCursor(range, 'prev')\n .onsuccess = event => {\n const cursor = event.target.result;\n if (cursor) {\n if (callback) {\n callback.call(context, cursor.value);\n }\n result.push(cursor.value);\n if (limit <= 0 || result.length < limit) {\n cursor.continue();\n } else {\n resolve(result);\n }\n } else {\n resolve(result);\n }\n };\n });\n }\n\n // Delete log\n\n /**\n * Add records of deleted messages.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} delId - id of the deletion transaction.\n * @param {Array.require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IDBProvider = idbProvider;\n }\n}\n","/**\n * @copyright 2015-2022 Tinode LLC.\n * @summary Minimally rich text representation and formatting for Tinode.\n * @license Apache 2.0\n *\n * @file Basic parser and formatter for very simple text markup. Mostly targeted at\n * mobile use cases similar to Telegram, WhatsApp, and FB Messenger.\n *\n * \n *
\n * Also supports forms and buttons.\n *\n * Nested formatting is supported, e.g. *abc _def_* -> abc def\n * URLs, @mentions, and #hashtags are extracted and converted into links.\n * Forms and buttons can be added procedurally.\n * JSON data representation is inspired by Draft.js raw formatting.\n *\n *\n * @example\n * Text:\n * abc\n * this is *bold*, `code` and _italic_, ~strike~\n * combined *bold and _italic_*\n * an url: https://www.example.com/abc#fragment and another _www.tinode.co_\n * this is a @mention and a #hashtag in a string\n * second #hashtag\n *
\n *\n * Sample JSON representation of the text above:\n * {\n * \"txt\": \"this is bold, code and italic, strike combined bold and italic an url: https://www.example.com/abc#fragment \" +\n * \"and another www.tinode.co this is a @mention and a #hashtag in a string second #hashtag\",\n * \"fmt\": [\n * { \"at\":8, \"len\":4,\"tp\":\"ST\" },{ \"at\":14, \"len\":4, \"tp\":\"CO\" },{ \"at\":23, \"len\":6, \"tp\":\"EM\"},\n * { \"at\":31, \"len\":6, \"tp\":\"DL\" },{ \"tp\":\"BR\", \"len\":1, \"at\":37 },{ \"at\":56, \"len\":6, \"tp\":\"EM\" },\n * { \"at\":47, \"len\":15, \"tp\":\"ST\" },{ \"tp\":\"BR\", \"len\":1, \"at\":62 },{ \"at\":120, \"len\":13, \"tp\":\"EM\" },\n * { \"at\":71, \"len\":36, \"key\":0 },{ \"at\":120, \"len\":13, \"key\":1 },{ \"tp\":\"BR\", \"len\":1, \"at\":133 },\n * { \"at\":144, \"len\":8, \"key\":2 },{ \"at\":159, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":179 },\n * { \"at\":187, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":195 }\n * ],\n * \"ent\": [\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"https://www.example.com/abc#fragment\" } },\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"http://www.tinode.co\" } },\n * { \"tp\":\"MN\", \"data\":{ \"val\":\"mention\" } },\n * { \"tp\":\"HT\", \"data\":{ \"val\":\"hashtag\" } }\n * ]\n * }\n */\n\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nconst MAX_FORM_ELEMENTS = 8;\nconst MAX_PREVIEW_ATTACHMENTS = 3;\nconst MAX_PREVIEW_DATA_SIZE = 64;\nconst JSON_MIME_TYPE = 'application/json';\nconst DRAFTY_MIME_TYPE = 'text/x-drafty';\nconst ALLOWED_ENT_FIELDS = ['act', 'height', 'duration', 'incoming', 'mime', 'name', 'premime', 'preref', 'preview',\n 'ref', 'size', 'state', 'url', 'val', 'width'\n];\n\n// Regular expressions for parsing inline formats. Javascript does not support lookbehind,\n// so it's a bit messy.\nconst INLINE_STYLES = [\n // Strong = bold, *bold text*\n {\n name: 'ST',\n start: /(?:^|[\\W_])(\\*)[^\\s*]/,\n end: /[^\\s*](\\*)(?=$|[\\W_])/\n },\n // Emphesized = italic, _italic text_\n {\n name: 'EM',\n start: /(?:^|\\W)(_)[^\\s_]/,\n end: /[^\\s_](_)(?=$|\\W)/\n },\n // Deleted, ~strike this though~\n {\n name: 'DL',\n start: /(?:^|[\\W_])(~)[^\\s~]/,\n end: /[^\\s~](~)(?=$|[\\W_])/\n },\n // Code block `this is monospace`\n {\n name: 'CO',\n start: /(?:^|\\W)(`)[^`]/,\n end: /[^`](`)(?=$|\\W)/\n }\n];\n\n// Relative weights of formatting spans. Greater index in array means greater weight.\nconst FMT_WEIGHT = ['QQ'];\n\n// RegExps for entity extraction (RF = reference)\nconst ENTITY_TYPES = [\n // URLs\n {\n name: 'LN',\n dataName: 'url',\n pack: function(val) {\n // Check if the protocol is specified, if not use http\n if (!/^[a-z]+:\\/\\//i.test(val)) {\n val = 'http://' + val;\n }\n return {\n url: val\n };\n },\n re: /(?:(?:https?|ftp):\\/\\/|www\\.|ftp\\.)[-A-Z0-9+&@#\\/%=~_|$?!:,.]*[A-Z0-9+&@#\\/%=~_|$]/ig\n },\n // Mentions @user (must be 2 or more characters)\n {\n name: 'MN',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B@([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n },\n // Hashtags #hashtag, like metion 2 or more characters.\n {\n name: 'HT',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B#([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n }\n];\n\n// HTML tag name suggestions\nconst FORMAT_TAGS = {\n AU: {\n html_tag: 'audio',\n md_tag: undefined,\n isVoid: false\n },\n BN: {\n html_tag: 'button',\n md_tag: undefined,\n isVoid: false\n },\n BR: {\n html_tag: 'br',\n md_tag: '\\n',\n isVoid: true\n },\n CO: {\n html_tag: 'tt',\n md_tag: '`',\n isVoid: false\n },\n DL: {\n html_tag: 'del',\n md_tag: '~',\n isVoid: false\n },\n EM: {\n html_tag: 'i',\n md_tag: '_',\n isVoid: false\n },\n EX: {\n html_tag: '',\n md_tag: undefined,\n isVoid: true\n },\n FM: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n HD: {\n html_tag: '',\n md_tag: undefined,\n isVoid: false\n },\n HL: {\n html_tag: 'span',\n md_tag: undefined,\n isVoid: false\n },\n HT: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n IM: {\n html_tag: 'img',\n md_tag: undefined,\n isVoid: false\n },\n LN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n MN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n RW: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false,\n },\n QQ: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n ST: {\n html_tag: 'b',\n md_tag: '*',\n isVoid: false\n },\n VC: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n VD: {\n html_tag: 'video',\n md_tag: undefined,\n isVoid: false\n }\n};\n\n// Convert base64-encoded string into Blob.\nfunction base64toObjectUrl(b64, contentType, logger) {\n if (!b64) {\n return null;\n }\n\n try {\n const bin = atob(b64);\n const length = bin.length;\n const buf = new ArrayBuffer(length);\n const arr = new Uint8Array(buf);\n for (let i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n\n return URL.createObjectURL(new Blob([buf], {\n type: contentType\n }));\n } catch (err) {\n if (logger) {\n logger(\"Drafty: failed to convert object.\", err.message);\n }\n }\n\n return null;\n}\n\nfunction base64toDataUrl(b64, contentType) {\n if (!b64) {\n return null;\n }\n contentType = contentType || 'image/jpeg';\n return 'data:' + contentType + ';base64,' + b64;\n}\n\n// Helpers for converting Drafty to HTML.\nconst DECORATORS = {\n // Visial styles\n ST: {\n open: _ => '',\n close: _ => ''\n },\n EM: {\n open: _ => '',\n close: _ => ''\n },\n DL: {\n open: _ => '',\n close: _ => ''\n },\n CO: {\n open: _ => '',\n close: _ => ''\n },\n // Line break\n BR: {\n open: _ => '
',\n close: _ => ''\n },\n // Hidden element\n HD: {\n open: _ => '',\n close: _ => ''\n },\n // Highlighted element.\n HL: {\n open: _ => '',\n close: _ => ''\n },\n // Link (URL)\n LN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n href: data.url,\n target: '_blank'\n } : null;\n },\n },\n // Mention\n MN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Hashtag\n HT: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Button\n BN: {\n open: _ => '',\n props: (data) => {\n return data ? {\n 'data-act': data.act,\n 'data-val': data.val,\n 'data-name': data.name,\n 'data-ref': data.ref\n } : null;\n },\n },\n // Audio recording\n AU: {\n open: (data) => {\n const url = data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger);\n return '',\n props: (data) => {\n if (!data) return null;\n return {\n // Embedded data or external link.\n src: data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-duration': data.duration,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n // Image\n IM: {\n open: data => {\n // Don't use data.ref for preview: it's a security risk.\n const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime);\n const previewUrl = base64toObjectUrl(data.val, data.mime, Drafty.logger);\n const downloadUrl = data.ref || previewUrl;\n return (data.name ? '' : '') +\n '';\n },\n close: data => {\n return (data.name ? '' : '');\n },\n props: data => {\n if (!data) return null;\n return {\n // Temporary preview, or permanent preview, or external link.\n src: base64toDataUrl(data._tempPreview, data.mime) ||\n data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n title: data.name,\n alt: data.name,\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n },\n },\n // Form - structured layout of elements.\n FM: {\n open: _ => '
';\n },\n close: _ => '',\n props: data => {\n if (!data) return null;\n const poster = data.preref || base64toObjectUrl(data.preview, data.premime || 'image/jpeg', Drafty.logger);\n return {\n // Embedded data or external link.\n src: poster,\n 'data-src': data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-preview': poster,\n 'data-duration': data.duration | 0,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n};\n\n/**\n * The main object which performs all the formatting actions.\n * @class Drafty\n * @constructor\n */\nconst Drafty = function() {\n this.txt = '';\n this.fmt = [];\n this.ent = [];\n}\n\n/**\n * Initialize Drafty document to a plain text string.\n *\n * @param {string} plainText - string to use as Drafty content.\n *\n * @returns new Drafty document or null is plainText is not a string or undefined.\n */\nDrafty.init = function(plainText) {\n if (typeof plainText == 'undefined') {\n plainText = '';\n } else if (typeof plainText != 'string') {\n return null;\n }\n\n return {\n txt: plainText\n };\n}\n\n/**\n * Parse plain text into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} content - plain-text content to parse.\n * @return {Drafty} parsed document or null if the source is not plain text.\n */\nDrafty.parse = function(content) {\n // Make sure we are parsing strings only.\n if (typeof content != 'string') {\n return null;\n }\n\n // Split text into lines. It makes further processing easier.\n const lines = content.split(/\\r?\\n/);\n\n // Holds entities referenced from text\n const entityMap = [];\n const entityIndex = {};\n\n // Processing lines one by one, hold intermediate result in blx.\n const blx = [];\n lines.forEach((line) => {\n let spans = [];\n let entities;\n\n // Find formatted spans in the string.\n // Try to match each style.\n INLINE_STYLES.forEach((tag) => {\n // Each style could be matched multiple times.\n spans = spans.concat(spannify(line, tag.start, tag.end, tag.name));\n });\n\n let block;\n if (spans.length == 0) {\n block = {\n txt: line\n };\n } else {\n // Sort spans by style occurence early -> late, then by length: first long then short.\n spans.sort((a, b) => {\n const diff = a.at - b.at;\n return diff != 0 ? diff : b.end - a.end;\n });\n\n // Convert an array of possibly overlapping spans into a tree.\n spans = toSpanTree(spans);\n\n // Build a tree representation of the entire string, not\n // just the formatted parts.\n const chunks = chunkify(line, 0, line.length, spans);\n\n const drafty = draftify(chunks, 0);\n\n block = {\n txt: drafty.txt,\n fmt: drafty.fmt\n };\n }\n\n // Extract entities from the cleaned up string.\n entities = extractEntities(block.txt);\n if (entities.length > 0) {\n const ranges = [];\n for (let i in entities) {\n // {offset: match['index'], unique: match[0], len: match[0].length, data: ent.packer(), type: ent.name}\n const entity = entities[i];\n let index = entityIndex[entity.unique];\n if (!index) {\n index = entityMap.length;\n entityIndex[entity.unique] = index;\n entityMap.push({\n tp: entity.type,\n data: entity.data\n });\n }\n ranges.push({\n at: entity.offset,\n len: entity.len,\n key: index\n });\n }\n block.ent = ranges;\n }\n\n blx.push(block);\n });\n\n const result = {\n txt: ''\n };\n\n // Merge lines and save line breaks as BR inline formatting.\n if (blx.length > 0) {\n result.txt = blx[0].txt;\n result.fmt = (blx[0].fmt || []).concat(blx[0].ent || []);\n\n for (let i = 1; i < blx.length; i++) {\n const block = blx[i];\n const offset = result.txt.length + 1;\n\n result.fmt.push({\n tp: 'BR',\n len: 1,\n at: offset - 1\n });\n\n result.txt += ' ' + block.txt;\n if (block.fmt) {\n result.fmt = result.fmt.concat(block.fmt.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n if (block.ent) {\n result.fmt = result.fmt.concat(block.ent.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n }\n\n if (result.fmt.length == 0) {\n delete result.fmt;\n }\n\n if (entityMap.length > 0) {\n result.ent = entityMap;\n }\n }\n return result;\n}\n\n/**\n * Append one Drafty document to another.\n *\n * @param {Drafty} first - Drafty document to append to.\n * @param {Drafty|string} second - Drafty document or string being appended.\n *\n * @return {Drafty} first document with the second appended to it.\n */\nDrafty.append = function(first, second) {\n if (!first) {\n return second;\n }\n if (!second) {\n return first;\n }\n\n first.txt = first.txt || '';\n const len = first.txt.length;\n\n if (typeof second == 'string') {\n first.txt += second;\n } else if (second.txt) {\n first.txt += second.txt;\n }\n\n if (Array.isArray(second.fmt)) {\n first.fmt = first.fmt || [];\n if (Array.isArray(second.ent)) {\n first.ent = first.ent || [];\n }\n second.fmt.forEach(src => {\n const fmt = {\n at: (src.at | 0) + len,\n len: src.len | 0\n };\n // Special case for the outside of the normal rendering flow styles.\n if (src.at == -1) {\n fmt.at = -1;\n fmt.len = 0;\n }\n if (src.tp) {\n fmt.tp = src.tp;\n } else {\n fmt.key = first.ent.length;\n first.ent.push(second.ent[src.key || 0]);\n }\n first.fmt.push(fmt);\n });\n }\n\n return first;\n}\n\n/**\n * Description of an image to attach.\n * @typedef {Object} ImageDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the image, e.g. \"image/png\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded image content. Could be null/undefined.\n * @property {string} preview - base64-encoded thumbnail of the image.\n * @property {integer} width - width of the image.\n * @property {integer} height - height of the image.\n * @property {string} filename - file name suggestion for downloading the image.\n * @property {integer} size - size of the image in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded image preview used during upload process; not serializable.\n * @property {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {integer} at - index where the object is inserted. The length of the image is always 1.\n * @param {ImageDesc} imageDesc - object with image paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertImage = function(content, at, imageDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'IM',\n data: {\n mime: imageDesc.mime,\n ref: imageDesc.refurl,\n val: imageDesc.bits || imageDesc.preview,\n width: imageDesc.width,\n height: imageDesc.height,\n name: imageDesc.filename,\n size: imageDesc.size | 0,\n }\n };\n\n if (imageDesc.urlPromise) {\n ex.data._tempPreview = imageDesc._tempPreview;\n ex.data._processing = true;\n imageDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Description of a video to attach.\n * @typedef {Object} VideoDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the video, e.g. \"video/mpeg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - in-band base64-encoded image data. Could be null/undefined.\n * @property {string} preview - base64-encoded screencapture from the video. Could be null/undefined.\n * @property {string} preref - reference to screencapture from the video. Could be null/undefined.\n * @property {integer} width - width of the video.\n * @property {integer} height - height of the video.\n * @property {integer} duration - duration of the video.\n * @property {string} filename - file name suggestion for downloading the video.\n * @property {integer} size - size of the video in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded screencapture used during upload process; not serializable.\n * @property {Promise} urlPromise - array of two promises, which return URLs of video and preview uploads correspondingly\n * (either could be null).\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add video to.\n * @param {integer} at - index where the object is inserted. The length of the video is always 1.\n * @param {VideoDesc} videoDesc - object with video paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertVideo = function(content, at, videoDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'VD',\n data: {\n mime: videoDesc.mime,\n ref: videoDesc.refurl,\n val: videoDesc.bits,\n preref: videoDesc.preref,\n preview: videoDesc.preview,\n width: videoDesc.width,\n height: videoDesc.height,\n duration: videoDesc.duration | 0,\n name: videoDesc.filename,\n size: videoDesc.size | 0,\n }\n };\n\n if (videoDesc.urlPromise) {\n ex.data._tempPreview = videoDesc._tempPreview;\n ex.data._processing = true;\n videoDesc.urlPromise.then(\n urls => {\n ex.data.ref = urls[0];\n ex.data.preref = urls[1];\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Description of an audio recording to attach.\n * @typedef {Object} AudioDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the audio, e.g. \"audio/ogg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded audio content. Could be null/undefined.\n * @property {integer} duration - duration of the record in milliseconds.\n * @property {string} preview - base64 encoded short array of amplitude values 0..100.\n * @property {string} filename - file name suggestion for downloading the audio.\n * @property {integer} size - size of the recording in bytes. Treat is as an untrusted hint.\n * @property {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert audio recording into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add audio record to.\n * @param {integer} at - index where the object is inserted. The length of the record is always 1.\n * @param {AudioDesc} audioDesc - object with the audio paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertAudio = function(content, at, audioDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'AU',\n data: {\n mime: audioDesc.mime,\n val: audioDesc.bits,\n duration: audioDesc.duration | 0,\n preview: audioDesc.preview,\n name: audioDesc.filename,\n size: audioDesc.size | 0,\n ref: audioDesc.refurl\n }\n };\n\n if (audioDesc.urlPromise) {\n ex.data._processing = true;\n audioDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Create a (self-contained) video call Drafty document.\n * @memberof Drafty\n * @static\n * @param {boolean} audioOnly
true if the call is initially audio-only.\n * @returns Video Call drafty document.\n */\nDrafty.videoCall = function(audioOnly) {\n const content = {\n txt: ' ',\n fmt: [{\n at: 0,\n len: 1,\n key: 0\n }],\n ent: [{\n tp: 'VC',\n data: {\n aonly: audioOnly\n },\n }]\n };\n return content;\n}\n\n/**\n * Update video call (VC) entity with the new status and duration.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - VC document to update.\n * @param {object} params - new video call parameters.\n * @param {string} params.state - state of video call.\n * @param {number} params.duration - duration of the video call in milliseconds.\n *\n * @returns the same document with update applied.\n */\nDrafty.updateVideoCall = function(content, params) {\n // The video element could be just a format or a format + entity.\n // Must ensure it's the latter first.\n const fmt = ((content || {}).fmt || [])[0];\n if (!fmt) {\n // Unrecognized content.\n return content;\n }\n\n let ent;\n if (fmt.tp == 'VC') {\n // Just a format, convert to format + entity.\n delete fmt.tp;\n fmt.key = 0;\n ent = {\n tp: 'VC'\n };\n content.ent = [ent];\n } else {\n ent = (content.ent || [])[fmt.key | 0];\n if (!ent || ent.tp != 'VC') {\n // Not a VC entity.\n return content;\n }\n }\n ent.data = ent.data || {};\n Object.assign(ent.data, params);\n return content;\n}\n\n/**\n * Create a quote to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} header - Quote header (title, etc.).\n * @param {string} uid - UID of the author to mention.\n * @param {Drafty} body - Body of the quoted message.\n *\n * @returns Reply quote Drafty doc with the quote formatting.\n */\nDrafty.quote = function(header, uid, body) {\n const quote = Drafty.append(Drafty.appendLineBreak(Drafty.mention(header, uid)), body);\n\n // Wrap into a quote.\n quote.fmt.push({\n at: 0,\n len: quote.txt.length,\n tp: 'QQ'\n });\n\n return quote;\n}\n\n/**\n * Create a Drafty document with a mention.\n *\n * @param {string} name - mentioned name.\n * @param {string} uid - mentioned user ID.\n *\n * @returns {Drafty} document with the mention.\n */\nDrafty.mention = function(name, uid) {\n return {\n txt: name || '',\n fmt: [{\n at: 0,\n len: (name || '').length,\n key: 0\n }],\n ent: [{\n tp: 'MN',\n data: {\n val: uid\n }\n }]\n };\n}\n\n/**\n * Append a link to a Drafty document.\n *\n * @param {Drafty} content - Drafty document to append link to.\n * @param {Object} linkData - Link info in format {txt: 'ankor text', url: 'http://...'}.\n *\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLink = function(content, linkData) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: content.txt.length,\n len: linkData.txt.length,\n key: content.ent.length\n });\n content.txt += linkData.txt;\n\n const ex = {\n tp: 'LN',\n data: {\n url: linkData.url\n }\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Append image to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {ImageDesc} imageDesc - object with image paramenets.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendImage = function(content, imageDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertImage(content, content.txt.length - 1, imageDesc);\n}\n\n/**\n * Append audio recodring to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add recording to.\n * @param {AudioDesc} audioDesc - object with audio data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendAudio = function(content, audioDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertAudio(content, content.txt.length - 1, audioDesc);\n}\n\n/**\n * Description of a file to attach.\n * @typedef {Object} AttachmentDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the attachment, e.g. \"application/octet-stream\"\n * @property {string} data - base64-encoded in-band content of small attachments. Could be null/undefined.\n * @property {string} filename - file name suggestion for downloading the attachment.\n * @property {integer} size - size of the file in bytes. Treat is as an untrusted hint.\n * @property {string} refurl - reference to the out-of-band content. Could be null/undefined.\n * @property {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Attach file to Drafty content. Either as a blob or as a reference.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to attach file to.\n * @param {AttachmentDesc} object - containing attachment description and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.attachFile = function(content, attachmentDesc) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'EX',\n data: {\n mime: attachmentDesc.mime,\n val: attachmentDesc.data,\n name: attachmentDesc.filename,\n ref: attachmentDesc.refurl,\n size: attachmentDesc.size | 0\n }\n }\n if (attachmentDesc.urlPromise) {\n ex.data._processing = true;\n attachmentDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n /* catch the error, otherwise it will appear in the console. */\n ex.data._processing = undefined;\n }\n );\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Wraps drafty document into a simple formatting style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - document or string to wrap into a style.\n * @param {string} style - two-letter style to wrap into.\n * @param {number} at - index where the style starts, default 0.\n * @param {number} len - length of the form content, default all of it.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapInto = function(content, style, at, len) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at || 0,\n len: len || content.txt.length,\n tp: style,\n });\n\n return content;\n}\n\n/**\n * Wraps content into an interactive form.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - to wrap into a form.\n * @param {number} at - index where the forms starts.\n * @param {number} len - length of the form content.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapAsForm = function(content, at, len) {\n return Drafty.wrapInto(content, 'FM', at, len);\n}\n\n/**\n * Insert clickable button into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {number} at - location where the button is inserted.\n * @param {number} len - the length of the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertButton = function(content, at, len, name, actionType, actionValue, refUrl) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n\n if (!content || !content.txt || content.txt.length < at + len) {\n return null;\n }\n\n if (len <= 0 || ['url', 'pub'].indexOf(actionType) == -1) {\n return null;\n }\n // Ensure refUrl is a string.\n if (actionType == 'url' && !refUrl) {\n return null;\n }\n refUrl = '' + refUrl;\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: len,\n key: content.ent.length\n });\n content.ent.push({\n tp: 'BN',\n data: {\n act: actionType,\n val: actionValue,\n ref: refUrl,\n name: name\n }\n });\n\n return content;\n}\n\n/**\n * Append clickable button to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {string} title - the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendButton = function(content, title, name, actionType, actionValue, refUrl) {\n content = content || {\n txt: ''\n };\n const at = content.txt.length;\n content.txt += title;\n return Drafty.insertButton(content, at, title.length, name, actionType, actionValue, refUrl);\n}\n\n/**\n * Attach a generic JS object. The object is attached as a json string.\n * Intended for representing a form response.\n *\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to attach file to.\n * @param {Object} data - data to convert to json string and attach.\n * @returns {Drafty} the same document as content.\n */\nDrafty.attachJSON = function(content, data) {\n content = content || {\n txt: ''\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n content.ent.push({\n tp: 'EX',\n data: {\n mime: JSON_MIME_TYPE,\n val: data\n }\n });\n\n return content;\n}\n/**\n * Append line break to a Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to append linebreak to.\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLineBreak = function(content) {\n content = content || {\n txt: ''\n };\n content.fmt = content.fmt || [];\n content.fmt.push({\n at: content.txt.length,\n len: 1,\n tp: 'BR'\n });\n content.txt += ' ';\n\n return content;\n}\n/**\n * Given Drafty document, convert it to HTML.\n * No attempt is made to strip pre-existing html markup.\n * This is potentially unsafe because content.txt may contain malicious HTML\n * markup.\n * @memberof Tinode.Drafty\n * @static\n *\n * @param {Drafty} doc - document to convert.\n *\n * @returns {string} HTML-representation of content.\n */\nDrafty.UNSAFE_toHTML = function(doc) {\n const tree = draftyToTree(doc);\n const htmlFormatter = function(type, data, values) {\n const tag = DECORATORS[type];\n let result = values ? values.join('') : '';\n if (tag) {\n result = tag.open(data) + result + tag.close(data);\n }\n return result;\n };\n return treeBottomUp(tree, htmlFormatter, 0);\n}\n\n/**\n * Callback for applying custom formatting to a Drafty document.\n * Called once for each style span.\n * @memberof Drafty\n * @static\n *\n * @callback Formatter\n * @param {string} style - style code such as \"ST\" or \"IM\".\n * @param {Object} data - entity's data.\n * @param {Object} values - possibly styled subspans contained in this style span.\n * @param {number} index - index of the element guaranteed to be unique.\n */\n\n/**\n * Convert Drafty document to a representation suitable for display.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|Object} content - Drafty document to transform.\n * @param {Formatter} formatter - callback which formats individual elements.\n * @param {Object} context - context provided to formatter as this.\n *\n * @return {Object} transformed object\n */\nDrafty.format = function(original, formatter, context) {\n return treeBottomUp(draftyToTree(original), formatter, 0, [], context);\n}\n\n/**\n * Shorten Drafty document making the drafty text no longer than the limit.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characrets to shorten to.\n * @param {boolean} light - remove heavy data from entities.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.shorten = function(original, limit, light) {\n let tree = draftyToTree(original);\n tree = shortenTree(tree, limit, '…');\n if (tree && light) {\n tree = lightEntity(tree);\n }\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Transform Drafty doc for forwarding: strip leading @mention and any leading line breaks or whitespace.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.forwardedContent = function(original) {\n let tree = draftyToTree(original);\n const rmMention = function(node) {\n if (node.type == 'MN') {\n if (!node.parent || !node.parent.type) {\n return null;\n }\n }\n return node;\n }\n // Strip leading mention.\n tree = treeTopDown(tree, rmMention);\n // Remove leading whitespace.\n tree = lTrim(tree);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Prepare Drafty doc for wrapping into QQ as a reply:\n * - Replace forwarding mention with symbol '➦' and remove data (UID).\n * - Remove quoted text completely.\n * - Replace line breaks with spaces.\n * - Strip entities of heavy content.\n * - Move attachments to the end of the document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.replyContent = function(original, limit) {\n const convMNnQQnBR = function(node) {\n if (node.type == 'QQ') {\n return null;\n } else if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n delete node.data;\n }\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.type;\n delete node.children;\n }\n return node;\n }\n\n let tree = draftyToTree(original);\n if (!tree) {\n return original;\n }\n\n // Strip leading mention.\n tree = treeTopDown(tree, convMNnQQnBR);\n // Move attachments to the end of the doc.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n // Shorten the doc.\n tree = shortenTree(tree, limit, '…');\n // Strip heavy elements except IM.data['val'] and VD.data['preview'] (have to keep them to generate previews later).\n const filter = node => {\n switch (node.type) {\n case 'IM':\n return ['val'];\n case 'VD':\n return ['preview'];\n }\n return null;\n };\n tree = lightEntity(tree, filter);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n\n/**\n * Generate drafty preview:\n * - Shorten the document.\n * - Strip all heavy entity data leaving just inline styles and entity references.\n * - Replace line breaks with spaces.\n * - Replace content of QQ with a space.\n * - Replace forwarding mention with symbol '➦'.\n * move all attachments to the end of the document and make them visible.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @param {boolean} forwarding - this a forwarding message preview.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.preview = function(original, limit, forwarding) {\n let tree = draftyToTree(original);\n\n // Move attachments to the end.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n\n // Convert leading mention to '➦' and replace QQ and BR with a space ' '.\n const convMNnQQnBR = function(node) {\n if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n }\n } else if (node.type == 'QQ') {\n node.text = ' ';\n delete node.children;\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.children;\n delete node.type;\n }\n return node;\n }\n tree = treeTopDown(tree, convMNnQQnBR);\n\n tree = shortenTree(tree, limit, '…');\n if (forwarding) {\n // Keep some IM and VD data for preview.\n const filter = {\n IM: ['val'],\n VD: ['preview']\n };\n tree = lightEntity(tree, node => {\n return filter[node.type];\n });\n } else {\n tree = lightEntity(tree);\n }\n\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Given Drafty document, convert it to plain text.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text.\n * @returns {string} plain-text representation of the drafty document.\n */\nDrafty.toPlainText = function(content) {\n return typeof content == 'string' ? content : content.txt;\n}\n\n/**\n * Check if the document has no markup and no entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for presence of markup.\n * @returns true is content is plain text, false otherwise.\n */\nDrafty.isPlainText = function(content) {\n return typeof content == 'string' || !(content.fmt || content.ent);\n}\n\n/**\n * Convert document to plain text with markdown. All elements which cannot\n * be represented in markdown are stripped.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text with markdown.\n */\nDrafty.toMarkdown = function(content) {\n let tree = draftyToTree(content);\n const mdFormatter = function(type, _, values) {\n const def = FORMAT_TAGS[type];\n let result = (values ? values.join('') : '');\n if (def) {\n if (def.isVoid) {\n result = def.md_tag || '';\n } else if (def.md_tag) {\n result = def.md_tag + result + def.md_tag;\n }\n }\n return result;\n };\n return treeBottomUp(tree, mdFormatter, 0);\n}\n\n/**\n * Checks if the object represets is a valid Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for validity.\n * @returns true is content is valid, false otherwise.\n */\nDrafty.isValid = function(content) {\n if (!content) {\n return false;\n }\n\n const {\n txt,\n fmt,\n ent\n } = content;\n\n if (!txt && txt !== '' && !fmt && !ent) {\n return false;\n }\n\n const txt_type = typeof txt;\n if (txt_type != 'string' && txt_type != 'undefined' && txt !== null) {\n return false;\n }\n\n if (typeof fmt != 'undefined' && !Array.isArray(fmt) && fmt !== null) {\n return false;\n }\n\n if (typeof ent != 'undefined' && !Array.isArray(ent) && ent !== null) {\n return false;\n }\n return true;\n}\n\n/**\n * Check if the drafty document has attachments: style EX and outside of normal rendering flow,\n * i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for attachments.\n * @returns true if there are attachments.\n */\nDrafty.hasAttachments = function(content) {\n if (!Array.isArray(content.fmt)) {\n return false;\n }\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n return ent && ent.tp == 'EX' && ent.data;\n }\n }\n return false;\n}\n\n/**\n * Callback for enumerating entities in a Drafty document.\n * Called once for each entity.\n * @memberof Drafty\n * @static\n *\n * @callback EntityCallback\n * @param {Object} data entity data.\n * @param {string} entity type.\n * @param {number} index entity's index in `content.ent`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate attachments: style EX and outside of normal rendering flow, i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to process for attachments.\n * @param {EntityCallback} callback - callback to call for each attachment.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.attachments = function(content, callback, context) {\n if (!Array.isArray(content.fmt)) {\n return;\n }\n let count = 0;\n for (let i in content.ent) {\n let fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n if (ent && ent.tp == 'EX' && ent.data) {\n if (callback.call(context, ent.data, count++, 'EX')) {\n break;\n }\n }\n }\n };\n}\n\n/**\n * Check if the drafty document has entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for entities.\n * @returns true if there are entities.\n */\nDrafty.hasEntities = function(content) {\n return content.ent && content.ent.length > 0;\n}\n\n/**\n * Enumerate entities. Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @param {EntityCallback} callback - callback to call for each entity.\n * @param {Object} context - value of \"this\" for callback.\n *\n */\nDrafty.entities = function(content, callback, context) {\n if (content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n if (content.ent[i]) {\n if (callback.call(context, content.ent[i].data, i, content.ent[i].tp)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Callback for enumerating styles (inline formats) in a Drafty document.\n * Called once for each style.\n * @memberof Drafty\n * @static\n *\n * @callback StyleCallback\n * @param {string} tp - format type.\n * @param {number} at - starting position of the format in text.\n * @param {number} len - extent of the format in characters.\n * @param {number} key - index of the entity if format is a reference.\n * @param {number} index - style's index in `content.fmt`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate styles (inline formats). Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with styles (formats) to enumerate.\n * @param {StyleCallback} callback - callback to call for each format.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.styles = function(content, callback, context) {\n if (content.fmt && content.fmt.length > 0) {\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt) {\n if (callback.call(context, fmt.tp, fmt.at, fmt.len, fmt.key, i)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Remove unrecognized fields from entity data\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @returns content.\n */\nDrafty.sanitizeEntities = function(content) {\n if (content && content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n const ent = content.ent[i];\n if (ent && ent.data) {\n const data = copyEntData(ent.data);\n if (data) {\n content.ent[i].data = data;\n } else {\n delete content.ent[i].data;\n }\n }\n }\n }\n return content;\n}\n\n/**\n * Given the entity, get URL which can be used for downloading\n * entity data.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the URl from.\n * @returns {string} URL to download entity data or null.\n */\nDrafty.getDownloadUrl = function(entData) {\n let url = null;\n if (entData.mime != JSON_MIME_TYPE && entData.val) {\n url = base64toObjectUrl(entData.val, entData.mime, Drafty.logger);\n } else if (typeof entData.ref == 'string') {\n url = entData.ref;\n }\n return url;\n}\n\n/**\n * Check if the entity data is not ready for sending, such as being uploaded to the server.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n * @returns {boolean} true if upload is in progress, false otherwise.\n */\nDrafty.isProcessing = function(entData) {\n return !!entData._processing;\n}\n\n/**\n * Given the entity, get URL which can be used for previewing\n * the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n *\n * @returns {string} url for previewing or null if no such url is available.\n */\nDrafty.getPreviewUrl = function(entData) {\n return entData.val ? base64toObjectUrl(entData.val, entData.mime, Drafty.logger) : null;\n}\n\n/**\n * Get approximate size of the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the size for.\n * @returns {number} size of entity data in bytes.\n */\nDrafty.getEntitySize = function(entData) {\n // Either size hint or length of value. The value is base64 encoded,\n // the actual object size is smaller than the encoded length.\n return entData.size ? entData.size : entData.val ? (entData.val.length * 0.75) | 0 : 0;\n}\n\n/**\n * Get entity mime type.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the type for.\n * @returns {string} mime type of entity.\n */\nDrafty.getEntityMimeType = function(entData) {\n return entData.mime || 'text/plain';\n}\n\n/**\n * Get HTML tag for a given two-letter style name.\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style, like ST or LN.\n *\n * @returns {string} HTML tag name if style is found, {code: undefined} if style is falsish or not found.\n */\nDrafty.tagName = function(style) {\n return FORMAT_TAGS[style] && FORMAT_TAGS[style].html_tag;\n}\n\n/**\n * For a given data bundle generate an object with HTML attributes,\n * for instance, given {url: \"http://www.example.com/\"} return\n * {href: \"http://www.example.com/\"}\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style to generate attributes for.\n * @param {Object} data - data bundle to convert to attributes\n *\n * @returns {Object} object with HTML attributes.\n */\nDrafty.attrValue = function(style, data) {\n if (data && DECORATORS[style]) {\n return DECORATORS[style].props(data);\n }\n\n return undefined;\n}\n\n/**\n * Drafty MIME type.\n * @memberof Drafty\n * @static\n *\n * @returns {string} content-Type \"text/x-drafty\".\n */\nDrafty.getContentType = function() {\n return DRAFTY_MIME_TYPE;\n}\n\n// =================\n// Utility methods.\n// =================\n\n// Take a string and defined earlier style spans, re-compose them into a tree where each leaf is\n// a same-style (including unstyled) string. I.e. 'hello *bold _italic_* and ~more~ world' ->\n// ('hello ', (b: 'bold ', (i: 'italic')), ' and ', (s: 'more'), ' world');\n//\n// This is needed in order to clear markup, i.e. 'hello *world*' -> 'hello world' and convert\n// ranges from markup-ed offsets to plain text offsets.\nfunction chunkify(line, start, end, spans) {\n const chunks = [];\n\n if (spans.length == 0) {\n return [];\n }\n\n for (let i in spans) {\n // Get the next chunk from the queue\n const span = spans[i];\n\n // Grab the initial unstyled chunk\n if (span.at > start) {\n chunks.push({\n txt: line.slice(start, span.at)\n });\n }\n\n // Grab the styled chunk. It may include subchunks.\n const chunk = {\n tp: span.tp\n };\n const chld = chunkify(line, span.at + 1, span.end, span.children);\n if (chld.length > 0) {\n chunk.children = chld;\n } else {\n chunk.txt = span.txt;\n }\n chunks.push(chunk);\n start = span.end + 1; // '+1' is to skip the formatting character\n }\n\n // Grab the remaining unstyled chunk, after the last span\n if (start < end) {\n chunks.push({\n txt: line.slice(start, end)\n });\n }\n\n return chunks;\n}\n\n// Detect starts and ends of formatting spans. Unformatted spans are\n// ignored at this stage.\nfunction spannify(original, re_start, re_end, type) {\n const result = [];\n let index = 0;\n let line = original.slice(0); // make a copy;\n\n while (line.length > 0) {\n // match[0]; // match, like '*abc*'\n // match[1]; // match captured in parenthesis, like 'abc'\n // match['index']; // offset where the match started.\n\n // Find the opening token.\n const start = re_start.exec(line);\n if (start == null) {\n break;\n }\n\n // Because javascript RegExp does not support lookbehind, the actual offset may not point\n // at the markup character. Find it in the matched string.\n let start_offset = start['index'] + start[0].lastIndexOf(start[1]);\n // Clip the processed part of the string.\n line = line.slice(start_offset + 1);\n // start_offset is an offset within the clipped string. Convert to original index.\n start_offset += index;\n // Index now point to the beginning of 'line' within the 'original' string.\n index = start_offset + 1;\n\n // Find the matching closing token.\n const end = re_end ? re_end.exec(line) : null;\n if (end == null) {\n break;\n }\n let end_offset = end['index'] + end[0].indexOf(end[1]);\n // Clip the processed part of the string.\n line = line.slice(end_offset + 1);\n // Update offsets\n end_offset += index;\n // Index now points to the beginning of 'line' within the 'original' string.\n index = end_offset + 1;\n\n result.push({\n txt: original.slice(start_offset + 1, end_offset),\n children: [],\n at: start_offset,\n end: end_offset,\n tp: type\n });\n }\n\n return result;\n}\n\n// Convert linear array or spans into a tree representation.\n// Keep standalone and nested spans, throw away partially overlapping spans.\nfunction toSpanTree(spans) {\n if (spans.length == 0) {\n return [];\n }\n\n const tree = [spans[0]];\n let last = spans[0];\n for (let i = 1; i < spans.length; i++) {\n // Keep spans which start after the end of the previous span or those which\n // are complete within the previous span.\n if (spans[i].at > last.end) {\n // Span is completely outside of the previous span.\n tree.push(spans[i]);\n last = spans[i];\n } else if (spans[i].end <= last.end) {\n // Span is fully inside of the previous span. Push to subnode.\n last.children.push(spans[i]);\n }\n // Span could partially overlap, ignoring it as invalid.\n }\n\n // Recursively rearrange the subnodes.\n for (let i in tree) {\n tree[i].children = toSpanTree(tree[i].children);\n }\n\n return tree;\n}\n\n// Convert drafty document to a tree.\nfunction draftyToTree(doc) {\n if (!doc) {\n return null;\n }\n\n doc = (typeof doc == 'string') ? {\n txt: doc\n } : doc;\n let {\n txt,\n fmt,\n ent\n } = doc;\n\n txt = txt || '';\n if (!Array.isArray(ent)) {\n ent = [];\n }\n\n if (!Array.isArray(fmt) || fmt.length == 0) {\n if (ent.length == 0) {\n return {\n text: txt\n };\n }\n\n // Handle special case when all values in fmt are 0 and fmt therefore is skipped.\n fmt = [{\n at: 0,\n len: 0,\n key: 0\n }];\n }\n\n // Sanitize spans.\n const spans = [];\n const attachments = [];\n fmt.forEach((span) => {\n if (!span || typeof span != 'object') {\n return;\n }\n\n if (!['undefined', 'number'].includes(typeof span.at)) {\n // Present, but non-numeric 'at'.\n return;\n }\n if (!['undefined', 'number'].includes(typeof span.len)) {\n // Present, but non-numeric 'len'.\n return;\n }\n let at = span.at | 0;\n let len = span.len | 0;\n if (len < 0) {\n // Invalid span length.\n return;\n }\n\n let key = span.key || 0;\n if (ent.length > 0 && (typeof key != 'number' || key < 0 || key >= ent.length)) {\n // Invalid key value.\n return;\n }\n\n if (at <= -1) {\n // Attachment. Store attachments separately.\n attachments.push({\n start: -1,\n end: 0,\n key: key\n });\n return;\n } else if (at + len > txt.length) {\n // Span is out of bounds.\n return;\n }\n\n if (!span.tp) {\n if (ent.length > 0 && (typeof ent[key] == 'object')) {\n spans.push({\n start: at,\n end: at + len,\n key: key\n });\n }\n } else {\n spans.push({\n type: span.tp,\n start: at,\n end: at + len\n });\n }\n });\n\n // Sort spans first by start index (asc) then by length (desc), then by weight.\n spans.sort((a, b) => {\n let diff = a.start - b.start;\n if (diff != 0) {\n return diff;\n }\n diff = b.end - a.end;\n if (diff != 0) {\n return diff;\n }\n return FMT_WEIGHT.indexOf(b.type) - FMT_WEIGHT.indexOf(a.type);\n });\n\n // Move attachments to the end of the list.\n if (attachments.length > 0) {\n spans.push(...attachments);\n }\n\n spans.forEach((span) => {\n if (ent.length > 0 && !span.type && ent[span.key] && typeof ent[span.key] == 'object') {\n span.type = ent[span.key].tp;\n span.data = ent[span.key].data;\n }\n\n // Is type still undefined? Hide the invalid element!\n if (!span.type) {\n span.type = 'HD';\n }\n });\n\n let tree = spansToTree({}, txt, 0, txt.length, spans);\n\n // Flatten tree nodes.\n const flatten = function(node) {\n if (Array.isArray(node.children) && node.children.length == 1) {\n // Unwrap.\n const child = node.children[0];\n if (!node.type) {\n const parent = node.parent;\n node = child;\n node.parent = parent;\n } else if (!child.type && !child.children) {\n node.text = child.text;\n delete node.children;\n }\n }\n return node;\n }\n tree = treeTopDown(tree, flatten);\n\n return tree;\n}\n\n// Add tree node to a parent tree.\nfunction addNode(parent, n) {\n if (!n) {\n return parent;\n }\n\n if (!parent.children) {\n parent.children = [];\n }\n\n // If text is present, move it to a subnode.\n if (parent.text) {\n parent.children.push({\n text: parent.text,\n parent: parent\n });\n delete parent.text;\n }\n\n n.parent = parent;\n parent.children.push(n);\n\n return parent;\n}\n\n// Returns a tree of nodes.\nfunction spansToTree(parent, text, start, end, spans) {\n if (!spans || spans.length == 0) {\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n return parent;\n }\n\n // Process subspans.\n for (let i = 0; i < spans.length; i++) {\n const span = spans[i];\n if (span.start < 0 && span.type == 'EX') {\n addNode(parent, {\n type: span.type,\n data: span.data,\n key: span.key,\n att: true\n });\n continue;\n }\n\n // Add un-styled range before the styled span starts.\n if (start < span.start) {\n addNode(parent, {\n text: text.substring(start, span.start)\n });\n start = span.start;\n }\n\n // Get all spans which are within the current span.\n const subspans = [];\n while (i < spans.length - 1) {\n const inner = spans[i + 1];\n if (inner.start < 0) {\n // Attachments are in the end. Stop.\n break;\n } else if (inner.start < span.end) {\n if (inner.end <= span.end) {\n const tag = FORMAT_TAGS[inner.tp] || {};\n if (inner.start < inner.end || tag.isVoid) {\n // Valid subspan: completely within the current span and\n // either non-zero length or zero length is acceptable.\n subspans.push(inner);\n }\n }\n i++;\n // Overlapping subspans are ignored.\n } else {\n // Past the end of the current span. Stop.\n break;\n }\n }\n\n addNode(parent, spansToTree({\n type: span.type,\n data: span.data,\n key: span.key\n }, text, start, span.end, subspans));\n start = span.end;\n }\n\n // Add the last unformatted range.\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n\n return parent;\n}\n\n// Append a tree to a Drafty doc.\nfunction treeToDrafty(doc, tree, keymap) {\n if (!tree) {\n return doc;\n }\n\n doc.txt = doc.txt || '';\n\n // Checkpoint to measure length of the current tree node.\n const start = doc.txt.length;\n\n if (tree.text) {\n doc.txt += tree.text;\n } else if (Array.isArray(tree.children)) {\n tree.children.forEach((c) => {\n treeToDrafty(doc, c, keymap);\n });\n }\n\n if (tree.type) {\n const len = doc.txt.length - start;\n doc.fmt = doc.fmt || [];\n if (Object.keys(tree.data || {}).length > 0) {\n doc.ent = doc.ent || [];\n const newKey = (typeof keymap[tree.key] == 'undefined') ? doc.ent.length : keymap[tree.key];\n keymap[tree.key] = newKey;\n doc.ent[newKey] = {\n tp: tree.type,\n data: tree.data\n };\n if (tree.att) {\n // Attachment.\n doc.fmt.push({\n at: -1,\n len: 0,\n key: newKey\n });\n } else {\n doc.fmt.push({\n at: start,\n len: len,\n key: newKey\n });\n }\n } else {\n doc.fmt.push({\n tp: tree.type,\n at: start,\n len: len\n });\n }\n }\n return doc;\n}\n\n// Traverse the tree top down transforming the nodes: apply transformer to every tree node.\nfunction treeTopDown(src, transformer, context) {\n if (!src) {\n return null;\n }\n\n let dst = transformer.call(context, src);\n if (!dst || !dst.children) {\n return dst;\n }\n\n const children = [];\n for (let i in dst.children) {\n let n = dst.children[i];\n if (n) {\n n = treeTopDown(n, transformer, context);\n if (n) {\n children.push(n);\n }\n }\n }\n\n if (children.length == 0) {\n dst.children = null;\n } else {\n dst.children = children;\n }\n\n return dst;\n}\n\n// Traverse the tree bottom-up: apply formatter to every node.\n// The formatter must maintain its state through context.\nfunction treeBottomUp(src, formatter, index, stack, context) {\n if (!src) {\n return null;\n }\n\n if (stack && src.type) {\n stack.push(src.type);\n }\n\n let values = [];\n for (let i in src.children) {\n const n = treeBottomUp(src.children[i], formatter, i, stack, context);\n if (n) {\n values.push(n);\n }\n }\n if (values.length == 0) {\n if (src.text) {\n values = [src.text];\n } else {\n values = null;\n }\n }\n\n if (stack && src.type) {\n stack.pop();\n }\n\n return formatter.call(context, src.type, src.data, values, index, stack);\n}\n\n// Clip tree to the provided limit.\nfunction shortenTree(tree, limit, tail) {\n if (!tree) {\n return null;\n }\n\n if (tail) {\n limit -= tail.length;\n }\n\n const shortener = function(node) {\n if (limit <= -1) {\n // Limit -1 means the doc was already clipped.\n return null;\n }\n\n if (node.att) {\n // Attachments are unchanged.\n return node;\n }\n if (limit == 0) {\n node.text = tail;\n limit = -1;\n } else if (node.text) {\n const len = node.text.length;\n if (len > limit) {\n node.text = node.text.substring(0, limit) + tail;\n limit = -1;\n } else {\n limit -= len;\n }\n }\n return node;\n }\n\n return treeTopDown(tree, shortener);\n}\n\n// Strip heavy entities from a tree.\nfunction lightEntity(tree, allow) {\n const lightCopy = node => {\n const data = copyEntData(node.data, true, allow ? allow(node) : null);\n if (data) {\n node.data = data;\n } else {\n delete node.data;\n }\n return node;\n }\n return treeTopDown(tree, lightCopy);\n}\n\n// Remove spaces and breaks on the left.\nfunction lTrim(tree) {\n if (tree.type == 'BR') {\n tree = null;\n } else if (tree.text) {\n if (!tree.type) {\n tree.text = tree.text.trimStart();\n if (!tree.text) {\n tree = null;\n }\n }\n } else if (!tree.type && tree.children && tree.children.length > 0) {\n const c = lTrim(tree.children[0]);\n if (c) {\n tree.children[0] = c;\n } else {\n tree.children.shift();\n if (!tree.type && tree.children.length == 0) {\n tree = null;\n }\n }\n }\n return tree;\n}\n\n// Move attachments to the end. Attachments must be at the top level, no need to traverse the tree.\nfunction attachmentsToEnd(tree, limit) {\n if (!tree) {\n return null;\n }\n\n if (tree.att) {\n tree.text = ' ';\n delete tree.att;\n delete tree.children;\n } else if (tree.children) {\n const attachments = [];\n const children = [];\n for (let i in tree.children) {\n const c = tree.children[i];\n if (c.att) {\n if (attachments.length == limit) {\n // Too many attachments to preview;\n continue;\n }\n if (c.data['mime'] == JSON_MIME_TYPE) {\n // JSON attachments are not shown in preview.\n continue;\n }\n\n delete c.att;\n delete c.children;\n c.text = ' ';\n attachments.push(c);\n } else {\n children.push(c);\n }\n }\n tree.children = children.concat(attachments);\n }\n return tree;\n}\n\n// Get a list of entities from a text.\nfunction extractEntities(line) {\n let match;\n let extracted = [];\n ENTITY_TYPES.forEach((entity) => {\n while ((match = entity.re.exec(line)) !== null) {\n extracted.push({\n offset: match['index'],\n len: match[0].length,\n unique: match[0],\n data: entity.pack(match[0]),\n type: entity.name\n });\n }\n });\n\n if (extracted.length == 0) {\n return extracted;\n }\n\n // Remove entities detected inside other entities, like #hashtag in a URL.\n extracted.sort((a, b) => {\n return a.offset - b.offset;\n });\n\n let idx = -1;\n extracted = extracted.filter((el) => {\n const result = (el.offset > idx);\n idx = el.offset + el.len;\n return result;\n });\n\n return extracted;\n}\n\n// Convert the chunks into format suitable for serialization.\nfunction draftify(chunks, startAt) {\n let plain = '';\n let ranges = [];\n for (let i in chunks) {\n const chunk = chunks[i];\n if (!chunk.txt) {\n const drafty = draftify(chunk.children, plain.length + startAt);\n chunk.txt = drafty.txt;\n ranges = ranges.concat(drafty.fmt);\n }\n\n if (chunk.tp) {\n ranges.push({\n at: plain.length + startAt,\n len: chunk.txt.length,\n tp: chunk.tp\n });\n }\n\n plain += chunk.txt;\n }\n return {\n txt: plain,\n fmt: ranges\n };\n}\n\n// Create a copy of entity data with (light=false) or without (light=true) the large payload.\n// The array 'allow' contains a list of fields exempt from stripping.\nfunction copyEntData(data, light, allow) {\n if (data && Object.entries(data).length > 0) {\n allow = allow || [];\n const dc = {};\n ALLOWED_ENT_FIELDS.forEach(key => {\n if (data[key]) {\n if (light && !allow.includes(key) &&\n (typeof data[key] == 'string' || Array.isArray(data[key])) &&\n data[key].length > MAX_PREVIEW_DATA_SIZE) {\n return;\n }\n if (typeof data[key] == 'object') {\n return;\n }\n dc[key] = data[key];\n }\n });\n\n if (Object.entries(dc).length != 0) {\n return dc;\n }\n }\n return null;\n}\n\nif (typeof module != 'undefined') {\n module.exports = Drafty;\n}\n","/**\n * @file Definition of 'fnd' topic.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport * as Const from './config.js';\nimport Topic from './topic.js';\nimport {\n mergeToCache\n} from './utils.js';\n\n\n/**\n * Special case of {@link Tinode.Topic} for searching for contacts and group topics\n * @extends Tinode.Topic\n *\n */\nexport default class TopicFnd extends Topic {\n // List of users and topics uid or topic_name -> Contact object)\n _contacts = {};\n\n /**\n * Create TopicFnd.\n *\n * @param {TopicFnd.Callbacks} callbacks - Callbacks to receive various events.\n */\n constructor(callbacks) {\n super(Const.TOPIC_FND, callbacks);\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = Object.getOwnPropertyNames(this._contacts).length;\n // Reset contact list.\n this._contacts = {};\n for (let idx in subs) {\n let sub = subs[idx];\n const indexBy = sub.topic ? sub.topic : sub.user;\n\n sub = mergeToCache(this._contacts, indexBy, sub);\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(sub);\n }\n }\n\n if (updateCount > 0 && this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._contacts));\n }\n }\n\n /**\n * Publishing to TopicFnd is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicFnd#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'fnd' is not supported\"));\n }\n\n /**\n * setMeta to TopicFnd resets contact list in addition to sending the message.\n * @memberof Tinode.TopicFnd#\n * @param {Tinode.SetParams} params parameters to update.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n setMeta(params) {\n return Object.getPrototypeOf(TopicFnd.prototype).setMeta.call(this, params).then(_ => {\n if (Object.keys(this._contacts).length > 0) {\n this._contacts = {};\n if (this.onSubsUpdated) {\n this.onSubsUpdated([]);\n }\n }\n });\n }\n\n /**\n * Iterate over found contacts. If callback is undefined, use {@link this.onMetaSub}.\n * @function\n * @memberof Tinode.TopicFnd#\n * @param {TopicFnd.ContactCallback} callback - Callback to call for each contact.\n * @param {Object} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._contacts) {\n cb.call(context, this._contacts[idx], idx, this._contacts);\n }\n }\n }\n}\n","/**\n * @file Utilities for uploading and downloading files.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n isUrlRelative,\n jsonParseHelper\n} from './utils.js';\n\nlet XHRProvider;\n\nfunction addURLParam(relUrl, key, value) {\n const url = new URL(relUrl, window.location.origin);\n url.searchParams.append(key, value);\n return url.toString().substring(window.location.origin.length);\n}\n\n/**\n * @class LargeFileHelper - utilities for uploading and downloading files out of band.\n * Don't instantiate this class directly. Use {Tinode.getLargeFileHelper} instead.\n * @memberof Tinode\n *\n * @param {Tinode} tinode - the main Tinode object.\n * @param {string} version - protocol version, i.e. '0'.\n */\nexport default class LargeFileHelper {\n constructor(tinode, version) {\n this._tinode = tinode;\n this._version = version;\n\n this._apiKey = tinode._apiKey;\n this._authToken = tinode.getAuthToken();\n\n // Ongoing requests.\n this.xhr = [];\n }\n\n /**\n * Start uploading the file to an endpoint at baseUrl.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} baseUrl base URL of upload server.\n * @param {File|Blob} data data to upload.\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure) {\n let url = `/v${this._version}/file/u/`;\n if (baseUrl) {\n let base = baseUrl;\n if (base.endsWith('/')) {\n // Removing trailing slash.\n base = base.slice(0, -1);\n }\n if (base.startsWith('http://') || base.startsWith('https://')) {\n url = base + url;\n } else {\n throw new Error(`Invalid base URL '${baseUrl}'`);\n }\n }\n\n const instance = this;\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n xhr.open('POST', url, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n if (this._authToken) {\n xhr.setRequestHeader('X-Tinode-Auth', `Token ${this._authToken.token}`);\n }\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n xhr.upload.onprogress = e => {\n if (e.lengthComputable) {\n if (onProgress) {\n onProgress(e.loaded / e.total);\n }\n if (this.onProgress) {\n this.onProgress(e.loaded / e.total);\n }\n }\n };\n\n xhr.onload = function() {\n let pkt;\n try {\n pkt = JSON.parse(this.response, jsonParseHelper);\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.response);\n pkt = {\n ctrl: {\n code: this.status,\n text: this.statusText\n }\n };\n }\n\n if (this.status >= 200 && this.status < 300) {\n if (toResolve) {\n toResolve(pkt.ctrl.params.url);\n }\n if (onSuccess) {\n onSuccess(pkt.ctrl);\n }\n } else if (this.status >= 400) {\n if (toReject) {\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n }\n if (onFailure) {\n onFailure(pkt.ctrl);\n }\n } else {\n instance._tinode.logger(\"ERROR: Unexpected server response status\", this.status, this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(e || new Error(\"failed\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n xhr.onabort = function(e) {\n if (toReject) {\n toReject(new Error(\"upload cancelled by user\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n try {\n const form = new FormData();\n form.append('file', data);\n form.set('id', this._tinode.getNextUniqueId());\n if (avatarFor) {\n form.set('topic', avatarFor);\n }\n xhr.send(form);\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onFailure) {\n onFailure(null);\n }\n }\n\n return result;\n }\n /**\n * Start uploading the file to default endpoint.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {File|Blob} data to upload\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n upload(data, avatarFor, onProgress, onSuccess, onFailure) {\n const baseUrl = (this._tinode._secure ? 'https://' : 'http://') + this._tinode._host;\n return this.uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure);\n }\n /**\n * Download the file from a given URL using GET request. This method works with the Tinode server only.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} relativeUrl - URL to download the file from. Must be relative url, i.e. must not contain the host.\n * @param {string=} filename - file name to use for the downloaded file.\n *\n * @returns {Promise} resolved/rejected when the download is completed/failed.\n */\n download(relativeUrl, filename, mimetype, onProgress, onError) {\n if (!isUrlRelative(relativeUrl)) {\n // As a security measure refuse to download from an absolute URL.\n if (onError) {\n onError(`The URL '${relativeUrl}' must be relative, not absolute`);\n }\n return;\n }\n if (!this._authToken) {\n if (onError) {\n onError(\"Must authenticate first\");\n }\n return;\n }\n const instance = this;\n\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n // Add '&asatt=1' to URL to request 'Content-Disposition: attachment' response header.\n relativeUrl = addURLParam(relativeUrl, 'asatt', '1');\n\n // Get data as blob (stored by the browser as a temporary file).\n xhr.open('GET', relativeUrl, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n xhr.setRequestHeader('X-Tinode-Auth', 'Token ' + this._authToken.token);\n xhr.responseType = 'blob';\n\n xhr.onprogress = function(e) {\n if (onProgress) {\n // Passing e.loaded instead of e.loaded/e.total because e.total\n // is always 0 with gzip compression enabled by the server.\n onProgress(e.loaded);\n }\n };\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n // The blob needs to be saved as file. There is no known way to\n // save the blob as file other than to fake a click on an .\n xhr.onload = function() {\n if (this.status == 200) {\n const link = document.createElement('a');\n // URL.createObjectURL is not available in non-browser environment. This call will fail.\n link.href = window.URL.createObjectURL(new Blob([this.response], {\n type: mimetype\n }));\n link.style.display = 'none';\n link.setAttribute('download', filename);\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n window.URL.revokeObjectURL(link.href);\n if (toResolve) {\n toResolve();\n }\n } else if (this.status >= 400 && toReject) {\n // The this.responseText is undefined, must use this.response which is a blob.\n // Need to convert this.response to JSON. The blob can only be accessed by the\n // FileReader.\n const reader = new FileReader();\n reader.onload = function() {\n try {\n const pkt = JSON.parse(this.result, jsonParseHelper);\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.result);\n toReject(err);\n }\n };\n reader.readAsText(this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(new Error(\"failed\"));\n }\n if (onError) {\n onError(e);\n }\n };\n\n xhr.onabort = function() {\n if (toReject) {\n toReject(null);\n }\n };\n\n try {\n xhr.send();\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onError) {\n onError(err);\n }\n }\n\n return result;\n }\n /**\n * Try to cancel all ongoing uploads or downloads.\n * @memberof Tinode.LargeFileHelper#\n */\n cancel() {\n this.xhr.forEach(req => {\n if (req.readyState < 4) {\n req.abort();\n }\n });\n }\n /**\n * To use LargeFileHelper in a non browser context, supply XMLHttpRequest provider.\n * @static\n * @memberof LargeFileHelper\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProvider(xhrProvider) {\n XHRProvider = xhrProvider;\n }\n}\n","/**\n * @file Definition of 'me' topic.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport * as Const from './config.js';\nimport Topic from './topic.js';\nimport {\n mergeObj\n} from './utils.js';\n\n/**\n * @class TopicMe - special case of {@link Tinode.Topic} for\n * managing data of the current user, including contact list.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicMe.Callbacks} callbacks - Callbacks to receive various events.\n */\nexport default class TopicMe extends Topic {\n onContactUpdate;\n\n constructor(callbacks) {\n super(Const.TOPIC_ME, callbacks);\n\n // me-specific callbacks\n if (callbacks) {\n this.onContactUpdate = callbacks.onContactUpdate;\n }\n }\n\n // Override the original Topic._processMetaDesc.\n _processMetaDesc(desc) {\n // Check if online contacts need to be turned off because P permission was removed.\n const turnOff = (desc.acs && !desc.acs.isPresencer()) && (this.acs && this.acs.isPresencer());\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n this._tinode._db.updTopic(this);\n // Update current user's record in the global cache.\n this._updateCachedUser(this._tinode._myUID, desc);\n\n // 'P' permission was removed. All topics are offline now.\n if (turnOff) {\n this._tinode.mapTopics((cont) => {\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n this._refreshContact('off', cont);\n }\n });\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = 0;\n subs.forEach((sub) => {\n const topicName = sub.topic;\n // Don't show 'me' and 'fnd' topics in the list of contacts.\n if (topicName == Const.TOPIC_FND || topicName == Const.TOPIC_ME) {\n return;\n }\n sub.online = !!sub.online;\n\n let cont = null;\n if (sub.deleted) {\n cont = sub;\n this._tinode.cacheRemTopic(topicName);\n this._tinode._db.remTopic(topicName);\n } else {\n // Ensure the values are defined and are integers.\n if (typeof sub.seq != 'undefined') {\n sub.seq = sub.seq | 0;\n sub.recv = sub.recv | 0;\n sub.read = sub.read | 0;\n sub.unread = sub.seq - sub.read;\n }\n\n const topic = this._tinode.getTopic(topicName);\n if (topic._new) {\n delete topic._new;\n }\n\n cont = mergeObj(topic, sub);\n this._tinode._db.updTopic(cont);\n\n if (Topic.isP2PTopicName(topicName)) {\n this._cachePutUser(topicName, cont);\n this._tinode._db.updUser(topicName, cont.public);\n }\n // Notify topic of the update if it's an external update.\n if (!sub._noForwarding && topic) {\n sub._noForwarding = true;\n topic._processMetaDesc(sub);\n }\n }\n\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(cont);\n }\n });\n\n if (this.onSubsUpdated && updateCount > 0) {\n const keys = [];\n subs.forEach((s) => {\n keys.push(s.topic);\n });\n this.onSubsUpdated(keys, updateCount);\n }\n }\n\n // Called by Tinode when meta.sub is recived.\n _processMetaCreds(creds, upd) {\n if (creds.length == 1 && creds[0] == Const.DEL_CHAR) {\n creds = [];\n }\n if (upd) {\n creds.forEach((cr) => {\n if (cr.val) {\n // Adding a credential.\n let idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && el.val == cr.val;\n });\n if (idx < 0) {\n // Not found.\n if (!cr.done) {\n // Unconfirmed credential replaces previous unconfirmed credential of the same method.\n idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n // Remove previous unconfirmed credential.\n this._credentials.splice(idx, 1);\n }\n }\n this._credentials.push(cr);\n } else {\n // Found. Maybe change 'done' status.\n this._credentials[idx].done = cr.done;\n }\n } else if (cr.resp) {\n // Handle credential confirmation.\n const idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n this._credentials[idx].done = true;\n }\n }\n });\n } else {\n this._credentials = creds;\n }\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n }\n\n // Process presence change message\n _routePres(pres) {\n if (pres.what == 'term') {\n // The 'me' topic itself is detached. Mark as unsubscribed.\n this._resetSub();\n return;\n }\n\n if (pres.what == 'upd' && pres.src == Const.TOPIC_ME) {\n // Update to me's description. Request updated value.\n this.getMeta(this.startMetaQuery().withDesc().build());\n return;\n }\n\n const cont = this._tinode.cacheGetTopic(pres.src);\n if (cont) {\n switch (pres.what) {\n case 'on': // topic came online\n cont.online = true;\n break;\n case 'off': // topic went offline\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n }\n break;\n case 'msg': // new message received\n cont._updateReceived(pres.seq, pres.act);\n break;\n case 'upd': // desc updated\n // Request updated subscription.\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n break;\n case 'acs': // access mode changed\n if (cont.acs) {\n cont.acs.updateAll(pres.dacs);\n } else {\n cont.acs = new AccessMode().updateAll(pres.dacs);\n }\n cont.touched = new Date();\n break;\n case 'ua':\n // user agent changed.\n cont.seen = {\n when: new Date(),\n ua: pres.ua\n };\n break;\n case 'recv':\n // user's other session marked some messges as received.\n pres.seq = pres.seq | 0;\n cont.recv = cont.recv ? Math.max(cont.recv, pres.seq) : pres.seq;\n break;\n case 'read':\n // user's other session marked some messages as read.\n pres.seq = pres.seq | 0;\n cont.read = cont.read ? Math.max(cont.read, pres.seq) : pres.seq;\n cont.recv = cont.recv ? Math.max(cont.read, cont.recv) : cont.recv;\n cont.unread = cont.seq - cont.read;\n break;\n case 'gone':\n // topic deleted or unsubscribed from.\n if (!cont._deleted) {\n cont._deleted = true;\n cont._attached = false;\n this._tinode._db.markTopicAsDeleted(pres.src);\n } else {\n this._tinode._db.remTopic(pres.src);\n }\n break;\n case 'del':\n // Update topic.del value.\n break;\n default:\n this._tinode.logger(\"INFO: Unsupported presence update in 'me'\", pres.what);\n }\n\n this._refreshContact(pres.what, cont);\n } else {\n if (pres.what == 'acs') {\n // New subscriptions and deleted/banned subscriptions have full\n // access mode (no + or - in the dacs string). Changes to known subscriptions are sent as\n // deltas, but they should not happen here.\n const acs = new AccessMode(pres.dacs);\n if (!acs || acs.mode == AccessMode._INVALID) {\n this._tinode.logger(\"ERROR: Invalid access mode update\", pres.src, pres.dacs);\n return;\n } else if (acs.mode == AccessMode._NONE) {\n this._tinode.logger(\"WARNING: Removing non-existent subscription\", pres.src, pres.dacs);\n return;\n } else {\n // New subscription. Send request for the full description.\n // Using .withOneSub (not .withLaterOneSub) to make sure IfModifiedSince is not set.\n this.getMeta(this.startMetaQuery().withOneSub(undefined, pres.src).build());\n // Create a dummy entry to catch online status update.\n const dummy = this._tinode.getTopic(pres.src);\n dummy.topic = pres.src;\n dummy.online = false;\n dummy.acs = acs;\n this._tinode._db.updTopic(dummy);\n }\n } else if (pres.what == 'tags') {\n this.getMeta(this.startMetaQuery().withTags().build());\n }\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n\n // Contact is updated, execute callbacks.\n _refreshContact(what, cont) {\n if (this.onContactUpdate) {\n this.onContactUpdate(what, cont);\n }\n }\n\n /**\n * Publishing to TopicMe is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicMe#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'me' is not supported\"));\n }\n\n /**\n * Delete validation credential.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} topic - Name of the topic to delete\n * @param {string} user - User ID to remove.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete credential in inactive 'me' topic\"));\n }\n // Send {del} message, return promise\n return this._tinode.delCredential(method, value).then(ctrl => {\n // Remove deleted credential from the cache.\n const index = this._credentials.findIndex((el) => {\n return el.meth == method && el.val == value;\n });\n if (index > -1) {\n this._credentials.splice(index, 1);\n }\n // Notify listeners\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n return ctrl;\n });\n }\n\n /**\n * @callback contactFilter\n * @param {Object} contact to check for inclusion.\n * @returns {boolean} true if contact should be processed, false to exclude it.\n */\n /**\n * Iterate over cached contacts.\n *\n * @function\n * @memberof Tinode.TopicMe#\n * @param {TopicMe.ContactCallback} callback - Callback to call for each contact.\n * @param {contactFilter=} filter - Optionally filter contacts; include all if filter is false-ish, otherwise\n * include those for which filter returns true-ish.\n * @param {Object=} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, filter, context) {\n this._tinode.mapTopics((c, idx) => {\n if (c.isCommType() && (!filter || filter(c))) {\n callback.call(context, c, idx);\n }\n });\n }\n\n /**\n * Get a contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get, either a UID (for p2p topics) or a topic name.\n * @returns {Tinode.Contact} - Contact or `undefined`.\n */\n getContact(name) {\n return this._tinode.cacheGetTopic(name);\n }\n\n /**\n * Get access mode of a given contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get access mode for, either a UID (for p2p topics)\n * or a topic name; if missing, access mode for the 'me' topic itself.\n * @returns {string} - access mode, such as `RWP`.\n */\n getAccessMode(name) {\n if (name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont ? cont.acs : null;\n }\n return this.acs;\n }\n\n /**\n * Check if contact is archived, i.e. contact.private.arch == true.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to check archived status, either a UID (for p2p topics) or a topic name.\n * @returns {boolean} - true if contact is archived, false otherwise.\n */\n isArchived(name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont && cont.private && !!cont.private.arch;\n }\n\n /**\n * @typedef Tinode.Credential\n * @memberof Tinode\n * @type Object\n * @property {string} meth - validation method such as 'email' or 'tel'.\n * @property {string} val - credential value, i.e. 'jdoe@example.com' or '+17025551234'\n * @property {boolean} done - true if credential is validated.\n */\n /**\n * Get the user's credentials: email, phone, etc.\n * @memberof Tinode.TopicMe#\n *\n * @returns {Tinode.Credential[]} - array of credentials.\n */\n getCredentials() {\n return this._credentials;\n }\n}\n","/**\n * @file Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport {\n listToRanges,\n normalizeRanges\n} from './utils';\n\n/**\n * Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @class MetaGetBuilder\n * @memberof Tinode\n *\n * @param {Tinode.Topic} parent topic which instantiated this builder.\n */\nexport default class MetaGetBuilder {\n constructor(parent) {\n this.topic = parent;\n this.what = {};\n }\n\n // Get timestamp of the most recent desc update.\n #get_desc_ims() {\n return this.topic.updated;\n }\n\n // Get timestamp of the most recent subs update.\n #get_subs_ims() {\n if (this.topic.isP2PType()) {\n return this.#get_desc_ims();\n }\n return this.topic._lastSubsUpdate;\n }\n /**\n * Add query parameters to fetch messages within explicit limits.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - messages newer than this (inclusive);\n * @param {number=} before - older than this (exclusive)\n * @param {number=} limit - number of messages to fetch\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withData(since, before, limit) {\n this.what['data'] = {\n since: since,\n before: before,\n limit: limit\n };\n return this;\n }\n /**\n * Add query parameters to fetch messages newer than the latest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of messages to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterData(limit) {\n return this.withData(this.topic._maxSeq > 0 ? this.topic._maxSeq + 1 : undefined, undefined, limit);\n }\n /**\n * Add query parameters to fetch messages within ID ranges.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Array.this object.\n */\n withDataRanges(ranges, limit) {\n this.what['data'] = {\n ranges: normalizeRanges(ranges, this.topic._maxSeq),\n limit: limit\n };\n return this;\n }\n /**\n * Add query parameters to fetch messages by an array of IDs.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number[]} list - array of seq IDs to fetch.\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDataList(list) {\n return this.withDataRanges(listToRanges(list));\n }\n /**\n * Add query parameters to fetch messages older than the earliest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of messages to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withEarlierData(limit) {\n return this.withData(undefined, this.topic._minSeq > 0 ? this.topic._minSeq : undefined, limit);\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the given timestamp.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch messages newer than this timestamp.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDesc(ims) {\n this.what['desc'] = {\n ims: ims\n };\n return this;\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDesc() {\n return this.withDesc(this.#get_desc_ims());\n }\n /**\n * Add query parameters to fetch subscriptions.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {number=} limit - maximum number of subscriptions to fetch.\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withSub(ims, limit, userOrTopic) {\n const opts = {\n ims: ims,\n limit: limit\n };\n if (this.topic.getType() == 'me') {\n opts.topic = userOrTopic;\n } else {\n opts.user = userOrTopic;\n }\n this.what['sub'] = opts;\n return this;\n }\n /**\n * Add query parameters to fetch a single subscription.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withOneSub(ims, userOrTopic) {\n return this.withSub(ims, undefined, userOrTopic);\n }\n /**\n * Add query parameters to fetch a single subscription if it's been updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterOneSub(userOrTopic) {\n return this.withOneSub(this.topic._lastSubsUpdate, userOrTopic);\n }\n /**\n * Add query parameters to fetch subscriptions updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of subscriptions to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterSub(limit) {\n return this.withSub(this.#get_subs_ims(), limit);\n }\n /**\n * Add query parameters to fetch topic tags.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withTags() {\n this.what['tags'] = true;\n return this;\n }\n /**\n * Add query parameters to fetch user's credentials. 'me' topic only.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withCred() {\n if (this.topic.getType() == 'me') {\n this.what['cred'] = true;\n } else {\n this.topic._tinode.logger(\"ERROR: Invalid topic type for MetaGetBuilder:withCreds\", this.topic.getType());\n }\n return this;\n }\n /**\n * Add query parameters to fetch topic tags.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withAux() {\n this.what['aux'] = true;\n return this;\n }\n /**\n * Add query parameters to fetch deleted messages within explicit limits. Any/all parameters can be null.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - ids of messages deleted since this 'del' id (inclusive)\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDel(since, limit) {\n if (since || limit) {\n this.what['del'] = {\n since: since,\n limit: limit\n };\n }\n return this;\n }\n /**\n * Add query parameters to fetch messages deleted after the saved 'del' id.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDel(limit) {\n // Specify 'since' only if we have already received some messages. If\n // we have no locally cached messages then we don't care if any messages were deleted.\n return this.withDel(this.topic._maxSeq > 0 ? this.topic._maxDel + 1 : undefined, limit);\n }\n\n /**\n * Extract subquery: get an object that contains specified subquery.\n * @memberof Tinode.MetaGetBuilder#\n * @param {string} what - subquery to return: one of 'data', 'sub', 'desc', 'tags', 'cred', 'del'.\n * @returns {Object} requested subquery or undefined.\n */\n extract(what) {\n return this.what[what];\n }\n\n /**\n * Construct parameters.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.GetQuery} Get query\n */\n build() {\n const what = [];\n let params = {};\n ['data', 'sub', 'desc', 'tags', 'cred', 'aux', 'del'].forEach((key) => {\n if (this.what.hasOwnProperty(key)) {\n what.push(key);\n if (Object.getOwnPropertyNames(this.what[key]).length > 0) {\n params[key] = this.what[key];\n }\n }\n });\n if (what.length > 0) {\n params.what = what.join(' ');\n } else {\n params = undefined;\n }\n return params;\n }\n}\n","/**\n * @file Topic management.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport CBuffer from './cbuffer.js';\nimport CommError from './comm-error.js';\nimport * as Const from './config.js';\nimport Drafty from './drafty.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport {\n listToRanges,\n mergeObj,\n mergeToCache,\n normalizeArray,\n normalizeRanges\n} from './utils.js';\n\n/**\n * Topic is a class representing a logical communication channel.\n */\nexport default class Topic {\n /**\n * @callback onData\n * @param {Data} data - Data packet\n */\n\n /**\n * Create topic.\n * @param {string} name - Name of the topic to create.\n * @param {Object=} callbacks - Object with various event callbacks.\n * @param {onData} callbacks.onData - Callback which receives a {data} message.\n * @param {callback} callbacks.onMeta - Callback which receives a {meta} message.\n * @param {callback} callbacks.onPres - Callback which receives a {pres} message.\n * @param {callback} callbacks.onInfo - Callback which receives an {info} message.\n * @param {callback} callbacks.onMetaDesc - Callback which receives changes to topic desctioption {@link desc}.\n * @param {callback} callbacks.onMetaSub - Called for a single subscription record change.\n * @param {callback} callbacks.onSubsUpdated - Called after a batch of subscription changes have been recieved and cached.\n * @param {callback} callbacks.onDeleteTopic - Called after the topic is deleted.\n * @param {callback} callbacls.onAllMessagesReceived - Called when all requested {data} messages have been recived.\n */\n constructor(name, callbacks) {\n // Parent Tinode object.\n this._tinode = null;\n\n // Server-provided data, locally immutable.\n // topic name\n this.name = name;\n // Timestamp when the topic was created.\n this.created = null;\n // Timestamp when the topic was last updated.\n this.updated = null;\n // Timestamp of the last messages\n this.touched = new Date(0);\n // Access mode, see AccessMode\n this.acs = new AccessMode(null);\n // Per-topic private data (accessible by current user only).\n this.private = null;\n // Per-topic public data (accessible by all users).\n this.public = null;\n // Per-topic system-provided data (accessible by all users).\n this.trusted = null;\n\n // Locally cached data\n // Subscribed users, for tracking read/recv/msg notifications.\n this._users = {};\n\n // Current value of locally issued seqId, used for pending messages.\n this._queuedSeqId = Const.LOCAL_SEQID;\n\n // The maximum known {data.seq} value.\n this._maxSeq = 0;\n // The minimum known {data.seq} value.\n this._minSeq = 0;\n // Indicator that the last request for earlier messages returned 0.\n this._noEarlierMsgs = false;\n // The maximum known deletion ID.\n this._maxDel = 0;\n // Timer object used to send 'recv' notifications.\n this._recvNotificationTimer = null;\n\n // User discovery tags\n this._tags = [];\n // Credentials such as email or phone number.\n this._credentials = [];\n // Auxiliary data\n this._aux = {};\n\n // Message versions cache (e.g. for edited messages).\n // Keys: original message seq ID.\n // Values: CBuffers containing newer versions of the original message\n // ordered by seq id.\n this._messageVersions = {};\n // Message cache, sorted by message seq values, from old to new.\n this._messages = new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n // Boolean, true if the topic is currently live\n this._attached = false;\n // Timestap of the most recently updated subscription.\n this._lastSubsUpdate = new Date(0);\n // Topic created but not yet synced with the server. Used only during initialization.\n this._new = true;\n // The topic is deleted at the server, this is a local copy.\n this._deleted = false;\n\n // Timer used to trgger {leave} request after a delay.\n this._delayedLeaveTimer = null;\n\n // Callbacks\n if (callbacks) {\n this.onData = callbacks.onData;\n this.onMeta = callbacks.onMeta;\n this.onPres = callbacks.onPres;\n this.onInfo = callbacks.onInfo;\n // A single desc update;\n this.onMetaDesc = callbacks.onMetaDesc;\n // A single subscription record;\n this.onMetaSub = callbacks.onMetaSub;\n // All subscription records received;\n this.onSubsUpdated = callbacks.onSubsUpdated;\n this.onTagsUpdated = callbacks.onTagsUpdated;\n this.onCredsUpdated = callbacks.onCredsUpdated;\n this.onAuxUpdated = callbacks.onAuxUpdated;\n this.onDeleteTopic = callbacks.onDeleteTopic;\n this.onAllMessagesReceived = callbacks.onAllMessagesReceived;\n }\n }\n\n // Static methods.\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n *\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n const types = {\n 'me': Const.TOPIC_ME,\n 'fnd': Const.TOPIC_FND,\n 'grp': Const.TOPIC_GRP,\n 'new': Const.TOPIC_GRP,\n 'nch': Const.TOPIC_GRP,\n 'chn': Const.TOPIC_GRP,\n 'usr': Const.TOPIC_P2P,\n 'sys': Const.TOPIC_SYS\n };\n return types[(typeof name == 'string') ? name.substring(0, 3) : 'xxx'];\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_ME;\n }\n\n /**\n * Check if the given topic name is a name of a group topic.\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_GRP;\n }\n\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_P2P;\n }\n\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isP2PTopicName(name) || Topic.isGroupTopicName(name);\n }\n\n /**\n * Check if the topic name is a name of a new topic.\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_NEW || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n /**\n * Check if the topic name is a name of a channel.\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_CHAN || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n // Returns true if pub is meant to replace another message (e.g. original message was edited).\n static #isReplacementMsg(pub) {\n return pub.head && pub.head.replace;\n }\n\n /**\n * Check if the topic is subscribed.\n * @returns {boolean} True is topic is attached/subscribed, false otherwise.\n */\n isSubscribed() {\n return this._attached;\n }\n\n /**\n * Request topic to subscribe. Wrapper for {@link Tinode#subscribe}.\n *\n * @param {Tinode.GetQuery=} getParams - get query parameters.\n * @param {Tinode.SetParams=} setParams - set parameters.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n subscribe(getParams, setParams) {\n // Clear request to leave topic.\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = null;\n\n // If the topic is already subscribed, return resolved promise\n if (this._attached) {\n return Promise.resolve(this);\n }\n\n // If the topic is deleted, reject subscription requests.\n if (this._deleted) {\n return Promise.reject(new Error(\"Conversation deleted\"));\n }\n\n // Send subscribe message, handle async response.\n // If topic name is explicitly provided, use it. If no name, then it's a new group topic,\n // use \"new\".\n return this._tinode.subscribe(this.name || Const.TOPIC_NEW, getParams, setParams).then(ctrl => {\n if (ctrl.code >= 300) {\n // Do nothing if subscription status has not changed.\n return ctrl;\n }\n\n this._attached = true;\n this._deleted = false;\n this.acs = (ctrl.params && ctrl.params.acs) ? ctrl.params.acs : this.acs;\n\n // Set topic name for new topics and add it to cache.\n if (this._new) {\n delete this._new;\n\n if (this.name != ctrl.topic) {\n // Name may change new123456 -> grpAbCdEf. Remove from cache under the old name.\n this._cacheDelSelf();\n this.name = ctrl.topic;\n }\n this._cachePutSelf();\n\n this.created = ctrl.ts;\n this.updated = ctrl.ts;\n\n if (this.name != Const.TOPIC_ME && this.name != Const.TOPIC_FND) {\n // Add the new topic to the list of contacts maintained by the 'me' topic.\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (setParams && setParams.desc) {\n setParams.desc._noForwarding = true;\n this._processMetaDesc(setParams.desc);\n }\n }\n return ctrl;\n });\n }\n\n /**\n * Create a draft of a message without sending it to the server.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Content to wrap in a draft.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * session. Otherwise the server will send a copy of the message to sender.\n *\n * @returns {Object} message draft.\n */\n createMessage(data, noEcho) {\n return this._tinode.createMessage(this.name, data, noEcho);\n }\n\n /**\n * Immediately publish data to topic. Wrapper for {@link Tinode#publish}.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Message to publish, either plain string or a Drafty object.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publish(data, noEcho) {\n return this.publishMessage(this.createMessage(data, noEcho));\n }\n\n /**\n * Publish message created by {@link Tinode.Topic#createMessage}.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - {data} object to publish. Must be created by {@link Tinode.Topic#createMessage}\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publishMessage(pub) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot publish on inactive topic\"));\n }\n if (this._sending) {\n return Promise.reject(new Error(\"The message is already being sent\"));\n }\n\n // Send data.\n pub._sending = true;\n pub._failed = false;\n\n // Extract refereces to attachments and out of band image records.\n let attachments = null;\n if (Drafty.hasEntities(pub.content)) {\n attachments = [];\n Drafty.entities(pub.content, data => {\n if (data) {\n if (data.ref) {\n attachments.push(data.ref);\n }\n if (data.preref) {\n attachments.push(data.preref);\n }\n }\n });\n if (attachments.length == 0) {\n attachments = null;\n }\n }\n\n return this._tinode.publishMessage(pub, attachments).then(ctrl => {\n pub._sending = false;\n pub.ts = ctrl.ts;\n this.swapMessageId(pub, ctrl.params.seq);\n this._maybeUpdateMessageVersionsCache(pub);\n this._routeData(pub);\n return ctrl;\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message rejected by the server\", err);\n pub._sending = false;\n pub._failed = true;\n if (this.onData) {\n this.onData();\n }\n });\n }\n\n /**\n * Add message to local message cache, send to the server when the promise is resolved.\n * If promise is null or undefined, the message will be sent immediately.\n * The message is sent when the\n * The message should be created by {@link Tinode.Topic#createMessage}.\n * This is probably not the final API.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - Message to use as a draft.\n * @param {Promise} prom - Message will be sent when this promise is resolved, discarded if rejected.\n *\n * @returns {Promise} derived promise.\n */\n publishDraft(pub, prom) {\n const seq = pub.seq || this._getQueuedSeqId();\n if (!pub._noForwarding) {\n // The 'seq', 'ts', and 'from' are added to mimic {data}. They are removed later\n // before the message is sent.\n pub._noForwarding = true;\n pub.seq = seq;\n pub.ts = new Date();\n pub.from = this._tinode.getCurrentUserID();\n\n // Don't need an echo message because the message is added to local cache right away.\n pub.noecho = true;\n // Add to cache.\n this._messages.put(pub);\n this._tinode._db.addMessage(pub);\n\n if (this.onData) {\n this.onData(pub);\n }\n }\n // If promise is provided, send the queued message when it's resolved.\n // If no promise is provided, create a resolved one and send immediately.\n return (prom || Promise.resolve())\n .then(_ => {\n if (pub._cancelled) {\n return {\n code: 300,\n text: \"cancelled\"\n };\n }\n return this.publishMessage(pub);\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message draft rejected\", err);\n pub._sending = false;\n pub._failed = true;\n pub._fatal = err instanceof CommError ? (err.code >= 400 && err.code < 500) : false;\n if (this.onData) {\n this.onData();\n }\n // Rethrow to let caller know that the operation failed.\n throw err;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean=} unsub - If true, unsubscribe, otherwise just leave.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n leave(unsub) {\n // It's possible to unsubscribe (unsub==true) from inactive topic.\n if (!this._attached && !unsub) {\n return Promise.reject(new Error(\"Cannot leave inactive topic\"));\n }\n\n // Send a 'leave' message, handle async response\n return this._tinode.leave(this.name, unsub).then(ctrl => {\n this._resetSub();\n if (unsub) {\n this._gone();\n }\n return ctrl;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe after a delay. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} unsub - If true, unsubscribe, otherwise just leave.\n * @param {number} delay - time in milliseconds to delay leave request.\n */\n leaveDelayed(unsub, delay) {\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = setTimeout(_ => {\n this._delayedLeaveTimer = null;\n this.leave(unsub)\n }, delay);\n }\n\n /**\n * Request topic metadata from the local cache or from the server.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.GetQuery} request parameters\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n getMeta(params) {\n // Send {get} message, return promise.\n return this._tinode.getMeta(this.name, params);\n }\n\n /**\n * Request more messages from the server. The goal is to load continous range of messages\n * covering at least between 'min' and 'max' + one full page forward (newer = true) or backwards\n * (newer=false).\n * @memberof Tinode.Topic#\n *\n * @param {number} limit number of messages to get.\n * @param {Array.null means to use default.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n invite(uid, mode) {\n return this.setMeta({\n sub: {\n user: uid,\n mode: mode\n }\n });\n }\n /**\n * Archive or un-archive the topic. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} arch - true to archive the topic, false otherwise.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n archive(arch) {\n if (this.private && (!this.private.arch == !arch)) {\n return Promise.resolve(arch);\n }\n return this.setMeta({\n desc: {\n private: {\n arch: arch ? true : Const.DEL_CHAR\n }\n }\n });\n }\n /**\n * Set message as pinned or unpinned by adding it to aux.pins array. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - seq ID of the message to pin or un-pin.\n * @param {boolean} pin - true to pin the message, false to un-pin.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n pinMessage(seq, pin) {\n let pinned = this.aux('pins');\n if (!Array.isArray(pinned)) {\n pinned = [];\n }\n let changed = false;\n if (pin) {\n if (!pinned.includes(seq)) {\n changed = true;\n if (pinned.length == Const.MAX_PINNED_COUNT) {\n pinned.shift();\n }\n pinned.push(seq);\n }\n } else {\n if (pinned.includes(seq)) {\n changed = true;\n pinned = pinned.filter(id => id != seq);\n if (pinned.length == 0) {\n pinned = Const.DEL_CHAR;\n }\n }\n }\n if (changed) {\n return this.setMeta({\n aux: {\n pins: pinned\n }\n });\n }\n return Promise.resolve();\n }\n /**\n * Delete messages. Hard-deleting messages requires Owner permission.\n * Wrapper for {@link Tinode#delMessages}.\n * @memberof Tinode.Topic#\n *\n * @param {Array.recv, read.\n * @param {number} seq - ID or the message read or received.\n */\n note(what, seq) {\n if (!this._attached) {\n // Cannot sending {note} on an inactive topic\".\n return;\n }\n\n // Update local cache with the new count.\n const user = this._users[this._tinode.getCurrentUserID()];\n let update = false;\n if (user) {\n // Self-subscription is found.\n if (!user[what] || user[what] < seq) {\n user[what] = seq;\n update = true;\n }\n } else {\n // Self-subscription is not found.\n update = (this[what] | 0) < seq;\n }\n\n if (update) {\n // Send notification to the server.\n this._tinode.note(this.name, what, seq);\n // Update locally cached contact with the new count.\n this._updateReadRecv(what, seq);\n\n if (this.acs != null && !this.acs.isMuted()) {\n const me = this._tinode.getMeTopic();\n // Sent a notification to 'me' listeners.\n me._refreshContact(what, this);\n }\n }\n }\n\n /**\n * Send a 'recv' receipt. Wrapper for {@link Tinode#noteRecv}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge.\n */\n noteRecv(seq) {\n this.note('recv', seq);\n }\n /**\n * Send a 'read' receipt. Wrapper for {@link Tinode#noteRead}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge or 0/undefined to acknowledge the latest messages.\n */\n noteRead(seq) {\n seq = seq || this._maxSeq;\n if (seq > 0) {\n this.note('read', seq);\n }\n }\n /**\n * Send a key-press notification. Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n */\n noteKeyPress() {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name);\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n /**\n * Send a notification than a video or audio message is . Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n * @param audioOnly - true if the recording is audio-only, false if it's a video recording.\n */\n noteRecording(audioOnly) {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name, audioOnly ? 'kpa' : 'kpv');\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n\n /**\n * Send a {note what='call'}. Wrapper for {@link Tinode#videoCall}.\n * @memberof Tinode#\n *\n * @param {string} evt - Call event.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(evt, seq, payload) {\n if (!this._attached && !['ringing', 'hang-up'].includes(evt)) {\n // Cannot {call} on an inactive topic\".\n return;\n }\n return this._tinode.videoCall(this.name, seq, evt, payload);\n }\n\n // Update cached read/recv/unread counts.\n _updateReadRecv(what, seq, ts) {\n let oldVal, doUpdate = false;\n\n seq = seq | 0;\n this.seq = this.seq | 0;\n this.read = this.read | 0;\n this.recv = this.recv | 0;\n switch (what) {\n case 'recv':\n oldVal = this.recv;\n this.recv = Math.max(this.recv, seq);\n doUpdate = (oldVal != this.recv);\n break;\n case 'read':\n oldVal = this.read;\n this.read = Math.max(this.read, seq);\n doUpdate = (oldVal != this.read);\n break;\n case 'msg':\n oldVal = this.seq;\n this.seq = Math.max(this.seq, seq);\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = (oldVal != this.seq);\n break;\n }\n\n // Sanity checks.\n if (this.recv < this.read) {\n this.recv = this.read;\n doUpdate = true;\n }\n if (this.seq < this.recv) {\n this.seq = this.recv;\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = true;\n }\n this.unread = this.seq - this.read;\n return doUpdate;\n }\n /**\n * Get user description from global cache. The user does not need to be a\n * subscriber of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - ID of the user to fetch.\n * @return {Object} user description or undefined.\n */\n userDesc(uid) {\n // TODO: handle asynchronous requests\n const user = this._cacheGetUser(uid);\n if (user) {\n return user; // Promise.resolve(user)\n }\n }\n /**\n * Get description of the p2p peer from subscription cache.\n * @memberof Tinode.Topic#\n *\n * @return {Object} peer's description or undefined.\n */\n p2pPeerDesc() {\n if (!this.isP2PType()) {\n return undefined;\n }\n return this._users[this.name];\n }\n /**\n * Iterate over cached subscribers. If callback is undefined, use this.onMetaSub.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive subscribers one by one.\n * @param {Object=} context - Value of `this` inside the `callback`.\n */\n subscribers(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._users) {\n cb.call(context, this._users[idx], idx, this._users);\n }\n }\n }\n /**\n * Get a copy of cached tags.\n * @memberof Tinode.Topic#\n *\n * @return {Array.key or undefined.\n */\n aux(key) {\n return this._aux[key];\n }\n /**\n * Get cached subscription for the given user ID.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - id of the user to query for\n * @return user description or undefined.\n */\n subscriber(uid) {\n return this._users[uid];\n }\n /**\n * Iterate over versions of a message: call callback for each version (excluding original).\n * If callback is undefined, does nothing.\n * @memberof Tinode.Topic#\n *\n * @param {number} origSeq - seq ID of the original message.\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messageVersions(origSeq, callback, context) {\n if (!callback) {\n // No callback? We are done then.\n return;\n }\n const versions = this._messageVersions[origSeq];\n if (!versions) {\n return;\n }\n versions.forEach(callback, undefined, undefined, context);\n }\n /**\n * Iterate over cached messages: call callback for each message in the range [sinceIdx, beforeIdx).\n * If callback is undefined, use this.onData.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {number} sinceId - Optional seqId to start iterating from (inclusive).\n * @param {number} beforeId - Optional seqId to stop iterating before it is reached (exclusive).\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messages(callback, sinceId, beforeId, context) {\n const cb = (callback || this.onData);\n if (cb) {\n const startIdx = typeof sinceId == 'number' ? this._messages.find({\n seq: sinceId\n }, true) : undefined;\n const beforeIdx = typeof beforeId == 'number' ? this._messages.find({\n seq: beforeId\n }, true) : undefined;\n if (startIdx != -1 && beforeIdx != -1) {\n // Step 1. Filter out all replacement messages and\n // save displayable messages in a temporary buffer.\n let msgs = [];\n this._messages.forEach((msg, unused1, unused2, i) => {\n if (Topic.#isReplacementMsg(msg)) {\n // Skip replacements.\n return;\n }\n if (msg._deleted) {\n // Skip deleted ranges.\n return;\n }\n // In case the massage was edited, replace timestamp of the version with the original's timestamp.\n const latest = this.latestMsgVersion(msg.seq) || msg;\n if (!latest._origTs) {\n latest._origTs = latest.ts;\n latest._origSeq = latest.seq;\n latest.ts = msg.ts;\n latest.seq = msg.seq;\n }\n msgs.push({\n data: latest,\n idx: i\n });\n }, startIdx, beforeIdx, {});\n // Step 2. Loop over displayble messages invoking cb on each of them.\n msgs.forEach((val, i) => {\n cb.call(context, val.data,\n (i > 0 ? msgs[i - 1].data : undefined),\n (i < msgs.length - 1 ? msgs[i + 1].data : undefined), val.idx);\n });\n }\n }\n }\n /**\n * Get the message from cache by literal seq (does not resolve message edits).\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message seqId to search for.\n * @returns {Object} the message with the given seq or undefined, if no such message is found.\n */\n findMessage(seq) {\n const idx = this._messages.find({\n seq: seq\n });\n if (idx >= 0) {\n return this._messages.getAt(idx);\n }\n return undefined;\n }\n /**\n * Get the most recent message from cache. This method counts all messages, including deleted ranges.\n * @memberof Tinode.Topic#\n *\n * @returns {Object} the most recent cached message or undefined, if no messages are cached.\n */\n latestMessage() {\n return this._messages.getLast();\n }\n /**\n * Get the latest version for message.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - original seq ID of the message.\n * @returns {Object} the latest version of the message or null if message not found.\n */\n latestMsgVersion(seq) {\n const versions = this._messageVersions[seq];\n return versions ? versions.getLast() : null;\n }\n /**\n * Get the maximum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest seq ID in cache.\n */\n maxMsgSeq() {\n return this._maxSeq;\n }\n /**\n * Get the minimum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the smallest seq ID in cache or 0.\n */\n minMsgSeq() {\n return this._minSeq;\n }\n /**\n * Get the maximum deletion ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest deletion ID.\n */\n maxClearId() {\n return this._maxDel;\n }\n /**\n * Get the number of messages in the cache.\n * @memberof Tinode.Topic#\n *\n * @returns {number} count of cached messages.\n */\n messageCount() {\n return this._messages.length();\n }\n /**\n * Iterate over cached unsent messages. Wraps {@link Tinode.Topic#messages}.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of this inside the callback.\n */\n queuedMessages(callback, context) {\n if (!callback) {\n throw new Error(\"Callback must be provided\");\n }\n this.messages(callback, Const.LOCAL_SEQID, undefined, context);\n }\n /**\n * Get the number of topic subscribers who marked this message as either recv or read\n * Current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {string} what - what action to consider: received \"recv\" or read \"read\".\n * @param {number} seq - ID or the message read or received.\n *\n * @returns {number} the number of subscribers who marked the message with the given ID as read or received.\n */\n msgReceiptCount(what, seq) {\n let count = 0;\n if (seq > 0) {\n const me = this._tinode.getCurrentUserID();\n for (let idx in this._users) {\n const user = this._users[idx];\n if (user.user !== me && user[what] >= seq) {\n count++;\n }\n }\n }\n return count;\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as read.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message id to check.\n * @returns {number} number of subscribers who claim to have received the message.\n */\n msgReadCount(seq) {\n return this.msgReceiptCount('read', seq);\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as received.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - Message id to check.\n * @returns {number} Number of subscribers who claim to have received the message.\n */\n msgRecvCount(seq) {\n return this.msgReceiptCount('recv', seq);\n }\n /**\n * Check if cached message IDs indicate that the server may have more messages.\n * @memberof Tinode.Topic#\n *\n * @param {number} min - smallest seq ID loaded range.\n * @param {number} max - greatest seq ID in loaded range.\n * @param {boolean} newer - if true, check for newer messages only.\n * @returns {Array.true if message was cancelled, false otherwise.\n */\n cancelSend(seqId) {\n const idx = this._messages.find({\n seq: seqId\n });\n if (idx >= 0) {\n const msg = this._messages.getAt(idx);\n const status = this.msgStatus(msg);\n if (status == Const.MESSAGE_STATUS_QUEUED ||\n status == Const.MESSAGE_STATUS_FAILED ||\n status == Const.MESSAGE_STATUS_FATAL) {\n this._tinode._db.remMessages(this.name, seqId);\n msg._cancelled = true;\n this._messages.delAt(idx);\n if (this.onData) {\n // Calling with no parameters to indicate the message was deleted.\n this.onData();\n }\n return true;\n }\n }\n return false;\n }\n /**\n * Get type of the topic: me, p2p, grp, fnd...\n * @memberof Tinode.Topic#\n *\n * @returns {string} One of 'me', 'p2p', 'grp', 'fnd', 'sys' or undefined.\n */\n getType() {\n return Topic.topicType(this.name);\n }\n /**\n * Get current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.AccessMode} - user's access mode\n */\n getAccessMode() {\n return this.acs;\n }\n /**\n * Set current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @param {AccessMode | Object} acs - access mode to set.\n */\n setAccessMode(acs) {\n return this.acs = new AccessMode(acs);\n }\n /**\n * Get topic's default access mode.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.DefAcs} - access mode, such as {auth: `RWP`, anon: `N`}.\n */\n getDefaultAccess() {\n return this.defacs;\n }\n /**\n * Initialize new meta {@link Tinode.GetQuery} builder. The query is attched to the current topic.\n * It will not work correctly if used with a different topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.MetaGetBuilder} query attached to the current topic.\n */\n startMetaQuery() {\n return new MetaGetBuilder(this);\n }\n /**\n * Check if topic is archived, i.e. private.arch == true.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is archived, false otherwise.\n */\n isArchived() {\n return this.private && !!this.private.arch;\n }\n /**\n * Check if topic is a 'me' topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a 'me' topic, false otherwise.\n */\n isMeType() {\n return Topic.isMeTopicName(this.name);\n }\n /**\n * Check if topic is a channel.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a channel, false otherwise.\n */\n isChannelType() {\n return Topic.isChannelTopicName(this.name);\n }\n /**\n * Check if topic is a group topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a group, false otherwise.\n */\n isGroupType() {\n return Topic.isGroupTopicName(this.name);\n }\n /**\n * Check if topic is a p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p topic, false otherwise.\n */\n isP2PType() {\n return Topic.isP2PTopicName(this.name);\n }\n /**\n * Check if topic is a communication topic, i.e. a group or p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p or group topic, false otherwise.\n */\n isCommType() {\n return Topic.isCommTopicName(this.name);\n }\n /**\n * Get status (queued, sent, received etc) of a given message in the context\n * of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {Message} msg - message to check for status.\n * @param {boolean} upd - update chached message status.\n *\n * @returns message status constant.\n */\n msgStatus(msg, upd) {\n let status = Const.MESSAGE_STATUS_NONE;\n if (this._tinode.isMe(msg.from)) {\n if (msg._sending) {\n status = Const.MESSAGE_STATUS_SENDING;\n } else if (msg._fatal || msg._cancelled) {\n status = Const.MESSAGE_STATUS_FATAL;\n } else if (msg._failed) {\n status = Const.MESSAGE_STATUS_FAILED;\n } else if (msg.seq >= Const.LOCAL_SEQID) {\n status = Const.MESSAGE_STATUS_QUEUED;\n } else if (this.msgReadCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_READ;\n } else if (this.msgRecvCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_RECEIVED;\n } else if (msg.seq > 0) {\n status = Const.MESSAGE_STATUS_SENT;\n }\n } else {\n status = Const.MESSAGE_STATUS_TO_ME;\n }\n\n if (upd && msg._status != status) {\n msg._status = status;\n this._tinode._db.updMessageStatus(this.name, msg.seq, status);\n }\n\n return status;\n }\n\n // If msg is a replacement for another message, save the msg in the message versions cache\n // as a newer version for the message it's supposed to replace.\n _maybeUpdateMessageVersionsCache(msg) {\n if (!Topic.#isReplacementMsg(msg)) {\n // Check if this message is the original in the chain of edits and if so\n // ensure all version have the same sender.\n if (this._messageVersions[msg.seq]) {\n // Remove versions with different 'from'.\n this._messageVersions[msg.seq].filter(version => version.from == msg.from);\n if (this._messageVersions[msg.seq].isEmpty()) {\n delete this._messageVersions[msg.seq];\n }\n }\n return;\n }\n\n const targetSeq = parseInt(msg.head.replace.split(':')[1]);\n if (targetSeq > msg.seq) {\n // Substitutes are supposed to have higher seq ids.\n return;\n }\n const targetMsg = this.findMessage(targetSeq);\n if (targetMsg && targetMsg.from != msg.from) {\n // Substitute cannot change the sender.\n return;\n }\n const versions = this._messageVersions[targetSeq] || new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n versions.put(msg);\n this._messageVersions[targetSeq] = versions;\n }\n\n // Process data message\n _routeData(data) {\n if (data.content) {\n if (!this.touched || this.touched < data.ts) {\n this.touched = data.ts;\n this._tinode._db.updTopic(this);\n }\n }\n\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n this.msgStatus(data, true);\n // Ackn receiving the message.\n clearTimeout(this._recvNotificationTimer);\n this._recvNotificationTimer = setTimeout(_ => {\n this._recvNotificationTimer = null;\n this.noteRecv(this._maxSeq);\n }, Const.RECV_TIMEOUT);\n }\n\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n\n const outgoing = ((!this.isChannelType() && !data.from) || this._tinode.isMe(data.from));\n\n if (data.head && data.head.webrtc && data.head.mime == Drafty.getContentType() && data.content) {\n // Rewrite VC body with info from the headers.\n data.content = Drafty.updateVideoCall(data.content, {\n state: data.head.webrtc,\n duration: data.head['webrtc-duration'],\n incoming: !outgoing,\n });\n }\n\n if (!data._noForwarding) {\n this._messages.put(data);\n this._tinode._db.addMessage(data);\n this._maybeUpdateMessageVersionsCache(data);\n }\n\n if (this.onData) {\n this.onData(data);\n }\n\n // Update locally cached contact with the new message count.\n const what = outgoing ? 'read' : 'msg';\n this._updateReadRecv(what, data.seq, data.ts);\n // Notify 'me' listeners of the change.\n this._tinode.getMeTopic()._refreshContact(what, this);\n }\n\n // Process metadata message\n _routeMeta(meta) {\n if (meta.desc) {\n this._processMetaDesc(meta.desc);\n }\n if (meta.sub && meta.sub.length > 0) {\n this._processMetaSub(meta.sub);\n }\n if (meta.del) {\n this._processDelMessages(meta.del.clear, meta.del.delseq);\n }\n if (meta.tags) {\n this._processMetaTags(meta.tags);\n }\n if (meta.cred) {\n this._processMetaCreds(meta.cred);\n }\n if (meta.aux) {\n this._processMetaAux(meta.aux);\n }\n if (this.onMeta) {\n this.onMeta(meta);\n }\n }\n // Process presence change message\n _routePres(pres) {\n let user, uid;\n switch (pres.what) {\n case 'del':\n // Delete cached messages.\n this._processDelMessages(pres.clear, pres.delseq);\n break;\n case 'on':\n case 'off':\n // Update online status of a subscription.\n user = this._users[pres.src];\n if (user) {\n user.online = pres.what == 'on';\n } else {\n this._tinode.logger(\"WARNING: Presence update for an unknown user\", this.name, pres.src);\n }\n break;\n case 'term':\n // Attachment to topic is terminated probably due to cluster rehashing.\n this._resetSub();\n break;\n case 'upd':\n // A topic subscriber has updated his description.\n // Issue {get sub} only if the current user has no p2p topics with the updated user (p2p name is not in cache).\n // Otherwise 'me' will issue a {get desc} request.\n if (pres.src && !this._tinode.isTopicCached(pres.src)) {\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n }\n break;\n case 'aux':\n // Auxiliary data updated.\n this.getMeta(this.startMetaQuery().withAux().build());\n break;\n case 'acs':\n uid = pres.src || this._tinode.getCurrentUserID();\n user = this._users[uid];\n if (!user) {\n // Update for an unknown user: notification of a new subscription.\n const acs = new AccessMode().updateAll(pres.dacs);\n if (acs && acs.mode != AccessMode._NONE) {\n user = this._cacheGetUser(uid);\n if (!user) {\n user = {\n user: uid,\n acs: acs\n };\n this.getMeta(this.startMetaQuery().withOneSub(undefined, uid).build());\n } else {\n user.acs = acs;\n }\n user.updated = new Date();\n this._processMetaSub([user]);\n }\n } else {\n // Known user\n user.acs.updateAll(pres.dacs);\n // Update user's access mode.\n this._processMetaSub([{\n user: uid,\n updated: new Date(),\n acs: user.acs\n }]);\n }\n break;\n default:\n this._tinode.logger(\"INFO: Ignored presence update\", pres.what);\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n // Process {info} message\n _routeInfo(info) {\n switch (info.what) {\n case 'recv':\n case 'read':\n const user = this._users[info.from];\n if (user) {\n user[info.what] = info.seq;\n if (user.recv < user.read) {\n user.recv = user.read;\n }\n }\n const msg = this.latestMessage();\n if (msg) {\n this.msgStatus(msg, true);\n }\n\n // If this is an update from the current user, update the cache with the new count.\n if (this._tinode.isMe(info.from)) {\n this._updateReadRecv(info.what, info.seq);\n }\n\n // Notify 'me' listener of the status change.\n this._tinode.getMeTopic()._refreshContact(info.what, this);\n break;\n case 'kp':\n // Do nothing.\n break;\n case 'call':\n // Do nothing here.\n break;\n default:\n this._tinode.logger(\"INFO: Ignored info update\", info.what);\n }\n\n if (this.onInfo) {\n this.onInfo(info);\n }\n }\n // Called by Tinode when meta.desc packet is received.\n // Called by 'me' topic on contact update (desc._noForwarding is true).\n _processMetaDesc(desc) {\n if (this.isP2PType()) {\n // Synthetic desc may include defacs for p2p topics which is useless.\n // Remove it.\n delete desc.defacs;\n\n // Update to p2p desc is the same as user update. Update cached user.\n this._tinode._db.updUser(this.name, desc.public);\n }\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n // Update persistent cache.\n this._tinode._db.updTopic(this);\n\n // Notify 'me' listener, if available:\n if (this.name !== Const.TOPIC_ME && !desc._noForwarding) {\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n // Called by Tinode when meta.sub is recived or in response to received\n // {ctrl} after setMeta-sub.\n _processMetaSub(subs) {\n for (let idx in subs) {\n const sub = subs[idx];\n\n // Fill defaults.\n sub.online = !!sub.online;\n // Update timestamp of the most recent subscription update.\n this._lastSubsUpdate = new Date(Math.max(this._lastSubsUpdate, sub.updated));\n\n let user = null;\n if (!sub.deleted) {\n // If this is a change to user's own permissions, update them in topic too.\n // Desc will update 'me' topic.\n if (this._tinode.isMe(sub.user) && sub.acs) {\n this._processMetaDesc({\n updated: sub.updated,\n touched: sub.touched,\n acs: sub.acs\n });\n }\n user = this._updateCachedUser(sub.user, sub);\n } else {\n // Subscription is deleted, remove it from topic (but leave in Users cache)\n delete this._users[sub.user];\n user = sub;\n }\n\n if (this.onMetaSub) {\n this.onMetaSub(user);\n }\n }\n\n if (this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._users));\n }\n }\n // Called by Tinode when meta.tags is recived.\n _processMetaTags(tags) {\n if (tags == Const.DEL_CHAR || (tags.length == 1 && tags[0] == Const.DEL_CHAR)) {\n tags = [];\n }\n this._tags = tags;\n this._tinode._db.updTopic(this);\n if (this.onTagsUpdated) {\n this.onTagsUpdated(tags);\n }\n }\n // Do nothing for topics other than 'me'\n _processMetaCreds(creds) {}\n\n // Called by Tinode when meta.aux is recived.\n _processMetaAux(aux) {\n aux = (!aux || aux == Const.DEL_CHAR) ? {} : aux;\n this._aux = mergeObj(this._aux, aux);\n this._tinode._db.updTopic(this);\n if (this.onAuxUpdated) {\n this.onAuxUpdated(this._aux);\n }\n }\n\n // Delete cached messages and update cached transaction IDs\n _processDelMessages(clear, delseq) {\n this._maxDel = Math.max(clear, this._maxDel);\n this.clear = Math.max(clear, this.clear);\n let count = 0;\n if (Array.isArray(delseq)) {\n delseq.forEach(rec => {\n if (!rec.hi) {\n count++;\n this.flushMessage(rec.low);\n } else {\n count += rec.hi - rec.low;\n this.flushMessageRange(rec.low, rec.hi);\n }\n this._messages.put({\n seq: rec.low,\n low: rec.low,\n hi: rec.hi,\n _deleted: true\n });\n });\n\n this._tinode._db.addDelLog(this.name, clear, delseq);\n }\n\n if (count > 0) {\n if (this.onData) {\n this.onData();\n }\n }\n }\n // Topic is informed that the entire response to {get what=data} has been received.\n _allMessagesReceived(count) {\n\n if (this.onAllMessagesReceived) {\n this.onAllMessagesReceived(count);\n }\n }\n // Reset subscribed state\n _resetSub() {\n this._attached = false;\n }\n // This topic is either deleted or unsubscribed from.\n _gone() {\n this._messages.reset();\n this._tinode._db.remMessages(this.name);\n this._users = {};\n this.acs = new AccessMode(null);\n this.private = null;\n this.public = null;\n this.trusted = null;\n this._maxSeq = 0;\n this._minSeq = 0;\n this._attached = false;\n\n const me = this._tinode.getMeTopic();\n if (me) {\n me._routePres({\n _noForwarding: true,\n what: 'gone',\n topic: Const.TOPIC_ME,\n src: this.name\n });\n }\n if (this.onDeleteTopic) {\n this.onDeleteTopic();\n }\n }\n // Update global user cache and local subscribers cache.\n // Don't call this method for non-subscribers.\n _updateCachedUser(uid, obj) {\n // Fetch user object from the global cache.\n // This is a clone of the stored object\n let cached = this._cacheGetUser(uid);\n cached = mergeObj(cached || {}, obj);\n // Save to global cache\n this._cachePutUser(uid, cached);\n // Save to the list of topic subsribers.\n return mergeToCache(this._users, uid, cached);\n }\n // Get local seqId for a queued message.\n _getQueuedSeqId() {\n return this._queuedSeqId++;\n }\n\n // Load most recent messages from persistent cache.\n _loadMessages(db, query) {\n query = query || {};\n query.limit = query.limit || Const.DEFAULT_MESSAGES_PAGE;\n\n // Count of message loaded from DB.\n let count = 0;\n return db.readMessages(this.name, query)\n .then(msgs => {\n msgs.forEach(data => {\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n }\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n this._messages.put(data);\n this._maybeUpdateMessageVersionsCache(data);\n });\n count = msgs.length;\n })\n .then(_ => db.readDelLog(this.name, query))\n .then(dellog => {\n return dellog.forEach(rec => {\n this._messages.put({\n seq: rec.low,\n low: rec.low,\n hi: rec.hi,\n _deleted: true\n });\n });\n })\n .then(_ => {\n // DEBUG\n return count;\n });\n }\n\n // Push or {pres}: message received.\n _updateReceived(seq, act) {\n this.touched = new Date();\n this.seq = seq | 0;\n // Check if message is sent by the current user. If so it's been read already.\n if (!act || this._tinode.isMe(act)) {\n this.read = this.read ? Math.max(this.read, this.seq) : this.seq;\n this.recv = this.recv ? Math.max(this.read, this.recv) : this.read;\n }\n this.unread = this.seq - (this.read | 0);\n this._tinode._db.updTopic(this);\n }\n}\n","/**\n * @file Utilities used in multiple places.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport {\n DEL_CHAR,\n LOCAL_SEQID\n} from './config.js';\n\n// Attempt to convert date and AccessMode strings to objects.\nexport function jsonParseHelper(key, val) {\n // Try to convert string timestamps with optional milliseconds to Date,\n // e.g. 2015-09-02T01:45:43[.123]Z\n if (typeof val == 'string' && val.length >= 20 && val.length <= 24 && ['ts', 'touched', 'updated', 'created', 'when', 'deleted', 'expires'].includes(key)) {\n const date = new Date(val);\n if (!isNaN(date)) {\n return date;\n }\n } else if (key === 'acs' && typeof val === 'object') {\n return new AccessMode(val);\n }\n return val;\n}\n\n// Checks if URL is a relative url, i.e. has no 'scheme://', including the case of missing scheme '//'.\n// The scheme is expected to be RFC-compliant, e.g. [a-z][a-z0-9+.-]*\n// example.html - ok\n// https:example.com - not ok.\n// http:/example.com - not ok.\n// ' ↲ https://example.com' - not ok. (↲ means carriage return)\nexport function isUrlRelative(url) {\n return url && !/^\\s*([a-z][a-z0-9+.-]*:|\\/\\/)/im.test(url);\n}\n\nfunction isValidDate(d) {\n return (d instanceof Date) && !isNaN(d) && (d.getTime() != 0);\n}\n\n// RFC3339 formater of Date\nexport function rfc3339DateString(d) {\n if (!isValidDate(d)) {\n return undefined;\n }\n\n const pad = function(val, sp) {\n sp = sp || 2;\n return '0'.repeat(sp - ('' + val).length) + val;\n };\n\n const millis = d.getUTCMilliseconds();\n return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) +\n 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) +\n (millis ? '.' + pad(millis, 3) : '') + 'Z';\n}\n\n// Recursively merge src's own properties to dst.\n// Ignore properties where ignore[property] is true.\n// Array and Date objects are shallow-copied.\nexport function mergeObj(dst, src, ignore) {\n if (typeof src != 'object') {\n if (src === undefined) {\n return dst;\n }\n if (src === DEL_CHAR) {\n return undefined;\n }\n return src;\n }\n // JS is crazy: typeof null is 'object'.\n if (src === null) {\n return src;\n }\n\n // Handle Date\n if (src instanceof Date && !isNaN(src)) {\n return (!dst || !(dst instanceof Date) || isNaN(dst) || dst < src) ? src : dst;\n }\n\n // Access mode\n if (src instanceof AccessMode) {\n return new AccessMode(src);\n }\n\n // Handle Array\n if (src instanceof Array) {\n return src;\n }\n\n if (!dst || dst === DEL_CHAR) {\n dst = src.constructor();\n }\n\n for (let prop in src) {\n if (src.hasOwnProperty(prop) && (!ignore || !ignore[prop]) && (prop != '_noForwarding')) {\n try {\n dst[prop] = mergeObj(dst[prop], src[prop]);\n } catch (err) {\n // FIXME: probably need to log something here.\n }\n }\n }\n return dst;\n}\n\n// Update object stored in a cache. Returns updated value.\nexport function mergeToCache(cache, key, newval, ignore) {\n cache[key] = mergeObj(cache[key], newval, ignore);\n return cache[key];\n}\n\n// Strips all values from an object of they evaluate to false or if their name starts with '_'.\n// Used on all outgoing object before serialization to string.\nexport function simplify(obj) {\n Object.keys(obj).forEach((key) => {\n if (key[0] == '_') {\n // Strip fields like \"obj._key\".\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (Array.isArray(obj[key]) && obj[key].length == 0) {\n // Strip empty arrays.\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (obj[key] instanceof Date) {\n // Strip invalid or zero date.\n if (!isValidDate(obj[key])) {\n delete obj[key];\n }\n } else if (typeof obj[key] == 'object') {\n simplify(obj[key]);\n // Strip empty objects.\n if (Object.getOwnPropertyNames(obj[key]).length == 0) {\n delete obj[key];\n }\n }\n });\n return obj;\n};\n\n\n// Trim whitespace, strip empty and duplicate elements elements.\n// If the result is an empty array, add a single element \"\\u2421\" (Unicode Del character).\nexport function normalizeArray(arr) {\n let out = [];\n if (Array.isArray(arr)) {\n // Trim, throw away very short and empty tags.\n for (let i = 0, l = arr.length; i < l; i++) {\n let t = arr[i];\n if (t) {\n t = t.trim().toLowerCase();\n if (t.length > 1) {\n out.push(t);\n }\n }\n }\n out.sort().filter((item, pos, ary) => {\n return !pos || item != ary[pos - 1];\n });\n }\n if (out.length == 0) {\n // Add single tag with a Unicode Del character, otherwise an ampty array\n // is ambiguos. The Del tag will be stripped by the server.\n out.push(DEL_CHAR);\n }\n return out;\n}\n\n// Convert input to valid ranges of IDs.\nexport function normalizeRanges(ranges, maxSeq) {\n if (!Array.isArray(ranges)) {\n return [];\n }\n\n // Sort ranges in accending order by low, then descending by hi.\n ranges.sort((r1, r2) => {\n if (r1.low < r2.low) {\n return true;\n }\n if (r1.low == r2.low) {\n return !r2.hi || (r1.hi >= r2.hi);\n }\n return false;\n });\n\n // Remove pending messages from ranges possibly clipping some ranges.\n return ranges.reduce((out, r) => {\n if (r.low < LOCAL_SEQID && r.low > 0) {\n if (!r.hi || r.hi < LOCAL_SEQID) {\n out.push(r);\n } else {\n // Clip hi to max allowed value.\n out.push({\n low: r.low,\n hi: maxSeq + 1\n });\n }\n }\n return out;\n }, []);\n}\n\n// Convert array of IDs to array of ranges.\nexport function listToRanges(list) {\n // Sort the list in ascending order\n list.sort((a, b) => a - b);\n // Convert the array of IDs to ranges.\n return list.reduce((out, id) => {\n if (out.length == 0) {\n // First element.\n out.push({\n low: id\n });\n } else {\n let prev = out[out.length - 1];\n if ((!prev.hi && (id != prev.low + 1)) || (id > prev.hi)) {\n // New range.\n out.push({\n low: id\n });\n } else {\n // Expand existing range.\n prev.hi = prev.hi ? Math.max(prev.hi, id + 1) : id + 1;\n }\n }\n return out;\n }, []);\n}\n\n// Cuts 'clip' range out of the 'src' range.\n// Returns an array with 0, 1 or 2 elements.\nexport function clipRange(src, clip) {\n if (clip.hi < src.low || clip.low >= src.hi) {\n // Clip is completely outside of src, no intersection.\n return [src];\n }\n\n if (clip.low <= src.low) {\n if (clip.hi >= src.hi) {\n // The source range is completely inside the clipping range.\n return [];\n }\n // Partial clipping at the top.\n return [{\n low: src.low,\n hi: clip.hi\n }];\n }\n\n // Range on the lower end.\n const result = [{\n low: src.low,\n hi: clip.low\n }];\n if (clip.hi < src.hi) {\n // Maybe a range on the higher end, if clip is completely inside the source.\n result.push({\n low: clip.hi,\n hi: src.hi\n });\n }\n\n return result;\n}\n","export const PACKAGE_VERSION = \"0.23.0-rc1\";\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * @module tinode-sdk\n *\n * @copyright 2015-2022 Tinode LLC.\n * @summary Javascript bindings for Tinode.\n * @license Apache 2.0\n * @version 0.20\n *\n * See https://github.com/tinode/webapp for real-life usage.\n *\n * @example\n * \n * \n * \n *\n * \n * ...\n * \n * \n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nimport AccessMode from './access-mode.js';\nimport * as Const from './config.js';\nimport CommError from './comm-error.js';\nimport Connection from './connection.js';\nimport DBCache from './db.js';\nimport Drafty from './drafty.js';\nimport LargeFileHelper from './large-file.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport Topic from './topic.js';\nimport TopicFnd from './fnd-topic.js';\nimport TopicMe from './me-topic.js';\n\nimport {\n isUrlRelative,\n jsonParseHelper,\n mergeObj,\n rfc3339DateString,\n simplify\n} from './utils.js';\n\n// Re-export AccessMode\nexport {\n AccessMode\n};\n\nlet WebSocketProvider;\nif (typeof WebSocket != 'undefined') {\n WebSocketProvider = WebSocket;\n}\n\nlet XHRProvider;\nif (typeof XMLHttpRequest != 'undefined') {\n XHRProvider = XMLHttpRequest;\n}\n\nlet IndexedDBProvider;\nif (typeof indexedDB != 'undefined') {\n IndexedDBProvider = indexedDB;\n}\n\n// Re-export Drafty.\nexport {\n Drafty\n}\n\ninitForNonBrowserApp();\n\n// Utility functions\n\n// Polyfill for non-browser context, e.g. NodeJs.\nfunction initForNonBrowserApp() {\n // Tinode requirement in native mode because react native doesn't provide Base64 method\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\n if (typeof btoa == 'undefined') {\n global.btoa = function(input = '') {\n let str = input;\n let output = '';\n\n for (let block = 0, charCode, i = 0, map = chars; str.charAt(i | 0) || (map = '=', i % 1); output += map.charAt(63 & block >> 8 - i % 1 * 8)) {\n\n charCode = str.charCodeAt(i += 3 / 4);\n\n if (charCode > 0xFF) {\n throw new Error(\"'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.\");\n }\n block = block << 8 | charCode;\n }\n\n return output;\n };\n }\n\n if (typeof atob == 'undefined') {\n global.atob = function(input = '') {\n let str = input.replace(/=+$/, '');\n let output = '';\n\n if (str.length % 4 == 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (let bc = 0, bs = 0, buffer, i = 0; buffer = str.charAt(i++);\n\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n }\n\n if (typeof window == 'undefined') {\n global.window = {\n WebSocket: WebSocketProvider,\n XMLHttpRequest: XHRProvider,\n indexedDB: IndexedDBProvider,\n URL: {\n createObjectURL: function() {\n throw new Error(\"Unable to use URL.createObjectURL in a non-browser application\");\n }\n }\n }\n }\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n DBCache.setDatabaseProvider(IndexedDBProvider);\n}\n\n// Detect find most useful network transport.\nfunction detectTransport() {\n if (typeof window == 'object') {\n if (window['WebSocket']) {\n return 'ws';\n } else if (window['XMLHttpRequest']) {\n // The browser or node has no websockets, using long polling.\n return 'lp';\n }\n }\n return null;\n}\n\n// btoa replacement. Stock btoa fails on on non-Latin1 strings.\nfunction b64EncodeUnicode(str) {\n // The encodeURIComponent percent-encodes UTF-8 string,\n // then the percent encoding is converted into raw bytes which\n // can be fed into btoa.\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,\n function toSolidBytes(match, p1) {\n return String.fromCharCode('0x' + p1);\n }));\n}\n\n// JSON stringify helper - pre-processor for JSON.stringify\nfunction jsonBuildHelper(key, val) {\n if (val instanceof Date) {\n // Convert javascript Date objects to rfc3339 strings\n val = rfc3339DateString(val);\n } else if (val instanceof AccessMode) {\n val = val.jsonHelper();\n } else if (val === undefined || val === null || val === false ||\n (Array.isArray(val) && val.length == 0) ||\n ((typeof val == 'object') && (Object.keys(val).length == 0))) {\n // strip out empty elements while serializing objects to JSON\n return undefined;\n }\n\n return val;\n};\n\n// Trims very long strings (encoded images) to make logged packets more readable.\nfunction jsonLoggerHelper(key, val) {\n if (typeof val == 'string' && val.length > 128) {\n return '<' + val.length + ', bytes: ' + val.substring(0, 12) + '...' + val.substring(val.length - 12) + '>';\n }\n return jsonBuildHelper(key, val);\n};\n\n// Parse browser user agent to extract browser name and version.\nfunction getBrowserInfo(ua, product) {\n ua = ua || '';\n let reactnative = '';\n // Check if this is a ReactNative app.\n if (/reactnative/i.test(product)) {\n reactnative = 'ReactNative; ';\n }\n let result;\n // Remove useless string.\n ua = ua.replace(' (KHTML, like Gecko)', '');\n // Test for WebKit-based browser.\n let m = ua.match(/(AppleWebKit\\/[.\\d]+)/i);\n if (m) {\n // List of common strings, from more useful to less useful.\n // All unknown strings get the highest (-1) priority.\n const priority = ['edg', 'chrome', 'safari', 'mobile', 'version'];\n let tmp = ua.substr(m.index + m[0].length).split(' ');\n let tokens = [];\n let version; // 1.0 in Version/1.0 or undefined;\n // Split string like 'Name/0.0.0' into ['Name', '0.0.0', 3] where the last element is the priority.\n for (let i = 0; i < tmp.length; i++) {\n let m2 = /([\\w.]+)[\\/]([\\.\\d]+)/.exec(tmp[i]);\n if (m2) {\n // Unknown values are highest priority (-1).\n tokens.push([m2[1], m2[2], priority.findIndex((e) => {\n return m2[1].toLowerCase().startsWith(e);\n })]);\n if (m2[1] == 'Version') {\n version = m2[2];\n }\n }\n }\n // Sort by priority: more interesting is earlier than less interesting.\n tokens.sort((a, b) => {\n return a[2] - b[2];\n });\n if (tokens.length > 0) {\n // Return the least common browser string and version.\n if (tokens[0][0].toLowerCase().startsWith('edg')) {\n tokens[0][0] = 'Edge';\n } else if (tokens[0][0] == 'OPR') {\n tokens[0][0] = 'Opera';\n } else if (tokens[0][0] == 'Safari' && version) {\n tokens[0][1] = version;\n }\n result = tokens[0][0] + '/' + tokens[0][1];\n } else {\n // Failed to ID the browser. Return the webkit version.\n result = m[1];\n }\n } else if (/firefox/i.test(ua)) {\n m = /Firefox\\/([.\\d]+)/g.exec(ua);\n if (m) {\n result = 'Firefox/' + m[1];\n } else {\n result = 'Firefox/?';\n }\n } else {\n // Neither AppleWebKit nor Firefox. Try the last resort.\n m = /([\\w.]+)\\/([.\\d]+)/.exec(ua);\n if (m) {\n result = m[1] + '/' + m[2];\n } else {\n m = ua.split(' ');\n result = m[0];\n }\n }\n\n // Shorten the version to one dot 'a.bb.ccc.d -> a.bb' at most.\n m = result.split('/');\n if (m.length > 1) {\n const v = m[1].split('.');\n const minor = v[1] ? '.' + v[1].substr(0, 2) : '';\n result = `${m[0]}/${v[0]}${minor}`;\n }\n return reactnative + result;\n}\n\n/**\n * The main class for interacting with Tinode server.\n */\nexport class Tinode {\n _host;\n _secure;\n\n _appName;\n\n // API Key.\n _apiKey;\n\n // Name and version of the browser.\n _browser = '';\n _platform;\n // Hardware\n _hwos = 'undefined';\n _humanLanguage = 'xx';\n\n // Logging to console enabled\n _loggingEnabled = false;\n // When logging, trip long strings (base64-encoded images) for readability\n _trimLongStrings = false;\n // UID of the currently authenticated user.\n _myUID = null;\n // Status of connection: authenticated or not.\n _authenticated = false;\n // Login used in the last successful basic authentication\n _login = null;\n // Token which can be used for login instead of login/password.\n _authToken = null;\n // Counter of received packets\n _inPacketCount = 0;\n // Counter for generating unique message IDs\n _messageId = Math.floor((Math.random() * 0xFFFF) + 0xFFFF);\n // Information about the server, if connected\n _serverInfo = null;\n // Push notification token. Called deviceToken for consistency with the Android SDK.\n _deviceToken = null;\n\n // Cache of pending promises by message id.\n _pendingPromises = {};\n // The Timeout object returned by the reject expired promises setInterval.\n _expirePromises = null;\n\n // Websocket or long polling connection.\n _connection = null;\n\n // Use indexDB for caching topics and messages.\n _persist = false;\n // IndexedDB wrapper object.\n _db = null;\n\n // Tinode's cache of objects\n _cache = {};\n\n /**\n * Create Tinode object.\n *\n * @param {Object} config - configuration parameters.\n * @param {string} config.appName - Name of the calling application to be reported in the User Agent.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - See {@link Tinode.Connection#transport}.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} config.platform - Optional platform identifier, one of \"ios\", \"web\", \"android\".\n * @param {boolen} config.persist - Use IndexedDB persistent storage.\n * @param {function} onComplete - callback to call when initialization is completed.\n */\n constructor(config, onComplete) {\n this._host = config.host;\n this._secure = config.secure;\n\n // Client-provided application name, format null if no valid credentials were given.\n */\n static credential(meth, val, params, resp) {\n if (typeof meth == 'object') {\n ({\n val,\n params,\n resp,\n meth\n } = meth);\n }\n if (meth && (val || resp)) {\n return [{\n 'meth': meth,\n 'val': val,\n 'resp': resp,\n 'params': params\n }];\n }\n return null;\n }\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n return Topic.topicType(name);\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.isMeTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a group topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.isGroupTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.isP2PTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isCommTopicName(name);\n }\n /**\n * Check if the topic name is a name of a new topic.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return Topic.isNewGroupTopicName(name);\n }\n /**\n * Check if the topic name is a name of a channel.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return Topic.isChannelTopicName(name);\n }\n /**\n * Get information about the current version of this Tinode client library.\n * @returns {string} semantic version of the library, e.g. \"0.15.5-rc1\".\n */\n static getVersion() {\n return Const.VERSION;\n }\n /**\n * To use Tinode in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n *\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n }\n /**\n * To use Tinode in a non browser context, supply indexedDB provider.\n * @static\n *\n * @param idbProvider indexedDB provider, e.g. for nodeJS , require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IndexedDBProvider = idbProvider;\n\n DBCache.setDatabaseProvider(IndexedDBProvider);\n }\n /**\n * Return information about the current name and version of this Tinode library.\n * @static\n *\n * @returns {string} the name of the library and it's version.\n */\n static getLibrary() {\n return Const.LIBRARY;\n }\n /**\n * Check if the given string represents NULL value as defined by Tinode ('\\u2421').\n * @param {string} str - string to check for NULL value.\n * @returns {boolean} true if string represents NULL value, false otherwise.\n */\n static isNullValue(str) {\n return str === Const.DEL_CHAR;\n }\n\n // Instance methods.\n\n // Generates unique message IDs\n getNextUniqueId() {\n return (this._messageId != 0) ? '' + this._messageId++ : undefined;\n };\n\n /**\n * Connect to the server.\n *\n * @param {string} host_ - name of the host to connect to.\n * @return {Promise} Promise resolved/rejected when the connection call completes:\n * resolve() is called without parameters, reject() receives the\n * Error as a single parameter.\n */\n connect(host_) {\n return this._connection.connect(host_);\n }\n\n /**\n * Attempt to reconnect to the server immediately.\n *\n * @param {string} force - if true, reconnect even if there is a connection already.\n */\n reconnect(force) {\n this._connection.reconnect(force);\n }\n\n /**\n * Disconnect from the server.\n */\n disconnect() {\n this._connection.disconnect();\n }\n\n /**\n * Clear persistent cache: remove IndexedDB.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n clearStorage() {\n if (this._db.isReady()) {\n return this._db.deleteDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Initialize persistent cache: create IndexedDB cache.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n initStorage() {\n if (!this._db.isReady()) {\n return this._db.initDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Send a network probe message to make sure the connection is alive.\n */\n networkProbe() {\n this._connection.probe();\n }\n\n /**\n * Check for live connection to server.\n *\n * @returns {boolean} true if there is a live connection, false otherwise.\n */\n isConnected() {\n return this._connection.isConnected();\n }\n\n /**\n * Check if connection is authenticated (last login was successful).\n *\n * @returns {boolean} true if authenticated, false otherwise.\n */\n isAuthenticated() {\n return this._authenticated;\n }\n\n /**\n * Add API key and auth token to the relative URL making it usable for getting data\n * from the server in a simple HTTP GET request.\n *\n * @param {string} URL - URL to wrap.\n * @returns {string} URL with appended API key and token, if valid token is present.\n */\n authorizeURL(url) {\n if (typeof url != 'string') {\n return url;\n }\n\n if (isUrlRelative(url)) {\n // Fake base to make the relative URL parseable.\n const base = 'scheme://host/';\n const parsed = new URL(url, base);\n if (this._apiKey) {\n parsed.searchParams.append('apikey', this._apiKey);\n }\n if (this._authToken && this._authToken.token) {\n parsed.searchParams.append('auth', 'token');\n parsed.searchParams.append('secret', this._authToken.token);\n }\n // Convert back to string and strip fake base URL except for the root slash.\n url = parsed.toString().substring(base.length - 1);\n }\n return url;\n }\n\n /**\n * @typedef AccountParams\n * @type {Object}\n * @property {DefAcs=} defacs - Default access parameters for user's me topic.\n * @property {Object=} public - Public application-defined data exposed on me topic.\n * @property {Object=} private - Private application-defined data accessible on me topic.\n * @property {Object=} trusted - Trusted user data which can be set by a root user only.\n * @property {Array.me for authenticated users.\n * @property {string=} anon - Access mode for me for anonymous users.\n */\n\n /**\n * Create or update an account.\n *\n * @param {string} uid - User id to update\n * @param {string} scheme - Authentication scheme; \"basic\" and \"anonymous\" are the currently supported schemes.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n account(uid, scheme, secret, login, params) {\n const pkt = this.#initPacket('acc');\n pkt.acc.user = uid;\n pkt.acc.scheme = scheme;\n pkt.acc.secret = secret;\n // Log in to the new account using selected scheme\n pkt.acc.login = login;\n\n if (params) {\n pkt.acc.desc.defacs = params.defacs;\n pkt.acc.desc.public = params.public;\n pkt.acc.desc.private = params.private;\n pkt.acc.desc.trusted = params.trusted;\n\n pkt.acc.tags = params.tags;\n pkt.acc.cred = params.cred;\n\n pkt.acc.tmpscheme = params.scheme;\n pkt.acc.tmpsecret = params.secret;\n\n if (Array.isArray(params.attachments) && params.attachments.length > 0) {\n pkt.extra = {\n attachments: params.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n }\n\n return this.#send(pkt, pkt.acc.id);\n }\n\n /**\n * Create a new user. Wrapper for {@link Tinode#account}.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccount(scheme, secret, login, params) {\n let promise = this.account(Const.USER_NEW, scheme, secret, login, params);\n if (login) {\n promise = promise.then(ctrl => this.#loginSuccessful(ctrl));\n }\n return promise;\n }\n\n /**\n * Create user with 'basic' authentication scheme and immediately\n * use it for authentication. Wrapper for {@link Tinode#account}.\n *\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccountBasic(username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.createAccount('basic',\n b64EncodeUnicode(username + ':' + password), true, params);\n }\n\n /**\n * Update user's credentials for 'basic' authentication scheme. Wrapper for {@link Tinode#account}.\n *\n * @param {string} uid - User ID to update.\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n updateAccountBasic(uid, username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.account(uid, 'basic',\n b64EncodeUnicode(username + ':' + password), false, params);\n }\n\n /**\n * Send handshake to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n hello() {\n const pkt = this.#initPacket('hi');\n\n return this.#send(pkt, pkt.hi.id)\n .then(ctrl => {\n // Reset backoff counter on successful connection.\n this._connection.backoffReset();\n\n // Server response contains server protocol version, build, constraints,\n // session ID for long polling. Save them.\n if (ctrl.params) {\n this._serverInfo = ctrl.params;\n }\n\n if (this.onConnect) {\n this.onConnect();\n }\n\n return ctrl;\n }).catch(err => {\n this._connection.reconnect(true);\n\n if (this.onDisconnect) {\n this.onDisconnect(err);\n }\n });\n }\n\n /**\n * Set or refresh the push notifications/device token. If the client is connected,\n * the deviceToken can be sent to the server.\n *\n * @param {string} dt - token obtained from the provider or false,\n * null or undefined to clear the token.\n *\n * @returns true if attempt was made to send the update to the server.\n */\n setDeviceToken(dt) {\n let sent = false;\n // Convert any falsish value to null.\n dt = dt || null;\n if (dt != this._deviceToken) {\n this._deviceToken = dt;\n if (this.isConnected() && this.isAuthenticated()) {\n this.#send({\n 'hi': {\n 'dev': dt || Tinode.DEL_CHAR\n }\n });\n sent = true;\n }\n }\n return sent;\n }\n\n /**\n * @typedef Credential\n * @type {Object}\n * @property {string} meth - validation method.\n * @property {string} val - value to validate (e.g. email or phone number).\n * @property {string} resp - validation response.\n * @property {Object} params - validation parameters.\n */\n /**\n * Authenticate current session.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n login(scheme, secret, cred) {\n const pkt = this.#initPacket('login');\n pkt.login.scheme = scheme;\n pkt.login.secret = secret;\n pkt.login.cred = cred;\n\n return this.#send(pkt, pkt.login.id)\n .then(ctrl => this.#loginSuccessful(ctrl));\n }\n\n /**\n * Wrapper for {@link Tinode#login} with basic authentication\n *\n * @param {string} uname - User name.\n * @param {string} password - Password.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginBasic(uname, password, cred) {\n return this.login('basic', b64EncodeUnicode(uname + ':' + password), cred)\n .then(ctrl => {\n this._login = uname;\n return ctrl;\n });\n }\n\n /**\n * Wrapper for {@link Tinode#login} with token authentication\n *\n * @param {string} token - Token received in response to earlier login.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginToken(token, cred) {\n return this.login('token', token, cred);\n }\n\n /**\n * Send a request for resetting an authentication secret.\n *\n * @param {string} scheme - authentication scheme to reset.\n * @param {string} method - method to use for resetting the secret, such as \"email\" or \"tel\".\n * @param {string} value - value of the credential to use, a specific email address or a phone number.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving the server reply.\n */\n requestResetAuthSecret(scheme, method, value) {\n return this.login('reset', b64EncodeUnicode(scheme + ':' + method + ':' + value));\n }\n\n /**\n * @typedef AuthToken\n * @type {Object}\n * @property {string} token - Token value.\n * @property {Date} expires - Token expiration time.\n */\n /**\n * Get stored authentication token.\n *\n * @returns {AuthToken} authentication token.\n */\n getAuthToken() {\n if (this._authToken && (this._authToken.expires.getTime() > Date.now())) {\n return this._authToken;\n } else {\n this._authToken = null;\n }\n return null;\n }\n\n /**\n * Application may provide a saved authentication token.\n *\n * @param {AuthToken} token - authentication token.\n */\n setAuthToken(token) {\n this._authToken = token;\n }\n\n /**\n * @typedef SetParams\n * @type {Object}\n * @property {SetDesc=} desc - Topic initialization parameters when creating a new topic or a new subscription.\n * @property {SetSub=} sub - Subscription initialization parameters.\n * @property {Array.true, detach and unsubscribe, otherwise just detach.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n leave(topic, unsub) {\n const pkt = this.#initPacket('leave', topic);\n pkt.leave.unsub = unsub;\n\n return this.#send(pkt, pkt.leave.id);\n }\n\n /**\n * Create message draft without sending it to the server.\n *\n * @param {string} topic - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Object} new message which can be sent to the server or otherwise used.\n */\n createMessage(topic, content, noEcho) {\n const pkt = this.#initPacket('pub', topic);\n\n let dft = typeof content == 'string' ? Drafty.parse(content) : content;\n if (dft && !Drafty.isPlainText(dft)) {\n pkt.pub.head = {\n mime: Drafty.getContentType()\n };\n content = dft;\n }\n pkt.pub.noecho = noEcho;\n pkt.pub.content = content;\n\n return pkt.pub;\n }\n\n /**\n * Publish {data} message to topic.\n *\n * @param {string} topicName - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n publish(topicName, content, noEcho) {\n return this.publishMessage(\n this.createMessage(topicName, content, noEcho)\n );\n }\n\n /**\n * Publish message to topic. The message should be created by {@link Tinode#createMessage}.\n *\n * @param {Object} pub - Message to publish.\n * @param {Array.'me' topic.\n *\n * @param {string} method - validation method such as 'email' or 'tel'.\n * @param {string} value - validation value, i.e. 'alice@example.com'.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n const pkt = this.#initPacket('del', Const.TOPIC_ME);\n pkt.del.what = 'cred';\n pkt.del.cred = {\n meth: method,\n val: value\n };\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Request to delete account of the current user.\n *\n * @param {boolean} hard - hard-delete user.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCurrentUser(hard) {\n const pkt = this.#initPacket('del', null);\n pkt.del.what = 'user';\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id).then(_ => {\n this._myUID = null;\n });\n }\n\n /**\n * Notify server that a message or messages were read or received. Does NOT return promise.\n *\n * @param {string} topicName - Name of the topic where the mesage is being aknowledged.\n * @param {string} what - Action being aknowledged, either \"read\" or \"recv\".\n * @param {number} seq - Maximum id of the message being acknowledged.\n */\n note(topicName, what, seq) {\n if (seq <= 0 || seq >= Const.LOCAL_SEQID) {\n throw new Error(`Invalid message id ${seq}`);\n }\n\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = what;\n pkt.note.seq = seq;\n this.#send(pkt);\n }\n\n /**\n * Broadcast a key-press notification to topic subscribers. Used to show\n * typing notifications \"user X is typing...\".\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {string=} type - notification to send, default is 'kp'.\n */\n noteKeyPress(topicName, type) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = type || 'kp';\n this.#send(pkt);\n }\n\n /**\n * Send a video call notification to topic subscribers (including dialing,\n * hangup, etc.).\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} evt - Call event.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(topicName, seq, evt, payload) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.seq = seq;\n pkt.note.what = 'call';\n pkt.note.event = evt;\n pkt.note.payload = payload;\n this.#send(pkt, pkt.note.id);\n }\n\n /**\n * Get a named topic, either pull it from cache or create a new instance.\n * There is a single instance of topic for each name.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested or newly created topic or undefined if topic name is invalid.\n */\n getTopic(topicName) {\n let topic = this.#cacheGet('topic', topicName);\n if (!topic && topicName) {\n if (topicName == Const.TOPIC_ME) {\n topic = new TopicMe();\n } else if (topicName == Const.TOPIC_FND) {\n topic = new TopicFnd();\n } else {\n topic = new Topic(topicName);\n }\n // Cache management.\n this.#attachCacheToTopic(topic);\n topic._cachePutSelf();\n // Don't save to DB here: a record will be added when the topic is subscribed.\n }\n return topic;\n }\n\n /**\n * Get a named topic from cache.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested topic or undefined if topic is not found in cache.\n */\n cacheGetTopic(topicName) {\n return this.#cacheGet('topic', topicName);\n }\n\n /**\n * Remove named topic from cache.\n *\n * @param {string} topicName - Name of the topic to remove from cache.\n */\n cacheRemTopic(topicName) {\n this.#cacheDel('topic', topicName);\n }\n\n /**\n * Iterate over cached topics.\n *\n * @param {Function} func - callback to call for each topic.\n * @param {Object} context - 'this' inside the 'func'.\n */\n mapTopics(func, context) {\n this.#cacheMap('topic', func, context);\n }\n\n /**\n * Check if named topic is already present in cache.\n *\n * @param {string} topicName - Name of the topic to check.\n * @returns {boolean} true if topic is found in cache, false otherwise.\n */\n isTopicCached(topicName) {\n return !!this.#cacheGet('topic', topicName);\n }\n\n /**\n * Generate unique name like 'new123456' suitable for creating a new group topic.\n *\n * @param {boolean} isChan - if the topic is channel-enabled.\n * @returns {string} name which can be used for creating a new group topic.\n */\n newGroupTopicName(isChan) {\n return (isChan ? Const.TOPIC_NEW_CHAN : Const.TOPIC_NEW) + this.getNextUniqueId();\n }\n\n /**\n * Instantiate 'me' topic or get it from cache.\n *\n * @returns {TopicMe} Instance of 'me' topic.\n */\n getMeTopic() {\n return this.getTopic(Const.TOPIC_ME);\n }\n\n /**\n * Instantiate 'fnd' (find) topic or get it from cache.\n *\n * @returns {Topic} Instance of 'fnd' topic.\n */\n getFndTopic() {\n return this.getTopic(Const.TOPIC_FND);\n }\n\n /**\n * Create a new {@link LargeFileHelper} instance\n *\n * @returns {LargeFileHelper} instance of a {@link Tinode.LargeFileHelper}.\n */\n getLargeFileHelper() {\n return new LargeFileHelper(this, Const.PROTOCOL_VERSION);\n }\n\n /**\n * Get the UID of the the current authenticated user.\n *\n * @returns {string} UID of the current user or undefined if the session is not yet\n * authenticated or if there is no session.\n */\n getCurrentUserID() {\n return this._myUID;\n }\n\n /**\n * Check if the given user ID is equal to the current user's UID.\n *\n * @param {string} uid - UID to check.\n *\n * @returns {boolean} true if the given UID belongs to the current logged in user.\n */\n isMe(uid) {\n return this._myUID === uid;\n }\n\n /**\n * Get login used for last successful authentication.\n *\n * @returns {string} login last used successfully or undefined.\n */\n getCurrentLogin() {\n return this._login;\n }\n\n /**\n * Return information about the server: protocol version and build timestamp.\n *\n * @returns {Object} build and version of the server or null if there is no connection or\n * if the first server response has not been received yet.\n */\n getServerInfo() {\n return this._serverInfo;\n }\n\n /**\n * Report a topic for abuse. Wrapper for {@link Tinode#publish}.\n *\n * @param {string} action - the only supported action is 'report'.\n * @param {string} target - name of the topic being reported.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n report(action, target) {\n return this.publish(Const.TOPIC_SYS, Drafty.attachJSON(null, {\n 'action': action,\n 'target': target\n }));\n }\n\n /**\n * Return server-provided configuration value.\n *\n * @param {string} name of the value to return.\n * @param {Object} defaultValue to return in case the parameter is not set or not found.\n *\n * @returns {Object} named value.\n */\n getServerParam(name, defaultValue) {\n return this._serverInfo && this._serverInfo[name] || defaultValue;\n }\n\n /**\n * Toggle console logging. Logging is off by default.\n *\n * @param {boolean} enabled - Set to true to enable logging to console.\n * @param {boolean} trimLongStrings - Set to true to trim long strings.\n */\n enableLogging(enabled, trimLongStrings) {\n this._loggingEnabled = enabled;\n this._trimLongStrings = enabled && trimLongStrings;\n }\n\n /**\n * Set UI language to report to the server. Must be called before 'hi' is sent, otherwise it will not be used.\n *\n * @param {string} hl - human (UI) language, like \"en_US\" or \"zh-Hans\".\n */\n setHumanLanguage(hl) {\n if (hl) {\n this._humanLanguage = hl;\n }\n }\n\n /**\n * Check if given topic is online.\n *\n * @param {string} name of the topic to test.\n * @returns {boolean} true if topic is online, false otherwise.\n */\n isTopicOnline(name) {\n const topic = this.#cacheGet('topic', name);\n return topic && topic.online;\n }\n\n /**\n * Get access mode for the given contact.\n *\n * @param {string} name of the topic to query.\n * @returns {AccessMode} access mode if topic is found, null otherwise.\n */\n getTopicAccessMode(name) {\n const topic = this.#cacheGet('topic', name);\n return topic ? topic.acs : null;\n }\n\n /**\n * Include message ID into all subsequest messages to server instructin it to send aknowledgemens.\n * Required for promises to function. Default is \"on\".\n *\n * @param {boolean} status - Turn aknowledgemens on or off.\n * @deprecated\n */\n wantAkn(status) {\n if (status) {\n this._messageId = Math.floor((Math.random() * 0xFFFFFF) + 0xFFFFFF);\n } else {\n this._messageId = 0;\n }\n }\n\n // Callbacks:\n /**\n * Callback to report when the websocket is opened. The callback has no parameters.\n *\n * @type {onWebsocketOpen}\n */\n onWebsocketOpen = undefined;\n\n /**\n * @typedef ServerParams\n *\n * @type {Object}\n * @property {string} ver - Server version\n * @property {string} build - Server build\n * @property {string=} sid - Session ID, long polling connections only.\n */\n\n /**\n * @callback onConnect\n * @param {number} code - Result code\n * @param {string} text - Text epxplaining the completion, i.e \"OK\" or an error message.\n * @param {ServerParams} params - Parameters returned by the server.\n */\n /**\n * Callback to report when connection with Tinode server is established.\n * @type {onConnect}\n */\n onConnect = undefined;\n\n /**\n * Callback to report when connection is lost. The callback has no parameters.\n * @type {onDisconnect}\n */\n onDisconnect = undefined;\n\n /**\n * @callback onLogin\n * @param {number} code - NUmeric completion code, same as HTTP status codes.\n * @param {string} text - Explanation of the completion code.\n */\n /**\n * Callback to report login completion.\n * @type {onLogin}\n */\n onLogin = undefined;\n\n /**\n * Callback to receive {ctrl} (control) messages.\n * @type {onCtrlMessage}\n */\n onCtrlMessage = undefined;\n\n /**\n * Callback to recieve {data} (content) messages.\n * @type {onDataMessage}\n */\n onDataMessage = undefined;\n\n /**\n * Callback to receive {pres} (presence) messages.\n * @type {onPresMessage}\n */\n onPresMessage = undefined;\n\n /**\n * Callback to receive all messages as objects.\n * @type {onMessage}\n */\n onMessage = undefined;\n\n /**\n * Callback to receive all messages as unparsed text.\n * @type {onRawMessage}\n */\n onRawMessage = undefined;\n\n /**\n * Callback to receive server responses to network probes. See {@link Tinode#networkProbe}\n * @type {onNetworkProbe}\n */\n onNetworkProbe = undefined;\n\n /**\n * Callback to be notified when exponential backoff is iterating.\n * @type {onAutoreconnectIteration}\n */\n onAutoreconnectIteration = undefined;\n};\n\n// Exported constants\nTinode.MESSAGE_STATUS_NONE = Const.MESSAGE_STATUS_NONE;\nTinode.MESSAGE_STATUS_QUEUED = Const.MESSAGE_STATUS_QUEUED;\nTinode.MESSAGE_STATUS_SENDING = Const.MESSAGE_STATUS_SENDING;\nTinode.MESSAGE_STATUS_FAILED = Const.MESSAGE_STATUS_FAILED;\nTinode.MESSAGE_STATUS_FATAL = Const.MESSAGE_STATUS_FATAL;\nTinode.MESSAGE_STATUS_SENT = Const.MESSAGE_STATUS_SENT;\nTinode.MESSAGE_STATUS_RECEIVED = Const.MESSAGE_STATUS_RECEIVED;\nTinode.MESSAGE_STATUS_READ = Const.MESSAGE_STATUS_READ;\nTinode.MESSAGE_STATUS_TO_ME = Const.MESSAGE_STATUS_TO_ME;\n\n// Unicode [del] symbol.\nTinode.DEL_CHAR = Const.DEL_CHAR;\n\n// Names of keys to server-provided configuration limits.\nTinode.MAX_MESSAGE_SIZE = 'maxMessageSize';\nTinode.MAX_SUBSCRIBER_COUNT = 'maxSubscriberCount';\nTinode.MAX_TAG_COUNT = 'maxTagCount';\nTinode.MAX_FILE_UPLOAD_SIZE = 'maxFileUploadSize';\nTinode.REQ_CRED_VALIDATORS = 'reqCred';\n"],"names":["AccessMode","constructor","acs","given","decode","want","mode","checkFlag","#checkFlag","val","side","flag","includes","Error","str","_BITMASK","_NONE","bitmask","_JOIN","_READ","_WRITE","_PRES","_APPROVE","_SHARE","_DELETE","_OWNER","m0","i","length","bit","charAt","toUpperCase","encode","_INVALID","res","update","upd","action","val0","parts","split","diff","a1","a2","toString","jsonHelper","setMode","m","updateMode","u","getMode","setGiven","g","updateGiven","getGiven","setWant","w","updateWant","getWant","getMissing","getExcessive","updateAll","isOwner","isPresencer","isMuted","isJoiner","isReader","isWriter","isApprover","isAdmin","isSharer","isDeleter","CBuffer","comparator","undefined","unique","buffer","compare_","unique_","a","b","findNearest","#findNearest","elem","arr","exact","start","end","pivot","found","idx","insertSorted","#insertSorted","count","splice","getAt","at","getLast","put","insert","arguments","Array","isArray","delAt","r","delRange","since","before","reset","forEach","callback","startIdx","beforeIdx","context","Math","max","min","call","find","nearest","filter","isEmpty","CommError","message","code","name","PACKAGE_VERSION","PROTOCOL_VERSION","VERSION","LIBRARY","TOPIC_NEW","TOPIC_NEW_CHAN","TOPIC_ME","TOPIC_FND","TOPIC_SYS","TOPIC_CHAN","TOPIC_GRP","TOPIC_P2P","USER_NEW","LOCAL_SEQID","MESSAGE_STATUS_NONE","MESSAGE_STATUS_QUEUED","MESSAGE_STATUS_SENDING","MESSAGE_STATUS_FAILED","MESSAGE_STATUS_FATAL","MESSAGE_STATUS_SENT","MESSAGE_STATUS_RECEIVED","MESSAGE_STATUS_READ","MESSAGE_STATUS_TO_ME","EXPIRE_PROMISES_TIMEOUT","EXPIRE_PROMISES_PERIOD","RECV_TIMEOUT","DEFAULT_MESSAGES_PAGE","DEL_CHAR","MAX_PINNED_COUNT","jsonParseHelper","WebSocketProvider","XHRProvider","NETWORK_ERROR","NETWORK_ERROR_TEXT","NETWORK_USER","NETWORK_USER_TEXT","_BOFF_BASE","_BOFF_MAX_ITER","_BOFF_JITTER","makeBaseUrl","host","protocol","version","apiKey","url","Connection","log","_","boffTimer","boffIteration","boffClosed","socket","secure","autoreconnect","initialized","config","version_","autoreconnect_","transport","init_lp","init_ws","setNetworkProviders","wsProvider","xhrProvider","logger","l","connect","host_","force","Promise","reject","reconnect","disconnect","sendText","msg","isConnected","probe","backoffReset","boffReset","boffReconnect","#boffReconnect","clearTimeout","timeout","pow","random","onAutoreconnectIteration","setTimeout","prom","catch","boffStop","#boffStop","#boffReset","#init_lp","XDR_UNSENT","XDR_OPENED","XDR_HEADERS_RECEIVED","XDR_LOADING","XDR_DONE","_lpURL","_poller","_sender","lp_sender","url_","sender","onreadystatechange","evt","readyState","status","open","lp_poller","resolve","poller","promiseCompleted","pkt","JSON","parse","responseText","ctrl","params","sid","send","onOpen","onMessage","onDisconnect","text","abort","err","#init_ws","OPEN","close","conn","onerror","onopen","onclose","onmessage","data","clipRange","DB_VERSION","DB_NAME","IDBProvider","DB","onError","db","disabled","mapObjects","#mapObjects","source","trx","transaction","event","target","error","objectStore","getAll","onsuccess","result","topic","initDatabase","req","onupgradeneeded","createObjectStore","keyPath","dellog","createIndex","deleteDatabase","onblocked","isReady","updTopic","oncomplete","get","serializeTopic","commit","markTopicAsDeleted","_deleted","remTopic","delete","IDBKeyRange","only","bound","Number","MAX_SAFE_INTEGER","mapTopics","deserializeTopic","src","updUser","uid","pub","public","remUser","mapUsers","getUser","user","updSubscription","topicName","sub","serializeSubscription","mapSubscriptions","addMessage","add","serializeMessage","updMessageStatus","seq","_status","remMessages","from","to","range","readMessages","query","ranges","key","hi","low","msgs","concat","push","limit","openCursor","cursor","value","continue","addDelLog","delId","clear","readDelLog","maxDelId","index","topic_fields","#deserializeTopic","f","hasOwnProperty","tags","_tags","setAccessMode","read","unread","#serializeTopic","dst","getAccessMode","#serializeSubscription","fields","#serializeMessage","setDatabaseProvider","idbProvider","MAX_FORM_ELEMENTS","MAX_PREVIEW_ATTACHMENTS","MAX_PREVIEW_DATA_SIZE","JSON_MIME_TYPE","DRAFTY_MIME_TYPE","ALLOWED_ENT_FIELDS","INLINE_STYLES","FMT_WEIGHT","ENTITY_TYPES","dataName","pack","test","re","slice","FORMAT_TAGS","AU","html_tag","md_tag","isVoid","BN","BR","CO","DL","EM","EX","FM","HD","HL","HT","IM","LN","MN","RW","QQ","ST","VC","VD","base64toObjectUrl","b64","contentType","bin","atob","buf","ArrayBuffer","Uint8Array","charCodeAt","URL","createObjectURL","Blob","type","base64toDataUrl","DECORATORS","props","href","id","act","ref","mime","Drafty","duration","size","tmpPreviewUrl","_tempPreview","previewUrl","downloadUrl","width","height","title","alt","state","preview","premime","poster","preref","txt","fmt","ent","init","plainText","content","lines","entityMap","entityIndex","blx","line","spans","entities","tag","spannify","block","sort","toSpanTree","chunks","chunkify","drafty","draftify","extractEntities","entity","tp","offset","len","map","s","append","first","second","insertImage","imageDesc","ex","refurl","bits","filename","urlPromise","_processing","then","insertVideo","videoDesc","urls","insertAudio","audioDesc","videoCall","audioOnly","aonly","updateVideoCall","Object","assign","quote","header","body","appendLineBreak","mention","appendLink","linkData","appendImage","appendAudio","attachFile","attachmentDesc","wrapInto","style","wrapAsForm","insertButton","actionType","actionValue","refUrl","indexOf","appendButton","attachJSON","UNSAFE_toHTML","doc","tree","draftyToTree","htmlFormatter","values","join","treeBottomUp","format","original","formatter","shorten","light","shortenTree","lightEntity","treeToDrafty","forwardedContent","rmMention","node","parent","treeTopDown","lTrim","replyContent","convMNnQQnBR","startsWith","children","attachmentsToEnd","forwarding","toPlainText","isPlainText","toMarkdown","mdFormatter","def","isValid","txt_type","hasAttachments","attachments","hasEntities","styles","sanitizeEntities","copyEntData","getDownloadUrl","entData","isProcessing","getPreviewUrl","getEntitySize","getEntityMimeType","tagName","attrValue","getContentType","span","chunk","chld","re_start","re_end","exec","start_offset","lastIndexOf","end_offset","last","spansToTree","flatten","child","addNode","n","substring","att","subspans","inner","keymap","c","keys","newKey","transformer","stack","pop","tail","shortener","allow","lightCopy","trimStart","shift","match","extracted","el","startAt","plain","entries","dc","module","exports","Const","Topic","mergeToCache","TopicFnd","_contacts","callbacks","_processMetaSub","subs","updateCount","getOwnPropertyNames","indexBy","onMetaSub","onSubsUpdated","publish","setMeta","getPrototypeOf","prototype","contacts","cb","isUrlRelative","addURLParam","relUrl","window","location","origin","searchParams","LargeFileHelper","tinode","_tinode","_version","_apiKey","_authToken","getAuthToken","xhr","uploadWithBaseUrl","baseUrl","avatarFor","onProgress","onSuccess","onFailure","base","endsWith","instance","setRequestHeader","token","toResolve","toReject","upload","onprogress","e","lengthComputable","loaded","total","onload","response","statusText","onabort","form","FormData","set","getNextUniqueId","_secure","_host","download","relativeUrl","mimetype","responseType","link","document","createElement","display","setAttribute","appendChild","click","removeChild","revokeObjectURL","reader","FileReader","readAsText","cancel","setNetworkProvider","mergeObj","TopicMe","onContactUpdate","_processMetaDesc","desc","turnOff","_db","_updateCachedUser","_myUID","cont","online","seen","when","Date","_refreshContact","onMetaDesc","deleted","cacheRemTopic","recv","getTopic","_new","isP2PTopicName","_cachePutUser","_noForwarding","_processMetaCreds","creds","cr","_credentials","findIndex","meth","done","resp","onCredsUpdated","_routePres","pres","what","_resetSub","getMeta","startMetaQuery","withDesc","build","cacheGetTopic","_updateReceived","withLaterOneSub","dacs","touched","ua","_attached","withOneSub","dummy","withTags","onPres","delCredential","method","isCommType","getContact","isArchived","private","arch","getCredentials","listToRanges","normalizeRanges","MetaGetBuilder","get_desc_ims","#get_desc_ims","updated","get_subs_ims","#get_subs_ims","isP2PType","_lastSubsUpdate","withData","withLaterData","_maxSeq","withDataRanges","withDataList","list","withEarlierData","_minSeq","ims","withLaterDesc","withSub","userOrTopic","opts","getType","withLaterSub","withCred","withAux","withDel","withLaterDel","_maxDel","extract","normalizeArray","created","trusted","_users","_queuedSeqId","_noEarlierMsgs","_recvNotificationTimer","_aux","_messageVersions","_messages","_delayedLeaveTimer","onData","onMeta","onInfo","onTagsUpdated","onAuxUpdated","onDeleteTopic","onAllMessagesReceived","topicType","types","isMeTopicName","isGroupTopicName","isCommTopicName","isNewGroupTopicName","isChannelTopicName","isReplacementMsg","#isReplacementMsg","head","replace","isSubscribed","subscribe","getParams","setParams","_cacheDelSelf","_cachePutSelf","ts","me","getMeTopic","createMessage","noEcho","publishMessage","_sending","_failed","swapMessageId","_maybeUpdateMessageVersionsCache","_routeData","publishDraft","_getQueuedSeqId","getCurrentUserID","noecho","_cancelled","_fatal","leave","unsub","_gone","leaveDelayed","delay","getMessagesPage","gaps","newer","_loadMessages","msgHasMoreMessages","getPinnedMessages","pins","aux","remains","_processMetaTags","cred","_processMetaAux","subscriber","am","invite","archive","pinMessage","pin","pinned","changed","delMessages","hard","tosend","del","rec","flushMessageRange","flushMessage","delMessagesAll","hardDel","_all","delMessagesList","delMessagesEdits","messageVersions","delTopic","delSubscription","note","_updateReadRecv","noteRecv","noteRead","noteKeyPress","noteRecording","payload","oldVal","doUpdate","userDesc","_cacheGetUser","p2pPeerDesc","subscribers","origSeq","versions","messages","sinceId","beforeId","unused1","unused2","latest","latestMsgVersion","_origTs","_origSeq","findMessage","latestMessage","maxMsgSeq","minMsgSeq","maxClearId","messageCount","queuedMessages","msgReceiptCount","msgReadCount","msgRecvCount","maxSeq","gap","prev","p","expected","isNewMessage","seqId","fromId","untilId","newSeqId","numMessages","cancelSend","msgStatus","getDefaultAccess","defacs","isMeType","isChannelType","isGroupType","isMe","targetSeq","parseInt","targetMsg","outgoing","webrtc","incoming","_routeMeta","meta","_processDelMessages","delseq","isTopicCached","_routeInfo","info","_allMessagesReceived","obj","cached","date","isNaN","isValidDate","d","getTime","rfc3339DateString","pad","sp","repeat","millis","getUTCMilliseconds","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","ignore","prop","cache","newval","simplify","out","t","trim","toLowerCase","item","pos","ary","r1","r2","reduce","clip","DBCache","WebSocket","XMLHttpRequest","IndexedDBProvider","indexedDB","initForNonBrowserApp","chars","btoa","global","input","output","charCode","bc","bs","String","fromCharCode","detectTransport","b64EncodeUnicode","encodeURIComponent","toSolidBytes","p1","jsonBuildHelper","jsonLoggerHelper","getBrowserInfo","product","reactnative","priority","tmp","substr","tokens","m2","v","minor","Tinode","_appName","_browser","_platform","_hwos","_humanLanguage","_loggingEnabled","_trimLongStrings","_authenticated","_login","_inPacketCount","_messageId","floor","_serverInfo","_deviceToken","_pendingPromises","_expirePromises","_connection","_persist","_cache","onComplete","appName","platform","navigator","userAgent","language","dispatchMessage","connectionOpen","disconnected","promise","persist","cacheGet","attachCacheToTopic","cachePut","all","dateString","_len","args","_key","console","makePromise","#makePromise","execPromise","#execPromise","onOK","errorText","#send","stringify","#dispatchMessage","onRawMessage","onNetworkProbe","onCtrlMessage","onMetaMessage","onDataMessage","onPresMessage","onInfoMessage","#connectionOpen","setInterval","expires","hello","#disconnected","clearInterval","cacheMap","getUserAgent","#getUserAgent","initPacket","#initPacket","#cachePut","#cacheGet","cacheDel","#cacheDel","#cacheMap","func","#attachCacheToTopic","_cacheDelUser","loginSuccessful","#loginSuccessful","onLogin","credential","getVersion","getLibrary","isNullValue","clearStorage","initStorage","networkProbe","isAuthenticated","authorizeURL","parsed","account","scheme","secret","login","acc","tmpscheme","tmpsecret","extra","createAccount","createAccountBasic","username","password","updateAccountBasic","onConnect","setDeviceToken","dt","sent","loginBasic","uname","loginToken","requestResetAuthSecret","now","setAuthToken","dft","oobNotification","xfrom","finally","modeGiven","modeWant","delCurrentUser","newGroupTopicName","isChan","getFndTopic","getLargeFileHelper","getCurrentLogin","getServerInfo","report","getServerParam","defaultValue","enableLogging","enabled","trimLongStrings","setHumanLanguage","hl","isTopicOnline","getTopicAccessMode","wantAkn","onWebsocketOpen","MAX_MESSAGE_SIZE","MAX_SUBSCRIBER_COUNT","MAX_TAG_COUNT","MAX_FILE_UPLOAD_SIZE","REQ_CRED_VALIDATORS"],"sourceRoot":""}
\ No newline at end of file
diff --git a/umd/tinode.prod.js b/umd/tinode.prod.js
index 25571a35..ae4900fd 100644
--- a/umd/tinode.prod.js
+++ b/umd/tinode.prod.js
@@ -1 +1 @@
-!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.tinode=t():e.tinode=t()}(this,(()=>(()=>{"use strict";var e={577:e=>{const t=64,s="application/json",i=["act","height","duration","incoming","mime","name","premime","preref","preview","ref","size","state","url","val","width"],n=[{name:"ST",start:/(?:^|[\W_])(\*)[^\s*]/,end:/[^\s*](\*)(?=$|[\W_])/},{name:"EM",start:/(?:^|\W)(_)[^\s_]/,end:/[^\s_](_)(?=$|\W)/},{name:"DL",start:/(?:^|[\W_])(~)[^\s~]/,end:/[^\s~](~)(?=$|[\W_])/},{name:"CO",start:/(?:^|\W)(`)[^`]/,end:/[^`](`)(?=$|\W)/}],r=["QQ"],a=[{name:"LN",dataName:"url",pack:function(e){return/^[a-z]+:\/\//i.test(e)||(e="http://"+e),{url:e}},re:/(?:(?:https?|ftp):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/gi},{name:"MN",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B@([\p{L}\p{N}][._\p{L}\p{N}]*[\p{L}\p{N}])/gu},{name:"HT",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B#([\p{L}\p{N}][._\p{L}\p{N}]*[\p{L}\p{N}])/gu}],o={AU:{html_tag:"audio",md_tag:void 0,isVoid:!1},BN:{html_tag:"button",md_tag:void 0,isVoid:!1},BR:{html_tag:"br",md_tag:"\n",isVoid:!0},CO:{html_tag:"tt",md_tag:"`",isVoid:!1},DL:{html_tag:"del",md_tag:"~",isVoid:!1},EM:{html_tag:"i",md_tag:"_",isVoid:!1},EX:{html_tag:"",md_tag:void 0,isVoid:!0},FM:{html_tag:"div",md_tag:void 0,isVoid:!1},HD:{html_tag:"",md_tag:void 0,isVoid:!1},HL:{html_tag:"span",md_tag:void 0,isVoid:!1},HT:{html_tag:"a",md_tag:void 0,isVoid:!1},IM:{html_tag:"img",md_tag:void 0,isVoid:!1},LN:{html_tag:"a",md_tag:void 0,isVoid:!1},MN:{html_tag:"a",md_tag:void 0,isVoid:!1},RW:{html_tag:"div",md_tag:void 0,isVoid:!1},QQ:{html_tag:"div",md_tag:void 0,isVoid:!1},ST:{html_tag:"b",md_tag:"*",isVoid:!1},VC:{html_tag:"div",md_tag:void 0,isVoid:!1},VD:{html_tag:"video",md_tag:void 0,isVoid:!1}};function h(e,t,s){if(!e)return null;try{const s=atob(e),i=s.length,n=new ArrayBuffer(i),r=new Uint8Array(n);for(let e=0;e"",close:e=>""},EM:{open:e=>"",close:e=>""},DL:{open:e=>"",close:e=>""},CO:{open:e=>"",close:e=>""},BR:{open:e=>"
",close:e=>""},HD:{open:e=>"",close:e=>""},HL:{open:e=>'',close:e=>""},LN:{open:e=>'',close:e=>"",props:e=>e?{href:e.url,target:"_blank"}:null},MN:{open:e=>'',close:e=>"",props:e=>e?{id:e.val}:null},HT:{open:e=>'',close:e=>"",props:e=>e?{id:e.val}:null},BN:{open:e=>"",props:e=>e?{"data-act":e.act,"data-val":e.val,"data-name":e.name,"data-ref":e.ref}:null},AU:{open:e=>'",props:e=>e?{src:e.ref||h(e.val,e.mime,l.logger),"data-preload":e.ref?"metadata":"auto","data-duration":e.duration,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}:null},IM:{open:e=>{const t=c(e._tempPreview,e.mime),s=h(e.val,e.mime,l.logger),i=e.ref||s;return(e.name?'':"")+''},close:e=>e.name?"":"",props:e=>e?{src:c(e._tempPreview,e.mime)||e.ref||h(e.val,e.mime,l.logger),title:e.name,alt:e.name,"data-width":e.width,"data-height":e.height,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}:null},FM:{open:e=>"
'},close:e=>"",props:e=>{if(!e)return null;const t=e.preref||h(e.preview,e.premime||"image/jpeg",l.logger);return{src:t,"data-src":e.ref||h(e.val,e.mime,l.logger),"data-width":e.width,"data-height":e.height,"data-preload":e.ref?"metadata":"auto","data-preview":t,"data-duration":0|e.duration,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}}}},l=function(){this.txt="",this.fmt=[],this.ent=[]};function u(e,t,s,i){const n=[];if(0==i.length)return[];for(let s in i){const r=i[s];r.at>t&&n.push({txt:e.slice(t,r.at)});const a={tp:r.tp},o=u(e,r.at+1,r.end,r.children);o.length>0?a.children=o:a.txt=r.txt,n.push(a),t=r.end+1}return t
s.end?(t.push(e[i]),s=e[i]):e[i].end<=s.end&&s.children.push(e[i]);for(let e in t)t[e].children=p(t[e].children);return t}function g(e){if(!e)return null;e="string"==typeof e?{txt:e}:e;let{txt:t,fmt:s,ent:i}=e;if(t=t||"",Array.isArray(i)||(i=[]),!Array.isArray(s)||0==s.length){if(0==i.length)return{text:t};s=[{at:0,len:0,key:0}]}const n=[],a=[];s.forEach((e=>{if(!e||"object"!=typeof e)return;if(!["undefined","number"].includes(typeof e.at))return;if(!["undefined","number"].includes(typeof e.len))return;let s=0|e.at,r=0|e.len;if(r<0)return;let o=e.key||0;i.length>0&&("number"!=typeof o||o<0||o>=i.length)||(s<=-1?a.push({start:-1,end:0,key:o}):s+r>t.length||(e.tp?n.push({type:e.tp,start:s,end:s+r}):i.length>0&&"object"==typeof i[o]&&n.push({start:s,end:s+r,key:o})))})),n.sort(((e,t)=>{let s=e.start-t.start;return 0!=s?s:(s=t.end-e.end,0!=s?s:r.indexOf(t.type)-r.indexOf(e.type))})),a.length>0&&n.push(...a),n.forEach((e=>{i.length>0&&!e.type&&i[e.key]&&"object"==typeof i[e.key]&&(e.type=i[e.key].tp,e.data=i[e.key].data),e.type||(e.type="HD")}));let o=f({},t,0,t.length,n);return o=b(o,(function(e){if(Array.isArray(e.children)&&1==e.children.length){const t=e.children[0];if(e.type)t.type||t.children||(e.text=t.text,delete e.children);else{const s=e.parent;(e=t).parent=s}}return e})),o}function m(e,t){return t?(e.children||(e.children=[]),e.text&&(e.children.push({text:e.text,parent:e}),delete e.text),t.parent=e,e.children.push(t),e):e}function f(e,t,s,i,n){if(!n||0==n.length)return s{_(e,t,s)})),t.type){const n=e.txt.length-i;if(e.fmt=e.fmt||[],Object.keys(t.data||{}).length>0){e.ent=e.ent||[];const r=void 0===s[t.key]?e.ent.length:s[t.key];s[t.key]=r,e.ent[r]={tp:t.type,data:t.data},t.att?e.fmt.push({at:-1,len:0,key:r}):e.fmt.push({at:i,len:n,key:r})}else e.fmt.push({tp:t.type,at:i,len:n})}return e}function b(e,t,s){if(!e)return null;let i=t.call(s,e);if(!i||!i.children)return i;const n=[];for(let e in i.children){let r=i.children[e];r&&(r=b(r,t,s),r&&n.push(r))}return 0==n.length?i.children=null:i.children=n,i}function w(e,t,s,i,n){if(!e)return null;i&&e.type&&i.push(e.type);let r=[];for(let s in e.children){const a=w(e.children[s],t,s,i,n);a&&r.push(a)}return 0==r.length&&(r=e.text?[e.text]:null),i&&e.type&&i.pop(),t.call(n,e.type,e.data,r,s,i)}function v(e,t,s){return e?(s&&(t-=s.length),b(e,(function(e){if(t<=-1)return null;if(e.att)return e;if(0==t)e.text=s,t=-1;else if(e.text){const i=e.text.length;i>t?(e.text=e.text.substring(0,t)+s,t=-1):t-=i}return e}))):null}function y(e,t){return b(e,(e=>{const s=P(e.data,!0,t?t(e):null);return s?e.data=s:delete e.data,e}))}function M(e){if("BR"==e.type)e=null;else if(e.text)e.type||(e.text=e.text.trimStart(),e.text||(e=null));else if(!e.type&&e.children&&e.children.length>0){const t=M(e.children[0]);t?e.children[0]=t:(e.children.shift(),e.type||0!=e.children.length||(e=null))}return e}function x(e,t){if(!e)return null;if(e.att)e.text=" ",delete e.att,delete e.children;else if(e.children){const i=[],n=[];for(let r in e.children){const a=e.children[r];if(a.att){if(i.length==t)continue;if(a.data.mime==s)continue;delete a.att,delete a.children,a.text=" ",i.push(a)}else n.push(a)}e.children=n.concat(i)}return e}function T(e,t){let s="",i=[];for(let n in e){const r=e[n];if(!r.txt){const e=T(r.children,s.length+t);r.txt=e.txt,i=i.concat(e.fmt)}r.tp&&i.push({at:s.length+t,len:r.txt.length,tp:r.tp}),s+=r.txt}return{txt:s,fmt:i}}function P(e,s,n){if(e&&Object.entries(e).length>0){n=n||[];const r={};if(i.forEach((i=>{if(e[i]){if(s&&!n.includes(i)&&("string"==typeof e[i]||Array.isArray(e[i]))&&e[i].length>t)return;if("object"==typeof e[i])return;r[i]=e[i]}})),0!=Object.entries(r).length)return r}return null}l.init=function(e){if(void 0===e)e="";else if("string"!=typeof e)return null;return{txt:e}},l.parse=function(e){if("string"!=typeof e)return null;const t=e.split(/\r?\n/),s=[],i={},r=[];t.forEach((e=>{let t,o,h=[];if(n.forEach((t=>{h=h.concat(function(e,t,s,i){const n=[];let r=0,a=e.slice(0);for(;a.length>0;){const o=t.exec(a);if(null==o)break;let h=o.index+o[0].lastIndexOf(o[1]);a=a.slice(h+1),h+=r,r=h+1;const c=s?s.exec(a):null;if(null==c)break;let d=c.index+c[0].indexOf(c[1]);a=a.slice(d+1),d+=r,r=d+1,n.push({txt:e.slice(h+1,d),children:[],at:h,end:d,tp:i})}return n}(e,t.start,t.end,t.name))})),0==h.length)o={txt:e};else{h.sort(((e,t)=>{const s=e.at-t.at;return 0!=s?s:t.end-e.end})),h=p(h);const t=T(u(e,0,e.length,h),0);o={txt:t.txt,fmt:t.fmt}}if(t=function(e){let t,s=[];if(a.forEach((i=>{for(;null!==(t=i.re.exec(e));)s.push({offset:t.index,len:t[0].length,unique:t[0],data:i.pack(t[0]),type:i.name})})),0==s.length)return s;s.sort(((e,t)=>e.offset-t.offset));let i=-1;return s=s.filter((e=>{const t=e.offset>i;return i=e.offset+e.len,t})),s}(o.txt),t.length>0){const e=[];for(let n in t){const r=t[n];let a=i[r.unique];a||(a=s.length,i[r.unique]=a,s.push({tp:r.type,data:r.data})),e.push({at:r.offset,len:r.len,key:a})}o.ent=e}r.push(o)}));const o={txt:""};if(r.length>0){o.txt=r[0].txt,o.fmt=(r[0].fmt||[]).concat(r[0].ent||[]);for(let e=1;e{"_"==t[0]?delete e[t]:e[t]?Array.isArray(e[t])&&0==e[t].length?delete e[t]:e[t]?e[t]instanceof Date?m(e[t])||delete e[t]:"object"==typeof e[t]&&(b(e[t]),0==Object.getOwnPropertyNames(e[t]).length&&delete e[t]):delete e[t]:delete e[t]})),e}function w(e,t){return Array.isArray(e)?(e.sort(((e,t)=>e.lowt?this.buffer[n-1]:void 0,n{if(V.#P(e))return;if(e._deleted)return;const r=this.latestMsgVersion(e.seq)||e;r._origTs||(r._origTs=r.ts,r._origSeq=r.seq,r.ts=e.ts,r.seq=e.seq),t.push({data:r,idx:n})}),e,r,{}),t.forEach(((e,s)=>{n.call(i,e.data,s>0?t[s-1].data:void 0,s{e._resetSub()}));for(let t in this._pendingPromises){const s=this._pendingPromises[t];s&&s.reject&&s.reject(e)}this._pendingPromises={},this.onDisconnect&&this.onDisconnect(e)}#U(){return this._appName+" ("+(this._browser?this._browser+"; ":"")+this._hwos+"); "+n}#O(e,s){switch(e){case"hi":return{hi:{id:this.getNextUniqueId(),ver:t,ua:this.#U(),dev:this._deviceToken,lang:this._humanLanguage,platf:this._platform}};case"acc":return{acc:{id:this.getNextUniqueId(),user:null,scheme:null,secret:null,tmpscheme:null,tmpsecret:null,login:!1,tags:null,desc:{},cred:{}}};case"login":return{login:{id:this.getNextUniqueId(),scheme:null,secret:null}};case"sub":return{sub:{id:this.getNextUniqueId(),topic:s,set:{},get:{}}};case"leave":return{leave:{id:this.getNextUniqueId(),topic:s,unsub:!1}};case"pub":return{pub:{id:this.getNextUniqueId(),topic:s,noecho:!1,head:null,content:{}}};case"get":return{get:{id:this.getNextUniqueId(),topic:s,what:null,desc:{},sub:{},data:{}}};case"set":return{set:{id:this.getNextUniqueId(),topic:s,desc:{},sub:{},tags:[],aux:{}}};case"del":return{del:{id:this.getNextUniqueId(),topic:s,what:null,delseq:null,user:null,hard:!1}};case"note":return{note:{topic:s,what:null,seq:void 0}};default:throw new Error(`Unknown packet type requested: ${e}`)}}#k(e,t,s){this._cache[e+":"+t]=s}#D(e,t){return this._cache[e+":"+t]}#j(e,t){delete this._cache[e+":"+t]}#I(e,t,s){const i=e?e+":":void 0;for(let e in this._cache)if((!i||0==e.indexOf(i))&&t.call(s,this._cache[e],e))break}#R(e){e._tinode=this,e._cacheGetUser=e=>{const t=this.#D("user",e);if(t)return{user:e,public:f({},t)}},e._cachePutUser=(e,t)=>{this.#k("user",e,f({},t.public))},e._cacheDelUser=e=>{this.#j("user",e)},e._cachePutSelf=t=>{this.#k("topic",e.name,e)},e._cacheDelSelf=t=>{this.#j("topic",e.name)}}#L(e){return e.params&&e.params.user?(this._myUID=e.params.user,this._authenticated=e&&e.code>=200&&e.code<300,e.params&&e.params.token&&e.params.expires?this._authToken={token:e.params.token,expires:e.params.expires}:this._authToken=null,this.onLogin&&this.onLogin(e.code,e.text),e):e}static credential(e,t,s,i){return"object"==typeof e&&({val:t,params:s,resp:i,meth:e}=e),e&&(t||i)?[{meth:e,val:t,resp:i,params:s}]:null}static topicType(e){return V.topicType(e)}static isMeTopicName(e){return V.isMeTopicName(e)}static isGroupTopicName(e){return V.isGroupTopicName(e)}static isP2PTopicName(e){return V.isP2PTopicName(e)}static isCommTopicName(e){return V.isCommTopicName(e)}static isNewGroupTopicName(e){return V.isNewGroupTopicName(e)}static isChannelTopicName(e){return V.isChannelTopicName(e)}static getVersion(){return t}static setNetworkProviders(e,t){C=e,I=t,A.setNetworkProviders(C,I),O.setNetworkProvider(I)}static setDatabaseProvider(e){U=e,R.setDatabaseProvider(U)}static getLibrary(){return n}static isNullValue(e){return e===l}getNextUniqueId(){return 0!=this._messageId?""+this._messageId++:void 0}connect(e){return this._connection.connect(e)}reconnect(e){this._connection.reconnect(e)}disconnect(){this._connection.disconnect()}clearStorage(){return this._db.isReady()?this._db.deleteDatabase():Promise.resolve()}initStorage(){return this._db.isReady()?Promise.resolve():this._db.initDatabase()}networkProbe(){this._connection.probe()}isConnected(){return this._connection.isConnected()}isAuthenticated(){return this._authenticated}authorizeURL(e){if("string"!=typeof e)return e;if(g(e)){const t="scheme://host/",s=new URL(e,t);this._apiKey&&s.searchParams.append("apikey",this._apiKey),this._authToken&&this._authToken.token&&(s.searchParams.append("auth","token"),s.searchParams.append("secret",this._authToken.token)),e=s.toString().substring(t.length-1)}return e}account(e,t,s,i,n){const r=this.#O("acc");return r.acc.user=e,r.acc.scheme=t,r.acc.secret=s,r.acc.login=i,n&&(r.acc.desc.defacs=n.defacs,r.acc.desc.public=n.public,r.acc.desc.private=n.private,r.acc.desc.trusted=n.trusted,r.acc.tags=n.tags,r.acc.cred=n.cred,r.acc.tmpscheme=n.scheme,r.acc.tmpsecret=n.secret,Array.isArray(n.attachments)&&n.attachments.length>0&&(r.extra={attachments:n.attachments.filter((e=>g(e)))})),this.#C(r,r.acc.id)}createAccount(e,t,s,i){let n=this.account("new",e,t,s,i);return s&&(n=n.then((e=>this.#L(e)))),n}createAccountBasic(e,t,s){return e=e||"",t=t||"",this.createAccount("basic",z(e+":"+t),!0,s)}updateAccountBasic(e,t,s,i){return t=t||"",s=s||"",this.account(e,"basic",z(t+":"+s),!1,i)}hello(){const e=this.#O("hi");return this.#C(e,e.hi.id).then((e=>(this._connection.backoffReset(),e.params&&(this._serverInfo=e.params),this.onConnect&&this.onConnect(),e))).catch((e=>{this._connection.reconnect(!0),this.onDisconnect&&this.onDisconnect(e)}))}setDeviceToken(e){let t=!1;return(e=e||null)!=this._deviceToken&&(this._deviceToken=e,this.isConnected()&&this.isAuthenticated()&&(this.#C({hi:{dev:e||K.DEL_CHAR}}),t=!0)),t}login(e,t,s){const i=this.#O("login");return i.login.scheme=e,i.login.secret=t,i.login.cred=s,this.#C(i,i.login.id).then((e=>this.#L(e)))}loginBasic(e,t,s){return this.login("basic",z(e+":"+t),s).then((t=>(this._login=e,t)))}loginToken(e,t){return this.login("token",e,t)}requestResetAuthSecret(e,t,s){return this.login("reset",z(e+":"+t+":"+s))}getAuthToken(){return this._authToken&&this._authToken.expires.getTime()>Date.now()?this._authToken:(this._authToken=null,null)}setAuthToken(e){this._authToken=e}subscribe(e,t,s){const i=this.#O("sub",e);if(e||(e=r),i.sub.get=t,s){if(s.sub&&(i.sub.set.sub=s.sub),s.desc){const t=s.desc;K.isNewGroupTopicName(e)?i.sub.set.desc=t:K.isP2PTopicName(e)&&t.defacs&&(i.sub.set.desc={defacs:t.defacs})}Array.isArray(s.attachments)&&s.attachments.length>0&&(i.extra={attachments:s.attachments.filter((e=>g(e)))}),s.tags&&(i.sub.set.tags=s.tags),s.aux&&(i.sub.set.aux=s.aux)}return this.#C(i,i.sub.id)}leave(e,t){const s=this.#O("leave",e);return s.leave.unsub=t,this.#C(s,s.leave.id)}createMessage(e,t,s){const i=this.#O("pub",e);let n="string"==typeof t?N().parse(t):t;return n&&!N().isPlainText(n)&&(i.pub.head={mime:N().getContentType()},t=n),i.pub.noecho=s,i.pub.content=t,i.pub}publish(e,t,s){return this.publishMessage(this.createMessage(e,t,s))}publishMessage(e,t){(e=Object.assign({},e)).seq=void 0,e.from=void 0,e.ts=void 0;const s={pub:e};return t&&(s.extra={attachments:t.filter((e=>g(e)))}),this.#C(s,e.id)}oobNotification(t){switch(this.logger("oob: "+(this._trimLongStrings?JSON.stringify(t,F):t)),t.what){case"msg":if(!t.seq||t.seq<1||!t.topic)break;if(!this.isConnected())break;const s=this.#D("topic",t.topic);if(!s)break;if(s.isSubscribed())break;s.maxMsgSeq()",close:e=>""},CO:{open:e=>"",close:e=>""},BR:{open:e=>"
",close:e=>""},HD:{open:e=>"",close:e=>""},HL:{open:e=>'',close:e=>""},LN:{open:e=>'',close:e=>"",props:e=>e?{href:e.url,target:"_blank"}:null},MN:{open:e=>'',close:e=>"",props:e=>e?{id:e.val}:null},HT:{open:e=>'',close:e=>"",props:e=>e?{id:e.val}:null},BN:{open:e=>"",props:e=>e?{"data-act":e.act,"data-val":e.val,"data-name":e.name,"data-ref":e.ref}:null},AU:{open:e=>'",props:e=>e?{src:e.ref||h(e.val,e.mime,l.logger),"data-preload":e.ref?"metadata":"auto","data-duration":e.duration,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}:null},IM:{open:e=>{const t=c(e._tempPreview,e.mime),s=h(e.val,e.mime,l.logger),i=e.ref||s;return(e.name?'':"")+''},close:e=>e.name?"":"",props:e=>e?{src:c(e._tempPreview,e.mime)||e.ref||h(e.val,e.mime,l.logger),title:e.name,alt:e.name,"data-width":e.width,"data-height":e.height,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}:null},FM:{open:e=>"
'},close:e=>"",props:e=>{if(!e)return null;const t=e.preref||h(e.preview,e.premime||"image/jpeg",l.logger);return{src:t,"data-src":e.ref||h(e.val,e.mime,l.logger),"data-width":e.width,"data-height":e.height,"data-preload":e.ref?"metadata":"auto","data-preview":t,"data-duration":0|e.duration,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}}}},l=function(){this.txt="",this.fmt=[],this.ent=[]};function u(e,t,s,i){const n=[];if(0==i.length)return[];for(let s in i){const r=i[s];r.at>t&&n.push({txt:e.slice(t,r.at)});const a={tp:r.tp},o=u(e,r.at+1,r.end,r.children);o.length>0?a.children=o:a.txt=r.txt,n.push(a),t=r.end+1}return t
s.end?(t.push(e[i]),s=e[i]):e[i].end<=s.end&&s.children.push(e[i]);for(let e in t)t[e].children=p(t[e].children);return t}function g(e){if(!e)return null;e="string"==typeof e?{txt:e}:e;let{txt:t,fmt:s,ent:i}=e;if(t=t||"",Array.isArray(i)||(i=[]),!Array.isArray(s)||0==s.length){if(0==i.length)return{text:t};s=[{at:0,len:0,key:0}]}const n=[],a=[];s.forEach((e=>{if(!e||"object"!=typeof e)return;if(!["undefined","number"].includes(typeof e.at))return;if(!["undefined","number"].includes(typeof e.len))return;let s=0|e.at,r=0|e.len;if(r<0)return;let o=e.key||0;i.length>0&&("number"!=typeof o||o<0||o>=i.length)||(s<=-1?a.push({start:-1,end:0,key:o}):s+r>t.length||(e.tp?n.push({type:e.tp,start:s,end:s+r}):i.length>0&&"object"==typeof i[o]&&n.push({start:s,end:s+r,key:o})))})),n.sort(((e,t)=>{let s=e.start-t.start;return 0!=s?s:(s=t.end-e.end,0!=s?s:r.indexOf(t.type)-r.indexOf(e.type))})),a.length>0&&n.push(...a),n.forEach((e=>{i.length>0&&!e.type&&i[e.key]&&"object"==typeof i[e.key]&&(e.type=i[e.key].tp,e.data=i[e.key].data),e.type||(e.type="HD")}));let o=f({},t,0,t.length,n);return o=b(o,(function(e){if(Array.isArray(e.children)&&1==e.children.length){const t=e.children[0];if(e.type)t.type||t.children||(e.text=t.text,delete e.children);else{const s=e.parent;(e=t).parent=s}}return e})),o}function m(e,t){return t?(e.children||(e.children=[]),e.text&&(e.children.push({text:e.text,parent:e}),delete e.text),t.parent=e,e.children.push(t),e):e}function f(e,t,s,i,n){if(!n||0==n.length)return s{_(e,t,s)})),t.type){const n=e.txt.length-i;if(e.fmt=e.fmt||[],Object.keys(t.data||{}).length>0){e.ent=e.ent||[];const r=void 0===s[t.key]?e.ent.length:s[t.key];s[t.key]=r,e.ent[r]={tp:t.type,data:t.data},t.att?e.fmt.push({at:-1,len:0,key:r}):e.fmt.push({at:i,len:n,key:r})}else e.fmt.push({tp:t.type,at:i,len:n})}return e}function b(e,t,s){if(!e)return null;let i=t.call(s,e);if(!i||!i.children)return i;const n=[];for(let e in i.children){let r=i.children[e];r&&(r=b(r,t,s),r&&n.push(r))}return 0==n.length?i.children=null:i.children=n,i}function w(e,t,s,i,n){if(!e)return null;i&&e.type&&i.push(e.type);let r=[];for(let s in e.children){const a=w(e.children[s],t,s,i,n);a&&r.push(a)}return 0==r.length&&(r=e.text?[e.text]:null),i&&e.type&&i.pop(),t.call(n,e.type,e.data,r,s,i)}function v(e,t,s){return e?(s&&(t-=s.length),b(e,(function(e){if(t<=-1)return null;if(e.att)return e;if(0==t)e.text=s,t=-1;else if(e.text){const i=e.text.length;i>t?(e.text=e.text.substring(0,t)+s,t=-1):t-=i}return e}))):null}function y(e,t){return b(e,(e=>{const s=P(e.data,!0,t?t(e):null);return s?e.data=s:delete e.data,e}))}function M(e){if("BR"==e.type)e=null;else if(e.text)e.type||(e.text=e.text.trimStart(),e.text||(e=null));else if(!e.type&&e.children&&e.children.length>0){const t=M(e.children[0]);t?e.children[0]=t:(e.children.shift(),e.type||0!=e.children.length||(e=null))}return e}function x(e,t){if(!e)return null;if(e.att)e.text=" ",delete e.att,delete e.children;else if(e.children){const i=[],n=[];for(let r in e.children){const a=e.children[r];if(a.att){if(i.length==t)continue;if(a.data.mime==s)continue;delete a.att,delete a.children,a.text=" ",i.push(a)}else n.push(a)}e.children=n.concat(i)}return e}function T(e,t){let s="",i=[];for(let n in e){const r=e[n];if(!r.txt){const e=T(r.children,s.length+t);r.txt=e.txt,i=i.concat(e.fmt)}r.tp&&i.push({at:s.length+t,len:r.txt.length,tp:r.tp}),s+=r.txt}return{txt:s,fmt:i}}function P(e,s,n){if(e&&Object.entries(e).length>0){n=n||[];const r={};if(i.forEach((i=>{if(e[i]){if(s&&!n.includes(i)&&("string"==typeof e[i]||Array.isArray(e[i]))&&e[i].length>t)return;if("object"==typeof e[i])return;r[i]=e[i]}})),0!=Object.entries(r).length)return r}return null}l.init=function(e){if(void 0===e)e="";else if("string"!=typeof e)return null;return{txt:e}},l.parse=function(e){if("string"!=typeof e)return null;const t=e.split(/\r?\n/),s=[],i={},r=[];t.forEach((e=>{let t,o,h=[];if(n.forEach((t=>{h=h.concat(function(e,t,s,i){const n=[];let r=0,a=e.slice(0);for(;a.length>0;){const o=t.exec(a);if(null==o)break;let h=o.index+o[0].lastIndexOf(o[1]);a=a.slice(h+1),h+=r,r=h+1;const c=s?s.exec(a):null;if(null==c)break;let d=c.index+c[0].indexOf(c[1]);a=a.slice(d+1),d+=r,r=d+1,n.push({txt:e.slice(h+1,d),children:[],at:h,end:d,tp:i})}return n}(e,t.start,t.end,t.name))})),0==h.length)o={txt:e};else{h.sort(((e,t)=>{const s=e.at-t.at;return 0!=s?s:t.end-e.end})),h=p(h);const t=T(u(e,0,e.length,h),0);o={txt:t.txt,fmt:t.fmt}}if(t=function(e){let t,s=[];if(a.forEach((i=>{for(;null!==(t=i.re.exec(e));)s.push({offset:t.index,len:t[0].length,unique:t[0],data:i.pack(t[0]),type:i.name})})),0==s.length)return s;s.sort(((e,t)=>e.offset-t.offset));let i=-1;return s=s.filter((e=>{const t=e.offset>i;return i=e.offset+e.len,t})),s}(o.txt),t.length>0){const e=[];for(let n in t){const r=t[n];let a=i[r.unique];a||(a=s.length,i[r.unique]=a,s.push({tp:r.type,data:r.data})),e.push({at:r.offset,len:r.len,key:a})}o.ent=e}r.push(o)}));const o={txt:""};if(r.length>0){o.txt=r[0].txt,o.fmt=(r[0].fmt||[]).concat(r[0].ent||[]);for(let e=1;e{"_"==t[0]?delete e[t]:e[t]?Array.isArray(e[t])&&0==e[t].length?delete e[t]:e[t]?e[t]instanceof Date?m(e[t])||delete e[t]:"object"==typeof e[t]&&(b(e[t]),0==Object.getOwnPropertyNames(e[t]).length&&delete e[t]):delete e[t]:delete e[t]})),e}function w(e,t){return Array.isArray(e)?(e.sort(((e,t)=>e.lowt?this.buffer[n-1]:void 0,n{if(V.#P(e))return;if(e._deleted)return;const r=this.latestMsgVersion(e.seq)||e;r._origTs||(r._origTs=r.ts,r._origSeq=r.seq,r.ts=e.ts,r.seq=e.seq),t.push({data:r,idx:n})}),e,r,{}),t.forEach(((e,s)=>{n.call(i,e.data,s>0?t[s-1].data:void 0,s{e._resetSub()}));for(let t in this._pendingPromises){const s=this._pendingPromises[t];s&&s.reject&&s.reject(e)}this._pendingPromises={},this.onDisconnect&&this.onDisconnect(e)}#U(){return this._appName+" ("+(this._browser?this._browser+"; ":"")+this._hwos+"); "+n}#O(e,s){switch(e){case"hi":return{hi:{id:this.getNextUniqueId(),ver:t,ua:this.#U(),dev:this._deviceToken,lang:this._humanLanguage,platf:this._platform}};case"acc":return{acc:{id:this.getNextUniqueId(),user:null,scheme:null,secret:null,tmpscheme:null,tmpsecret:null,login:!1,tags:null,desc:{},cred:{}}};case"login":return{login:{id:this.getNextUniqueId(),scheme:null,secret:null}};case"sub":return{sub:{id:this.getNextUniqueId(),topic:s,set:{},get:{}}};case"leave":return{leave:{id:this.getNextUniqueId(),topic:s,unsub:!1}};case"pub":return{pub:{id:this.getNextUniqueId(),topic:s,noecho:!1,head:null,content:{}}};case"get":return{get:{id:this.getNextUniqueId(),topic:s,what:null,desc:{},sub:{},data:{}}};case"set":return{set:{id:this.getNextUniqueId(),topic:s,desc:{},sub:{},tags:[],aux:{}}};case"del":return{del:{id:this.getNextUniqueId(),topic:s,what:null,delseq:null,user:null,hard:!1}};case"note":return{note:{topic:s,what:null,seq:void 0}};default:throw new Error(`Unknown packet type requested: ${e}`)}}#k(e,t,s){this._cache[e+":"+t]=s}#D(e,t){return this._cache[e+":"+t]}#j(e,t){delete this._cache[e+":"+t]}#I(e,t,s){const i=e?e+":":void 0;for(let e in this._cache)if((!i||0==e.indexOf(i))&&t.call(s,this._cache[e],e))break}#R(e){e._tinode=this,e._cacheGetUser=e=>{const t=this.#D("user",e);if(t)return{user:e,public:f({},t)}},e._cachePutUser=(e,t)=>{this.#k("user",e,f({},t.public))},e._cacheDelUser=e=>{this.#j("user",e)},e._cachePutSelf=t=>{this.#k("topic",e.name,e)},e._cacheDelSelf=t=>{this.#j("topic",e.name)}}#L(e){return e.params&&e.params.user?(this._myUID=e.params.user,this._authenticated=e&&e.code>=200&&e.code<300,e.params&&e.params.token&&e.params.expires?this._authToken={token:e.params.token,expires:e.params.expires}:this._authToken=null,this.onLogin&&this.onLogin(e.code,e.text),e):e}static credential(e,t,s,i){return"object"==typeof e&&({val:t,params:s,resp:i,meth:e}=e),e&&(t||i)?[{meth:e,val:t,resp:i,params:s}]:null}static topicType(e){return V.topicType(e)}static isMeTopicName(e){return V.isMeTopicName(e)}static isGroupTopicName(e){return V.isGroupTopicName(e)}static isP2PTopicName(e){return V.isP2PTopicName(e)}static isCommTopicName(e){return V.isCommTopicName(e)}static isNewGroupTopicName(e){return V.isNewGroupTopicName(e)}static isChannelTopicName(e){return V.isChannelTopicName(e)}static getVersion(){return t}static setNetworkProviders(e,t){C=e,I=t,A.setNetworkProviders(C,I),O.setNetworkProvider(I)}static setDatabaseProvider(e){U=e,R.setDatabaseProvider(U)}static getLibrary(){return n}static isNullValue(e){return e===l}getNextUniqueId(){return 0!=this._messageId?""+this._messageId++:void 0}connect(e){return this._connection.connect(e)}reconnect(e){this._connection.reconnect(e)}disconnect(){this._connection.disconnect()}clearStorage(){return this._db.isReady()?this._db.deleteDatabase():Promise.resolve()}initStorage(){return this._db.isReady()?Promise.resolve():this._db.initDatabase()}networkProbe(){this._connection.probe()}isConnected(){return this._connection.isConnected()}isAuthenticated(){return this._authenticated}authorizeURL(e){if("string"!=typeof e)return e;if(g(e)){const t="scheme://host/",s=new URL(e,t);this._apiKey&&s.searchParams.append("apikey",this._apiKey),this._authToken&&this._authToken.token&&(s.searchParams.append("auth","token"),s.searchParams.append("secret",this._authToken.token)),e=s.toString().substring(t.length-1)}return e}account(e,t,s,i,n){const r=this.#O("acc");return r.acc.user=e,r.acc.scheme=t,r.acc.secret=s,r.acc.login=i,n&&(r.acc.desc.defacs=n.defacs,r.acc.desc.public=n.public,r.acc.desc.private=n.private,r.acc.desc.trusted=n.trusted,r.acc.tags=n.tags,r.acc.cred=n.cred,r.acc.tmpscheme=n.scheme,r.acc.tmpsecret=n.secret,Array.isArray(n.attachments)&&n.attachments.length>0&&(r.extra={attachments:n.attachments.filter((e=>g(e)))})),this.#C(r,r.acc.id)}createAccount(e,t,s,i){let n=this.account("new",e,t,s,i);return s&&(n=n.then((e=>this.#L(e)))),n}createAccountBasic(e,t,s){return e=e||"",t=t||"",this.createAccount("basic",z(e+":"+t),!0,s)}updateAccountBasic(e,t,s,i){return t=t||"",s=s||"",this.account(e,"basic",z(t+":"+s),!1,i)}hello(){const e=this.#O("hi");return this.#C(e,e.hi.id).then((e=>(this._connection.backoffReset(),e.params&&(this._serverInfo=e.params),this.onConnect&&this.onConnect(),e))).catch((e=>{this._connection.reconnect(!0),this.onDisconnect&&this.onDisconnect(e)}))}setDeviceToken(e){let t=!1;return(e=e||null)!=this._deviceToken&&(this._deviceToken=e,this.isConnected()&&this.isAuthenticated()&&(this.#C({hi:{dev:e||K.DEL_CHAR}}),t=!0)),t}login(e,t,s){const i=this.#O("login");return i.login.scheme=e,i.login.secret=t,i.login.cred=s,this.#C(i,i.login.id).then((e=>this.#L(e)))}loginBasic(e,t,s){return this.login("basic",z(e+":"+t),s).then((t=>(this._login=e,t)))}loginToken(e,t){return this.login("token",e,t)}requestResetAuthSecret(e,t,s){return this.login("reset",z(e+":"+t+":"+s))}getAuthToken(){return this._authToken&&this._authToken.expires.getTime()>Date.now()?this._authToken:(this._authToken=null,null)}setAuthToken(e){this._authToken=e}subscribe(e,t,s){const i=this.#O("sub",e);if(e||(e=r),i.sub.get=t,s){if(s.sub&&(i.sub.set.sub=s.sub),s.desc){const t=s.desc;K.isNewGroupTopicName(e)?i.sub.set.desc=t:K.isP2PTopicName(e)&&t.defacs&&(i.sub.set.desc={defacs:t.defacs})}Array.isArray(s.attachments)&&s.attachments.length>0&&(i.extra={attachments:s.attachments.filter((e=>g(e)))}),s.tags&&(i.sub.set.tags=s.tags),s.aux&&(i.sub.set.aux=s.aux)}return this.#C(i,i.sub.id)}leave(e,t){const s=this.#O("leave",e);return s.leave.unsub=t,this.#C(s,s.leave.id)}createMessage(e,t,s){const i=this.#O("pub",e);let n="string"==typeof t?N().parse(t):t;return n&&!N().isPlainText(n)&&(i.pub.head={mime:N().getContentType()},t=n),i.pub.noecho=s,i.pub.content=t,i.pub}publish(e,t,s){return this.publishMessage(this.createMessage(e,t,s))}publishMessage(e,t){(e=Object.assign({},e)).seq=void 0,e.from=void 0,e.ts=void 0;const s={pub:e};return t&&(s.extra={attachments:t.filter((e=>g(e)))}),this.#C(s,e.id)}oobNotification(t){switch(this.logger("oob: "+(this._trimLongStrings?JSON.stringify(t,F):t)),t.what){case"msg":if(!t.seq||t.seq<1||!t.topic)break;if(!this.isConnected())break;const s=this.#D("topic",t.topic);if(!s)break;if(s.isSubscribed())break;s.maxMsgSeq()\n *
\n * Also supports forms and buttons.\n *\n * Nested formatting is supported, e.g. *abc _def_* -> abc def\n * URLs, @mentions, and #hashtags are extracted and converted into links.\n * Forms and buttons can be added procedurally.\n * JSON data representation is inspired by Draft.js raw formatting.\n *\n *\n * @example\n * Text:\n * abc\n * this is *bold*, `code` and _italic_, ~strike~\n * combined *bold and _italic_*\n * an url: https://www.example.com/abc#fragment and another _www.tinode.co_\n * this is a @mention and a #hashtag in a string\n * second #hashtag\n *
\n *\n * Sample JSON representation of the text above:\n * {\n * \"txt\": \"this is bold, code and italic, strike combined bold and italic an url: https://www.example.com/abc#fragment \" +\n * \"and another www.tinode.co this is a @mention and a #hashtag in a string second #hashtag\",\n * \"fmt\": [\n * { \"at\":8, \"len\":4,\"tp\":\"ST\" },{ \"at\":14, \"len\":4, \"tp\":\"CO\" },{ \"at\":23, \"len\":6, \"tp\":\"EM\"},\n * { \"at\":31, \"len\":6, \"tp\":\"DL\" },{ \"tp\":\"BR\", \"len\":1, \"at\":37 },{ \"at\":56, \"len\":6, \"tp\":\"EM\" },\n * { \"at\":47, \"len\":15, \"tp\":\"ST\" },{ \"tp\":\"BR\", \"len\":1, \"at\":62 },{ \"at\":120, \"len\":13, \"tp\":\"EM\" },\n * { \"at\":71, \"len\":36, \"key\":0 },{ \"at\":120, \"len\":13, \"key\":1 },{ \"tp\":\"BR\", \"len\":1, \"at\":133 },\n * { \"at\":144, \"len\":8, \"key\":2 },{ \"at\":159, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":179 },\n * { \"at\":187, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":195 }\n * ],\n * \"ent\": [\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"https://www.example.com/abc#fragment\" } },\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"http://www.tinode.co\" } },\n * { \"tp\":\"MN\", \"data\":{ \"val\":\"mention\" } },\n * { \"tp\":\"HT\", \"data\":{ \"val\":\"hashtag\" } }\n * ]\n * }\n */\n\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nconst MAX_FORM_ELEMENTS = 8;\nconst MAX_PREVIEW_ATTACHMENTS = 3;\nconst MAX_PREVIEW_DATA_SIZE = 64;\nconst JSON_MIME_TYPE = 'application/json';\nconst DRAFTY_MIME_TYPE = 'text/x-drafty';\nconst ALLOWED_ENT_FIELDS = ['act', 'height', 'duration', 'incoming', 'mime', 'name', 'premime', 'preref', 'preview',\n 'ref', 'size', 'state', 'url', 'val', 'width'\n];\n\n// Regular expressions for parsing inline formats. Javascript does not support lookbehind,\n// so it's a bit messy.\nconst INLINE_STYLES = [\n // Strong = bold, *bold text*\n {\n name: 'ST',\n start: /(?:^|[\\W_])(\\*)[^\\s*]/,\n end: /[^\\s*](\\*)(?=$|[\\W_])/\n },\n // Emphesized = italic, _italic text_\n {\n name: 'EM',\n start: /(?:^|\\W)(_)[^\\s_]/,\n end: /[^\\s_](_)(?=$|\\W)/\n },\n // Deleted, ~strike this though~\n {\n name: 'DL',\n start: /(?:^|[\\W_])(~)[^\\s~]/,\n end: /[^\\s~](~)(?=$|[\\W_])/\n },\n // Code block `this is monospace`\n {\n name: 'CO',\n start: /(?:^|\\W)(`)[^`]/,\n end: /[^`](`)(?=$|\\W)/\n }\n];\n\n// Relative weights of formatting spans. Greater index in array means greater weight.\nconst FMT_WEIGHT = ['QQ'];\n\n// RegExps for entity extraction (RF = reference)\nconst ENTITY_TYPES = [\n // URLs\n {\n name: 'LN',\n dataName: 'url',\n pack: function(val) {\n // Check if the protocol is specified, if not use http\n if (!/^[a-z]+:\\/\\//i.test(val)) {\n val = 'http://' + val;\n }\n return {\n url: val\n };\n },\n re: /(?:(?:https?|ftp):\\/\\/|www\\.|ftp\\.)[-A-Z0-9+&@#\\/%=~_|$?!:,.]*[A-Z0-9+&@#\\/%=~_|$]/ig\n },\n // Mentions @user (must be 2 or more characters)\n {\n name: 'MN',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B@([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n },\n // Hashtags #hashtag, like metion 2 or more characters.\n {\n name: 'HT',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B#([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n }\n];\n\n// HTML tag name suggestions\nconst FORMAT_TAGS = {\n AU: {\n html_tag: 'audio',\n md_tag: undefined,\n isVoid: false\n },\n BN: {\n html_tag: 'button',\n md_tag: undefined,\n isVoid: false\n },\n BR: {\n html_tag: 'br',\n md_tag: '\\n',\n isVoid: true\n },\n CO: {\n html_tag: 'tt',\n md_tag: '`',\n isVoid: false\n },\n DL: {\n html_tag: 'del',\n md_tag: '~',\n isVoid: false\n },\n EM: {\n html_tag: 'i',\n md_tag: '_',\n isVoid: false\n },\n EX: {\n html_tag: '',\n md_tag: undefined,\n isVoid: true\n },\n FM: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n HD: {\n html_tag: '',\n md_tag: undefined,\n isVoid: false\n },\n HL: {\n html_tag: 'span',\n md_tag: undefined,\n isVoid: false\n },\n HT: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n IM: {\n html_tag: 'img',\n md_tag: undefined,\n isVoid: false\n },\n LN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n MN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n RW: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false,\n },\n QQ: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n ST: {\n html_tag: 'b',\n md_tag: '*',\n isVoid: false\n },\n VC: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n VD: {\n html_tag: 'video',\n md_tag: undefined,\n isVoid: false\n }\n};\n\n// Convert base64-encoded string into Blob.\nfunction base64toObjectUrl(b64, contentType, logger) {\n if (!b64) {\n return null;\n }\n\n try {\n const bin = atob(b64);\n const length = bin.length;\n const buf = new ArrayBuffer(length);\n const arr = new Uint8Array(buf);\n for (let i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n\n return URL.createObjectURL(new Blob([buf], {\n type: contentType\n }));\n } catch (err) {\n if (logger) {\n logger(\"Drafty: failed to convert object.\", err.message);\n }\n }\n\n return null;\n}\n\nfunction base64toDataUrl(b64, contentType) {\n if (!b64) {\n return null;\n }\n contentType = contentType || 'image/jpeg';\n return 'data:' + contentType + ';base64,' + b64;\n}\n\n// Helpers for converting Drafty to HTML.\nconst DECORATORS = {\n // Visial styles\n ST: {\n open: _ => '',\n close: _ => ''\n },\n EM: {\n open: _ => '',\n close: _ => ''\n },\n DL: {\n open: _ => '',\n close: _ => ''\n },\n CO: {\n open: _ => '',\n close: _ => ''\n },\n // Line break\n BR: {\n open: _ => '
',\n close: _ => ''\n },\n // Hidden element\n HD: {\n open: _ => '',\n close: _ => ''\n },\n // Highlighted element.\n HL: {\n open: _ => '',\n close: _ => ''\n },\n // Link (URL)\n LN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n href: data.url,\n target: '_blank'\n } : null;\n },\n },\n // Mention\n MN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Hashtag\n HT: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Button\n BN: {\n open: _ => '',\n props: (data) => {\n return data ? {\n 'data-act': data.act,\n 'data-val': data.val,\n 'data-name': data.name,\n 'data-ref': data.ref\n } : null;\n },\n },\n // Audio recording\n AU: {\n open: (data) => {\n const url = data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger);\n return '',\n props: (data) => {\n if (!data) return null;\n return {\n // Embedded data or external link.\n src: data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-duration': data.duration,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n // Image\n IM: {\n open: data => {\n // Don't use data.ref for preview: it's a security risk.\n const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime);\n const previewUrl = base64toObjectUrl(data.val, data.mime, Drafty.logger);\n const downloadUrl = data.ref || previewUrl;\n return (data.name ? '' : '') +\n '';\n },\n close: data => {\n return (data.name ? '' : '');\n },\n props: data => {\n if (!data) return null;\n return {\n // Temporary preview, or permanent preview, or external link.\n src: base64toDataUrl(data._tempPreview, data.mime) ||\n data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n title: data.name,\n alt: data.name,\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n },\n },\n // Form - structured layout of elements.\n FM: {\n open: _ => '
';\n },\n close: _ => '',\n props: data => {\n if (!data) return null;\n const poster = data.preref || base64toObjectUrl(data.preview, data.premime || 'image/jpeg', Drafty.logger);\n return {\n // Embedded data or external link.\n src: poster,\n 'data-src': data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-preview': poster,\n 'data-duration': data.duration | 0,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n};\n\n/**\n * The main object which performs all the formatting actions.\n * @class Drafty\n * @constructor\n */\nconst Drafty = function() {\n this.txt = '';\n this.fmt = [];\n this.ent = [];\n}\n\n/**\n * Initialize Drafty document to a plain text string.\n *\n * @param {string} plainText - string to use as Drafty content.\n *\n * @returns new Drafty document or null is plainText is not a string or undefined.\n */\nDrafty.init = function(plainText) {\n if (typeof plainText == 'undefined') {\n plainText = '';\n } else if (typeof plainText != 'string') {\n return null;\n }\n\n return {\n txt: plainText\n };\n}\n\n/**\n * Parse plain text into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} content - plain-text content to parse.\n * @return {Drafty} parsed document or null if the source is not plain text.\n */\nDrafty.parse = function(content) {\n // Make sure we are parsing strings only.\n if (typeof content != 'string') {\n return null;\n }\n\n // Split text into lines. It makes further processing easier.\n const lines = content.split(/\\r?\\n/);\n\n // Holds entities referenced from text\n const entityMap = [];\n const entityIndex = {};\n\n // Processing lines one by one, hold intermediate result in blx.\n const blx = [];\n lines.forEach((line) => {\n let spans = [];\n let entities;\n\n // Find formatted spans in the string.\n // Try to match each style.\n INLINE_STYLES.forEach((tag) => {\n // Each style could be matched multiple times.\n spans = spans.concat(spannify(line, tag.start, tag.end, tag.name));\n });\n\n let block;\n if (spans.length == 0) {\n block = {\n txt: line\n };\n } else {\n // Sort spans by style occurence early -> late, then by length: first long then short.\n spans.sort((a, b) => {\n const diff = a.at - b.at;\n return diff != 0 ? diff : b.end - a.end;\n });\n\n // Convert an array of possibly overlapping spans into a tree.\n spans = toSpanTree(spans);\n\n // Build a tree representation of the entire string, not\n // just the formatted parts.\n const chunks = chunkify(line, 0, line.length, spans);\n\n const drafty = draftify(chunks, 0);\n\n block = {\n txt: drafty.txt,\n fmt: drafty.fmt\n };\n }\n\n // Extract entities from the cleaned up string.\n entities = extractEntities(block.txt);\n if (entities.length > 0) {\n const ranges = [];\n for (let i in entities) {\n // {offset: match['index'], unique: match[0], len: match[0].length, data: ent.packer(), type: ent.name}\n const entity = entities[i];\n let index = entityIndex[entity.unique];\n if (!index) {\n index = entityMap.length;\n entityIndex[entity.unique] = index;\n entityMap.push({\n tp: entity.type,\n data: entity.data\n });\n }\n ranges.push({\n at: entity.offset,\n len: entity.len,\n key: index\n });\n }\n block.ent = ranges;\n }\n\n blx.push(block);\n });\n\n const result = {\n txt: ''\n };\n\n // Merge lines and save line breaks as BR inline formatting.\n if (blx.length > 0) {\n result.txt = blx[0].txt;\n result.fmt = (blx[0].fmt || []).concat(blx[0].ent || []);\n\n for (let i = 1; i < blx.length; i++) {\n const block = blx[i];\n const offset = result.txt.length + 1;\n\n result.fmt.push({\n tp: 'BR',\n len: 1,\n at: offset - 1\n });\n\n result.txt += ' ' + block.txt;\n if (block.fmt) {\n result.fmt = result.fmt.concat(block.fmt.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n if (block.ent) {\n result.fmt = result.fmt.concat(block.ent.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n }\n\n if (result.fmt.length == 0) {\n delete result.fmt;\n }\n\n if (entityMap.length > 0) {\n result.ent = entityMap;\n }\n }\n return result;\n}\n\n/**\n * Append one Drafty document to another.\n *\n * @param {Drafty} first - Drafty document to append to.\n * @param {Drafty|string} second - Drafty document or string being appended.\n *\n * @return {Drafty} first document with the second appended to it.\n */\nDrafty.append = function(first, second) {\n if (!first) {\n return second;\n }\n if (!second) {\n return first;\n }\n\n first.txt = first.txt || '';\n const len = first.txt.length;\n\n if (typeof second == 'string') {\n first.txt += second;\n } else if (second.txt) {\n first.txt += second.txt;\n }\n\n if (Array.isArray(second.fmt)) {\n first.fmt = first.fmt || [];\n if (Array.isArray(second.ent)) {\n first.ent = first.ent || [];\n }\n second.fmt.forEach(src => {\n const fmt = {\n at: (src.at | 0) + len,\n len: src.len | 0\n };\n // Special case for the outside of the normal rendering flow styles.\n if (src.at == -1) {\n fmt.at = -1;\n fmt.len = 0;\n }\n if (src.tp) {\n fmt.tp = src.tp;\n } else {\n fmt.key = first.ent.length;\n first.ent.push(second.ent[src.key || 0]);\n }\n first.fmt.push(fmt);\n });\n }\n\n return first;\n}\n\n/**\n * Description of an image to attach.\n * @typedef {Object} ImageDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the image, e.g. \"image/png\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded image content. Could be null/undefined.\n * @property {string} preview - base64-encoded thumbnail of the image.\n * @property {integer} width - width of the image.\n * @property {integer} height - height of the image.\n * @property {string} filename - file name suggestion for downloading the image.\n * @property {integer} size - size of the image in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded image preview used during upload process; not serializable.\n * @property {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {integer} at - index where the object is inserted. The length of the image is always 1.\n * @param {ImageDesc} imageDesc - object with image paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertImage = function(content, at, imageDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'IM',\n data: {\n mime: imageDesc.mime,\n ref: imageDesc.refurl,\n val: imageDesc.bits || imageDesc.preview,\n width: imageDesc.width,\n height: imageDesc.height,\n name: imageDesc.filename,\n size: imageDesc.size | 0,\n }\n };\n\n if (imageDesc.urlPromise) {\n ex.data._tempPreview = imageDesc._tempPreview;\n ex.data._processing = true;\n imageDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Description of a video to attach.\n * @typedef {Object} VideoDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the video, e.g. \"video/mpeg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - in-band base64-encoded image data. Could be null/undefined.\n * @property {string} preview - base64-encoded screencapture from the video. Could be null/undefined.\n * @property {string} preref - reference to screencapture from the video. Could be null/undefined.\n * @property {integer} width - width of the video.\n * @property {integer} height - height of the video.\n * @property {integer} duration - duration of the video.\n * @property {string} filename - file name suggestion for downloading the video.\n * @property {integer} size - size of the video in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded screencapture used during upload process; not serializable.\n * @property {Promise} urlPromise - array of two promises, which return URLs of video and preview uploads correspondingly\n * (either could be null).\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add video to.\n * @param {integer} at - index where the object is inserted. The length of the video is always 1.\n * @param {VideoDesc} videoDesc - object with video paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertVideo = function(content, at, videoDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'VD',\n data: {\n mime: videoDesc.mime,\n ref: videoDesc.refurl,\n val: videoDesc.bits,\n preref: videoDesc.preref,\n preview: videoDesc.preview,\n width: videoDesc.width,\n height: videoDesc.height,\n duration: videoDesc.duration | 0,\n name: videoDesc.filename,\n size: videoDesc.size | 0,\n }\n };\n\n if (videoDesc.urlPromise) {\n ex.data._tempPreview = videoDesc._tempPreview;\n ex.data._processing = true;\n videoDesc.urlPromise.then(\n urls => {\n ex.data.ref = urls[0];\n ex.data.preref = urls[1];\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Description of an audio recording to attach.\n * @typedef {Object} AudioDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the audio, e.g. \"audio/ogg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded audio content. Could be null/undefined.\n * @property {integer} duration - duration of the record in milliseconds.\n * @property {string} preview - base64 encoded short array of amplitude values 0..100.\n * @property {string} filename - file name suggestion for downloading the audio.\n * @property {integer} size - size of the recording in bytes. Treat is as an untrusted hint.\n * @property {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert audio recording into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add audio record to.\n * @param {integer} at - index where the object is inserted. The length of the record is always 1.\n * @param {AudioDesc} audioDesc - object with the audio paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertAudio = function(content, at, audioDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'AU',\n data: {\n mime: audioDesc.mime,\n val: audioDesc.bits,\n duration: audioDesc.duration | 0,\n preview: audioDesc.preview,\n name: audioDesc.filename,\n size: audioDesc.size | 0,\n ref: audioDesc.refurl\n }\n };\n\n if (audioDesc.urlPromise) {\n ex.data._processing = true;\n audioDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Create a (self-contained) video call Drafty document.\n * @memberof Drafty\n * @static\n * @param {boolean} audioOnly
true if the call is initially audio-only.\n * @returns Video Call drafty document.\n */\nDrafty.videoCall = function(audioOnly) {\n const content = {\n txt: ' ',\n fmt: [{\n at: 0,\n len: 1,\n key: 0\n }],\n ent: [{\n tp: 'VC',\n data: {\n aonly: audioOnly\n },\n }]\n };\n return content;\n}\n\n/**\n * Update video call (VC) entity with the new status and duration.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - VC document to update.\n * @param {object} params - new video call parameters.\n * @param {string} params.state - state of video call.\n * @param {number} params.duration - duration of the video call in milliseconds.\n *\n * @returns the same document with update applied.\n */\nDrafty.updateVideoCall = function(content, params) {\n // The video element could be just a format or a format + entity.\n // Must ensure it's the latter first.\n const fmt = ((content || {}).fmt || [])[0];\n if (!fmt) {\n // Unrecognized content.\n return content;\n }\n\n let ent;\n if (fmt.tp == 'VC') {\n // Just a format, convert to format + entity.\n delete fmt.tp;\n fmt.key = 0;\n ent = {\n tp: 'VC'\n };\n content.ent = [ent];\n } else {\n ent = (content.ent || [])[fmt.key | 0];\n if (!ent || ent.tp != 'VC') {\n // Not a VC entity.\n return content;\n }\n }\n ent.data = ent.data || {};\n Object.assign(ent.data, params);\n return content;\n}\n\n/**\n * Create a quote to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} header - Quote header (title, etc.).\n * @param {string} uid - UID of the author to mention.\n * @param {Drafty} body - Body of the quoted message.\n *\n * @returns Reply quote Drafty doc with the quote formatting.\n */\nDrafty.quote = function(header, uid, body) {\n const quote = Drafty.append(Drafty.appendLineBreak(Drafty.mention(header, uid)), body);\n\n // Wrap into a quote.\n quote.fmt.push({\n at: 0,\n len: quote.txt.length,\n tp: 'QQ'\n });\n\n return quote;\n}\n\n/**\n * Create a Drafty document with a mention.\n *\n * @param {string} name - mentioned name.\n * @param {string} uid - mentioned user ID.\n *\n * @returns {Drafty} document with the mention.\n */\nDrafty.mention = function(name, uid) {\n return {\n txt: name || '',\n fmt: [{\n at: 0,\n len: (name || '').length,\n key: 0\n }],\n ent: [{\n tp: 'MN',\n data: {\n val: uid\n }\n }]\n };\n}\n\n/**\n * Append a link to a Drafty document.\n *\n * @param {Drafty} content - Drafty document to append link to.\n * @param {Object} linkData - Link info in format {txt: 'ankor text', url: 'http://...'}.\n *\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLink = function(content, linkData) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: content.txt.length,\n len: linkData.txt.length,\n key: content.ent.length\n });\n content.txt += linkData.txt;\n\n const ex = {\n tp: 'LN',\n data: {\n url: linkData.url\n }\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Append image to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {ImageDesc} imageDesc - object with image paramenets.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendImage = function(content, imageDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertImage(content, content.txt.length - 1, imageDesc);\n}\n\n/**\n * Append audio recodring to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add recording to.\n * @param {AudioDesc} audioDesc - object with audio data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendAudio = function(content, audioDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertAudio(content, content.txt.length - 1, audioDesc);\n}\n\n/**\n * Description of a file to attach.\n * @typedef {Object} AttachmentDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the attachment, e.g. \"application/octet-stream\"\n * @property {string} data - base64-encoded in-band content of small attachments. Could be null/undefined.\n * @property {string} filename - file name suggestion for downloading the attachment.\n * @property {integer} size - size of the file in bytes. Treat is as an untrusted hint.\n * @property {string} refurl - reference to the out-of-band content. Could be null/undefined.\n * @property {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Attach file to Drafty content. Either as a blob or as a reference.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to attach file to.\n * @param {AttachmentDesc} object - containing attachment description and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.attachFile = function(content, attachmentDesc) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'EX',\n data: {\n mime: attachmentDesc.mime,\n val: attachmentDesc.data,\n name: attachmentDesc.filename,\n ref: attachmentDesc.refurl,\n size: attachmentDesc.size | 0\n }\n }\n if (attachmentDesc.urlPromise) {\n ex.data._processing = true;\n attachmentDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n /* catch the error, otherwise it will appear in the console. */\n ex.data._processing = undefined;\n }\n );\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Wraps drafty document into a simple formatting style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - document or string to wrap into a style.\n * @param {string} style - two-letter style to wrap into.\n * @param {number} at - index where the style starts, default 0.\n * @param {number} len - length of the form content, default all of it.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapInto = function(content, style, at, len) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at || 0,\n len: len || content.txt.length,\n tp: style,\n });\n\n return content;\n}\n\n/**\n * Wraps content into an interactive form.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - to wrap into a form.\n * @param {number} at - index where the forms starts.\n * @param {number} len - length of the form content.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapAsForm = function(content, at, len) {\n return Drafty.wrapInto(content, 'FM', at, len);\n}\n\n/**\n * Insert clickable button into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {number} at - location where the button is inserted.\n * @param {number} len - the length of the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertButton = function(content, at, len, name, actionType, actionValue, refUrl) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n\n if (!content || !content.txt || content.txt.length < at + len) {\n return null;\n }\n\n if (len <= 0 || ['url', 'pub'].indexOf(actionType) == -1) {\n return null;\n }\n // Ensure refUrl is a string.\n if (actionType == 'url' && !refUrl) {\n return null;\n }\n refUrl = '' + refUrl;\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: len,\n key: content.ent.length\n });\n content.ent.push({\n tp: 'BN',\n data: {\n act: actionType,\n val: actionValue,\n ref: refUrl,\n name: name\n }\n });\n\n return content;\n}\n\n/**\n * Append clickable button to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {string} title - the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendButton = function(content, title, name, actionType, actionValue, refUrl) {\n content = content || {\n txt: ''\n };\n const at = content.txt.length;\n content.txt += title;\n return Drafty.insertButton(content, at, title.length, name, actionType, actionValue, refUrl);\n}\n\n/**\n * Attach a generic JS object. The object is attached as a json string.\n * Intended for representing a form response.\n *\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to attach file to.\n * @param {Object} data - data to convert to json string and attach.\n * @returns {Drafty} the same document as content.\n */\nDrafty.attachJSON = function(content, data) {\n content = content || {\n txt: ''\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n content.ent.push({\n tp: 'EX',\n data: {\n mime: JSON_MIME_TYPE,\n val: data\n }\n });\n\n return content;\n}\n/**\n * Append line break to a Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to append linebreak to.\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLineBreak = function(content) {\n content = content || {\n txt: ''\n };\n content.fmt = content.fmt || [];\n content.fmt.push({\n at: content.txt.length,\n len: 1,\n tp: 'BR'\n });\n content.txt += ' ';\n\n return content;\n}\n/**\n * Given Drafty document, convert it to HTML.\n * No attempt is made to strip pre-existing html markup.\n * This is potentially unsafe because content.txt may contain malicious HTML\n * markup.\n * @memberof Tinode.Drafty\n * @static\n *\n * @param {Drafty} doc - document to convert.\n *\n * @returns {string} HTML-representation of content.\n */\nDrafty.UNSAFE_toHTML = function(doc) {\n const tree = draftyToTree(doc);\n const htmlFormatter = function(type, data, values) {\n const tag = DECORATORS[type];\n let result = values ? values.join('') : '';\n if (tag) {\n result = tag.open(data) + result + tag.close(data);\n }\n return result;\n };\n return treeBottomUp(tree, htmlFormatter, 0);\n}\n\n/**\n * Callback for applying custom formatting to a Drafty document.\n * Called once for each style span.\n * @memberof Drafty\n * @static\n *\n * @callback Formatter\n * @param {string} style - style code such as \"ST\" or \"IM\".\n * @param {Object} data - entity's data.\n * @param {Object} values - possibly styled subspans contained in this style span.\n * @param {number} index - index of the element guaranteed to be unique.\n */\n\n/**\n * Convert Drafty document to a representation suitable for display.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|Object} content - Drafty document to transform.\n * @param {Formatter} formatter - callback which formats individual elements.\n * @param {Object} context - context provided to formatter as this.\n *\n * @return {Object} transformed object\n */\nDrafty.format = function(original, formatter, context) {\n return treeBottomUp(draftyToTree(original), formatter, 0, [], context);\n}\n\n/**\n * Shorten Drafty document making the drafty text no longer than the limit.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characrets to shorten to.\n * @param {boolean} light - remove heavy data from entities.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.shorten = function(original, limit, light) {\n let tree = draftyToTree(original);\n tree = shortenTree(tree, limit, '…');\n if (tree && light) {\n tree = lightEntity(tree);\n }\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Transform Drafty doc for forwarding: strip leading @mention and any leading line breaks or whitespace.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.forwardedContent = function(original) {\n let tree = draftyToTree(original);\n const rmMention = function(node) {\n if (node.type == 'MN') {\n if (!node.parent || !node.parent.type) {\n return null;\n }\n }\n return node;\n }\n // Strip leading mention.\n tree = treeTopDown(tree, rmMention);\n // Remove leading whitespace.\n tree = lTrim(tree);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Prepare Drafty doc for wrapping into QQ as a reply:\n * - Replace forwarding mention with symbol '➦' and remove data (UID).\n * - Remove quoted text completely.\n * - Replace line breaks with spaces.\n * - Strip entities of heavy content.\n * - Move attachments to the end of the document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.replyContent = function(original, limit) {\n const convMNnQQnBR = function(node) {\n if (node.type == 'QQ') {\n return null;\n } else if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n delete node.data;\n }\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.type;\n delete node.children;\n }\n return node;\n }\n\n let tree = draftyToTree(original);\n if (!tree) {\n return original;\n }\n\n // Strip leading mention.\n tree = treeTopDown(tree, convMNnQQnBR);\n // Move attachments to the end of the doc.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n // Shorten the doc.\n tree = shortenTree(tree, limit, '…');\n // Strip heavy elements except IM.data['val'] and VD.data['preview'] (have to keep them to generate previews later).\n const filter = node => {\n switch (node.type) {\n case 'IM':\n return ['val'];\n case 'VD':\n return ['preview'];\n }\n return null;\n };\n tree = lightEntity(tree, filter);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n\n/**\n * Generate drafty preview:\n * - Shorten the document.\n * - Strip all heavy entity data leaving just inline styles and entity references.\n * - Replace line breaks with spaces.\n * - Replace content of QQ with a space.\n * - Replace forwarding mention with symbol '➦'.\n * move all attachments to the end of the document and make them visible.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @param {boolean} forwarding - this a forwarding message preview.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.preview = function(original, limit, forwarding) {\n let tree = draftyToTree(original);\n\n // Move attachments to the end.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n\n // Convert leading mention to '➦' and replace QQ and BR with a space ' '.\n const convMNnQQnBR = function(node) {\n if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n }\n } else if (node.type == 'QQ') {\n node.text = ' ';\n delete node.children;\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.children;\n delete node.type;\n }\n return node;\n }\n tree = treeTopDown(tree, convMNnQQnBR);\n\n tree = shortenTree(tree, limit, '…');\n if (forwarding) {\n // Keep some IM and VD data for preview.\n const filter = {\n IM: ['val'],\n VD: ['preview']\n };\n tree = lightEntity(tree, node => {\n return filter[node.type];\n });\n } else {\n tree = lightEntity(tree);\n }\n\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Given Drafty document, convert it to plain text.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text.\n * @returns {string} plain-text representation of the drafty document.\n */\nDrafty.toPlainText = function(content) {\n return typeof content == 'string' ? content : content.txt;\n}\n\n/**\n * Check if the document has no markup and no entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for presence of markup.\n * @returns true is content is plain text, false otherwise.\n */\nDrafty.isPlainText = function(content) {\n return typeof content == 'string' || !(content.fmt || content.ent);\n}\n\n/**\n * Convert document to plain text with markdown. All elements which cannot\n * be represented in markdown are stripped.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text with markdown.\n */\nDrafty.toMarkdown = function(content) {\n let tree = draftyToTree(content);\n const mdFormatter = function(type, _, values) {\n const def = FORMAT_TAGS[type];\n let result = (values ? values.join('') : '');\n if (def) {\n if (def.isVoid) {\n result = def.md_tag || '';\n } else if (def.md_tag) {\n result = def.md_tag + result + def.md_tag;\n }\n }\n return result;\n };\n return treeBottomUp(tree, mdFormatter, 0);\n}\n\n/**\n * Checks if the object represets is a valid Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for validity.\n * @returns true is content is valid, false otherwise.\n */\nDrafty.isValid = function(content) {\n if (!content) {\n return false;\n }\n\n const {\n txt,\n fmt,\n ent\n } = content;\n\n if (!txt && txt !== '' && !fmt && !ent) {\n return false;\n }\n\n const txt_type = typeof txt;\n if (txt_type != 'string' && txt_type != 'undefined' && txt !== null) {\n return false;\n }\n\n if (typeof fmt != 'undefined' && !Array.isArray(fmt) && fmt !== null) {\n return false;\n }\n\n if (typeof ent != 'undefined' && !Array.isArray(ent) && ent !== null) {\n return false;\n }\n return true;\n}\n\n/**\n * Check if the drafty document has attachments: style EX and outside of normal rendering flow,\n * i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for attachments.\n * @returns true if there are attachments.\n */\nDrafty.hasAttachments = function(content) {\n if (!Array.isArray(content.fmt)) {\n return false;\n }\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n return ent && ent.tp == 'EX' && ent.data;\n }\n }\n return false;\n}\n\n/**\n * Callback for enumerating entities in a Drafty document.\n * Called once for each entity.\n * @memberof Drafty\n * @static\n *\n * @callback EntityCallback\n * @param {Object} data entity data.\n * @param {string} entity type.\n * @param {number} index entity's index in `content.ent`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate attachments: style EX and outside of normal rendering flow, i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to process for attachments.\n * @param {EntityCallback} callback - callback to call for each attachment.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.attachments = function(content, callback, context) {\n if (!Array.isArray(content.fmt)) {\n return;\n }\n let count = 0;\n for (let i in content.ent) {\n let fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n if (ent && ent.tp == 'EX' && ent.data) {\n if (callback.call(context, ent.data, count++, 'EX')) {\n break;\n }\n }\n }\n };\n}\n\n/**\n * Check if the drafty document has entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for entities.\n * @returns true if there are entities.\n */\nDrafty.hasEntities = function(content) {\n return content.ent && content.ent.length > 0;\n}\n\n/**\n * Enumerate entities. Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @param {EntityCallback} callback - callback to call for each entity.\n * @param {Object} context - value of \"this\" for callback.\n *\n */\nDrafty.entities = function(content, callback, context) {\n if (content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n if (content.ent[i]) {\n if (callback.call(context, content.ent[i].data, i, content.ent[i].tp)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Callback for enumerating styles (inline formats) in a Drafty document.\n * Called once for each style.\n * @memberof Drafty\n * @static\n *\n * @callback StyleCallback\n * @param {string} tp - format type.\n * @param {number} at - starting position of the format in text.\n * @param {number} len - extent of the format in characters.\n * @param {number} key - index of the entity if format is a reference.\n * @param {number} index - style's index in `content.fmt`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate styles (inline formats). Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with styles (formats) to enumerate.\n * @param {StyleCallback} callback - callback to call for each format.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.styles = function(content, callback, context) {\n if (content.fmt && content.fmt.length > 0) {\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt) {\n if (callback.call(context, fmt.tp, fmt.at, fmt.len, fmt.key, i)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Remove unrecognized fields from entity data\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @returns content.\n */\nDrafty.sanitizeEntities = function(content) {\n if (content && content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n const ent = content.ent[i];\n if (ent && ent.data) {\n const data = copyEntData(ent.data);\n if (data) {\n content.ent[i].data = data;\n } else {\n delete content.ent[i].data;\n }\n }\n }\n }\n return content;\n}\n\n/**\n * Given the entity, get URL which can be used for downloading\n * entity data.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the URl from.\n * @returns {string} URL to download entity data or null.\n */\nDrafty.getDownloadUrl = function(entData) {\n let url = null;\n if (entData.mime != JSON_MIME_TYPE && entData.val) {\n url = base64toObjectUrl(entData.val, entData.mime, Drafty.logger);\n } else if (typeof entData.ref == 'string') {\n url = entData.ref;\n }\n return url;\n}\n\n/**\n * Check if the entity data is not ready for sending, such as being uploaded to the server.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n * @returns {boolean} true if upload is in progress, false otherwise.\n */\nDrafty.isProcessing = function(entData) {\n return !!entData._processing;\n}\n\n/**\n * Given the entity, get URL which can be used for previewing\n * the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n *\n * @returns {string} url for previewing or null if no such url is available.\n */\nDrafty.getPreviewUrl = function(entData) {\n return entData.val ? base64toObjectUrl(entData.val, entData.mime, Drafty.logger) : null;\n}\n\n/**\n * Get approximate size of the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the size for.\n * @returns {number} size of entity data in bytes.\n */\nDrafty.getEntitySize = function(entData) {\n // Either size hint or length of value. The value is base64 encoded,\n // the actual object size is smaller than the encoded length.\n return entData.size ? entData.size : entData.val ? (entData.val.length * 0.75) | 0 : 0;\n}\n\n/**\n * Get entity mime type.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the type for.\n * @returns {string} mime type of entity.\n */\nDrafty.getEntityMimeType = function(entData) {\n return entData.mime || 'text/plain';\n}\n\n/**\n * Get HTML tag for a given two-letter style name.\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style, like ST or LN.\n *\n * @returns {string} HTML tag name if style is found, {code: undefined} if style is falsish or not found.\n */\nDrafty.tagName = function(style) {\n return FORMAT_TAGS[style] && FORMAT_TAGS[style].html_tag;\n}\n\n/**\n * For a given data bundle generate an object with HTML attributes,\n * for instance, given {url: \"http://www.example.com/\"} return\n * {href: \"http://www.example.com/\"}\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style to generate attributes for.\n * @param {Object} data - data bundle to convert to attributes\n *\n * @returns {Object} object with HTML attributes.\n */\nDrafty.attrValue = function(style, data) {\n if (data && DECORATORS[style]) {\n return DECORATORS[style].props(data);\n }\n\n return undefined;\n}\n\n/**\n * Drafty MIME type.\n * @memberof Drafty\n * @static\n *\n * @returns {string} content-Type \"text/x-drafty\".\n */\nDrafty.getContentType = function() {\n return DRAFTY_MIME_TYPE;\n}\n\n// =================\n// Utility methods.\n// =================\n\n// Take a string and defined earlier style spans, re-compose them into a tree where each leaf is\n// a same-style (including unstyled) string. I.e. 'hello *bold _italic_* and ~more~ world' ->\n// ('hello ', (b: 'bold ', (i: 'italic')), ' and ', (s: 'more'), ' world');\n//\n// This is needed in order to clear markup, i.e. 'hello *world*' -> 'hello world' and convert\n// ranges from markup-ed offsets to plain text offsets.\nfunction chunkify(line, start, end, spans) {\n const chunks = [];\n\n if (spans.length == 0) {\n return [];\n }\n\n for (let i in spans) {\n // Get the next chunk from the queue\n const span = spans[i];\n\n // Grab the initial unstyled chunk\n if (span.at > start) {\n chunks.push({\n txt: line.slice(start, span.at)\n });\n }\n\n // Grab the styled chunk. It may include subchunks.\n const chunk = {\n tp: span.tp\n };\n const chld = chunkify(line, span.at + 1, span.end, span.children);\n if (chld.length > 0) {\n chunk.children = chld;\n } else {\n chunk.txt = span.txt;\n }\n chunks.push(chunk);\n start = span.end + 1; // '+1' is to skip the formatting character\n }\n\n // Grab the remaining unstyled chunk, after the last span\n if (start < end) {\n chunks.push({\n txt: line.slice(start, end)\n });\n }\n\n return chunks;\n}\n\n// Detect starts and ends of formatting spans. Unformatted spans are\n// ignored at this stage.\nfunction spannify(original, re_start, re_end, type) {\n const result = [];\n let index = 0;\n let line = original.slice(0); // make a copy;\n\n while (line.length > 0) {\n // match[0]; // match, like '*abc*'\n // match[1]; // match captured in parenthesis, like 'abc'\n // match['index']; // offset where the match started.\n\n // Find the opening token.\n const start = re_start.exec(line);\n if (start == null) {\n break;\n }\n\n // Because javascript RegExp does not support lookbehind, the actual offset may not point\n // at the markup character. Find it in the matched string.\n let start_offset = start['index'] + start[0].lastIndexOf(start[1]);\n // Clip the processed part of the string.\n line = line.slice(start_offset + 1);\n // start_offset is an offset within the clipped string. Convert to original index.\n start_offset += index;\n // Index now point to the beginning of 'line' within the 'original' string.\n index = start_offset + 1;\n\n // Find the matching closing token.\n const end = re_end ? re_end.exec(line) : null;\n if (end == null) {\n break;\n }\n let end_offset = end['index'] + end[0].indexOf(end[1]);\n // Clip the processed part of the string.\n line = line.slice(end_offset + 1);\n // Update offsets\n end_offset += index;\n // Index now points to the beginning of 'line' within the 'original' string.\n index = end_offset + 1;\n\n result.push({\n txt: original.slice(start_offset + 1, end_offset),\n children: [],\n at: start_offset,\n end: end_offset,\n tp: type\n });\n }\n\n return result;\n}\n\n// Convert linear array or spans into a tree representation.\n// Keep standalone and nested spans, throw away partially overlapping spans.\nfunction toSpanTree(spans) {\n if (spans.length == 0) {\n return [];\n }\n\n const tree = [spans[0]];\n let last = spans[0];\n for (let i = 1; i < spans.length; i++) {\n // Keep spans which start after the end of the previous span or those which\n // are complete within the previous span.\n if (spans[i].at > last.end) {\n // Span is completely outside of the previous span.\n tree.push(spans[i]);\n last = spans[i];\n } else if (spans[i].end <= last.end) {\n // Span is fully inside of the previous span. Push to subnode.\n last.children.push(spans[i]);\n }\n // Span could partially overlap, ignoring it as invalid.\n }\n\n // Recursively rearrange the subnodes.\n for (let i in tree) {\n tree[i].children = toSpanTree(tree[i].children);\n }\n\n return tree;\n}\n\n// Convert drafty document to a tree.\nfunction draftyToTree(doc) {\n if (!doc) {\n return null;\n }\n\n doc = (typeof doc == 'string') ? {\n txt: doc\n } : doc;\n let {\n txt,\n fmt,\n ent\n } = doc;\n\n txt = txt || '';\n if (!Array.isArray(ent)) {\n ent = [];\n }\n\n if (!Array.isArray(fmt) || fmt.length == 0) {\n if (ent.length == 0) {\n return {\n text: txt\n };\n }\n\n // Handle special case when all values in fmt are 0 and fmt therefore is skipped.\n fmt = [{\n at: 0,\n len: 0,\n key: 0\n }];\n }\n\n // Sanitize spans.\n const spans = [];\n const attachments = [];\n fmt.forEach((span) => {\n if (!span || typeof span != 'object') {\n return;\n }\n\n if (!['undefined', 'number'].includes(typeof span.at)) {\n // Present, but non-numeric 'at'.\n return;\n }\n if (!['undefined', 'number'].includes(typeof span.len)) {\n // Present, but non-numeric 'len'.\n return;\n }\n let at = span.at | 0;\n let len = span.len | 0;\n if (len < 0) {\n // Invalid span length.\n return;\n }\n\n let key = span.key || 0;\n if (ent.length > 0 && (typeof key != 'number' || key < 0 || key >= ent.length)) {\n // Invalid key value.\n return;\n }\n\n if (at <= -1) {\n // Attachment. Store attachments separately.\n attachments.push({\n start: -1,\n end: 0,\n key: key\n });\n return;\n } else if (at + len > txt.length) {\n // Span is out of bounds.\n return;\n }\n\n if (!span.tp) {\n if (ent.length > 0 && (typeof ent[key] == 'object')) {\n spans.push({\n start: at,\n end: at + len,\n key: key\n });\n }\n } else {\n spans.push({\n type: span.tp,\n start: at,\n end: at + len\n });\n }\n });\n\n // Sort spans first by start index (asc) then by length (desc), then by weight.\n spans.sort((a, b) => {\n let diff = a.start - b.start;\n if (diff != 0) {\n return diff;\n }\n diff = b.end - a.end;\n if (diff != 0) {\n return diff;\n }\n return FMT_WEIGHT.indexOf(b.type) - FMT_WEIGHT.indexOf(a.type);\n });\n\n // Move attachments to the end of the list.\n if (attachments.length > 0) {\n spans.push(...attachments);\n }\n\n spans.forEach((span) => {\n if (ent.length > 0 && !span.type && ent[span.key] && typeof ent[span.key] == 'object') {\n span.type = ent[span.key].tp;\n span.data = ent[span.key].data;\n }\n\n // Is type still undefined? Hide the invalid element!\n if (!span.type) {\n span.type = 'HD';\n }\n });\n\n let tree = spansToTree({}, txt, 0, txt.length, spans);\n\n // Flatten tree nodes.\n const flatten = function(node) {\n if (Array.isArray(node.children) && node.children.length == 1) {\n // Unwrap.\n const child = node.children[0];\n if (!node.type) {\n const parent = node.parent;\n node = child;\n node.parent = parent;\n } else if (!child.type && !child.children) {\n node.text = child.text;\n delete node.children;\n }\n }\n return node;\n }\n tree = treeTopDown(tree, flatten);\n\n return tree;\n}\n\n// Add tree node to a parent tree.\nfunction addNode(parent, n) {\n if (!n) {\n return parent;\n }\n\n if (!parent.children) {\n parent.children = [];\n }\n\n // If text is present, move it to a subnode.\n if (parent.text) {\n parent.children.push({\n text: parent.text,\n parent: parent\n });\n delete parent.text;\n }\n\n n.parent = parent;\n parent.children.push(n);\n\n return parent;\n}\n\n// Returns a tree of nodes.\nfunction spansToTree(parent, text, start, end, spans) {\n if (!spans || spans.length == 0) {\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n return parent;\n }\n\n // Process subspans.\n for (let i = 0; i < spans.length; i++) {\n const span = spans[i];\n if (span.start < 0 && span.type == 'EX') {\n addNode(parent, {\n type: span.type,\n data: span.data,\n key: span.key,\n att: true\n });\n continue;\n }\n\n // Add un-styled range before the styled span starts.\n if (start < span.start) {\n addNode(parent, {\n text: text.substring(start, span.start)\n });\n start = span.start;\n }\n\n // Get all spans which are within the current span.\n const subspans = [];\n while (i < spans.length - 1) {\n const inner = spans[i + 1];\n if (inner.start < 0) {\n // Attachments are in the end. Stop.\n break;\n } else if (inner.start < span.end) {\n if (inner.end <= span.end) {\n const tag = FORMAT_TAGS[inner.tp] || {};\n if (inner.start < inner.end || tag.isVoid) {\n // Valid subspan: completely within the current span and\n // either non-zero length or zero length is acceptable.\n subspans.push(inner);\n }\n }\n i++;\n // Overlapping subspans are ignored.\n } else {\n // Past the end of the current span. Stop.\n break;\n }\n }\n\n addNode(parent, spansToTree({\n type: span.type,\n data: span.data,\n key: span.key\n }, text, start, span.end, subspans));\n start = span.end;\n }\n\n // Add the last unformatted range.\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n\n return parent;\n}\n\n// Append a tree to a Drafty doc.\nfunction treeToDrafty(doc, tree, keymap) {\n if (!tree) {\n return doc;\n }\n\n doc.txt = doc.txt || '';\n\n // Checkpoint to measure length of the current tree node.\n const start = doc.txt.length;\n\n if (tree.text) {\n doc.txt += tree.text;\n } else if (Array.isArray(tree.children)) {\n tree.children.forEach((c) => {\n treeToDrafty(doc, c, keymap);\n });\n }\n\n if (tree.type) {\n const len = doc.txt.length - start;\n doc.fmt = doc.fmt || [];\n if (Object.keys(tree.data || {}).length > 0) {\n doc.ent = doc.ent || [];\n const newKey = (typeof keymap[tree.key] == 'undefined') ? doc.ent.length : keymap[tree.key];\n keymap[tree.key] = newKey;\n doc.ent[newKey] = {\n tp: tree.type,\n data: tree.data\n };\n if (tree.att) {\n // Attachment.\n doc.fmt.push({\n at: -1,\n len: 0,\n key: newKey\n });\n } else {\n doc.fmt.push({\n at: start,\n len: len,\n key: newKey\n });\n }\n } else {\n doc.fmt.push({\n tp: tree.type,\n at: start,\n len: len\n });\n }\n }\n return doc;\n}\n\n// Traverse the tree top down transforming the nodes: apply transformer to every tree node.\nfunction treeTopDown(src, transformer, context) {\n if (!src) {\n return null;\n }\n\n let dst = transformer.call(context, src);\n if (!dst || !dst.children) {\n return dst;\n }\n\n const children = [];\n for (let i in dst.children) {\n let n = dst.children[i];\n if (n) {\n n = treeTopDown(n, transformer, context);\n if (n) {\n children.push(n);\n }\n }\n }\n\n if (children.length == 0) {\n dst.children = null;\n } else {\n dst.children = children;\n }\n\n return dst;\n}\n\n// Traverse the tree bottom-up: apply formatter to every node.\n// The formatter must maintain its state through context.\nfunction treeBottomUp(src, formatter, index, stack, context) {\n if (!src) {\n return null;\n }\n\n if (stack && src.type) {\n stack.push(src.type);\n }\n\n let values = [];\n for (let i in src.children) {\n const n = treeBottomUp(src.children[i], formatter, i, stack, context);\n if (n) {\n values.push(n);\n }\n }\n if (values.length == 0) {\n if (src.text) {\n values = [src.text];\n } else {\n values = null;\n }\n }\n\n if (stack && src.type) {\n stack.pop();\n }\n\n return formatter.call(context, src.type, src.data, values, index, stack);\n}\n\n// Clip tree to the provided limit.\nfunction shortenTree(tree, limit, tail) {\n if (!tree) {\n return null;\n }\n\n if (tail) {\n limit -= tail.length;\n }\n\n const shortener = function(node) {\n if (limit <= -1) {\n // Limit -1 means the doc was already clipped.\n return null;\n }\n\n if (node.att) {\n // Attachments are unchanged.\n return node;\n }\n if (limit == 0) {\n node.text = tail;\n limit = -1;\n } else if (node.text) {\n const len = node.text.length;\n if (len > limit) {\n node.text = node.text.substring(0, limit) + tail;\n limit = -1;\n } else {\n limit -= len;\n }\n }\n return node;\n }\n\n return treeTopDown(tree, shortener);\n}\n\n// Strip heavy entities from a tree.\nfunction lightEntity(tree, allow) {\n const lightCopy = node => {\n const data = copyEntData(node.data, true, allow ? allow(node) : null);\n if (data) {\n node.data = data;\n } else {\n delete node.data;\n }\n return node;\n }\n return treeTopDown(tree, lightCopy);\n}\n\n// Remove spaces and breaks on the left.\nfunction lTrim(tree) {\n if (tree.type == 'BR') {\n tree = null;\n } else if (tree.text) {\n if (!tree.type) {\n tree.text = tree.text.trimStart();\n if (!tree.text) {\n tree = null;\n }\n }\n } else if (!tree.type && tree.children && tree.children.length > 0) {\n const c = lTrim(tree.children[0]);\n if (c) {\n tree.children[0] = c;\n } else {\n tree.children.shift();\n if (!tree.type && tree.children.length == 0) {\n tree = null;\n }\n }\n }\n return tree;\n}\n\n// Move attachments to the end. Attachments must be at the top level, no need to traverse the tree.\nfunction attachmentsToEnd(tree, limit) {\n if (!tree) {\n return null;\n }\n\n if (tree.att) {\n tree.text = ' ';\n delete tree.att;\n delete tree.children;\n } else if (tree.children) {\n const attachments = [];\n const children = [];\n for (let i in tree.children) {\n const c = tree.children[i];\n if (c.att) {\n if (attachments.length == limit) {\n // Too many attachments to preview;\n continue;\n }\n if (c.data['mime'] == JSON_MIME_TYPE) {\n // JSON attachments are not shown in preview.\n continue;\n }\n\n delete c.att;\n delete c.children;\n c.text = ' ';\n attachments.push(c);\n } else {\n children.push(c);\n }\n }\n tree.children = children.concat(attachments);\n }\n return tree;\n}\n\n// Get a list of entities from a text.\nfunction extractEntities(line) {\n let match;\n let extracted = [];\n ENTITY_TYPES.forEach((entity) => {\n while ((match = entity.re.exec(line)) !== null) {\n extracted.push({\n offset: match['index'],\n len: match[0].length,\n unique: match[0],\n data: entity.pack(match[0]),\n type: entity.name\n });\n }\n });\n\n if (extracted.length == 0) {\n return extracted;\n }\n\n // Remove entities detected inside other entities, like #hashtag in a URL.\n extracted.sort((a, b) => {\n return a.offset - b.offset;\n });\n\n let idx = -1;\n extracted = extracted.filter((el) => {\n const result = (el.offset > idx);\n idx = el.offset + el.len;\n return result;\n });\n\n return extracted;\n}\n\n// Convert the chunks into format suitable for serialization.\nfunction draftify(chunks, startAt) {\n let plain = '';\n let ranges = [];\n for (let i in chunks) {\n const chunk = chunks[i];\n if (!chunk.txt) {\n const drafty = draftify(chunk.children, plain.length + startAt);\n chunk.txt = drafty.txt;\n ranges = ranges.concat(drafty.fmt);\n }\n\n if (chunk.tp) {\n ranges.push({\n at: plain.length + startAt,\n len: chunk.txt.length,\n tp: chunk.tp\n });\n }\n\n plain += chunk.txt;\n }\n return {\n txt: plain,\n fmt: ranges\n };\n}\n\n// Create a copy of entity data with (light=false) or without (light=true) the large payload.\n// The array 'allow' contains a list of fields exempt from stripping.\nfunction copyEntData(data, light, allow) {\n if (data && Object.entries(data).length > 0) {\n allow = allow || [];\n const dc = {};\n ALLOWED_ENT_FIELDS.forEach(key => {\n if (data[key]) {\n if (light && !allow.includes(key) &&\n (typeof data[key] == 'string' || Array.isArray(data[key])) &&\n data[key].length > MAX_PREVIEW_DATA_SIZE) {\n return;\n }\n if (typeof data[key] == 'object') {\n return;\n }\n dc[key] = data[key];\n }\n });\n\n if (Object.entries(dc).length != 0) {\n return dc;\n }\n }\n return null;\n}\n\nif (typeof module != 'undefined') {\n module.exports = Drafty;\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * @file Access control model.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\n/**\n * Helper class for handling access mode.\n *\n * @class AccessMode\n * @memberof Tinode\n *\n * @param {AccessMode|Object=} acs - AccessMode to copy or access mode object received from the server.\n */\nexport default class AccessMode {\n constructor(acs) {\n if (acs) {\n this.given = typeof acs.given == 'number' ? acs.given : AccessMode.decode(acs.given);\n this.want = typeof acs.want == 'number' ? acs.want : AccessMode.decode(acs.want);\n this.mode = acs.mode ? (typeof acs.mode == 'number' ? acs.mode : AccessMode.decode(acs.mode)) :\n (this.given & this.want);\n }\n }\n\n static #checkFlag(val, side, flag) {\n side = side || 'mode';\n if (['given', 'want', 'mode'].includes(side)) {\n return ((val[side] & flag) != 0);\n }\n throw new Error(`Invalid AccessMode component '${side}'`);\n }\n /**\n * Parse string into an access mode value.\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {string | Number} mode - either a String representation of the access mode to parse or a set of bits to assign.\n * @returns {number} - Access mode as a numeric value.\n */\n static decode(str) {\n if (!str) {\n return null;\n } else if (typeof str == 'number') {\n return str & AccessMode._BITMASK;\n } else if (str === 'N' || str === 'n') {\n return AccessMode._NONE;\n }\n\n const bitmask = {\n 'J': AccessMode._JOIN,\n 'R': AccessMode._READ,\n 'W': AccessMode._WRITE,\n 'P': AccessMode._PRES,\n 'A': AccessMode._APPROVE,\n 'S': AccessMode._SHARE,\n 'D': AccessMode._DELETE,\n 'O': AccessMode._OWNER\n };\n\n let m0 = AccessMode._NONE;\n\n for (let i = 0; i < str.length; i++) {\n const bit = bitmask[str.charAt(i).toUpperCase()];\n if (!bit) {\n // Unrecognized bit, skip.\n continue;\n }\n m0 |= bit;\n }\n return m0;\n }\n /**\n * Convert numeric representation of the access mode into a string.\n *\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {number} val - access mode value to convert to a string.\n * @returns {string} - Access mode as a string.\n */\n static encode(val) {\n if (val === null || val === AccessMode._INVALID) {\n return null;\n } else if (val === AccessMode._NONE) {\n return 'N';\n }\n\n const bitmask = ['J', 'R', 'W', 'P', 'A', 'S', 'D', 'O'];\n let res = '';\n for (let i = 0; i < bitmask.length; i++) {\n if ((val & (1 << i)) != 0) {\n res = res + bitmask[i];\n }\n }\n return res;\n }\n /**\n * Update numeric representation of access mode with the new value. The value\n * is one of the following:\n * - a string starting with '+' or '-' then the bits to add or remove, e.g. '+R-W' or '-PS'.\n * - a new value of access mode\n *\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {number} val - access mode value to update.\n * @param {string} upd - update to apply to val.\n * @returns {number} - updated access mode.\n */\n static update(val, upd) {\n if (!upd || typeof upd != 'string') {\n return val;\n }\n\n let action = upd.charAt(0);\n if (action == '+' || action == '-') {\n let val0 = val;\n // Split delta-string like '+ABC-DEF+Z' into an array of parts including + and -.\n const parts = upd.split(/([-+])/);\n // Starting iteration from 1 because String.split() creates an array with the first empty element.\n // Iterating by 2 because we parse pairs +/- then data.\n for (let i = 1; i < parts.length - 1; i += 2) {\n action = parts[i];\n const m0 = AccessMode.decode(parts[i + 1]);\n if (m0 == AccessMode._INVALID) {\n return val;\n }\n if (m0 == null) {\n continue;\n }\n if (action === '+') {\n val0 |= m0;\n } else if (action === '-') {\n val0 &= ~m0;\n }\n }\n val = val0;\n } else {\n // The string is an explicit new value 'ABC' rather than delta.\n const val0 = AccessMode.decode(upd);\n if (val0 != AccessMode._INVALID) {\n val = val0;\n }\n }\n\n return val;\n }\n /**\n * Bits present in a1 but missing in a2.\n *\n * @static\n * @memberof Tinode\n *\n * @param {number | string} a1 - access mode to subtract from.\n * @param {number | string} a2 - access mode to subtract.\n * @returns {number} access mode with bits present in a1 but missing in a2.\n */\n static diff(a1, a2) {\n a1 = AccessMode.decode(a1);\n a2 = AccessMode.decode(a2);\n\n if (a1 == AccessMode._INVALID || a2 == AccessMode._INVALID) {\n return AccessMode._INVALID;\n }\n return a1 & ~a2;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Custom formatter\n */\n toString() {\n return '{\"mode\": \"' + AccessMode.encode(this.mode) +\n '\", \"given\": \"' + AccessMode.encode(this.given) +\n '\", \"want\": \"' + AccessMode.encode(this.want) + '\"}';\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Converts numeric values to strings.\n */\n jsonHelper() {\n return {\n mode: AccessMode.encode(this.mode),\n given: AccessMode.encode(this.given),\n want: AccessMode.encode(this.want)\n };\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign value to 'mode'.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} m - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setMode(m) {\n this.mode = AccessMode.decode(m);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update mode value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateMode(u) {\n this.mode = AccessMode.update(this.mode, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get mode value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - mode value.\n */\n getMode() {\n return AccessMode.encode(this.mode);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign given value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} g - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setGiven(g) {\n this.given = AccessMode.decode(g);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'given' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateGiven(u) {\n this.given = AccessMode.update(this.given, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'given' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - given value.\n */\n getGiven() {\n return AccessMode.encode(this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} w - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setWant(w) {\n this.want = AccessMode.decode(w);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateWant(u) {\n this.want = AccessMode.update(this.want, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'want' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - want value.\n */\n getWant() {\n return AccessMode.encode(this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'want' but missing in 'given'.\n * Inverse of {@link Tinode.AccessMode#getExcessive}\n *\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in want but missing in given.\n */\n getMissing() {\n return AccessMode.encode(this.want & ~this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'given' but missing in 'want'.\n * Inverse of {@link Tinode.AccessMode#getMissing}\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in given but missing in want.\n */\n getExcessive() {\n return AccessMode.encode(this.given & ~this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want', 'give', and 'mode' values.\n * @memberof Tinode.AccessMode\n *\n * @param {AccessMode} val - new access mode value.\n * @returns {AccessMode} - this AccessMode.\n */\n updateAll(val) {\n if (val) {\n this.updateGiven(val.given);\n this.updateWant(val.want);\n this.mode = this.given & this.want;\n }\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Owner (O) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isOwner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._OWNER);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isPresencer(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._PRES);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is NOT set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isMuted(side) {\n return !this.isPresencer(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Join (J) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isJoiner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._JOIN);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Reader (R) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isReader(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._READ);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Writer (W) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isWriter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._WRITE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Approver (A) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isApprover(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._APPROVE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O) or Approver (A) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isAdmin(side) {\n return this.isOwner(side) || this.isApprover(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O), Approver (A), or Sharer (S) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isSharer(side) {\n return this.isAdmin(side) || AccessMode.#checkFlag(this, side, AccessMode._SHARE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Deleter (D) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isDeleter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._DELETE);\n }\n}\n\nAccessMode._NONE = 0x00;\nAccessMode._JOIN = 0x01;\nAccessMode._READ = 0x02;\nAccessMode._WRITE = 0x04;\nAccessMode._PRES = 0x08;\nAccessMode._APPROVE = 0x10;\nAccessMode._SHARE = 0x20;\nAccessMode._DELETE = 0x40;\nAccessMode._OWNER = 0x80;\n\nAccessMode._BITMASK = AccessMode._JOIN | AccessMode._READ | AccessMode._WRITE | AccessMode._PRES |\n AccessMode._APPROVE | AccessMode._SHARE | AccessMode._DELETE | AccessMode._OWNER;\nAccessMode._INVALID = 0x100000;\n","export const PACKAGE_VERSION = \"0.23.0-rc1\";\n","/**\n * @file Global constants and configuration parameters.\n *\n * @copyright 2015-2023 Tinode LLC\n */\n'use strict';\n\nimport {\n PACKAGE_VERSION\n} from '../version.js';\n\n// Global constants\nexport const PROTOCOL_VERSION = '0'; // Major component of the version, e.g. '0' in '0.17.1'.\nexport const VERSION = PACKAGE_VERSION || '0.21';\nexport const LIBRARY = 'tinodejs/' + VERSION;\n\n// Topic name prefixes.\nexport const TOPIC_NEW = 'new';\nexport const TOPIC_NEW_CHAN = 'nch';\nexport const TOPIC_ME = 'me';\nexport const TOPIC_FND = 'fnd';\nexport const TOPIC_SYS = 'sys';\nexport const TOPIC_CHAN = 'chn';\nexport const TOPIC_GRP = 'grp';\nexport const TOPIC_P2P = 'p2p';\nexport const USER_NEW = 'new';\n\n// Starting value of a locally-generated seqId used for pending messages.\nexport const LOCAL_SEQID = 0xFFFFFFF;\n\n// Status codes.\nexport const MESSAGE_STATUS_NONE = 0; // Status not assigned.\nexport const MESSAGE_STATUS_QUEUED = 10; // Local ID assigned, in progress to be sent.\nexport const MESSAGE_STATUS_SENDING = 20; // Transmission started.\nexport const MESSAGE_STATUS_FAILED = 30; // At least one attempt was made to send the message.\nexport const MESSAGE_STATUS_FATAL = 40; // Message sending failed and it should not be retried.\nexport const MESSAGE_STATUS_SENT = 50; // Delivered to the server.\nexport const MESSAGE_STATUS_RECEIVED = 60; // Received by the client.\nexport const MESSAGE_STATUS_READ = 70; // Read by the user.\nexport const MESSAGE_STATUS_TO_ME = 80; // The message is received from another user.\n\n// Reject unresolved futures after this many milliseconds.\nexport const EXPIRE_PROMISES_TIMEOUT = 5_000;\n// Periodicity of garbage collection of unresolved futures.\nexport const EXPIRE_PROMISES_PERIOD = 1_000;\n\n// Delay before acknowledging that a message was recived.\nexport const RECV_TIMEOUT = 100;\n\n// Default number of messages to pull into memory from persistent cache.\nexport const DEFAULT_MESSAGES_PAGE = 24;\n\n// Unicode DEL character indicating data was deleted.\nexport const DEL_CHAR = '\\u2421';\n\n// Maximum number of pinnned messages;\nexport const MAX_PINNED_COUNT = 5;\n","/**\n * @file Throwable error with numeric error code.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nexport default class CommError extends Error {\n constructor(message, code) {\n super(`${message} (${code})`);\n this.name = 'CommError';\n this.code = code;\n }\n}\n","/**\n * @file Utilities used in multiple places.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport {\n DEL_CHAR,\n LOCAL_SEQID\n} from './config.js';\n\n// Attempt to convert date and AccessMode strings to objects.\nexport function jsonParseHelper(key, val) {\n // Try to convert string timestamps with optional milliseconds to Date,\n // e.g. 2015-09-02T01:45:43[.123]Z\n if (typeof val == 'string' && val.length >= 20 && val.length <= 24 && ['ts', 'touched', 'updated', 'created', 'when', 'deleted', 'expires'].includes(key)) {\n const date = new Date(val);\n if (!isNaN(date)) {\n return date;\n }\n } else if (key === 'acs' && typeof val === 'object') {\n return new AccessMode(val);\n }\n return val;\n}\n\n// Checks if URL is a relative url, i.e. has no 'scheme://', including the case of missing scheme '//'.\n// The scheme is expected to be RFC-compliant, e.g. [a-z][a-z0-9+.-]*\n// example.html - ok\n// https:example.com - not ok.\n// http:/example.com - not ok.\n// ' ↲ https://example.com' - not ok. (↲ means carriage return)\nexport function isUrlRelative(url) {\n return url && !/^\\s*([a-z][a-z0-9+.-]*:|\\/\\/)/im.test(url);\n}\n\nfunction isValidDate(d) {\n return (d instanceof Date) && !isNaN(d) && (d.getTime() != 0);\n}\n\n// RFC3339 formater of Date\nexport function rfc3339DateString(d) {\n if (!isValidDate(d)) {\n return undefined;\n }\n\n const pad = function(val, sp) {\n sp = sp || 2;\n return '0'.repeat(sp - ('' + val).length) + val;\n };\n\n const millis = d.getUTCMilliseconds();\n return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) +\n 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) +\n (millis ? '.' + pad(millis, 3) : '') + 'Z';\n}\n\n// Recursively merge src's own properties to dst.\n// Ignore properties where ignore[property] is true.\n// Array and Date objects are shallow-copied.\nexport function mergeObj(dst, src, ignore) {\n if (typeof src != 'object') {\n if (src === undefined) {\n return dst;\n }\n if (src === DEL_CHAR) {\n return undefined;\n }\n return src;\n }\n // JS is crazy: typeof null is 'object'.\n if (src === null) {\n return src;\n }\n\n // Handle Date\n if (src instanceof Date && !isNaN(src)) {\n return (!dst || !(dst instanceof Date) || isNaN(dst) || dst < src) ? src : dst;\n }\n\n // Access mode\n if (src instanceof AccessMode) {\n return new AccessMode(src);\n }\n\n // Handle Array\n if (src instanceof Array) {\n return src;\n }\n\n if (!dst || dst === DEL_CHAR) {\n dst = src.constructor();\n }\n\n for (let prop in src) {\n if (src.hasOwnProperty(prop) && (!ignore || !ignore[prop]) && (prop != '_noForwarding')) {\n try {\n dst[prop] = mergeObj(dst[prop], src[prop]);\n } catch (err) {\n // FIXME: probably need to log something here.\n }\n }\n }\n return dst;\n}\n\n// Update object stored in a cache. Returns updated value.\nexport function mergeToCache(cache, key, newval, ignore) {\n cache[key] = mergeObj(cache[key], newval, ignore);\n return cache[key];\n}\n\n// Strips all values from an object of they evaluate to false or if their name starts with '_'.\n// Used on all outgoing object before serialization to string.\nexport function simplify(obj) {\n Object.keys(obj).forEach((key) => {\n if (key[0] == '_') {\n // Strip fields like \"obj._key\".\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (Array.isArray(obj[key]) && obj[key].length == 0) {\n // Strip empty arrays.\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (obj[key] instanceof Date) {\n // Strip invalid or zero date.\n if (!isValidDate(obj[key])) {\n delete obj[key];\n }\n } else if (typeof obj[key] == 'object') {\n simplify(obj[key]);\n // Strip empty objects.\n if (Object.getOwnPropertyNames(obj[key]).length == 0) {\n delete obj[key];\n }\n }\n });\n return obj;\n};\n\n\n// Trim whitespace, strip empty and duplicate elements elements.\n// If the result is an empty array, add a single element \"\\u2421\" (Unicode Del character).\nexport function normalizeArray(arr) {\n let out = [];\n if (Array.isArray(arr)) {\n // Trim, throw away very short and empty tags.\n for (let i = 0, l = arr.length; i < l; i++) {\n let t = arr[i];\n if (t) {\n t = t.trim().toLowerCase();\n if (t.length > 1) {\n out.push(t);\n }\n }\n }\n out.sort().filter((item, pos, ary) => {\n return !pos || item != ary[pos - 1];\n });\n }\n if (out.length == 0) {\n // Add single tag with a Unicode Del character, otherwise an ampty array\n // is ambiguos. The Del tag will be stripped by the server.\n out.push(DEL_CHAR);\n }\n return out;\n}\n\n// Convert input to valid ranges of IDs.\nexport function normalizeRanges(ranges, maxSeq) {\n if (!Array.isArray(ranges)) {\n return [];\n }\n\n // Sort ranges in accending order by low, then descending by hi.\n ranges.sort((r1, r2) => {\n if (r1.low < r2.low) {\n return true;\n }\n if (r1.low == r2.low) {\n return !r2.hi || (r1.hi >= r2.hi);\n }\n return false;\n });\n\n // Remove pending messages from ranges possibly clipping some ranges.\n return ranges.reduce((out, r) => {\n if (r.low < LOCAL_SEQID && r.low > 0) {\n if (!r.hi || r.hi < LOCAL_SEQID) {\n out.push(r);\n } else {\n // Clip hi to max allowed value.\n out.push({\n low: r.low,\n hi: maxSeq + 1\n });\n }\n }\n return out;\n }, []);\n}\n\n// Convert array of IDs to array of ranges.\nexport function listToRanges(list) {\n // Sort the list in ascending order\n list.sort((a, b) => a - b);\n // Convert the array of IDs to ranges.\n return list.reduce((out, id) => {\n if (out.length == 0) {\n // First element.\n out.push({\n low: id\n });\n } else {\n let prev = out[out.length - 1];\n if ((!prev.hi && (id != prev.low + 1)) || (id > prev.hi)) {\n // New range.\n out.push({\n low: id\n });\n } else {\n // Expand existing range.\n prev.hi = prev.hi ? Math.max(prev.hi, id + 1) : id + 1;\n }\n }\n return out;\n }, []);\n}\n\n// Cuts 'clip' range out of the 'src' range.\n// Returns an array with 0, 1 or 2 elements.\nexport function clipRange(src, clip) {\n if (clip.hi < src.low || clip.low >= src.hi) {\n // Clip is completely outside of src, no intersection.\n return [src];\n }\n\n if (clip.low <= src.low) {\n if (clip.hi >= src.hi) {\n // The source range is completely inside the clipping range.\n return [];\n }\n // Partial clipping at the top.\n return [{\n low: src.low,\n hi: clip.hi\n }];\n }\n\n // Range on the lower end.\n const result = [{\n low: src.low,\n hi: clip.low\n }];\n if (clip.hi < src.hi) {\n // Maybe a range on the higher end, if clip is completely inside the source.\n result.push({\n low: clip.hi,\n hi: src.hi\n });\n }\n\n return result;\n}\n","/**\n * @file Abstraction layer for websocket and long polling connections.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n jsonParseHelper\n} from './utils.js';\n\nlet WebSocketProvider;\nlet XHRProvider;\n\n// Error code to return in case of a network problem.\nconst NETWORK_ERROR = 503;\nconst NETWORK_ERROR_TEXT = \"Connection failed\";\n\n// Error code to return when user disconnected from server.\nconst NETWORK_USER = 418;\nconst NETWORK_USER_TEXT = \"Disconnected by client\";\n\n// Settings for exponential backoff\nconst _BOFF_BASE = 2000; // 2000 milliseconds, minimum delay between reconnects\nconst _BOFF_MAX_ITER = 10; // Maximum delay between reconnects 2^10 * 2000 ~ 34 minutes\nconst _BOFF_JITTER = 0.3; // Add random delay\n\n// Helper function for creating an endpoint URL.\nfunction makeBaseUrl(host, protocol, version, apiKey) {\n let url = null;\n\n if (['http', 'https', 'ws', 'wss'].includes(protocol)) {\n url = `${protocol}://${host}`;\n if (url.charAt(url.length - 1) !== '/') {\n url += '/';\n }\n url += 'v' + version + '/channels';\n if (['http', 'https'].includes(protocol)) {\n // Long polling endpoint ends with \"lp\", i.e.\n // '/v0/channels/lp' vs just '/v0/channels' for ws\n url += '/lp';\n }\n url += '?apikey=' + apiKey;\n }\n return url;\n}\n\n/**\n * An abstraction for a websocket or a long polling connection.\n *\n * @class Connection\n * @memberof Tinode\n\n * @param {Object} config - configuration parameters.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - Network transport to use, either \"ws\"/\"wss\" for websocket or\n * lp for long polling.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} version_ - Major value of the protocol version, e.g. '0' in '0.17.1'.\n * @param {boolean} autoreconnect_ - If connection is lost, try to reconnect automatically.\n */\nexport default class Connection {\n // Logger, does nothing by default.\n static #log = _ => {};\n\n #boffTimer = null;\n #boffIteration = 0;\n #boffClosed = false; // Indicator if the socket was manually closed - don't autoreconnect if true.\n\n // Websocket.\n #socket = null;\n\n host;\n secure;\n apiKey;\n\n version;\n autoreconnect;\n\n initialized;\n\n // (config.host, config.apiKey, config.transport, config.secure), PROTOCOL_VERSION, true\n constructor(config, version_, autoreconnect_) {\n this.host = config.host;\n this.secure = config.secure;\n this.apiKey = config.apiKey;\n\n this.version = version_;\n this.autoreconnect = autoreconnect_;\n\n if (config.transport === 'lp') {\n // explicit request to use long polling\n this.#init_lp();\n this.initialized = 'lp';\n } else if (config.transport === 'ws') {\n // explicit request to use web socket\n // if websockets are not available, horrible things will happen\n this.#init_ws();\n this.initialized = 'ws';\n }\n\n if (!this.initialized) {\n // Invalid or undefined network transport.\n Connection.#log(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n throw new Error(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n }\n }\n\n /**\n * To use Connection in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n * @memberof Connection\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n }\n\n /**\n * Assign a non-default logger.\n * @static\n * @memberof Connection\n * @param {function} l variadic logging function.\n */\n static set logger(l) {\n Connection.#log = l;\n }\n\n /**\n * Initiate a new connection\n * @memberof Tinode.Connection#\n * @param {string} host_ Host name to connect to; if null the old host name will be used.\n * @param {boolean} force Force new connection even if one already exists.\n * @return {Promise} Promise resolved/rejected when the connection call completes, resolution is called without\n * parameters, rejection passes the {Error} as parameter.\n */\n connect(host_, force) {\n return Promise.reject(null);\n }\n\n /**\n * Try to restore a network connection, also reset backoff.\n * @memberof Tinode.Connection#\n *\n * @param {boolean} force - reconnect even if there is a live connection already.\n */\n reconnect(force) {}\n\n /**\n * Terminate the network connection\n * @memberof Tinode.Connection#\n */\n disconnect() {}\n\n /**\n * Send a string to the server.\n * @memberof Tinode.Connection#\n *\n * @param {string} msg - String to send.\n * @throws Throws an exception if the underlying connection is not live.\n */\n sendText(msg) {}\n\n /**\n * Check if connection is alive.\n * @memberof Tinode.Connection#\n * @returns {boolean} true if connection is live, false otherwise.\n */\n isConnected() {\n return false;\n }\n\n /**\n * Get the name of the current network transport.\n * @memberof Tinode.Connection#\n * @returns {string} name of the transport such as \"ws\" or \"lp\".\n */\n transport() {\n return this.initialized;\n }\n\n /**\n * Send network probe to check if connection is indeed live.\n * @memberof Tinode.Connection#\n */\n probe() {\n this.sendText('1');\n }\n\n /**\n * Reset autoreconnect counter to zero.\n * @memberof Tinode.Connection#\n */\n backoffReset() {\n this.#boffReset();\n }\n\n // Backoff implementation - reconnect after a timeout.\n #boffReconnect() {\n // Clear timer\n clearTimeout(this.#boffTimer);\n // Calculate when to fire the reconnect attempt\n const timeout = _BOFF_BASE * (Math.pow(2, this.#boffIteration) * (1.0 + _BOFF_JITTER * Math.random()));\n // Update iteration counter for future use\n this.#boffIteration = (this.#boffIteration >= _BOFF_MAX_ITER ? this.#boffIteration : this.#boffIteration + 1);\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(timeout);\n }\n\n this.#boffTimer = setTimeout(_ => {\n Connection.#log(`Reconnecting, iter=${this.#boffIteration}, timeout=${timeout}`);\n // Maybe the socket was closed while we waited for the timer?\n if (!this.#boffClosed) {\n const prom = this.connect();\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(0, prom);\n } else {\n // Suppress error if it's not used.\n prom.catch(_ => {\n /* do nothing */\n });\n }\n } else if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(-1);\n }\n }, timeout);\n }\n\n // Terminate auto-reconnect process.\n #boffStop() {\n clearTimeout(this.#boffTimer);\n this.#boffTimer = null;\n }\n\n // Reset auto-reconnect iteration counter.\n #boffReset() {\n this.#boffIteration = 0;\n }\n\n // Initialization for long polling.\n #init_lp() {\n const XDR_UNSENT = 0; // Client has been created. open() not called yet.\n const XDR_OPENED = 1; // open() has been called.\n const XDR_HEADERS_RECEIVED = 2; // send() has been called, and headers and status are available.\n const XDR_LOADING = 3; // Downloading; responseText holds partial data.\n const XDR_DONE = 4; // The operation is complete.\n\n // Fully composed endpoint URL, with API key & SID\n let _lpURL = null;\n\n let _poller = null;\n let _sender = null;\n\n let lp_sender = (url_) => {\n const sender = new XHRProvider();\n sender.onreadystatechange = (evt) => {\n if (sender.readyState == XDR_DONE && sender.status >= 400) {\n // Some sort of error response\n throw new CommError(\"LP sender failed\", sender.status);\n }\n };\n\n sender.open('POST', url_, true);\n return sender;\n }\n\n let lp_poller = (url_, resolve, reject) => {\n let poller = new XHRProvider();\n let promiseCompleted = false;\n\n poller.onreadystatechange = evt => {\n if (poller.readyState == XDR_DONE) {\n if (poller.status == 201) { // 201 == HTTP.Created, get SID\n let pkt = JSON.parse(poller.responseText, jsonParseHelper);\n _lpURL = url_ + '&sid=' + pkt.ctrl.params.sid;\n poller = lp_poller(_lpURL);\n poller.send(null);\n if (this.onOpen) {\n this.onOpen();\n }\n\n if (resolve) {\n promiseCompleted = true;\n resolve();\n }\n\n if (this.autoreconnect) {\n this.#boffStop();\n }\n } else if (poller.status > 0 && poller.status < 400) { // 0 = network error; 400 = HTTP.BadRequest\n if (this.onMessage) {\n this.onMessage(poller.responseText);\n }\n poller = lp_poller(_lpURL);\n poller.send(null);\n } else {\n // Don't throw an error here, gracefully handle server errors\n if (reject && !promiseCompleted) {\n promiseCompleted = true;\n reject(poller.responseText);\n }\n if (this.onMessage && poller.responseText) {\n this.onMessage(poller.responseText);\n }\n if (this.onDisconnect) {\n const code = poller.status || (this.#boffClosed ? NETWORK_USER : NETWORK_ERROR);\n const text = poller.responseText || (this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT);\n this.onDisconnect(new CommError(text, code), code);\n }\n\n // Polling has stopped. Indicate it by setting poller to null.\n poller = null;\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n }\n }\n };\n // Using POST to avoid caching response by service worker.\n poller.open('POST', url_, true);\n return poller;\n }\n\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (_poller) {\n if (!force) {\n return Promise.resolve();\n }\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'https' : 'http', this.version, this.apiKey);\n Connection.#log(\"LP connecting to:\", url);\n _poller = lp_poller(url, resolve, reject);\n _poller.send(null);\n }).catch(err => {\n Connection.#log(\"LP connection failed:\", err);\n });\n };\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (_sender) {\n _sender.onreadystatechange = undefined;\n _sender.abort();\n _sender = null;\n }\n if (_poller) {\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (this.onDisconnect) {\n this.onDisconnect(new CommError(NETWORK_USER_TEXT, NETWORK_USER), NETWORK_USER);\n }\n // Ensure it's reconstructed\n _lpURL = null;\n };\n\n this.sendText = (msg) => {\n _sender = lp_sender(_lpURL);\n if (_sender && (_sender.readyState == XDR_OPENED)) { // 1 == OPENED\n _sender.send(msg);\n } else {\n throw new Error(\"Long poller failed to connect\");\n }\n };\n\n this.isConnected = _ => {\n return (_poller && true);\n };\n }\n\n // Initialization for Websocket\n #init_ws() {\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (this.#socket) {\n if (!force && this.#socket.readyState == this.#socket.OPEN) {\n return Promise.resolve();\n }\n this.#socket.close();\n this.#socket = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'wss' : 'ws', this.version, this.apiKey);\n\n Connection.#log(\"WS connecting to: \", url);\n\n // It throws when the server is not accessible but the exception cannot be caught:\n // https://stackoverflow.com/questions/31002592/javascript-doesnt-catch-error-in-websocket-instantiation/31003057\n const conn = new WebSocketProvider(url);\n\n conn.onerror = err => {\n reject(err);\n };\n\n conn.onopen = _ => {\n if (this.autoreconnect) {\n this.#boffStop();\n }\n\n if (this.onOpen) {\n this.onOpen();\n }\n\n resolve();\n };\n\n conn.onclose = _ => {\n this.#socket = null;\n\n if (this.onDisconnect) {\n const code = this.#boffClosed ? NETWORK_USER : NETWORK_ERROR;\n this.onDisconnect(new CommError(this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT, code), code);\n }\n\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n };\n\n conn.onmessage = evt => {\n if (this.onMessage) {\n this.onMessage(evt.data);\n }\n };\n\n this.#socket = conn;\n });\n }\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (!this.#socket) {\n return;\n }\n this.#socket.close();\n this.#socket = null;\n };\n\n this.sendText = msg => {\n if (this.#socket && (this.#socket.readyState == this.#socket.OPEN)) {\n this.#socket.send(msg);\n } else {\n throw new Error(\"Websocket is not connected\");\n }\n };\n\n this.isConnected = _ => {\n return (this.#socket && (this.#socket.readyState == this.#socket.OPEN));\n };\n }\n\n // Callbacks:\n\n /**\n * A callback to pass incoming messages to. See {@link Tinode.Connection#onMessage}.\n * @callback Tinode.Connection.OnMessage\n * @memberof Tinode.Connection\n * @param {string} message - Message to process.\n */\n onMessage = undefined;\n\n /**\n * A callback for reporting a dropped connection.\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onDisconnect = undefined;\n\n /**\n * A callback called when the connection is ready to be used for sending. For websockets it's socket open,\n * for long polling it's readyState=1 (OPENED)\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onOpen = undefined;\n\n /**\n * A callback to notify of reconnection attempts. See {@link Tinode.Connection#onAutoreconnectIteration}.\n * @memberof Tinode.Connection\n * @callback AutoreconnectIterationType\n * @param {string} timeout - time till the next reconnect attempt in milliseconds. -1 means reconnect was skipped.\n * @param {Promise} promise resolved or rejected when the reconnect attemp completes.\n *\n */\n /**\n * A callback to inform when the next attampt to reconnect will happen and to receive connection promise.\n * @memberof Tinode.Connection#\n * @type {Tinode.Connection.AutoreconnectIterationType}\n */\n onAutoreconnectIteration = undefined;\n}\n\nConnection.NETWORK_ERROR = NETWORK_ERROR;\nConnection.NETWORK_ERROR_TEXT = NETWORK_ERROR_TEXT;\nConnection.NETWORK_USER = NETWORK_USER;\nConnection.NETWORK_USER_TEXT = NETWORK_USER_TEXT;\n","/**\n * @file Helper methods for dealing with IndexedDB cache of messages, users, and topics.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nimport {\n clipRange\n} from './utils.js';\n\nconst DB_VERSION = 3;\nconst DB_NAME = 'tinode-web';\n\nlet IDBProvider;\n\nexport default class DB {\n #onError = _ => {};\n #logger = _ => {};\n\n // Instance of IndexDB.\n db = null;\n // Indicator that the cache is disabled.\n disabled = false;\n\n constructor(onError, logger) {\n this.#onError = onError || this.#onError;\n this.#logger = logger || this.#logger;\n }\n\n #mapObjects(source, callback, context) {\n if (!this.db) {\n return disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction([source]);\n trx.onerror = event => {\n this.#logger('PCache', 'mapObjects', source, event.target.error);\n reject(event.target.error);\n };\n trx.objectStore(source).getAll().onsuccess = event => {\n if (callback) {\n event.target.result.forEach(topic => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n /**\n * Initialize persistent cache: open or create/upgrade if needed.\n * @returns {Promise} promise to be resolved/rejected when the DB is initialized.\n */\n initDatabase() {\n return new Promise((resolve, reject) => {\n // Open the database and initialize callbacks.\n const req = IDBProvider.open(DB_NAME, DB_VERSION);\n req.onsuccess = event => {\n this.db = event.target.result;\n this.disabled = false;\n resolve(this.db);\n };\n req.onerror = event => {\n this.#logger('PCache', \"failed to initialize\", event);\n reject(event.target.error);\n this.#onError(event.target.error);\n };\n req.onupgradeneeded = event => {\n this.db = event.target.result;\n\n this.db.onerror = event => {\n this.#logger('PCache', \"failed to create storage\", event);\n this.#onError(event.target.error);\n };\n\n // Individual object stores.\n // Object store (table) for topics. The primary key is topic name.\n this.db.createObjectStore('topic', {\n keyPath: 'name'\n });\n\n // Users object store. UID is the primary key.\n this.db.createObjectStore('user', {\n keyPath: 'uid'\n });\n\n // Subscriptions object store topic <-> user. Topic name + UID is the primary key.\n this.db.createObjectStore('subscription', {\n keyPath: ['topic', 'uid']\n });\n\n // Messages object store. The primary key is topic name + seq.\n this.db.createObjectStore('message', {\n keyPath: ['topic', 'seq']\n });\n\n // Records of deleted message ranges. The primary key is topic name + low seq.\n const dellog = this.db.createObjectStore('dellog', {\n keyPath: ['topic', 'low', 'hi']\n });\n dellog.createIndex('topic_clear', ['topic', 'clear'], {\n unique: false\n });\n };\n });\n }\n\n /**\n * Delete persistent cache.\n */\n deleteDatabase() {\n // Close connection, otherwise operations will fail with 'onblocked'.\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n return new Promise((resolve, reject) => {\n const req = IDBProvider.deleteDatabase(DB_NAME);\n req.onblocked = _ => {\n if (this.db) {\n this.db.close();\n }\n const err = new Error(\"blocked\");\n this.#logger('PCache', 'deleteDatabase', err);\n reject(err);\n };\n req.onsuccess = _ => {\n this.db = null;\n this.disabled = true;\n resolve(true);\n };\n req.onerror = event => {\n this.#logger('PCache', 'deleteDatabase', event.target.error);\n reject(event.target.error);\n };\n });\n }\n\n /**\n * Check if persistent cache is ready for use.\n * @memberOf DB\n * @returns {boolean} true if cache is ready, false otherwise.\n */\n isReady() {\n return !!this.db;\n }\n\n // Topics.\n\n /**\n * Save to cache or update topic in persistent cache.\n * @memberOf DB\n * @param {Topic} topic - topic to be added or updated.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updTopic(topic) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updTopic', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(topic.name);\n req.onsuccess = _ => {\n trx.objectStore('topic').put(DB.#serializeTopic(req.result, topic));\n trx.commit();\n };\n });\n }\n\n /**\n * Mark or unmark topic as deleted.\n * @memberOf DB\n * @param {string} name - name of the topic to mark or unmark.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n markTopicAsDeleted(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'markTopicAsDeleted', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(name);\n req.onsuccess = event => {\n const topic = event.target.result;\n topic._deleted = true;\n trx.objectStore('topic').put(topic);\n trx.commit();\n };\n });\n }\n\n /**\n * Remove topic from persistent cache.\n * @memberOf DB\n * @param {string} name - name of the topic to remove from database.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remTopic(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic', 'subscription', 'message'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remTopic', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('topic').delete(IDBKeyRange.only(name));\n trx.objectStore('subscription').delete(IDBKeyRange.bound([name, '-'], [name, '~']));\n trx.objectStore('message').delete(IDBKeyRange.bound([name, 0], [name, Number.MAX_SAFE_INTEGER]));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored topic.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapTopics(callback, context) {\n return this.#mapObjects('topic', callback, context);\n }\n\n /**\n * Copy data from serialized object to topic.\n * @memberOf DB\n * @param {Topic} topic - target to deserialize to.\n * @param {Object} src - serialized data to copy from.\n */\n deserializeTopic(topic, src) {\n DB.#deserializeTopic(topic, src);\n }\n\n // Users.\n /**\n * Add or update user object in the persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to save or update.\n * @param {Object} pub - user's public information.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updUser(uid, pub) {\n if (arguments.length < 2 || pub === undefined) {\n // No point inupdating user with invalid data.\n return;\n }\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').put({\n uid: uid,\n public: pub\n });\n trx.commit();\n });\n }\n\n /**\n * Remove user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to remove from the cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').delete(IDBKeyRange.only(uid));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored user.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapUsers(callback, context) {\n return this.#mapObjects('user', callback, context);\n }\n\n /**\n * Read a single user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to fetch from cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n getUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user']);\n trx.oncomplete = event => {\n const user = event.target.result;\n resolve({\n user: user.uid,\n public: user.public\n });\n };\n trx.onerror = event => {\n this.#logger('PCache', 'getUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').get(uid);\n });\n }\n\n // Subscriptions.\n /**\n * Add or update subscription in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {string} uid - ID of the subscribed user.\n * @param {Object} sub - subscription to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updSubscription(topicName, uid, sub) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updSubscription', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').get([topicName, uid]).onsuccess = (event) => {\n trx.objectStore('subscription').put(DB.#serializeSubscription(event.target.result, topicName, uid, sub));\n trx.commit();\n };\n });\n }\n\n /**\n * Execute a callback for each cached subscription in a given topic.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the subscriptions.\n * @param {function} callback - function to call for each subscription.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapSubscriptions(topicName, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription']);\n trx.onerror = (event) => {\n this.#logger('PCache', 'mapSubscriptions', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').getAll(IDBKeyRange.bound([topicName, '-'], [topicName, '~'])).onsuccess = (event) => {\n if (callback) {\n event.target.result.forEach((topic) => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n // Messages.\n\n /**\n * Save message to persistent cache.\n * @memberOf DB\n * @param {Object} msg - message to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n addMessage(msg) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'addMessage', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').add(DB.#serializeMessage(null, msg));\n trx.commit();\n });\n }\n\n /**\n * Update delivery status of a message stored in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} seq - ID of the message to update\n * @param {number} status - new delivery status of the message.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updMessageStatus(topicName, seq, status) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updMessageStatus', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('message').get(IDBKeyRange.only([topicName, seq]));\n req.onsuccess = event => {\n const src = req.result || event.target.result;\n if (!src || src._status == status) {\n trx.commit();\n return;\n }\n trx.objectStore('message').put(DB.#serializeMessage(src, {\n topic: topicName,\n seq: seq,\n _status: status\n }));\n trx.commit();\n };\n });\n }\n\n /**\n * Remove one or more messages from persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} from - id of the message to remove or lower boundary when removing range (inclusive).\n * @param {number=} to - upper boundary (exclusive) when removing a range of messages.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remMessages(topicName, from, to) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n if (!from && !to) {\n from = 0;\n to = Number.MAX_SAFE_INTEGER;\n }\n const range = to > 0 ? IDBKeyRange.bound([topicName, from], [topicName, to], false, true) :\n IDBKeyRange.only([topicName, from]);\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remMessages', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').delete(range);\n trx.commit();\n });\n }\n\n /**\n * Retrieve messages from persistent store.\n * @memberOf DB\n * @param {string} topicName - name of the topic to retrieve messages from.\n * @param {function} callback to call for each retrieved message.\n * @param {GetDataType} query - parameters of the message range to retrieve.\n *\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n readMessages(topicName, query, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n\n const trx = this.db.transaction(['message']);\n let result = [];\n\n // Handle individual message ranges.\n if (Array.isArray(query.ranges)) {\n return new Promise((resolve, reject) => {\n trx.onerror = event => {\n this.#logger('PCache', 'readMessages', event.target.error);\n reject(event.target.error);\n };\n\n let count = 0;\n query.ranges.forEach(range => {\n const key = range.hi ? IDBKeyRange.bound([topicName, range.low], [topicName, range.hi], false, true) :\n IDBKeyRange.only([topicName, range.low]);\n trx.objectStore('message').getAll(key).onsuccess = event => {\n const msgs = event.target.result;\n if (msgs) {\n if (callback) {\n callback.call(context, msgs);\n }\n if (Array.isArray(msgs)) {\n result = result.concat(msgs);\n } else {\n result.push(msgs);\n }\n }\n count++;\n if (count == query.ranges.length) {\n resolve(result);\n }\n };\n });\n });\n }\n\n return new Promise((resolve, reject) => {\n query = query || {};\n const since = query.since > 0 ? query.since : 0;\n const before = query.before > 0 ? query.before : Number.MAX_SAFE_INTEGER;\n const limit = query.limit | 0;\n\n trx.onerror = event => {\n this.#logger('PCache', 'readMessages', event.target.error);\n reject(event.target.error);\n };\n\n const range = IDBKeyRange.bound([topicName, since], [topicName, before], false, true);\n // Iterate in descending order.\n trx.objectStore('message').openCursor(range, 'prev')\n .onsuccess = event => {\n const cursor = event.target.result;\n if (cursor) {\n if (callback) {\n callback.call(context, cursor.value);\n }\n result.push(cursor.value);\n if (limit <= 0 || result.length < limit) {\n cursor.continue();\n } else {\n resolve(result);\n }\n } else {\n resolve(result);\n }\n };\n });\n }\n\n // Delete log\n\n /**\n * Add records of deleted messages.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} delId - id of the deletion transaction.\n * @param {Array.require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IDBProvider = idbProvider;\n }\n}\n","/**\n * @file Utilities for uploading and downloading files.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n isUrlRelative,\n jsonParseHelper\n} from './utils.js';\n\nlet XHRProvider;\n\nfunction addURLParam(relUrl, key, value) {\n const url = new URL(relUrl, window.location.origin);\n url.searchParams.append(key, value);\n return url.toString().substring(window.location.origin.length);\n}\n\n/**\n * @class LargeFileHelper - utilities for uploading and downloading files out of band.\n * Don't instantiate this class directly. Use {Tinode.getLargeFileHelper} instead.\n * @memberof Tinode\n *\n * @param {Tinode} tinode - the main Tinode object.\n * @param {string} version - protocol version, i.e. '0'.\n */\nexport default class LargeFileHelper {\n constructor(tinode, version) {\n this._tinode = tinode;\n this._version = version;\n\n this._apiKey = tinode._apiKey;\n this._authToken = tinode.getAuthToken();\n\n // Ongoing requests.\n this.xhr = [];\n }\n\n /**\n * Start uploading the file to an endpoint at baseUrl.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} baseUrl base URL of upload server.\n * @param {File|Blob} data data to upload.\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure) {\n let url = `/v${this._version}/file/u/`;\n if (baseUrl) {\n let base = baseUrl;\n if (base.endsWith('/')) {\n // Removing trailing slash.\n base = base.slice(0, -1);\n }\n if (base.startsWith('http://') || base.startsWith('https://')) {\n url = base + url;\n } else {\n throw new Error(`Invalid base URL '${baseUrl}'`);\n }\n }\n\n const instance = this;\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n xhr.open('POST', url, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n if (this._authToken) {\n xhr.setRequestHeader('X-Tinode-Auth', `Token ${this._authToken.token}`);\n }\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n xhr.upload.onprogress = e => {\n if (e.lengthComputable) {\n if (onProgress) {\n onProgress(e.loaded / e.total);\n }\n if (this.onProgress) {\n this.onProgress(e.loaded / e.total);\n }\n }\n };\n\n xhr.onload = function() {\n let pkt;\n try {\n pkt = JSON.parse(this.response, jsonParseHelper);\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.response);\n pkt = {\n ctrl: {\n code: this.status,\n text: this.statusText\n }\n };\n }\n\n if (this.status >= 200 && this.status < 300) {\n if (toResolve) {\n toResolve(pkt.ctrl.params.url);\n }\n if (onSuccess) {\n onSuccess(pkt.ctrl);\n }\n } else if (this.status >= 400) {\n if (toReject) {\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n }\n if (onFailure) {\n onFailure(pkt.ctrl);\n }\n } else {\n instance._tinode.logger(\"ERROR: Unexpected server response status\", this.status, this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(e || new Error(\"failed\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n xhr.onabort = function(e) {\n if (toReject) {\n toReject(new Error(\"upload cancelled by user\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n try {\n const form = new FormData();\n form.append('file', data);\n form.set('id', this._tinode.getNextUniqueId());\n if (avatarFor) {\n form.set('topic', avatarFor);\n }\n xhr.send(form);\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onFailure) {\n onFailure(null);\n }\n }\n\n return result;\n }\n /**\n * Start uploading the file to default endpoint.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {File|Blob} data to upload\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n upload(data, avatarFor, onProgress, onSuccess, onFailure) {\n const baseUrl = (this._tinode._secure ? 'https://' : 'http://') + this._tinode._host;\n return this.uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure);\n }\n /**\n * Download the file from a given URL using GET request. This method works with the Tinode server only.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} relativeUrl - URL to download the file from. Must be relative url, i.e. must not contain the host.\n * @param {string=} filename - file name to use for the downloaded file.\n *\n * @returns {Promise} resolved/rejected when the download is completed/failed.\n */\n download(relativeUrl, filename, mimetype, onProgress, onError) {\n if (!isUrlRelative(relativeUrl)) {\n // As a security measure refuse to download from an absolute URL.\n if (onError) {\n onError(`The URL '${relativeUrl}' must be relative, not absolute`);\n }\n return;\n }\n if (!this._authToken) {\n if (onError) {\n onError(\"Must authenticate first\");\n }\n return;\n }\n const instance = this;\n\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n // Add '&asatt=1' to URL to request 'Content-Disposition: attachment' response header.\n relativeUrl = addURLParam(relativeUrl, 'asatt', '1');\n\n // Get data as blob (stored by the browser as a temporary file).\n xhr.open('GET', relativeUrl, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n xhr.setRequestHeader('X-Tinode-Auth', 'Token ' + this._authToken.token);\n xhr.responseType = 'blob';\n\n xhr.onprogress = function(e) {\n if (onProgress) {\n // Passing e.loaded instead of e.loaded/e.total because e.total\n // is always 0 with gzip compression enabled by the server.\n onProgress(e.loaded);\n }\n };\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n // The blob needs to be saved as file. There is no known way to\n // save the blob as file other than to fake a click on an .\n xhr.onload = function() {\n if (this.status == 200) {\n const link = document.createElement('a');\n // URL.createObjectURL is not available in non-browser environment. This call will fail.\n link.href = window.URL.createObjectURL(new Blob([this.response], {\n type: mimetype\n }));\n link.style.display = 'none';\n link.setAttribute('download', filename);\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n window.URL.revokeObjectURL(link.href);\n if (toResolve) {\n toResolve();\n }\n } else if (this.status >= 400 && toReject) {\n // The this.responseText is undefined, must use this.response which is a blob.\n // Need to convert this.response to JSON. The blob can only be accessed by the\n // FileReader.\n const reader = new FileReader();\n reader.onload = function() {\n try {\n const pkt = JSON.parse(this.result, jsonParseHelper);\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.result);\n toReject(err);\n }\n };\n reader.readAsText(this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(new Error(\"failed\"));\n }\n if (onError) {\n onError(e);\n }\n };\n\n xhr.onabort = function() {\n if (toReject) {\n toReject(null);\n }\n };\n\n try {\n xhr.send();\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onError) {\n onError(err);\n }\n }\n\n return result;\n }\n /**\n * Try to cancel all ongoing uploads or downloads.\n * @memberof Tinode.LargeFileHelper#\n */\n cancel() {\n this.xhr.forEach(req => {\n if (req.readyState < 4) {\n req.abort();\n }\n });\n }\n /**\n * To use LargeFileHelper in a non browser context, supply XMLHttpRequest provider.\n * @static\n * @memberof LargeFileHelper\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProvider(xhrProvider) {\n XHRProvider = xhrProvider;\n }\n}\n","/**\n * @module tinode-sdk\n *\n * @copyright 2015-2022 Tinode LLC.\n * @summary Javascript bindings for Tinode.\n * @license Apache 2.0\n * @version 0.20\n *\n * See https://github.com/tinode/webapp for real-life usage.\n *\n * @example\n * \n * \n * \n *\n * \n * ...\n * \n * \n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nimport AccessMode from './access-mode.js';\nimport * as Const from './config.js';\nimport CommError from './comm-error.js';\nimport Connection from './connection.js';\nimport DBCache from './db.js';\nimport Drafty from './drafty.js';\nimport LargeFileHelper from './large-file.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport Topic from './topic.js';\nimport TopicFnd from './fnd-topic.js';\nimport TopicMe from './me-topic.js';\n\nimport {\n isUrlRelative,\n jsonParseHelper,\n mergeObj,\n rfc3339DateString,\n simplify\n} from './utils.js';\n\n// Re-export AccessMode\nexport {\n AccessMode\n};\n\nlet WebSocketProvider;\nif (typeof WebSocket != 'undefined') {\n WebSocketProvider = WebSocket;\n}\n\nlet XHRProvider;\nif (typeof XMLHttpRequest != 'undefined') {\n XHRProvider = XMLHttpRequest;\n}\n\nlet IndexedDBProvider;\nif (typeof indexedDB != 'undefined') {\n IndexedDBProvider = indexedDB;\n}\n\n// Re-export Drafty.\nexport {\n Drafty\n}\n\ninitForNonBrowserApp();\n\n// Utility functions\n\n// Polyfill for non-browser context, e.g. NodeJs.\nfunction initForNonBrowserApp() {\n // Tinode requirement in native mode because react native doesn't provide Base64 method\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\n if (typeof btoa == 'undefined') {\n global.btoa = function(input = '') {\n let str = input;\n let output = '';\n\n for (let block = 0, charCode, i = 0, map = chars; str.charAt(i | 0) || (map = '=', i % 1); output += map.charAt(63 & block >> 8 - i % 1 * 8)) {\n\n charCode = str.charCodeAt(i += 3 / 4);\n\n if (charCode > 0xFF) {\n throw new Error(\"'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.\");\n }\n block = block << 8 | charCode;\n }\n\n return output;\n };\n }\n\n if (typeof atob == 'undefined') {\n global.atob = function(input = '') {\n let str = input.replace(/=+$/, '');\n let output = '';\n\n if (str.length % 4 == 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (let bc = 0, bs = 0, buffer, i = 0; buffer = str.charAt(i++);\n\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n }\n\n if (typeof window == 'undefined') {\n global.window = {\n WebSocket: WebSocketProvider,\n XMLHttpRequest: XHRProvider,\n indexedDB: IndexedDBProvider,\n URL: {\n createObjectURL: function() {\n throw new Error(\"Unable to use URL.createObjectURL in a non-browser application\");\n }\n }\n }\n }\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n DBCache.setDatabaseProvider(IndexedDBProvider);\n}\n\n// Detect find most useful network transport.\nfunction detectTransport() {\n if (typeof window == 'object') {\n if (window['WebSocket']) {\n return 'ws';\n } else if (window['XMLHttpRequest']) {\n // The browser or node has no websockets, using long polling.\n return 'lp';\n }\n }\n return null;\n}\n\n// btoa replacement. Stock btoa fails on on non-Latin1 strings.\nfunction b64EncodeUnicode(str) {\n // The encodeURIComponent percent-encodes UTF-8 string,\n // then the percent encoding is converted into raw bytes which\n // can be fed into btoa.\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,\n function toSolidBytes(match, p1) {\n return String.fromCharCode('0x' + p1);\n }));\n}\n\n// JSON stringify helper - pre-processor for JSON.stringify\nfunction jsonBuildHelper(key, val) {\n if (val instanceof Date) {\n // Convert javascript Date objects to rfc3339 strings\n val = rfc3339DateString(val);\n } else if (val instanceof AccessMode) {\n val = val.jsonHelper();\n } else if (val === undefined || val === null || val === false ||\n (Array.isArray(val) && val.length == 0) ||\n ((typeof val == 'object') && (Object.keys(val).length == 0))) {\n // strip out empty elements while serializing objects to JSON\n return undefined;\n }\n\n return val;\n};\n\n// Trims very long strings (encoded images) to make logged packets more readable.\nfunction jsonLoggerHelper(key, val) {\n if (typeof val == 'string' && val.length > 128) {\n return '<' + val.length + ', bytes: ' + val.substring(0, 12) + '...' + val.substring(val.length - 12) + '>';\n }\n return jsonBuildHelper(key, val);\n};\n\n// Parse browser user agent to extract browser name and version.\nfunction getBrowserInfo(ua, product) {\n ua = ua || '';\n let reactnative = '';\n // Check if this is a ReactNative app.\n if (/reactnative/i.test(product)) {\n reactnative = 'ReactNative; ';\n }\n let result;\n // Remove useless string.\n ua = ua.replace(' (KHTML, like Gecko)', '');\n // Test for WebKit-based browser.\n let m = ua.match(/(AppleWebKit\\/[.\\d]+)/i);\n if (m) {\n // List of common strings, from more useful to less useful.\n // All unknown strings get the highest (-1) priority.\n const priority = ['edg', 'chrome', 'safari', 'mobile', 'version'];\n let tmp = ua.substr(m.index + m[0].length).split(' ');\n let tokens = [];\n let version; // 1.0 in Version/1.0 or undefined;\n // Split string like 'Name/0.0.0' into ['Name', '0.0.0', 3] where the last element is the priority.\n for (let i = 0; i < tmp.length; i++) {\n let m2 = /([\\w.]+)[\\/]([\\.\\d]+)/.exec(tmp[i]);\n if (m2) {\n // Unknown values are highest priority (-1).\n tokens.push([m2[1], m2[2], priority.findIndex((e) => {\n return m2[1].toLowerCase().startsWith(e);\n })]);\n if (m2[1] == 'Version') {\n version = m2[2];\n }\n }\n }\n // Sort by priority: more interesting is earlier than less interesting.\n tokens.sort((a, b) => {\n return a[2] - b[2];\n });\n if (tokens.length > 0) {\n // Return the least common browser string and version.\n if (tokens[0][0].toLowerCase().startsWith('edg')) {\n tokens[0][0] = 'Edge';\n } else if (tokens[0][0] == 'OPR') {\n tokens[0][0] = 'Opera';\n } else if (tokens[0][0] == 'Safari' && version) {\n tokens[0][1] = version;\n }\n result = tokens[0][0] + '/' + tokens[0][1];\n } else {\n // Failed to ID the browser. Return the webkit version.\n result = m[1];\n }\n } else if (/firefox/i.test(ua)) {\n m = /Firefox\\/([.\\d]+)/g.exec(ua);\n if (m) {\n result = 'Firefox/' + m[1];\n } else {\n result = 'Firefox/?';\n }\n } else {\n // Neither AppleWebKit nor Firefox. Try the last resort.\n m = /([\\w.]+)\\/([.\\d]+)/.exec(ua);\n if (m) {\n result = m[1] + '/' + m[2];\n } else {\n m = ua.split(' ');\n result = m[0];\n }\n }\n\n // Shorten the version to one dot 'a.bb.ccc.d -> a.bb' at most.\n m = result.split('/');\n if (m.length > 1) {\n const v = m[1].split('.');\n const minor = v[1] ? '.' + v[1].substr(0, 2) : '';\n result = `${m[0]}/${v[0]}${minor}`;\n }\n return reactnative + result;\n}\n\n/**\n * The main class for interacting with Tinode server.\n */\nexport class Tinode {\n _host;\n _secure;\n\n _appName;\n\n // API Key.\n _apiKey;\n\n // Name and version of the browser.\n _browser = '';\n _platform;\n // Hardware\n _hwos = 'undefined';\n _humanLanguage = 'xx';\n\n // Logging to console enabled\n _loggingEnabled = false;\n // When logging, trip long strings (base64-encoded images) for readability\n _trimLongStrings = false;\n // UID of the currently authenticated user.\n _myUID = null;\n // Status of connection: authenticated or not.\n _authenticated = false;\n // Login used in the last successful basic authentication\n _login = null;\n // Token which can be used for login instead of login/password.\n _authToken = null;\n // Counter of received packets\n _inPacketCount = 0;\n // Counter for generating unique message IDs\n _messageId = Math.floor((Math.random() * 0xFFFF) + 0xFFFF);\n // Information about the server, if connected\n _serverInfo = null;\n // Push notification token. Called deviceToken for consistency with the Android SDK.\n _deviceToken = null;\n\n // Cache of pending promises by message id.\n _pendingPromises = {};\n // The Timeout object returned by the reject expired promises setInterval.\n _expirePromises = null;\n\n // Websocket or long polling connection.\n _connection = null;\n\n // Use indexDB for caching topics and messages.\n _persist = false;\n // IndexedDB wrapper object.\n _db = null;\n\n // Tinode's cache of objects\n _cache = {};\n\n /**\n * Create Tinode object.\n *\n * @param {Object} config - configuration parameters.\n * @param {string} config.appName - Name of the calling application to be reported in the User Agent.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - See {@link Tinode.Connection#transport}.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} config.platform - Optional platform identifier, one of \"ios\", \"web\", \"android\".\n * @param {boolen} config.persist - Use IndexedDB persistent storage.\n * @param {function} onComplete - callback to call when initialization is completed.\n */\n constructor(config, onComplete) {\n this._host = config.host;\n this._secure = config.secure;\n\n // Client-provided application name, format null if no valid credentials were given.\n */\n static credential(meth, val, params, resp) {\n if (typeof meth == 'object') {\n ({\n val,\n params,\n resp,\n meth\n } = meth);\n }\n if (meth && (val || resp)) {\n return [{\n 'meth': meth,\n 'val': val,\n 'resp': resp,\n 'params': params\n }];\n }\n return null;\n }\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n return Topic.topicType(name);\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.isMeTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a group topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.isGroupTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.isP2PTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isCommTopicName(name);\n }\n /**\n * Check if the topic name is a name of a new topic.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return Topic.isNewGroupTopicName(name);\n }\n /**\n * Check if the topic name is a name of a channel.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return Topic.isChannelTopicName(name);\n }\n /**\n * Get information about the current version of this Tinode client library.\n * @returns {string} semantic version of the library, e.g. \"0.15.5-rc1\".\n */\n static getVersion() {\n return Const.VERSION;\n }\n /**\n * To use Tinode in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n *\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n }\n /**\n * To use Tinode in a non browser context, supply indexedDB provider.\n * @static\n *\n * @param idbProvider indexedDB provider, e.g. for nodeJS , require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IndexedDBProvider = idbProvider;\n\n DBCache.setDatabaseProvider(IndexedDBProvider);\n }\n /**\n * Return information about the current name and version of this Tinode library.\n * @static\n *\n * @returns {string} the name of the library and it's version.\n */\n static getLibrary() {\n return Const.LIBRARY;\n }\n /**\n * Check if the given string represents NULL value as defined by Tinode ('\\u2421').\n * @param {string} str - string to check for NULL value.\n * @returns {boolean} true if string represents NULL value, false otherwise.\n */\n static isNullValue(str) {\n return str === Const.DEL_CHAR;\n }\n\n // Instance methods.\n\n // Generates unique message IDs\n getNextUniqueId() {\n return (this._messageId != 0) ? '' + this._messageId++ : undefined;\n };\n\n /**\n * Connect to the server.\n *\n * @param {string} host_ - name of the host to connect to.\n * @return {Promise} Promise resolved/rejected when the connection call completes:\n * resolve() is called without parameters, reject() receives the\n * Error as a single parameter.\n */\n connect(host_) {\n return this._connection.connect(host_);\n }\n\n /**\n * Attempt to reconnect to the server immediately.\n *\n * @param {string} force - if true, reconnect even if there is a connection already.\n */\n reconnect(force) {\n this._connection.reconnect(force);\n }\n\n /**\n * Disconnect from the server.\n */\n disconnect() {\n this._connection.disconnect();\n }\n\n /**\n * Clear persistent cache: remove IndexedDB.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n clearStorage() {\n if (this._db.isReady()) {\n return this._db.deleteDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Initialize persistent cache: create IndexedDB cache.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n initStorage() {\n if (!this._db.isReady()) {\n return this._db.initDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Send a network probe message to make sure the connection is alive.\n */\n networkProbe() {\n this._connection.probe();\n }\n\n /**\n * Check for live connection to server.\n *\n * @returns {boolean} true if there is a live connection, false otherwise.\n */\n isConnected() {\n return this._connection.isConnected();\n }\n\n /**\n * Check if connection is authenticated (last login was successful).\n *\n * @returns {boolean} true if authenticated, false otherwise.\n */\n isAuthenticated() {\n return this._authenticated;\n }\n\n /**\n * Add API key and auth token to the relative URL making it usable for getting data\n * from the server in a simple HTTP GET request.\n *\n * @param {string} URL - URL to wrap.\n * @returns {string} URL with appended API key and token, if valid token is present.\n */\n authorizeURL(url) {\n if (typeof url != 'string') {\n return url;\n }\n\n if (isUrlRelative(url)) {\n // Fake base to make the relative URL parseable.\n const base = 'scheme://host/';\n const parsed = new URL(url, base);\n if (this._apiKey) {\n parsed.searchParams.append('apikey', this._apiKey);\n }\n if (this._authToken && this._authToken.token) {\n parsed.searchParams.append('auth', 'token');\n parsed.searchParams.append('secret', this._authToken.token);\n }\n // Convert back to string and strip fake base URL except for the root slash.\n url = parsed.toString().substring(base.length - 1);\n }\n return url;\n }\n\n /**\n * @typedef AccountParams\n * @type {Object}\n * @property {DefAcs=} defacs - Default access parameters for user's me topic.\n * @property {Object=} public - Public application-defined data exposed on me topic.\n * @property {Object=} private - Private application-defined data accessible on me topic.\n * @property {Object=} trusted - Trusted user data which can be set by a root user only.\n * @property {Array.me for authenticated users.\n * @property {string=} anon - Access mode for me for anonymous users.\n */\n\n /**\n * Create or update an account.\n *\n * @param {string} uid - User id to update\n * @param {string} scheme - Authentication scheme; \"basic\" and \"anonymous\" are the currently supported schemes.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n account(uid, scheme, secret, login, params) {\n const pkt = this.#initPacket('acc');\n pkt.acc.user = uid;\n pkt.acc.scheme = scheme;\n pkt.acc.secret = secret;\n // Log in to the new account using selected scheme\n pkt.acc.login = login;\n\n if (params) {\n pkt.acc.desc.defacs = params.defacs;\n pkt.acc.desc.public = params.public;\n pkt.acc.desc.private = params.private;\n pkt.acc.desc.trusted = params.trusted;\n\n pkt.acc.tags = params.tags;\n pkt.acc.cred = params.cred;\n\n pkt.acc.tmpscheme = params.scheme;\n pkt.acc.tmpsecret = params.secret;\n\n if (Array.isArray(params.attachments) && params.attachments.length > 0) {\n pkt.extra = {\n attachments: params.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n }\n\n return this.#send(pkt, pkt.acc.id);\n }\n\n /**\n * Create a new user. Wrapper for {@link Tinode#account}.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccount(scheme, secret, login, params) {\n let promise = this.account(Const.USER_NEW, scheme, secret, login, params);\n if (login) {\n promise = promise.then(ctrl => this.#loginSuccessful(ctrl));\n }\n return promise;\n }\n\n /**\n * Create user with 'basic' authentication scheme and immediately\n * use it for authentication. Wrapper for {@link Tinode#account}.\n *\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccountBasic(username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.createAccount('basic',\n b64EncodeUnicode(username + ':' + password), true, params);\n }\n\n /**\n * Update user's credentials for 'basic' authentication scheme. Wrapper for {@link Tinode#account}.\n *\n * @param {string} uid - User ID to update.\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n updateAccountBasic(uid, username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.account(uid, 'basic',\n b64EncodeUnicode(username + ':' + password), false, params);\n }\n\n /**\n * Send handshake to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n hello() {\n const pkt = this.#initPacket('hi');\n\n return this.#send(pkt, pkt.hi.id)\n .then(ctrl => {\n // Reset backoff counter on successful connection.\n this._connection.backoffReset();\n\n // Server response contains server protocol version, build, constraints,\n // session ID for long polling. Save them.\n if (ctrl.params) {\n this._serverInfo = ctrl.params;\n }\n\n if (this.onConnect) {\n this.onConnect();\n }\n\n return ctrl;\n }).catch(err => {\n this._connection.reconnect(true);\n\n if (this.onDisconnect) {\n this.onDisconnect(err);\n }\n });\n }\n\n /**\n * Set or refresh the push notifications/device token. If the client is connected,\n * the deviceToken can be sent to the server.\n *\n * @param {string} dt - token obtained from the provider or false,\n * null or undefined to clear the token.\n *\n * @returns true if attempt was made to send the update to the server.\n */\n setDeviceToken(dt) {\n let sent = false;\n // Convert any falsish value to null.\n dt = dt || null;\n if (dt != this._deviceToken) {\n this._deviceToken = dt;\n if (this.isConnected() && this.isAuthenticated()) {\n this.#send({\n 'hi': {\n 'dev': dt || Tinode.DEL_CHAR\n }\n });\n sent = true;\n }\n }\n return sent;\n }\n\n /**\n * @typedef Credential\n * @type {Object}\n * @property {string} meth - validation method.\n * @property {string} val - value to validate (e.g. email or phone number).\n * @property {string} resp - validation response.\n * @property {Object} params - validation parameters.\n */\n /**\n * Authenticate current session.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n login(scheme, secret, cred) {\n const pkt = this.#initPacket('login');\n pkt.login.scheme = scheme;\n pkt.login.secret = secret;\n pkt.login.cred = cred;\n\n return this.#send(pkt, pkt.login.id)\n .then(ctrl => this.#loginSuccessful(ctrl));\n }\n\n /**\n * Wrapper for {@link Tinode#login} with basic authentication\n *\n * @param {string} uname - User name.\n * @param {string} password - Password.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginBasic(uname, password, cred) {\n return this.login('basic', b64EncodeUnicode(uname + ':' + password), cred)\n .then(ctrl => {\n this._login = uname;\n return ctrl;\n });\n }\n\n /**\n * Wrapper for {@link Tinode#login} with token authentication\n *\n * @param {string} token - Token received in response to earlier login.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginToken(token, cred) {\n return this.login('token', token, cred);\n }\n\n /**\n * Send a request for resetting an authentication secret.\n *\n * @param {string} scheme - authentication scheme to reset.\n * @param {string} method - method to use for resetting the secret, such as \"email\" or \"tel\".\n * @param {string} value - value of the credential to use, a specific email address or a phone number.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving the server reply.\n */\n requestResetAuthSecret(scheme, method, value) {\n return this.login('reset', b64EncodeUnicode(scheme + ':' + method + ':' + value));\n }\n\n /**\n * @typedef AuthToken\n * @type {Object}\n * @property {string} token - Token value.\n * @property {Date} expires - Token expiration time.\n */\n /**\n * Get stored authentication token.\n *\n * @returns {AuthToken} authentication token.\n */\n getAuthToken() {\n if (this._authToken && (this._authToken.expires.getTime() > Date.now())) {\n return this._authToken;\n } else {\n this._authToken = null;\n }\n return null;\n }\n\n /**\n * Application may provide a saved authentication token.\n *\n * @param {AuthToken} token - authentication token.\n */\n setAuthToken(token) {\n this._authToken = token;\n }\n\n /**\n * @typedef SetParams\n * @type {Object}\n * @property {SetDesc=} desc - Topic initialization parameters when creating a new topic or a new subscription.\n * @property {SetSub=} sub - Subscription initialization parameters.\n * @property {Array.true, detach and unsubscribe, otherwise just detach.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n leave(topic, unsub) {\n const pkt = this.#initPacket('leave', topic);\n pkt.leave.unsub = unsub;\n\n return this.#send(pkt, pkt.leave.id);\n }\n\n /**\n * Create message draft without sending it to the server.\n *\n * @param {string} topic - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Object} new message which can be sent to the server or otherwise used.\n */\n createMessage(topic, content, noEcho) {\n const pkt = this.#initPacket('pub', topic);\n\n let dft = typeof content == 'string' ? Drafty.parse(content) : content;\n if (dft && !Drafty.isPlainText(dft)) {\n pkt.pub.head = {\n mime: Drafty.getContentType()\n };\n content = dft;\n }\n pkt.pub.noecho = noEcho;\n pkt.pub.content = content;\n\n return pkt.pub;\n }\n\n /**\n * Publish {data} message to topic.\n *\n * @param {string} topicName - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n publish(topicName, content, noEcho) {\n return this.publishMessage(\n this.createMessage(topicName, content, noEcho)\n );\n }\n\n /**\n * Publish message to topic. The message should be created by {@link Tinode#createMessage}.\n *\n * @param {Object} pub - Message to publish.\n * @param {Array.'me' topic.\n *\n * @param {string} method - validation method such as 'email' or 'tel'.\n * @param {string} value - validation value, i.e. 'alice@example.com'.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n const pkt = this.#initPacket('del', Const.TOPIC_ME);\n pkt.del.what = 'cred';\n pkt.del.cred = {\n meth: method,\n val: value\n };\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Request to delete account of the current user.\n *\n * @param {boolean} hard - hard-delete user.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCurrentUser(hard) {\n const pkt = this.#initPacket('del', null);\n pkt.del.what = 'user';\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id).then(_ => {\n this._myUID = null;\n });\n }\n\n /**\n * Notify server that a message or messages were read or received. Does NOT return promise.\n *\n * @param {string} topicName - Name of the topic where the mesage is being aknowledged.\n * @param {string} what - Action being aknowledged, either \"read\" or \"recv\".\n * @param {number} seq - Maximum id of the message being acknowledged.\n */\n note(topicName, what, seq) {\n if (seq <= 0 || seq >= Const.LOCAL_SEQID) {\n throw new Error(`Invalid message id ${seq}`);\n }\n\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = what;\n pkt.note.seq = seq;\n this.#send(pkt);\n }\n\n /**\n * Broadcast a key-press notification to topic subscribers. Used to show\n * typing notifications \"user X is typing...\".\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {string=} type - notification to send, default is 'kp'.\n */\n noteKeyPress(topicName, type) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = type || 'kp';\n this.#send(pkt);\n }\n\n /**\n * Send a video call notification to topic subscribers (including dialing,\n * hangup, etc.).\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} evt - Call event.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(topicName, seq, evt, payload) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.seq = seq;\n pkt.note.what = 'call';\n pkt.note.event = evt;\n pkt.note.payload = payload;\n this.#send(pkt, pkt.note.id);\n }\n\n /**\n * Get a named topic, either pull it from cache or create a new instance.\n * There is a single instance of topic for each name.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested or newly created topic or undefined if topic name is invalid.\n */\n getTopic(topicName) {\n let topic = this.#cacheGet('topic', topicName);\n if (!topic && topicName) {\n if (topicName == Const.TOPIC_ME) {\n topic = new TopicMe();\n } else if (topicName == Const.TOPIC_FND) {\n topic = new TopicFnd();\n } else {\n topic = new Topic(topicName);\n }\n // Cache management.\n this.#attachCacheToTopic(topic);\n topic._cachePutSelf();\n // Don't save to DB here: a record will be added when the topic is subscribed.\n }\n return topic;\n }\n\n /**\n * Get a named topic from cache.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested topic or undefined if topic is not found in cache.\n */\n cacheGetTopic(topicName) {\n return this.#cacheGet('topic', topicName);\n }\n\n /**\n * Remove named topic from cache.\n *\n * @param {string} topicName - Name of the topic to remove from cache.\n */\n cacheRemTopic(topicName) {\n this.#cacheDel('topic', topicName);\n }\n\n /**\n * Iterate over cached topics.\n *\n * @param {Function} func - callback to call for each topic.\n * @param {Object} context - 'this' inside the 'func'.\n */\n mapTopics(func, context) {\n this.#cacheMap('topic', func, context);\n }\n\n /**\n * Check if named topic is already present in cache.\n *\n * @param {string} topicName - Name of the topic to check.\n * @returns {boolean} true if topic is found in cache, false otherwise.\n */\n isTopicCached(topicName) {\n return !!this.#cacheGet('topic', topicName);\n }\n\n /**\n * Generate unique name like 'new123456' suitable for creating a new group topic.\n *\n * @param {boolean} isChan - if the topic is channel-enabled.\n * @returns {string} name which can be used for creating a new group topic.\n */\n newGroupTopicName(isChan) {\n return (isChan ? Const.TOPIC_NEW_CHAN : Const.TOPIC_NEW) + this.getNextUniqueId();\n }\n\n /**\n * Instantiate 'me' topic or get it from cache.\n *\n * @returns {TopicMe} Instance of 'me' topic.\n */\n getMeTopic() {\n return this.getTopic(Const.TOPIC_ME);\n }\n\n /**\n * Instantiate 'fnd' (find) topic or get it from cache.\n *\n * @returns {Topic} Instance of 'fnd' topic.\n */\n getFndTopic() {\n return this.getTopic(Const.TOPIC_FND);\n }\n\n /**\n * Create a new {@link LargeFileHelper} instance\n *\n * @returns {LargeFileHelper} instance of a {@link Tinode.LargeFileHelper}.\n */\n getLargeFileHelper() {\n return new LargeFileHelper(this, Const.PROTOCOL_VERSION);\n }\n\n /**\n * Get the UID of the the current authenticated user.\n *\n * @returns {string} UID of the current user or undefined if the session is not yet\n * authenticated or if there is no session.\n */\n getCurrentUserID() {\n return this._myUID;\n }\n\n /**\n * Check if the given user ID is equal to the current user's UID.\n *\n * @param {string} uid - UID to check.\n *\n * @returns {boolean} true if the given UID belongs to the current logged in user.\n */\n isMe(uid) {\n return this._myUID === uid;\n }\n\n /**\n * Get login used for last successful authentication.\n *\n * @returns {string} login last used successfully or undefined.\n */\n getCurrentLogin() {\n return this._login;\n }\n\n /**\n * Return information about the server: protocol version and build timestamp.\n *\n * @returns {Object} build and version of the server or null if there is no connection or\n * if the first server response has not been received yet.\n */\n getServerInfo() {\n return this._serverInfo;\n }\n\n /**\n * Report a topic for abuse. Wrapper for {@link Tinode#publish}.\n *\n * @param {string} action - the only supported action is 'report'.\n * @param {string} target - name of the topic being reported.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n report(action, target) {\n return this.publish(Const.TOPIC_SYS, Drafty.attachJSON(null, {\n 'action': action,\n 'target': target\n }));\n }\n\n /**\n * Return server-provided configuration value.\n *\n * @param {string} name of the value to return.\n * @param {Object} defaultValue to return in case the parameter is not set or not found.\n *\n * @returns {Object} named value.\n */\n getServerParam(name, defaultValue) {\n return this._serverInfo && this._serverInfo[name] || defaultValue;\n }\n\n /**\n * Toggle console logging. Logging is off by default.\n *\n * @param {boolean} enabled - Set to true to enable logging to console.\n * @param {boolean} trimLongStrings - Set to true to trim long strings.\n */\n enableLogging(enabled, trimLongStrings) {\n this._loggingEnabled = enabled;\n this._trimLongStrings = enabled && trimLongStrings;\n }\n\n /**\n * Set UI language to report to the server. Must be called before 'hi' is sent, otherwise it will not be used.\n *\n * @param {string} hl - human (UI) language, like \"en_US\" or \"zh-Hans\".\n */\n setHumanLanguage(hl) {\n if (hl) {\n this._humanLanguage = hl;\n }\n }\n\n /**\n * Check if given topic is online.\n *\n * @param {string} name of the topic to test.\n * @returns {boolean} true if topic is online, false otherwise.\n */\n isTopicOnline(name) {\n const topic = this.#cacheGet('topic', name);\n return topic && topic.online;\n }\n\n /**\n * Get access mode for the given contact.\n *\n * @param {string} name of the topic to query.\n * @returns {AccessMode} access mode if topic is found, null otherwise.\n */\n getTopicAccessMode(name) {\n const topic = this.#cacheGet('topic', name);\n return topic ? topic.acs : null;\n }\n\n /**\n * Include message ID into all subsequest messages to server instructin it to send aknowledgemens.\n * Required for promises to function. Default is \"on\".\n *\n * @param {boolean} status - Turn aknowledgemens on or off.\n * @deprecated\n */\n wantAkn(status) {\n if (status) {\n this._messageId = Math.floor((Math.random() * 0xFFFFFF) + 0xFFFFFF);\n } else {\n this._messageId = 0;\n }\n }\n\n // Callbacks:\n /**\n * Callback to report when the websocket is opened. The callback has no parameters.\n *\n * @type {onWebsocketOpen}\n */\n onWebsocketOpen = undefined;\n\n /**\n * @typedef ServerParams\n *\n * @type {Object}\n * @property {string} ver - Server version\n * @property {string} build - Server build\n * @property {string=} sid - Session ID, long polling connections only.\n */\n\n /**\n * @callback onConnect\n * @param {number} code - Result code\n * @param {string} text - Text epxplaining the completion, i.e \"OK\" or an error message.\n * @param {ServerParams} params - Parameters returned by the server.\n */\n /**\n * Callback to report when connection with Tinode server is established.\n * @type {onConnect}\n */\n onConnect = undefined;\n\n /**\n * Callback to report when connection is lost. The callback has no parameters.\n * @type {onDisconnect}\n */\n onDisconnect = undefined;\n\n /**\n * @callback onLogin\n * @param {number} code - NUmeric completion code, same as HTTP status codes.\n * @param {string} text - Explanation of the completion code.\n */\n /**\n * Callback to report login completion.\n * @type {onLogin}\n */\n onLogin = undefined;\n\n /**\n * Callback to receive {ctrl} (control) messages.\n * @type {onCtrlMessage}\n */\n onCtrlMessage = undefined;\n\n /**\n * Callback to recieve {data} (content) messages.\n * @type {onDataMessage}\n */\n onDataMessage = undefined;\n\n /**\n * Callback to receive {pres} (presence) messages.\n * @type {onPresMessage}\n */\n onPresMessage = undefined;\n\n /**\n * Callback to receive all messages as objects.\n * @type {onMessage}\n */\n onMessage = undefined;\n\n /**\n * Callback to receive all messages as unparsed text.\n * @type {onRawMessage}\n */\n onRawMessage = undefined;\n\n /**\n * Callback to receive server responses to network probes. See {@link Tinode#networkProbe}\n * @type {onNetworkProbe}\n */\n onNetworkProbe = undefined;\n\n /**\n * Callback to be notified when exponential backoff is iterating.\n * @type {onAutoreconnectIteration}\n */\n onAutoreconnectIteration = undefined;\n};\n\n// Exported constants\nTinode.MESSAGE_STATUS_NONE = Const.MESSAGE_STATUS_NONE;\nTinode.MESSAGE_STATUS_QUEUED = Const.MESSAGE_STATUS_QUEUED;\nTinode.MESSAGE_STATUS_SENDING = Const.MESSAGE_STATUS_SENDING;\nTinode.MESSAGE_STATUS_FAILED = Const.MESSAGE_STATUS_FAILED;\nTinode.MESSAGE_STATUS_FATAL = Const.MESSAGE_STATUS_FATAL;\nTinode.MESSAGE_STATUS_SENT = Const.MESSAGE_STATUS_SENT;\nTinode.MESSAGE_STATUS_RECEIVED = Const.MESSAGE_STATUS_RECEIVED;\nTinode.MESSAGE_STATUS_READ = Const.MESSAGE_STATUS_READ;\nTinode.MESSAGE_STATUS_TO_ME = Const.MESSAGE_STATUS_TO_ME;\n\n// Unicode [del] symbol.\nTinode.DEL_CHAR = Const.DEL_CHAR;\n\n// Names of keys to server-provided configuration limits.\nTinode.MAX_MESSAGE_SIZE = 'maxMessageSize';\nTinode.MAX_SUBSCRIBER_COUNT = 'maxSubscriberCount';\nTinode.MAX_TAG_COUNT = 'maxTagCount';\nTinode.MAX_FILE_UPLOAD_SIZE = 'maxFileUploadSize';\nTinode.REQ_CRED_VALIDATORS = 'reqCred';\n","/**\n * @file Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport {\n listToRanges,\n normalizeRanges\n} from './utils';\n\n/**\n * Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @class MetaGetBuilder\n * @memberof Tinode\n *\n * @param {Tinode.Topic} parent topic which instantiated this builder.\n */\nexport default class MetaGetBuilder {\n constructor(parent) {\n this.topic = parent;\n this.what = {};\n }\n\n // Get timestamp of the most recent desc update.\n #get_desc_ims() {\n return this.topic.updated;\n }\n\n // Get timestamp of the most recent subs update.\n #get_subs_ims() {\n if (this.topic.isP2PType()) {\n return this.#get_desc_ims();\n }\n return this.topic._lastSubsUpdate;\n }\n /**\n * Add query parameters to fetch messages within explicit limits.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - messages newer than this (inclusive);\n * @param {number=} before - older than this (exclusive)\n * @param {number=} limit - number of messages to fetch\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withData(since, before, limit) {\n this.what['data'] = {\n since: since,\n before: before,\n limit: limit\n };\n return this;\n }\n /**\n * Add query parameters to fetch messages newer than the latest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of messages to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterData(limit) {\n return this.withData(this.topic._maxSeq > 0 ? this.topic._maxSeq + 1 : undefined, undefined, limit);\n }\n /**\n * Add query parameters to fetch messages within ID ranges.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Array.this object.\n */\n withDataRanges(ranges, limit) {\n this.what['data'] = {\n ranges: normalizeRanges(ranges, this.topic._maxSeq),\n limit: limit\n };\n return this;\n }\n /**\n * Add query parameters to fetch messages by an array of IDs.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number[]} list - array of seq IDs to fetch.\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDataList(list) {\n return this.withDataRanges(listToRanges(list));\n }\n /**\n * Add query parameters to fetch messages older than the earliest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of messages to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withEarlierData(limit) {\n return this.withData(undefined, this.topic._minSeq > 0 ? this.topic._minSeq : undefined, limit);\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the given timestamp.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch messages newer than this timestamp.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDesc(ims) {\n this.what['desc'] = {\n ims: ims\n };\n return this;\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDesc() {\n return this.withDesc(this.#get_desc_ims());\n }\n /**\n * Add query parameters to fetch subscriptions.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {number=} limit - maximum number of subscriptions to fetch.\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withSub(ims, limit, userOrTopic) {\n const opts = {\n ims: ims,\n limit: limit\n };\n if (this.topic.getType() == 'me') {\n opts.topic = userOrTopic;\n } else {\n opts.user = userOrTopic;\n }\n this.what['sub'] = opts;\n return this;\n }\n /**\n * Add query parameters to fetch a single subscription.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withOneSub(ims, userOrTopic) {\n return this.withSub(ims, undefined, userOrTopic);\n }\n /**\n * Add query parameters to fetch a single subscription if it's been updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterOneSub(userOrTopic) {\n return this.withOneSub(this.topic._lastSubsUpdate, userOrTopic);\n }\n /**\n * Add query parameters to fetch subscriptions updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of subscriptions to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterSub(limit) {\n return this.withSub(this.#get_subs_ims(), limit);\n }\n /**\n * Add query parameters to fetch topic tags.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withTags() {\n this.what['tags'] = true;\n return this;\n }\n /**\n * Add query parameters to fetch user's credentials. 'me' topic only.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withCred() {\n if (this.topic.getType() == 'me') {\n this.what['cred'] = true;\n } else {\n this.topic._tinode.logger(\"ERROR: Invalid topic type for MetaGetBuilder:withCreds\", this.topic.getType());\n }\n return this;\n }\n /**\n * Add query parameters to fetch topic tags.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withAux() {\n this.what['aux'] = true;\n return this;\n }\n /**\n * Add query parameters to fetch deleted messages within explicit limits. Any/all parameters can be null.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - ids of messages deleted since this 'del' id (inclusive)\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDel(since, limit) {\n if (since || limit) {\n this.what['del'] = {\n since: since,\n limit: limit\n };\n }\n return this;\n }\n /**\n * Add query parameters to fetch messages deleted after the saved 'del' id.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDel(limit) {\n // Specify 'since' only if we have already received some messages. If\n // we have no locally cached messages then we don't care if any messages were deleted.\n return this.withDel(this.topic._maxSeq > 0 ? this.topic._maxDel + 1 : undefined, limit);\n }\n\n /**\n * Extract subquery: get an object that contains specified subquery.\n * @memberof Tinode.MetaGetBuilder#\n * @param {string} what - subquery to return: one of 'data', 'sub', 'desc', 'tags', 'cred', 'del'.\n * @returns {Object} requested subquery or undefined.\n */\n extract(what) {\n return this.what[what];\n }\n\n /**\n * Construct parameters.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.GetQuery} Get query\n */\n build() {\n const what = [];\n let params = {};\n ['data', 'sub', 'desc', 'tags', 'cred', 'aux', 'del'].forEach((key) => {\n if (this.what.hasOwnProperty(key)) {\n what.push(key);\n if (Object.getOwnPropertyNames(this.what[key]).length > 0) {\n params[key] = this.what[key];\n }\n }\n });\n if (what.length > 0) {\n params.what = what.join(' ');\n } else {\n params = undefined;\n }\n return params;\n }\n}\n","/**\n * @file In-memory sorted cache of objects.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n/**\n * In-memory sorted cache of objects.\n *\n * @class CBuffer\n * @memberof Tinode\n * @protected\n *\n * @param {function} compare custom comparator of objects. Takes two parameters a and b;\n * returns -1 if a < b, 0 if a == b, 1 otherwise.\n * @param {boolean} unique enforce element uniqueness: when true replace existing element with a new\n * one on conflict; when false keep both elements.\n */\nexport default class CBuffer {\n #comparator = undefined;\n #unique = false;\n buffer = [];\n\n constructor(compare_, unique_) {\n this.#comparator = compare_ || ((a, b) => {\n return a === b ? 0 : a < b ? -1 : 1;\n });\n this.#unique = unique_;\n }\n\n #findNearest(elem, arr, exact) {\n let start = 0;\n let end = arr.length - 1;\n let pivot = 0;\n let diff = 0;\n let found = false;\n\n while (start <= end) {\n pivot = (start + end) / 2 | 0;\n diff = this.#comparator(arr[pivot], elem);\n if (diff < 0) {\n start = pivot + 1;\n } else if (diff > 0) {\n end = pivot - 1;\n } else {\n found = true;\n break;\n }\n }\n if (found) {\n return {\n idx: pivot,\n exact: true\n };\n }\n if (exact) {\n return {\n idx: -1\n };\n }\n // Not exact - insertion point\n return {\n idx: diff < 0 ? pivot + 1 : pivot\n };\n }\n\n // Insert element into a sorted array.\n #insertSorted(elem, arr) {\n const found = this.#findNearest(elem, arr, false);\n const count = (found.exact && this.#unique) ? 1 : 0;\n arr.splice(found.idx, count, elem);\n return arr;\n }\n\n /**\n * Get an element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to fetch from.\n * @returns {Object} Element at the given position or undefined.\n */\n getAt(at) {\n return this.buffer[at];\n }\n\n /**\n * Convenience method for getting the element from the end of the buffer.\n * @memberof Tinode.CBuffer#\n * @param {number} at - position to fetch from, counting from the end;\n * undefined or null mean \"last\".\n * @returns {Object} The last element in the buffer or undefined if buffer is empty.\n */\n getLast(at) {\n at |= 0;\n return this.buffer.length > at ? this.buffer[this.buffer.length - 1 - at] : undefined;\n }\n\n /**\n * Insert new element(s) to the buffer at the correct position according to the sort method.\n * Variadic: takes one or more arguments. If an array is passed as a single argument, its\n * elements are inserted individually.\n * @memberof Tinode.CBuffer#\n *\n * @param {...Object|Array} - One or more objects to insert.\n */\n put() {\n let insert;\n // inspect arguments: if array, insert its elements, if one or more non-array arguments, insert them one by one\n if (arguments.length == 1 && Array.isArray(arguments[0])) {\n insert = arguments[0];\n } else {\n insert = arguments;\n }\n for (let idx in insert) {\n this.#insertSorted(insert[idx], this.buffer);\n }\n }\n\n /**\n * Remove element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to delete at.\n * @returns {Object} Element at the given position or undefined.\n */\n delAt(at) {\n at |= 0;\n let r = this.buffer.splice(at, 1);\n if (r && r.length > 0) {\n return r[0];\n }\n return undefined;\n }\n\n /**\n * Remove elements between two positions.\n * @memberof Tinode.CBuffer#\n * @param {number} since - Position to delete from (inclusive).\n * @param {number} before - Position to delete to (exclusive).\n *\n * @returns {Array} array of removed elements (could be zero length).\n */\n delRange(since, before) {\n return this.buffer.splice(since, before - since);\n }\n\n /**\n * Return the number of elements the buffer holds.\n * @memberof Tinode.CBuffer#\n * @return {number} Number of elements in the buffer.\n */\n length() {\n return this.buffer.length;\n }\n\n /**\n * Reset the buffer discarding all elements\n * @memberof Tinode.CBuffer#\n */\n reset() {\n this.buffer = [];\n }\n\n /**\n * Callback for iterating contents of buffer. See {@link Tinode.CBuffer#forEach}.\n * @callback ForEachCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {Object} prev - Previous element of the buffer.\n * @param {Object} next - Next element of the buffer.\n * @param {number} index - Index of the current element.\n */\n\n /**\n * Apply given callback to all elements of the buffer.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.ForEachCallbackType} callback - Function to call for each element.\n * @param {number} startIdx - Optional index to start iterating from (inclusive), default: 0.\n * @param {number} beforeIdx - Optional index to stop iterating before (exclusive), default: length of the buffer.\n * @param {Object} context - calling context (i.e. value of this in callback)\n */\n forEach(callback, startIdx, beforeIdx, context) {\n startIdx = Math.max(0, startIdx | 0);\n beforeIdx = Math.min(beforeIdx || this.buffer.length, this.buffer.length);\n\n for (let i = startIdx; i < beforeIdx; i++) {\n callback.call(context, this.buffer[i],\n (i > startIdx ? this.buffer[i - 1] : undefined),\n (i < beforeIdx - 1 ? this.buffer[i + 1] : undefined), i);\n }\n }\n\n /**\n * Find element in buffer using buffer's comparison function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Object} elem - element to find.\n * @param {boolean=} nearest - when true and exact match is not found, return the nearest element (insertion point).\n * @returns {number} index of the element in the buffer or -1.\n */\n find(elem, nearest) {\n const {\n idx\n } = this.#findNearest(elem, this.buffer, !nearest);\n return idx;\n }\n\n /**\n * Callback for filtering the buffer. See {@link Tinode.CBuffer#filter}.\n * @callback FilterCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {number} index - Index of the current element.\n * @returns {boolen} true to keep the element, false to remove.\n */\n\n /**\n * Remove all elements that do not pass the test implemented by the provided callback function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.FilterCallbackType} callback - Function to call for each element.\n * @param {Object} context - calling context (i.e. value of this in the callback)\n */\n filter(callback, context) {\n let count = 0;\n for (let i = 0; i < this.buffer.length; i++) {\n if (callback.call(context, this.buffer[i], i)) {\n this.buffer[count] = this.buffer[i];\n count++;\n }\n }\n\n this.buffer.splice(count);\n }\n\n /**\n * Check if buffer is empty.\n * @returns {boolean} true if the buffer is empty, false otherwise.\n */\n isEmpty() {\n return this.buffer.length == 0;\n }\n}\n","/**\n * @file Topic management.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport CBuffer from './cbuffer.js';\nimport CommError from './comm-error.js';\nimport * as Const from './config.js';\nimport Drafty from './drafty.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport {\n listToRanges,\n mergeObj,\n mergeToCache,\n normalizeArray,\n normalizeRanges\n} from './utils.js';\n\n/**\n * Topic is a class representing a logical communication channel.\n */\nexport default class Topic {\n /**\n * @callback onData\n * @param {Data} data - Data packet\n */\n\n /**\n * Create topic.\n * @param {string} name - Name of the topic to create.\n * @param {Object=} callbacks - Object with various event callbacks.\n * @param {onData} callbacks.onData - Callback which receives a {data} message.\n * @param {callback} callbacks.onMeta - Callback which receives a {meta} message.\n * @param {callback} callbacks.onPres - Callback which receives a {pres} message.\n * @param {callback} callbacks.onInfo - Callback which receives an {info} message.\n * @param {callback} callbacks.onMetaDesc - Callback which receives changes to topic desctioption {@link desc}.\n * @param {callback} callbacks.onMetaSub - Called for a single subscription record change.\n * @param {callback} callbacks.onSubsUpdated - Called after a batch of subscription changes have been recieved and cached.\n * @param {callback} callbacks.onDeleteTopic - Called after the topic is deleted.\n * @param {callback} callbacls.onAllMessagesReceived - Called when all requested {data} messages have been recived.\n */\n constructor(name, callbacks) {\n // Parent Tinode object.\n this._tinode = null;\n\n // Server-provided data, locally immutable.\n // topic name\n this.name = name;\n // Timestamp when the topic was created.\n this.created = null;\n // Timestamp when the topic was last updated.\n this.updated = null;\n // Timestamp of the last messages\n this.touched = new Date(0);\n // Access mode, see AccessMode\n this.acs = new AccessMode(null);\n // Per-topic private data (accessible by current user only).\n this.private = null;\n // Per-topic public data (accessible by all users).\n this.public = null;\n // Per-topic system-provided data (accessible by all users).\n this.trusted = null;\n\n // Locally cached data\n // Subscribed users, for tracking read/recv/msg notifications.\n this._users = {};\n\n // Current value of locally issued seqId, used for pending messages.\n this._queuedSeqId = Const.LOCAL_SEQID;\n\n // The maximum known {data.seq} value.\n this._maxSeq = 0;\n // The minimum known {data.seq} value.\n this._minSeq = 0;\n // Indicator that the last request for earlier messages returned 0.\n this._noEarlierMsgs = false;\n // The maximum known deletion ID.\n this._maxDel = 0;\n // Timer object used to send 'recv' notifications.\n this._recvNotificationTimer = null;\n\n // User discovery tags\n this._tags = [];\n // Credentials such as email or phone number.\n this._credentials = [];\n // Auxiliary data\n this._aux = {};\n\n // Message versions cache (e.g. for edited messages).\n // Keys: original message seq ID.\n // Values: CBuffers containing newer versions of the original message\n // ordered by seq id.\n this._messageVersions = {};\n // Message cache, sorted by message seq values, from old to new.\n this._messages = new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n // Boolean, true if the topic is currently live\n this._attached = false;\n // Timestap of the most recently updated subscription.\n this._lastSubsUpdate = new Date(0);\n // Topic created but not yet synced with the server. Used only during initialization.\n this._new = true;\n // The topic is deleted at the server, this is a local copy.\n this._deleted = false;\n\n // Timer used to trgger {leave} request after a delay.\n this._delayedLeaveTimer = null;\n\n // Callbacks\n if (callbacks) {\n this.onData = callbacks.onData;\n this.onMeta = callbacks.onMeta;\n this.onPres = callbacks.onPres;\n this.onInfo = callbacks.onInfo;\n // A single desc update;\n this.onMetaDesc = callbacks.onMetaDesc;\n // A single subscription record;\n this.onMetaSub = callbacks.onMetaSub;\n // All subscription records received;\n this.onSubsUpdated = callbacks.onSubsUpdated;\n this.onTagsUpdated = callbacks.onTagsUpdated;\n this.onCredsUpdated = callbacks.onCredsUpdated;\n this.onAuxUpdated = callbacks.onAuxUpdated;\n this.onDeleteTopic = callbacks.onDeleteTopic;\n this.onAllMessagesReceived = callbacks.onAllMessagesReceived;\n }\n }\n\n // Static methods.\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n *\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n const types = {\n 'me': Const.TOPIC_ME,\n 'fnd': Const.TOPIC_FND,\n 'grp': Const.TOPIC_GRP,\n 'new': Const.TOPIC_GRP,\n 'nch': Const.TOPIC_GRP,\n 'chn': Const.TOPIC_GRP,\n 'usr': Const.TOPIC_P2P,\n 'sys': Const.TOPIC_SYS\n };\n return types[(typeof name == 'string') ? name.substring(0, 3) : 'xxx'];\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_ME;\n }\n\n /**\n * Check if the given topic name is a name of a group topic.\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_GRP;\n }\n\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_P2P;\n }\n\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isP2PTopicName(name) || Topic.isGroupTopicName(name);\n }\n\n /**\n * Check if the topic name is a name of a new topic.\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_NEW || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n /**\n * Check if the topic name is a name of a channel.\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_CHAN || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n // Returns true if pub is meant to replace another message (e.g. original message was edited).\n static #isReplacementMsg(pub) {\n return pub.head && pub.head.replace;\n }\n\n /**\n * Check if the topic is subscribed.\n * @returns {boolean} True is topic is attached/subscribed, false otherwise.\n */\n isSubscribed() {\n return this._attached;\n }\n\n /**\n * Request topic to subscribe. Wrapper for {@link Tinode#subscribe}.\n *\n * @param {Tinode.GetQuery=} getParams - get query parameters.\n * @param {Tinode.SetParams=} setParams - set parameters.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n subscribe(getParams, setParams) {\n // Clear request to leave topic.\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = null;\n\n // If the topic is already subscribed, return resolved promise\n if (this._attached) {\n return Promise.resolve(this);\n }\n\n // If the topic is deleted, reject subscription requests.\n if (this._deleted) {\n return Promise.reject(new Error(\"Conversation deleted\"));\n }\n\n // Send subscribe message, handle async response.\n // If topic name is explicitly provided, use it. If no name, then it's a new group topic,\n // use \"new\".\n return this._tinode.subscribe(this.name || Const.TOPIC_NEW, getParams, setParams).then(ctrl => {\n if (ctrl.code >= 300) {\n // Do nothing if subscription status has not changed.\n return ctrl;\n }\n\n this._attached = true;\n this._deleted = false;\n this.acs = (ctrl.params && ctrl.params.acs) ? ctrl.params.acs : this.acs;\n\n // Set topic name for new topics and add it to cache.\n if (this._new) {\n delete this._new;\n\n if (this.name != ctrl.topic) {\n // Name may change new123456 -> grpAbCdEf. Remove from cache under the old name.\n this._cacheDelSelf();\n this.name = ctrl.topic;\n }\n this._cachePutSelf();\n\n this.created = ctrl.ts;\n this.updated = ctrl.ts;\n\n if (this.name != Const.TOPIC_ME && this.name != Const.TOPIC_FND) {\n // Add the new topic to the list of contacts maintained by the 'me' topic.\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (setParams && setParams.desc) {\n setParams.desc._noForwarding = true;\n this._processMetaDesc(setParams.desc);\n }\n }\n return ctrl;\n });\n }\n\n /**\n * Create a draft of a message without sending it to the server.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Content to wrap in a draft.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * session. Otherwise the server will send a copy of the message to sender.\n *\n * @returns {Object} message draft.\n */\n createMessage(data, noEcho) {\n return this._tinode.createMessage(this.name, data, noEcho);\n }\n\n /**\n * Immediately publish data to topic. Wrapper for {@link Tinode#publish}.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Message to publish, either plain string or a Drafty object.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publish(data, noEcho) {\n return this.publishMessage(this.createMessage(data, noEcho));\n }\n\n /**\n * Publish message created by {@link Tinode.Topic#createMessage}.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - {data} object to publish. Must be created by {@link Tinode.Topic#createMessage}\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publishMessage(pub) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot publish on inactive topic\"));\n }\n if (this._sending) {\n return Promise.reject(new Error(\"The message is already being sent\"));\n }\n\n // Send data.\n pub._sending = true;\n pub._failed = false;\n\n // Extract refereces to attachments and out of band image records.\n let attachments = null;\n if (Drafty.hasEntities(pub.content)) {\n attachments = [];\n Drafty.entities(pub.content, data => {\n if (data) {\n if (data.ref) {\n attachments.push(data.ref);\n }\n if (data.preref) {\n attachments.push(data.preref);\n }\n }\n });\n if (attachments.length == 0) {\n attachments = null;\n }\n }\n\n return this._tinode.publishMessage(pub, attachments).then(ctrl => {\n pub._sending = false;\n pub.ts = ctrl.ts;\n this.swapMessageId(pub, ctrl.params.seq);\n this._maybeUpdateMessageVersionsCache(pub);\n this._routeData(pub);\n return ctrl;\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message rejected by the server\", err);\n pub._sending = false;\n pub._failed = true;\n if (this.onData) {\n this.onData();\n }\n });\n }\n\n /**\n * Add message to local message cache, send to the server when the promise is resolved.\n * If promise is null or undefined, the message will be sent immediately.\n * The message is sent when the\n * The message should be created by {@link Tinode.Topic#createMessage}.\n * This is probably not the final API.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - Message to use as a draft.\n * @param {Promise} prom - Message will be sent when this promise is resolved, discarded if rejected.\n *\n * @returns {Promise} derived promise.\n */\n publishDraft(pub, prom) {\n const seq = pub.seq || this._getQueuedSeqId();\n if (!pub._noForwarding) {\n // The 'seq', 'ts', and 'from' are added to mimic {data}. They are removed later\n // before the message is sent.\n pub._noForwarding = true;\n pub.seq = seq;\n pub.ts = new Date();\n pub.from = this._tinode.getCurrentUserID();\n\n // Don't need an echo message because the message is added to local cache right away.\n pub.noecho = true;\n // Add to cache.\n this._messages.put(pub);\n this._tinode._db.addMessage(pub);\n\n if (this.onData) {\n this.onData(pub);\n }\n }\n // If promise is provided, send the queued message when it's resolved.\n // If no promise is provided, create a resolved one and send immediately.\n return (prom || Promise.resolve())\n .then(_ => {\n if (pub._cancelled) {\n return {\n code: 300,\n text: \"cancelled\"\n };\n }\n return this.publishMessage(pub);\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message draft rejected\", err);\n pub._sending = false;\n pub._failed = true;\n pub._fatal = err instanceof CommError ? (err.code >= 400 && err.code < 500) : false;\n if (this.onData) {\n this.onData();\n }\n // Rethrow to let caller know that the operation failed.\n throw err;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean=} unsub - If true, unsubscribe, otherwise just leave.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n leave(unsub) {\n // It's possible to unsubscribe (unsub==true) from inactive topic.\n if (!this._attached && !unsub) {\n return Promise.reject(new Error(\"Cannot leave inactive topic\"));\n }\n\n // Send a 'leave' message, handle async response\n return this._tinode.leave(this.name, unsub).then(ctrl => {\n this._resetSub();\n if (unsub) {\n this._gone();\n }\n return ctrl;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe after a delay. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} unsub - If true, unsubscribe, otherwise just leave.\n * @param {number} delay - time in milliseconds to delay leave request.\n */\n leaveDelayed(unsub, delay) {\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = setTimeout(_ => {\n this._delayedLeaveTimer = null;\n this.leave(unsub)\n }, delay);\n }\n\n /**\n * Request topic metadata from the local cache or from the server.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.GetQuery} request parameters\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n getMeta(params) {\n // Send {get} message, return promise.\n return this._tinode.getMeta(this.name, params);\n }\n\n /**\n * Request more messages from the server. The goal is to load continous range of messages\n * covering at least between 'min' and 'max' + one full page forward (newer = true) or backwards\n * (newer=false).\n * @memberof Tinode.Topic#\n *\n * @param {number} limit number of messages to get.\n * @param {Array.null means to use default.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n invite(uid, mode) {\n return this.setMeta({\n sub: {\n user: uid,\n mode: mode\n }\n });\n }\n /**\n * Archive or un-archive the topic. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} arch - true to archive the topic, false otherwise.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n archive(arch) {\n if (this.private && (!this.private.arch == !arch)) {\n return Promise.resolve(arch);\n }\n return this.setMeta({\n desc: {\n private: {\n arch: arch ? true : Const.DEL_CHAR\n }\n }\n });\n }\n /**\n * Set message as pinned or unpinned by adding it to aux.pins array. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - seq ID of the message to pin or un-pin.\n * @param {boolean} pin - true to pin the message, false to un-pin.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n pinMessage(seq, pin) {\n let pinned = this.aux('pins');\n if (!Array.isArray(pinned)) {\n pinned = [];\n }\n let changed = false;\n if (pin) {\n if (!pinned.includes(seq)) {\n changed = true;\n if (pinned.length == Const.MAX_PINNED_COUNT) {\n pinned.shift();\n }\n pinned.push(seq);\n }\n } else {\n if (pinned.includes(seq)) {\n changed = true;\n pinned = pinned.filter(id => id != seq);\n if (pinned.length == 0) {\n pinned = Const.DEL_CHAR;\n }\n }\n }\n if (changed) {\n return this.setMeta({\n aux: {\n pins: pinned\n }\n });\n }\n return Promise.resolve();\n }\n /**\n * Delete messages. Hard-deleting messages requires Owner permission.\n * Wrapper for {@link Tinode#delMessages}.\n * @memberof Tinode.Topic#\n *\n * @param {Array.recv, read.\n * @param {number} seq - ID or the message read or received.\n */\n note(what, seq) {\n if (!this._attached) {\n // Cannot sending {note} on an inactive topic\".\n return;\n }\n\n // Update local cache with the new count.\n const user = this._users[this._tinode.getCurrentUserID()];\n let update = false;\n if (user) {\n // Self-subscription is found.\n if (!user[what] || user[what] < seq) {\n user[what] = seq;\n update = true;\n }\n } else {\n // Self-subscription is not found.\n update = (this[what] | 0) < seq;\n }\n\n if (update) {\n // Send notification to the server.\n this._tinode.note(this.name, what, seq);\n // Update locally cached contact with the new count.\n this._updateReadRecv(what, seq);\n\n if (this.acs != null && !this.acs.isMuted()) {\n const me = this._tinode.getMeTopic();\n // Sent a notification to 'me' listeners.\n me._refreshContact(what, this);\n }\n }\n }\n\n /**\n * Send a 'recv' receipt. Wrapper for {@link Tinode#noteRecv}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge.\n */\n noteRecv(seq) {\n this.note('recv', seq);\n }\n /**\n * Send a 'read' receipt. Wrapper for {@link Tinode#noteRead}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge or 0/undefined to acknowledge the latest messages.\n */\n noteRead(seq) {\n seq = seq || this._maxSeq;\n if (seq > 0) {\n this.note('read', seq);\n }\n }\n /**\n * Send a key-press notification. Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n */\n noteKeyPress() {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name);\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n /**\n * Send a notification than a video or audio message is . Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n * @param audioOnly - true if the recording is audio-only, false if it's a video recording.\n */\n noteRecording(audioOnly) {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name, audioOnly ? 'kpa' : 'kpv');\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n\n /**\n * Send a {note what='call'}. Wrapper for {@link Tinode#videoCall}.\n * @memberof Tinode#\n *\n * @param {string} evt - Call event.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(evt, seq, payload) {\n if (!this._attached && !['ringing', 'hang-up'].includes(evt)) {\n // Cannot {call} on an inactive topic\".\n return;\n }\n return this._tinode.videoCall(this.name, seq, evt, payload);\n }\n\n // Update cached read/recv/unread counts.\n _updateReadRecv(what, seq, ts) {\n let oldVal, doUpdate = false;\n\n seq = seq | 0;\n this.seq = this.seq | 0;\n this.read = this.read | 0;\n this.recv = this.recv | 0;\n switch (what) {\n case 'recv':\n oldVal = this.recv;\n this.recv = Math.max(this.recv, seq);\n doUpdate = (oldVal != this.recv);\n break;\n case 'read':\n oldVal = this.read;\n this.read = Math.max(this.read, seq);\n doUpdate = (oldVal != this.read);\n break;\n case 'msg':\n oldVal = this.seq;\n this.seq = Math.max(this.seq, seq);\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = (oldVal != this.seq);\n break;\n }\n\n // Sanity checks.\n if (this.recv < this.read) {\n this.recv = this.read;\n doUpdate = true;\n }\n if (this.seq < this.recv) {\n this.seq = this.recv;\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = true;\n }\n this.unread = this.seq - this.read;\n return doUpdate;\n }\n /**\n * Get user description from global cache. The user does not need to be a\n * subscriber of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - ID of the user to fetch.\n * @return {Object} user description or undefined.\n */\n userDesc(uid) {\n // TODO: handle asynchronous requests\n const user = this._cacheGetUser(uid);\n if (user) {\n return user; // Promise.resolve(user)\n }\n }\n /**\n * Get description of the p2p peer from subscription cache.\n * @memberof Tinode.Topic#\n *\n * @return {Object} peer's description or undefined.\n */\n p2pPeerDesc() {\n if (!this.isP2PType()) {\n return undefined;\n }\n return this._users[this.name];\n }\n /**\n * Iterate over cached subscribers. If callback is undefined, use this.onMetaSub.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive subscribers one by one.\n * @param {Object=} context - Value of `this` inside the `callback`.\n */\n subscribers(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._users) {\n cb.call(context, this._users[idx], idx, this._users);\n }\n }\n }\n /**\n * Get a copy of cached tags.\n * @memberof Tinode.Topic#\n *\n * @return {Array.key or undefined.\n */\n aux(key) {\n return this._aux[key];\n }\n /**\n * Get cached subscription for the given user ID.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - id of the user to query for\n * @return user description or undefined.\n */\n subscriber(uid) {\n return this._users[uid];\n }\n /**\n * Iterate over versions of a message: call callback for each version (excluding original).\n * If callback is undefined, does nothing.\n * @memberof Tinode.Topic#\n *\n * @param {number} origSeq - seq ID of the original message.\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messageVersions(origSeq, callback, context) {\n if (!callback) {\n // No callback? We are done then.\n return;\n }\n const versions = this._messageVersions[origSeq];\n if (!versions) {\n return;\n }\n versions.forEach(callback, undefined, undefined, context);\n }\n /**\n * Iterate over cached messages: call callback for each message in the range [sinceIdx, beforeIdx).\n * If callback is undefined, use this.onData.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {number} sinceId - Optional seqId to start iterating from (inclusive).\n * @param {number} beforeId - Optional seqId to stop iterating before it is reached (exclusive).\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messages(callback, sinceId, beforeId, context) {\n const cb = (callback || this.onData);\n if (cb) {\n const startIdx = typeof sinceId == 'number' ? this._messages.find({\n seq: sinceId\n }, true) : undefined;\n const beforeIdx = typeof beforeId == 'number' ? this._messages.find({\n seq: beforeId\n }, true) : undefined;\n if (startIdx != -1 && beforeIdx != -1) {\n // Step 1. Filter out all replacement messages and\n // save displayable messages in a temporary buffer.\n let msgs = [];\n this._messages.forEach((msg, unused1, unused2, i) => {\n if (Topic.#isReplacementMsg(msg)) {\n // Skip replacements.\n return;\n }\n if (msg._deleted) {\n // Skip deleted ranges.\n return;\n }\n // In case the massage was edited, replace timestamp of the version with the original's timestamp.\n const latest = this.latestMsgVersion(msg.seq) || msg;\n if (!latest._origTs) {\n latest._origTs = latest.ts;\n latest._origSeq = latest.seq;\n latest.ts = msg.ts;\n latest.seq = msg.seq;\n }\n msgs.push({\n data: latest,\n idx: i\n });\n }, startIdx, beforeIdx, {});\n // Step 2. Loop over displayble messages invoking cb on each of them.\n msgs.forEach((val, i) => {\n cb.call(context, val.data,\n (i > 0 ? msgs[i - 1].data : undefined),\n (i < msgs.length - 1 ? msgs[i + 1].data : undefined), val.idx);\n });\n }\n }\n }\n /**\n * Get the message from cache by literal seq (does not resolve message edits).\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message seqId to search for.\n * @returns {Object} the message with the given seq or undefined, if no such message is found.\n */\n findMessage(seq) {\n const idx = this._messages.find({\n seq: seq\n });\n if (idx >= 0) {\n return this._messages.getAt(idx);\n }\n return undefined;\n }\n /**\n * Get the most recent message from cache. This method counts all messages, including deleted ranges.\n * @memberof Tinode.Topic#\n *\n * @returns {Object} the most recent cached message or undefined, if no messages are cached.\n */\n latestMessage() {\n return this._messages.getLast();\n }\n /**\n * Get the latest version for message.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - original seq ID of the message.\n * @returns {Object} the latest version of the message or null if message not found.\n */\n latestMsgVersion(seq) {\n const versions = this._messageVersions[seq];\n return versions ? versions.getLast() : null;\n }\n /**\n * Get the maximum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest seq ID in cache.\n */\n maxMsgSeq() {\n return this._maxSeq;\n }\n /**\n * Get the minimum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the smallest seq ID in cache or 0.\n */\n minMsgSeq() {\n return this._minSeq;\n }\n /**\n * Get the maximum deletion ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest deletion ID.\n */\n maxClearId() {\n return this._maxDel;\n }\n /**\n * Get the number of messages in the cache.\n * @memberof Tinode.Topic#\n *\n * @returns {number} count of cached messages.\n */\n messageCount() {\n return this._messages.length();\n }\n /**\n * Iterate over cached unsent messages. Wraps {@link Tinode.Topic#messages}.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of this inside the callback.\n */\n queuedMessages(callback, context) {\n if (!callback) {\n throw new Error(\"Callback must be provided\");\n }\n this.messages(callback, Const.LOCAL_SEQID, undefined, context);\n }\n /**\n * Get the number of topic subscribers who marked this message as either recv or read\n * Current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {string} what - what action to consider: received \"recv\" or read \"read\".\n * @param {number} seq - ID or the message read or received.\n *\n * @returns {number} the number of subscribers who marked the message with the given ID as read or received.\n */\n msgReceiptCount(what, seq) {\n let count = 0;\n if (seq > 0) {\n const me = this._tinode.getCurrentUserID();\n for (let idx in this._users) {\n const user = this._users[idx];\n if (user.user !== me && user[what] >= seq) {\n count++;\n }\n }\n }\n return count;\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as read.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message id to check.\n * @returns {number} number of subscribers who claim to have received the message.\n */\n msgReadCount(seq) {\n return this.msgReceiptCount('read', seq);\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as received.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - Message id to check.\n * @returns {number} Number of subscribers who claim to have received the message.\n */\n msgRecvCount(seq) {\n return this.msgReceiptCount('recv', seq);\n }\n /**\n * Check if cached message IDs indicate that the server may have more messages.\n * @memberof Tinode.Topic#\n *\n * @param {number} min - smallest seq ID loaded range.\n * @param {number} max - greatest seq ID in loaded range.\n * @param {boolean} newer - if true, check for newer messages only.\n * @returns {Array.true if message was cancelled, false otherwise.\n */\n cancelSend(seqId) {\n const idx = this._messages.find({\n seq: seqId\n });\n if (idx >= 0) {\n const msg = this._messages.getAt(idx);\n const status = this.msgStatus(msg);\n if (status == Const.MESSAGE_STATUS_QUEUED ||\n status == Const.MESSAGE_STATUS_FAILED ||\n status == Const.MESSAGE_STATUS_FATAL) {\n this._tinode._db.remMessages(this.name, seqId);\n msg._cancelled = true;\n this._messages.delAt(idx);\n if (this.onData) {\n // Calling with no parameters to indicate the message was deleted.\n this.onData();\n }\n return true;\n }\n }\n return false;\n }\n /**\n * Get type of the topic: me, p2p, grp, fnd...\n * @memberof Tinode.Topic#\n *\n * @returns {string} One of 'me', 'p2p', 'grp', 'fnd', 'sys' or undefined.\n */\n getType() {\n return Topic.topicType(this.name);\n }\n /**\n * Get current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.AccessMode} - user's access mode\n */\n getAccessMode() {\n return this.acs;\n }\n /**\n * Set current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @param {AccessMode | Object} acs - access mode to set.\n */\n setAccessMode(acs) {\n return this.acs = new AccessMode(acs);\n }\n /**\n * Get topic's default access mode.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.DefAcs} - access mode, such as {auth: `RWP`, anon: `N`}.\n */\n getDefaultAccess() {\n return this.defacs;\n }\n /**\n * Initialize new meta {@link Tinode.GetQuery} builder. The query is attched to the current topic.\n * It will not work correctly if used with a different topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.MetaGetBuilder} query attached to the current topic.\n */\n startMetaQuery() {\n return new MetaGetBuilder(this);\n }\n /**\n * Check if topic is archived, i.e. private.arch == true.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is archived, false otherwise.\n */\n isArchived() {\n return this.private && !!this.private.arch;\n }\n /**\n * Check if topic is a 'me' topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a 'me' topic, false otherwise.\n */\n isMeType() {\n return Topic.isMeTopicName(this.name);\n }\n /**\n * Check if topic is a channel.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a channel, false otherwise.\n */\n isChannelType() {\n return Topic.isChannelTopicName(this.name);\n }\n /**\n * Check if topic is a group topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a group, false otherwise.\n */\n isGroupType() {\n return Topic.isGroupTopicName(this.name);\n }\n /**\n * Check if topic is a p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p topic, false otherwise.\n */\n isP2PType() {\n return Topic.isP2PTopicName(this.name);\n }\n /**\n * Check if topic is a communication topic, i.e. a group or p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p or group topic, false otherwise.\n */\n isCommType() {\n return Topic.isCommTopicName(this.name);\n }\n /**\n * Get status (queued, sent, received etc) of a given message in the context\n * of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {Message} msg - message to check for status.\n * @param {boolean} upd - update chached message status.\n *\n * @returns message status constant.\n */\n msgStatus(msg, upd) {\n let status = Const.MESSAGE_STATUS_NONE;\n if (this._tinode.isMe(msg.from)) {\n if (msg._sending) {\n status = Const.MESSAGE_STATUS_SENDING;\n } else if (msg._fatal || msg._cancelled) {\n status = Const.MESSAGE_STATUS_FATAL;\n } else if (msg._failed) {\n status = Const.MESSAGE_STATUS_FAILED;\n } else if (msg.seq >= Const.LOCAL_SEQID) {\n status = Const.MESSAGE_STATUS_QUEUED;\n } else if (this.msgReadCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_READ;\n } else if (this.msgRecvCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_RECEIVED;\n } else if (msg.seq > 0) {\n status = Const.MESSAGE_STATUS_SENT;\n }\n } else {\n status = Const.MESSAGE_STATUS_TO_ME;\n }\n\n if (upd && msg._status != status) {\n msg._status = status;\n this._tinode._db.updMessageStatus(this.name, msg.seq, status);\n }\n\n return status;\n }\n\n // If msg is a replacement for another message, save the msg in the message versions cache\n // as a newer version for the message it's supposed to replace.\n _maybeUpdateMessageVersionsCache(msg) {\n if (!Topic.#isReplacementMsg(msg)) {\n // Check if this message is the original in the chain of edits and if so\n // ensure all version have the same sender.\n if (this._messageVersions[msg.seq]) {\n // Remove versions with different 'from'.\n this._messageVersions[msg.seq].filter(version => version.from == msg.from);\n if (this._messageVersions[msg.seq].isEmpty()) {\n delete this._messageVersions[msg.seq];\n }\n }\n return;\n }\n\n const targetSeq = parseInt(msg.head.replace.split(':')[1]);\n if (targetSeq > msg.seq) {\n // Substitutes are supposed to have higher seq ids.\n return;\n }\n const targetMsg = this.findMessage(targetSeq);\n if (targetMsg && targetMsg.from != msg.from) {\n // Substitute cannot change the sender.\n return;\n }\n const versions = this._messageVersions[targetSeq] || new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n versions.put(msg);\n this._messageVersions[targetSeq] = versions;\n }\n\n // Process data message\n _routeData(data) {\n if (data.content) {\n if (!this.touched || this.touched < data.ts) {\n this.touched = data.ts;\n this._tinode._db.updTopic(this);\n }\n }\n\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n this.msgStatus(data, true);\n // Ackn receiving the message.\n clearTimeout(this._recvNotificationTimer);\n this._recvNotificationTimer = setTimeout(_ => {\n this._recvNotificationTimer = null;\n this.noteRecv(this._maxSeq);\n }, Const.RECV_TIMEOUT);\n }\n\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n\n const outgoing = ((!this.isChannelType() && !data.from) || this._tinode.isMe(data.from));\n\n if (data.head && data.head.webrtc && data.head.mime == Drafty.getContentType() && data.content) {\n // Rewrite VC body with info from the headers.\n data.content = Drafty.updateVideoCall(data.content, {\n state: data.head.webrtc,\n duration: data.head['webrtc-duration'],\n incoming: !outgoing,\n });\n }\n\n if (!data._noForwarding) {\n this._messages.put(data);\n this._tinode._db.addMessage(data);\n this._maybeUpdateMessageVersionsCache(data);\n }\n\n if (this.onData) {\n this.onData(data);\n }\n\n // Update locally cached contact with the new message count.\n const what = outgoing ? 'read' : 'msg';\n this._updateReadRecv(what, data.seq, data.ts);\n // Notify 'me' listeners of the change.\n this._tinode.getMeTopic()._refreshContact(what, this);\n }\n\n // Process metadata message\n _routeMeta(meta) {\n if (meta.desc) {\n this._processMetaDesc(meta.desc);\n }\n if (meta.sub && meta.sub.length > 0) {\n this._processMetaSub(meta.sub);\n }\n if (meta.del) {\n this._processDelMessages(meta.del.clear, meta.del.delseq);\n }\n if (meta.tags) {\n this._processMetaTags(meta.tags);\n }\n if (meta.cred) {\n this._processMetaCreds(meta.cred);\n }\n if (meta.aux) {\n this._processMetaAux(meta.aux);\n }\n if (this.onMeta) {\n this.onMeta(meta);\n }\n }\n // Process presence change message\n _routePres(pres) {\n let user, uid;\n switch (pres.what) {\n case 'del':\n // Delete cached messages.\n this._processDelMessages(pres.clear, pres.delseq);\n break;\n case 'on':\n case 'off':\n // Update online status of a subscription.\n user = this._users[pres.src];\n if (user) {\n user.online = pres.what == 'on';\n } else {\n this._tinode.logger(\"WARNING: Presence update for an unknown user\", this.name, pres.src);\n }\n break;\n case 'term':\n // Attachment to topic is terminated probably due to cluster rehashing.\n this._resetSub();\n break;\n case 'upd':\n // A topic subscriber has updated his description.\n // Issue {get sub} only if the current user has no p2p topics with the updated user (p2p name is not in cache).\n // Otherwise 'me' will issue a {get desc} request.\n if (pres.src && !this._tinode.isTopicCached(pres.src)) {\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n }\n break;\n case 'aux':\n // Auxiliary data updated.\n this.getMeta(this.startMetaQuery().withAux().build());\n break;\n case 'acs':\n uid = pres.src || this._tinode.getCurrentUserID();\n user = this._users[uid];\n if (!user) {\n // Update for an unknown user: notification of a new subscription.\n const acs = new AccessMode().updateAll(pres.dacs);\n if (acs && acs.mode != AccessMode._NONE) {\n user = this._cacheGetUser(uid);\n if (!user) {\n user = {\n user: uid,\n acs: acs\n };\n this.getMeta(this.startMetaQuery().withOneSub(undefined, uid).build());\n } else {\n user.acs = acs;\n }\n user.updated = new Date();\n this._processMetaSub([user]);\n }\n } else {\n // Known user\n user.acs.updateAll(pres.dacs);\n // Update user's access mode.\n this._processMetaSub([{\n user: uid,\n updated: new Date(),\n acs: user.acs\n }]);\n }\n break;\n default:\n this._tinode.logger(\"INFO: Ignored presence update\", pres.what);\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n // Process {info} message\n _routeInfo(info) {\n switch (info.what) {\n case 'recv':\n case 'read':\n const user = this._users[info.from];\n if (user) {\n user[info.what] = info.seq;\n if (user.recv < user.read) {\n user.recv = user.read;\n }\n }\n const msg = this.latestMessage();\n if (msg) {\n this.msgStatus(msg, true);\n }\n\n // If this is an update from the current user, update the cache with the new count.\n if (this._tinode.isMe(info.from)) {\n this._updateReadRecv(info.what, info.seq);\n }\n\n // Notify 'me' listener of the status change.\n this._tinode.getMeTopic()._refreshContact(info.what, this);\n break;\n case 'kp':\n // Do nothing.\n break;\n case 'call':\n // Do nothing here.\n break;\n default:\n this._tinode.logger(\"INFO: Ignored info update\", info.what);\n }\n\n if (this.onInfo) {\n this.onInfo(info);\n }\n }\n // Called by Tinode when meta.desc packet is received.\n // Called by 'me' topic on contact update (desc._noForwarding is true).\n _processMetaDesc(desc) {\n if (this.isP2PType()) {\n // Synthetic desc may include defacs for p2p topics which is useless.\n // Remove it.\n delete desc.defacs;\n\n // Update to p2p desc is the same as user update. Update cached user.\n this._tinode._db.updUser(this.name, desc.public);\n }\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n // Update persistent cache.\n this._tinode._db.updTopic(this);\n\n // Notify 'me' listener, if available:\n if (this.name !== Const.TOPIC_ME && !desc._noForwarding) {\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n // Called by Tinode when meta.sub is recived or in response to received\n // {ctrl} after setMeta-sub.\n _processMetaSub(subs) {\n for (let idx in subs) {\n const sub = subs[idx];\n\n // Fill defaults.\n sub.online = !!sub.online;\n // Update timestamp of the most recent subscription update.\n this._lastSubsUpdate = new Date(Math.max(this._lastSubsUpdate, sub.updated));\n\n let user = null;\n if (!sub.deleted) {\n // If this is a change to user's own permissions, update them in topic too.\n // Desc will update 'me' topic.\n if (this._tinode.isMe(sub.user) && sub.acs) {\n this._processMetaDesc({\n updated: sub.updated,\n touched: sub.touched,\n acs: sub.acs\n });\n }\n user = this._updateCachedUser(sub.user, sub);\n } else {\n // Subscription is deleted, remove it from topic (but leave in Users cache)\n delete this._users[sub.user];\n user = sub;\n }\n\n if (this.onMetaSub) {\n this.onMetaSub(user);\n }\n }\n\n if (this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._users));\n }\n }\n // Called by Tinode when meta.tags is recived.\n _processMetaTags(tags) {\n if (tags == Const.DEL_CHAR || (tags.length == 1 && tags[0] == Const.DEL_CHAR)) {\n tags = [];\n }\n this._tags = tags;\n this._tinode._db.updTopic(this);\n if (this.onTagsUpdated) {\n this.onTagsUpdated(tags);\n }\n }\n // Do nothing for topics other than 'me'\n _processMetaCreds(creds) {}\n\n // Called by Tinode when meta.aux is recived.\n _processMetaAux(aux) {\n aux = (!aux || aux == Const.DEL_CHAR) ? {} : aux;\n this._aux = mergeObj(this._aux, aux);\n this._tinode._db.updTopic(this);\n if (this.onAuxUpdated) {\n this.onAuxUpdated(this._aux);\n }\n }\n\n // Delete cached messages and update cached transaction IDs\n _processDelMessages(clear, delseq) {\n this._maxDel = Math.max(clear, this._maxDel);\n this.clear = Math.max(clear, this.clear);\n let count = 0;\n if (Array.isArray(delseq)) {\n delseq.forEach(range => {\n if (!range.hi) {\n count++;\n this.flushMessage(range.low);\n } else {\n count += range.hi - range.low;\n this.flushMessageRange(range.low, range.hi);\n }\n });\n\n this._tinode._db.addDelLog(this.name, clear, delseq);\n }\n\n if (count > 0) {\n if (this.onData) {\n this.onData();\n }\n }\n }\n // Topic is informed that the entire response to {get what=data} has been received.\n _allMessagesReceived(count) {\n\n if (this.onAllMessagesReceived) {\n this.onAllMessagesReceived(count);\n }\n }\n // Reset subscribed state\n _resetSub() {\n this._attached = false;\n }\n // This topic is either deleted or unsubscribed from.\n _gone() {\n this._messages.reset();\n this._tinode._db.remMessages(this.name);\n this._users = {};\n this.acs = new AccessMode(null);\n this.private = null;\n this.public = null;\n this.trusted = null;\n this._maxSeq = 0;\n this._minSeq = 0;\n this._attached = false;\n\n const me = this._tinode.getMeTopic();\n if (me) {\n me._routePres({\n _noForwarding: true,\n what: 'gone',\n topic: Const.TOPIC_ME,\n src: this.name\n });\n }\n if (this.onDeleteTopic) {\n this.onDeleteTopic();\n }\n }\n // Update global user cache and local subscribers cache.\n // Don't call this method for non-subscribers.\n _updateCachedUser(uid, obj) {\n // Fetch user object from the global cache.\n // This is a clone of the stored object\n let cached = this._cacheGetUser(uid);\n cached = mergeObj(cached || {}, obj);\n // Save to global cache\n this._cachePutUser(uid, cached);\n // Save to the list of topic subsribers.\n return mergeToCache(this._users, uid, cached);\n }\n // Get local seqId for a queued message.\n _getQueuedSeqId() {\n return this._queuedSeqId++;\n }\n\n // Load most recent messages from persistent cache.\n _loadMessages(db, query) {\n query = query || {};\n query.limit = query.limit || Const.DEFAULT_MESSAGES_PAGE;\n\n // Count of message loaded from DB.\n let count = 0;\n return db.readMessages(this.name, query)\n .then(msgs => {\n msgs.forEach(data => {\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n }\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n this._messages.put(data);\n this._maybeUpdateMessageVersionsCache(data);\n });\n count = msgs.length;\n })\n .then(_ => db.readDelLog(this.name, query))\n .then(dellog => {\n return dellog.forEach(rec => {\n this._messages.put({\n seq: rec.low,\n low: rec.low,\n hi: rec.hi,\n _deleted: true\n });\n });\n })\n .then(_ => {\n // DEBUG\n return count;\n });\n }\n\n // Push or {pres}: message received.\n _updateReceived(seq, act) {\n this.touched = new Date();\n this.seq = seq | 0;\n // Check if message is sent by the current user. If so it's been read already.\n if (!act || this._tinode.isMe(act)) {\n this.read = this.read ? Math.max(this.read, this.seq) : this.seq;\n this.recv = this.recv ? Math.max(this.read, this.recv) : this.read;\n }\n this.unread = this.seq - (this.read | 0);\n this._tinode._db.updTopic(this);\n }\n}\n","/**\n * @file Definition of 'fnd' topic.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport * as Const from './config.js';\nimport Topic from './topic.js';\nimport {\n mergeToCache\n} from './utils.js';\n\n\n/**\n * Special case of {@link Tinode.Topic} for searching for contacts and group topics\n * @extends Tinode.Topic\n *\n */\nexport default class TopicFnd extends Topic {\n // List of users and topics uid or topic_name -> Contact object)\n _contacts = {};\n\n /**\n * Create TopicFnd.\n *\n * @param {TopicFnd.Callbacks} callbacks - Callbacks to receive various events.\n */\n constructor(callbacks) {\n super(Const.TOPIC_FND, callbacks);\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = Object.getOwnPropertyNames(this._contacts).length;\n // Reset contact list.\n this._contacts = {};\n for (let idx in subs) {\n let sub = subs[idx];\n const indexBy = sub.topic ? sub.topic : sub.user;\n\n sub = mergeToCache(this._contacts, indexBy, sub);\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(sub);\n }\n }\n\n if (updateCount > 0 && this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._contacts));\n }\n }\n\n /**\n * Publishing to TopicFnd is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicFnd#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'fnd' is not supported\"));\n }\n\n /**\n * setMeta to TopicFnd resets contact list in addition to sending the message.\n * @memberof Tinode.TopicFnd#\n * @param {Tinode.SetParams} params parameters to update.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n setMeta(params) {\n return Object.getPrototypeOf(TopicFnd.prototype).setMeta.call(this, params).then(_ => {\n if (Object.keys(this._contacts).length > 0) {\n this._contacts = {};\n if (this.onSubsUpdated) {\n this.onSubsUpdated([]);\n }\n }\n });\n }\n\n /**\n * Iterate over found contacts. If callback is undefined, use {@link this.onMetaSub}.\n * @function\n * @memberof Tinode.TopicFnd#\n * @param {TopicFnd.ContactCallback} callback - Callback to call for each contact.\n * @param {Object} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._contacts) {\n cb.call(context, this._contacts[idx], idx, this._contacts);\n }\n }\n }\n}\n","/**\n * @file Definition of 'me' topic.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport * as Const from './config.js';\nimport Topic from './topic.js';\nimport {\n mergeObj\n} from './utils.js';\n\n/**\n * @class TopicMe - special case of {@link Tinode.Topic} for\n * managing data of the current user, including contact list.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicMe.Callbacks} callbacks - Callbacks to receive various events.\n */\nexport default class TopicMe extends Topic {\n onContactUpdate;\n\n constructor(callbacks) {\n super(Const.TOPIC_ME, callbacks);\n\n // me-specific callbacks\n if (callbacks) {\n this.onContactUpdate = callbacks.onContactUpdate;\n }\n }\n\n // Override the original Topic._processMetaDesc.\n _processMetaDesc(desc) {\n // Check if online contacts need to be turned off because P permission was removed.\n const turnOff = (desc.acs && !desc.acs.isPresencer()) && (this.acs && this.acs.isPresencer());\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n this._tinode._db.updTopic(this);\n // Update current user's record in the global cache.\n this._updateCachedUser(this._tinode._myUID, desc);\n\n // 'P' permission was removed. All topics are offline now.\n if (turnOff) {\n this._tinode.mapTopics((cont) => {\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n this._refreshContact('off', cont);\n }\n });\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = 0;\n subs.forEach((sub) => {\n const topicName = sub.topic;\n // Don't show 'me' and 'fnd' topics in the list of contacts.\n if (topicName == Const.TOPIC_FND || topicName == Const.TOPIC_ME) {\n return;\n }\n sub.online = !!sub.online;\n\n let cont = null;\n if (sub.deleted) {\n cont = sub;\n this._tinode.cacheRemTopic(topicName);\n this._tinode._db.remTopic(topicName);\n } else {\n // Ensure the values are defined and are integers.\n if (typeof sub.seq != 'undefined') {\n sub.seq = sub.seq | 0;\n sub.recv = sub.recv | 0;\n sub.read = sub.read | 0;\n sub.unread = sub.seq - sub.read;\n }\n\n const topic = this._tinode.getTopic(topicName);\n if (topic._new) {\n delete topic._new;\n }\n\n cont = mergeObj(topic, sub);\n this._tinode._db.updTopic(cont);\n\n if (Topic.isP2PTopicName(topicName)) {\n this._cachePutUser(topicName, cont);\n this._tinode._db.updUser(topicName, cont.public);\n }\n // Notify topic of the update if it's an external update.\n if (!sub._noForwarding && topic) {\n sub._noForwarding = true;\n topic._processMetaDesc(sub);\n }\n }\n\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(cont);\n }\n });\n\n if (this.onSubsUpdated && updateCount > 0) {\n const keys = [];\n subs.forEach((s) => {\n keys.push(s.topic);\n });\n this.onSubsUpdated(keys, updateCount);\n }\n }\n\n // Called by Tinode when meta.sub is recived.\n _processMetaCreds(creds, upd) {\n if (creds.length == 1 && creds[0] == Const.DEL_CHAR) {\n creds = [];\n }\n if (upd) {\n creds.forEach((cr) => {\n if (cr.val) {\n // Adding a credential.\n let idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && el.val == cr.val;\n });\n if (idx < 0) {\n // Not found.\n if (!cr.done) {\n // Unconfirmed credential replaces previous unconfirmed credential of the same method.\n idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n // Remove previous unconfirmed credential.\n this._credentials.splice(idx, 1);\n }\n }\n this._credentials.push(cr);\n } else {\n // Found. Maybe change 'done' status.\n this._credentials[idx].done = cr.done;\n }\n } else if (cr.resp) {\n // Handle credential confirmation.\n const idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n this._credentials[idx].done = true;\n }\n }\n });\n } else {\n this._credentials = creds;\n }\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n }\n\n // Process presence change message\n _routePres(pres) {\n if (pres.what == 'term') {\n // The 'me' topic itself is detached. Mark as unsubscribed.\n this._resetSub();\n return;\n }\n\n if (pres.what == 'upd' && pres.src == Const.TOPIC_ME) {\n // Update to me's description. Request updated value.\n this.getMeta(this.startMetaQuery().withDesc().build());\n return;\n }\n\n const cont = this._tinode.cacheGetTopic(pres.src);\n if (cont) {\n switch (pres.what) {\n case 'on': // topic came online\n cont.online = true;\n break;\n case 'off': // topic went offline\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n }\n break;\n case 'msg': // new message received\n cont._updateReceived(pres.seq, pres.act);\n break;\n case 'upd': // desc updated\n // Request updated subscription.\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n break;\n case 'acs': // access mode changed\n if (cont.acs) {\n cont.acs.updateAll(pres.dacs);\n } else {\n cont.acs = new AccessMode().updateAll(pres.dacs);\n }\n cont.touched = new Date();\n break;\n case 'ua':\n // user agent changed.\n cont.seen = {\n when: new Date(),\n ua: pres.ua\n };\n break;\n case 'recv':\n // user's other session marked some messges as received.\n pres.seq = pres.seq | 0;\n cont.recv = cont.recv ? Math.max(cont.recv, pres.seq) : pres.seq;\n break;\n case 'read':\n // user's other session marked some messages as read.\n pres.seq = pres.seq | 0;\n cont.read = cont.read ? Math.max(cont.read, pres.seq) : pres.seq;\n cont.recv = cont.recv ? Math.max(cont.read, cont.recv) : cont.recv;\n cont.unread = cont.seq - cont.read;\n break;\n case 'gone':\n // topic deleted or unsubscribed from.\n if (!cont._deleted) {\n cont._deleted = true;\n cont._attached = false;\n this._tinode._db.markTopicAsDeleted(pres.src);\n } else {\n this._tinode._db.remTopic(pres.src);\n }\n break;\n case 'del':\n // Update topic.del value.\n break;\n default:\n this._tinode.logger(\"INFO: Unsupported presence update in 'me'\", pres.what);\n }\n\n this._refreshContact(pres.what, cont);\n } else {\n if (pres.what == 'acs') {\n // New subscriptions and deleted/banned subscriptions have full\n // access mode (no + or - in the dacs string). Changes to known subscriptions are sent as\n // deltas, but they should not happen here.\n const acs = new AccessMode(pres.dacs);\n if (!acs || acs.mode == AccessMode._INVALID) {\n this._tinode.logger(\"ERROR: Invalid access mode update\", pres.src, pres.dacs);\n return;\n } else if (acs.mode == AccessMode._NONE) {\n this._tinode.logger(\"WARNING: Removing non-existent subscription\", pres.src, pres.dacs);\n return;\n } else {\n // New subscription. Send request for the full description.\n // Using .withOneSub (not .withLaterOneSub) to make sure IfModifiedSince is not set.\n this.getMeta(this.startMetaQuery().withOneSub(undefined, pres.src).build());\n // Create a dummy entry to catch online status update.\n const dummy = this._tinode.getTopic(pres.src);\n dummy.topic = pres.src;\n dummy.online = false;\n dummy.acs = acs;\n this._tinode._db.updTopic(dummy);\n }\n } else if (pres.what == 'tags') {\n this.getMeta(this.startMetaQuery().withTags().build());\n }\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n\n // Contact is updated, execute callbacks.\n _refreshContact(what, cont) {\n if (this.onContactUpdate) {\n this.onContactUpdate(what, cont);\n }\n }\n\n /**\n * Publishing to TopicMe is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicMe#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'me' is not supported\"));\n }\n\n /**\n * Delete validation credential.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} topic - Name of the topic to delete\n * @param {string} user - User ID to remove.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete credential in inactive 'me' topic\"));\n }\n // Send {del} message, return promise\n return this._tinode.delCredential(method, value).then(ctrl => {\n // Remove deleted credential from the cache.\n const index = this._credentials.findIndex((el) => {\n return el.meth == method && el.val == value;\n });\n if (index > -1) {\n this._credentials.splice(index, 1);\n }\n // Notify listeners\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n return ctrl;\n });\n }\n\n /**\n * @callback contactFilter\n * @param {Object} contact to check for inclusion.\n * @returns {boolean} true if contact should be processed, false to exclude it.\n */\n /**\n * Iterate over cached contacts.\n *\n * @function\n * @memberof Tinode.TopicMe#\n * @param {TopicMe.ContactCallback} callback - Callback to call for each contact.\n * @param {contactFilter=} filter - Optionally filter contacts; include all if filter is false-ish, otherwise\n * include those for which filter returns true-ish.\n * @param {Object=} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, filter, context) {\n this._tinode.mapTopics((c, idx) => {\n if (c.isCommType() && (!filter || filter(c))) {\n callback.call(context, c, idx);\n }\n });\n }\n\n /**\n * Get a contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get, either a UID (for p2p topics) or a topic name.\n * @returns {Tinode.Contact} - Contact or `undefined`.\n */\n getContact(name) {\n return this._tinode.cacheGetTopic(name);\n }\n\n /**\n * Get access mode of a given contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get access mode for, either a UID (for p2p topics)\n * or a topic name; if missing, access mode for the 'me' topic itself.\n * @returns {string} - access mode, such as `RWP`.\n */\n getAccessMode(name) {\n if (name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont ? cont.acs : null;\n }\n return this.acs;\n }\n\n /**\n * Check if contact is archived, i.e. contact.private.arch == true.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to check archived status, either a UID (for p2p topics) or a topic name.\n * @returns {boolean} - true if contact is archived, false otherwise.\n */\n isArchived(name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont && cont.private && !!cont.private.arch;\n }\n\n /**\n * @typedef Tinode.Credential\n * @memberof Tinode\n * @type Object\n * @property {string} meth - validation method such as 'email' or 'tel'.\n * @property {string} val - credential value, i.e. 'jdoe@example.com' or '+17025551234'\n * @property {boolean} done - true if credential is validated.\n */\n /**\n * Get the user's credentials: email, phone, etc.\n * @memberof Tinode.TopicMe#\n *\n * @returns {Tinode.Credential[]} - array of credentials.\n */\n getCredentials() {\n return this._credentials;\n }\n}\n"],"names":["root","factory","exports","module","define","amd","this","MAX_PREVIEW_DATA_SIZE","JSON_MIME_TYPE","ALLOWED_ENT_FIELDS","INLINE_STYLES","name","start","end","FMT_WEIGHT","ENTITY_TYPES","dataName","pack","val","test","url","re","slice","FORMAT_TAGS","AU","html_tag","md_tag","undefined","isVoid","BN","BR","CO","DL","EM","EX","FM","HD","HL","HT","IM","LN","MN","RW","QQ","ST","VC","VD","base64toObjectUrl","b64","contentType","logger","bin","atob","length","buf","ArrayBuffer","arr","Uint8Array","i","charCodeAt","URL","createObjectURL","Blob","type","err","message","base64toDataUrl","DECORATORS","open","_","close","data","props","href","target","id","act","ref","mime","Drafty","src","duration","size","tmpPreviewUrl","_tempPreview","previewUrl","downloadUrl","width","height","title","alt","state","preview","premime","poster","preref","txt","fmt","ent","chunkify","line","spans","chunks","span","at","push","chunk","tp","chld","children","toSpanTree","tree","last","draftyToTree","doc","Array","isArray","text","len","key","attachments","forEach","includes","sort","a","b","diff","indexOf","spansToTree","treeTopDown","node","child","parent","addNode","n","substring","att","subspans","inner","tag","treeToDrafty","keymap","c","Object","keys","newKey","transformer","context","dst","call","treeBottomUp","formatter","index","stack","values","pop","shortenTree","limit","tail","lightEntity","allow","copyEntData","lTrim","trimStart","shift","attachmentsToEnd","concat","draftify","startAt","plain","ranges","drafty","light","entries","dc","init","plainText","parse","content","lines","split","entityMap","entityIndex","blx","entities","block","original","re_start","re_end","result","exec","start_offset","lastIndexOf","end_offset","spannify","match","extracted","entity","offset","unique","idx","filter","el","extractEntities","map","s","append","first","second","insertImage","imageDesc","ex","refurl","bits","filename","urlPromise","_processing","then","insertVideo","videoDesc","urls","insertAudio","audioDesc","videoCall","audioOnly","aonly","updateVideoCall","params","assign","quote","header","uid","body","appendLineBreak","mention","appendLink","linkData","appendImage","appendAudio","attachFile","attachmentDesc","wrapInto","style","wrapAsForm","insertButton","actionType","actionValue","refUrl","appendButton","attachJSON","UNSAFE_toHTML","join","format","shorten","forwardedContent","replyContent","startsWith","forwarding","toPlainText","isPlainText","toMarkdown","def","isValid","txt_type","hasAttachments","callback","count","hasEntities","styles","sanitizeEntities","getDownloadUrl","entData","isProcessing","getPreviewUrl","getEntitySize","getEntityMimeType","tagName","attrValue","getContentType","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","getter","__esModule","d","definition","o","defineProperty","enumerable","get","g","globalThis","Function","e","window","obj","prop","prototype","hasOwnProperty","r","Symbol","toStringTag","value","AccessMode","constructor","acs","given","decode","want","mode","static","side","flag","Error","str","_BITMASK","_NONE","bitmask","_JOIN","_READ","_WRITE","_PRES","_APPROVE","_SHARE","_DELETE","_OWNER","m0","bit","charAt","toUpperCase","_INVALID","res","upd","action","val0","parts","a1","a2","toString","encode","jsonHelper","setMode","m","updateMode","u","update","getMode","setGiven","updateGiven","getGiven","setWant","w","updateWant","getWant","getMissing","getExcessive","updateAll","isOwner","isPresencer","isMuted","isJoiner","isReader","isWriter","isApprover","isAdmin","isSharer","isDeleter","VERSION","LIBRARY","TOPIC_NEW","TOPIC_NEW_CHAN","TOPIC_ME","TOPIC_FND","TOPIC_GRP","LOCAL_SEQID","DEL_CHAR","CommError","code","super","jsonParseHelper","date","Date","isNaN","isUrlRelative","isValidDate","getTime","mergeObj","ignore","mergeToCache","cache","newval","simplify","getOwnPropertyNames","normalizeRanges","maxSeq","r1","r2","low","hi","reduce","out","listToRanges","list","prev","Math","max","WebSocketProvider","XHRProvider","NETWORK_ERROR_TEXT","NETWORK_USER","NETWORK_USER_TEXT","makeBaseUrl","host","protocol","version","apiKey","Connection","secure","autoreconnect","initialized","config","version_","autoreconnect_","transport","wsProvider","xhrProvider","l","connect","host_","force","Promise","reject","reconnect","disconnect","sendText","msg","isConnected","probe","backoffReset","clearTimeout","timeout","pow","random","onAutoreconnectIteration","setTimeout","prom","catch","_lpURL","_poller","_sender","lp_poller","url_","resolve","poller","promiseCompleted","onreadystatechange","evt","readyState","status","pkt","JSON","responseText","ctrl","sid","send","onOpen","onMessage","onDisconnect","abort","sender","lp_sender","OPEN","conn","onerror","onopen","onclose","onmessage","NETWORK_ERROR","DB_NAME","IDBProvider","DB","db","disabled","onError","source","trx","transaction","event","error","objectStore","getAll","onsuccess","topic","initDatabase","req","onupgradeneeded","createObjectStore","keyPath","createIndex","deleteDatabase","onblocked","isReady","updTopic","oncomplete","put","commit","markTopicAsDeleted","_deleted","remTopic","delete","IDBKeyRange","only","bound","Number","MAX_SAFE_INTEGER","mapTopics","deserializeTopic","updUser","pub","arguments","public","remUser","mapUsers","getUser","user","updSubscription","topicName","sub","mapSubscriptions","addMessage","add","updMessageStatus","seq","_status","remMessages","from","to","range","readMessages","query","msgs","since","before","openCursor","cursor","continue","addDelLog","delId","clear","readDelLog","maxDelId","f","tags","_tags","setAccessMode","read","unread","getAccessMode","idbProvider","IndexedDBProvider","LargeFileHelper","tinode","_tinode","_version","_apiKey","_authToken","getAuthToken","xhr","uploadWithBaseUrl","baseUrl","avatarFor","onProgress","onSuccess","onFailure","base","endsWith","instance","setRequestHeader","token","toResolve","toReject","upload","onprogress","lengthComputable","loaded","total","onload","response","statusText","onabort","form","FormData","set","getNextUniqueId","_secure","_host","download","relativeUrl","mimetype","relUrl","location","origin","searchParams","addURLParam","responseType","link","document","createElement","display","setAttribute","appendChild","click","removeChild","revokeObjectURL","reader","FileReader","readAsText","cancel","MetaGetBuilder","what","updated","isP2PType","_lastSubsUpdate","withData","withLaterData","_maxSeq","withDataRanges","withDataList","withEarlierData","_minSeq","withDesc","ims","withLaterDesc","withSub","userOrTopic","opts","getType","withOneSub","withLaterOneSub","withLaterSub","withTags","withCred","withAux","withDel","withLaterDel","_maxDel","extract","build","CBuffer","buffer","compare_","unique_","elem","exact","pivot","found","splice","getAt","getLast","insert","delAt","delRange","reset","startIdx","beforeIdx","min","find","nearest","isEmpty","Topic","callbacks","created","touched","private","trusted","_users","_queuedSeqId","Const","_noEarlierMsgs","_recvNotificationTimer","_credentials","_aux","_messageVersions","_messages","_attached","_new","_delayedLeaveTimer","onData","onMeta","onPres","onInfo","onMetaDesc","onMetaSub","onSubsUpdated","onTagsUpdated","onCredsUpdated","onAuxUpdated","onDeleteTopic","onAllMessagesReceived","topicType","isP2PTopicName","isGroupTopicName","head","replace","isSubscribed","subscribe","getParams","setParams","_cacheDelSelf","_cachePutSelf","ts","me","getMeTopic","desc","_noForwarding","_processMetaDesc","createMessage","noEcho","publish","publishMessage","_sending","_failed","swapMessageId","_maybeUpdateMessageVersionsCache","_routeData","publishDraft","_getQueuedSeqId","getCurrentUserID","noecho","_db","_cancelled","_fatal","leave","unsub","_resetSub","_gone","leaveDelayed","delay","getMeta","getMessagesPage","gaps","newer","startMetaQuery","_loadMessages","msgHasMoreMessages","getPinnedMessages","pins","aux","remains","setMeta","t","trim","toLowerCase","item","pos","ary","normalizeArray","_processMetaSub","_processMetaTags","cred","_processMetaCreds","_processMetaAux","subscriber","am","invite","archive","arch","pinMessage","pin","pinned","changed","delMessages","hard","tosend","del","flushMessageRange","flushMessage","delMessagesAll","hardDel","_all","delMessagesList","delMessagesEdits","messageVersions","delTopic","delSubscription","note","_updateReadRecv","_refreshContact","noteRecv","noteRead","noteKeyPress","noteRecording","payload","oldVal","doUpdate","recv","userDesc","_cacheGetUser","p2pPeerDesc","subscribers","cb","origSeq","versions","messages","sinceId","beforeId","unused1","unused2","latest","latestMsgVersion","_origTs","_origSeq","findMessage","latestMessage","maxMsgSeq","minMsgSeq","maxClearId","messageCount","queuedMessages","msgReceiptCount","msgReadCount","msgRecvCount","gap","p","expected","isNewMessage","seqId","fromId","untilId","newSeqId","numMessages","cancelSend","msgStatus","getDefaultAccess","defacs","isArchived","isMeType","isMeTopicName","isChannelType","isChannelTopicName","isGroupType","isCommType","isCommTopicName","isMe","targetSeq","parseInt","targetMsg","outgoing","webrtc","incoming","_routeMeta","meta","_processDelMessages","delseq","_routePres","pres","online","isTopicCached","dacs","_routeInfo","info","subs","deleted","_updateCachedUser","creds","_allMessagesReceived","cached","_cachePutUser","dellog","rec","_updateReceived","TopicFnd","_contacts","updateCount","indexBy","getPrototypeOf","contacts","TopicMe","onContactUpdate","turnOff","_myUID","cont","seen","when","cacheRemTopic","getTopic","cr","findIndex","meth","done","resp","cacheGetTopic","ua","dummy","delCredential","method","getContact","getCredentials","b64EncodeUnicode","btoa","encodeURIComponent","p1","String","fromCharCode","jsonBuildHelper","pad","sp","repeat","millis","getUTCMilliseconds","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","rfc3339DateString","jsonLoggerHelper","WebSocket","XMLHttpRequest","indexedDB","chars","global","output","charCode","bc","bs","setNetworkProviders","setNetworkProvider","DBCache","initForNonBrowserApp","Tinode","_appName","_browser","_platform","_hwos","_humanLanguage","_loggingEnabled","_trimLongStrings","_authenticated","_login","_inPacketCount","_messageId","floor","_serverInfo","_deviceToken","_pendingPromises","_expirePromises","_connection","_persist","_cache","onComplete","appName","platform","navigator","product","reactnative","priority","tmp","substr","tokens","m2","v","minor","getBrowserInfo","userAgent","language","detectTransport","promise","persist","all","dateString","_len","args","_key","console","log","onOK","errorText","stringify","onRawMessage","onNetworkProbe","onCtrlMessage","onMetaMessage","onDataMessage","onPresMessage","onInfoMessage","setInterval","expires","hello","clearInterval","func","_cacheDelUser","onLogin","isNewGroupTopicName","clearStorage","initStorage","networkProbe","isAuthenticated","authorizeURL","parsed","account","scheme","secret","login","acc","tmpscheme","tmpsecret","extra","createAccount","createAccountBasic","username","password","updateAccountBasic","onConnect","setDeviceToken","dt","sent","loginBasic","uname","loginToken","requestResetAuthSecret","now","setAuthToken","dft","oobNotification","xfrom","finally","modeGiven","modeWant","delCurrentUser","newGroupTopicName","isChan","getFndTopic","getLargeFileHelper","getCurrentLogin","getServerInfo","report","getServerParam","defaultValue","enableLogging","enabled","trimLongStrings","setHumanLanguage","hl","isTopicOnline","getTopicAccessMode","wantAkn","onWebsocketOpen","MESSAGE_STATUS_NONE","MESSAGE_STATUS_QUEUED","MESSAGE_STATUS_SENDING","MESSAGE_STATUS_FAILED","MESSAGE_STATUS_FATAL","MESSAGE_STATUS_SENT","MESSAGE_STATUS_RECEIVED","MESSAGE_STATUS_READ","MESSAGE_STATUS_TO_ME","MAX_MESSAGE_SIZE","MAX_SUBSCRIBER_COUNT","MAX_TAG_COUNT","MAX_FILE_UPLOAD_SIZE","REQ_CRED_VALIDATORS"],"sourceRoot":""}
\ No newline at end of file
+{"version":3,"file":"tinode.prod.js","mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAgB,OAAID,IAEpBD,EAAa,OAAIC,GAClB,CATD,CASGK,MAAM,I,kCCmDT,MAEMC,EAAwB,GACxBC,EAAiB,mBAEjBC,EAAqB,CAAC,MAAO,SAAU,WAAY,WAAY,OAAQ,OAAQ,UAAW,SAAU,UACxG,MAAO,OAAQ,QAAS,MAAO,MAAO,SAKlCC,EAAgB,CAEpB,CACEC,KAAM,KACNC,MAAO,wBACPC,IAAK,yBAGP,CACEF,KAAM,KACNC,MAAO,oBACPC,IAAK,qBAGP,CACEF,KAAM,KACNC,MAAO,uBACPC,IAAK,wBAGP,CACEF,KAAM,KACNC,MAAO,kBACPC,IAAK,oBAKHC,EAAa,CAAC,MAGdC,EAAe,CAEnB,CACEJ,KAAM,KACNK,SAAU,MACVC,KAAM,SAASC,GAKb,MAHK,gBAAgBC,KAAKD,KACxBA,EAAM,UAAYA,GAEb,CACLE,IAAKF,EAET,EACAG,GAAI,wFAGN,CACEV,KAAM,KACNK,SAAU,MACVC,KAA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I,EAAOkI,qBAAuB,oBAC9BlI,EAAOmI,oBAAsB,S","sources":["webpack://tinode/webpack/universalModuleDefinition","webpack://tinode/./src/drafty.js","webpack://tinode/webpack/bootstrap","webpack://tinode/webpack/runtime/compat get default export","webpack://tinode/webpack/runtime/define property getters","webpack://tinode/webpack/runtime/global","webpack://tinode/webpack/runtime/hasOwnProperty shorthand","webpack://tinode/webpack/runtime/make namespace object","webpack://tinode/./src/access-mode.js","webpack://tinode/./version.js","webpack://tinode/./src/config.js","webpack://tinode/./src/comm-error.js","webpack://tinode/./src/utils.js","webpack://tinode/./src/connection.js","webpack://tinode/./src/db.js","webpack://tinode/./src/large-file.js","webpack://tinode/./src/tinode.js","webpack://tinode/./src/meta-builder.js","webpack://tinode/./src/cbuffer.js","webpack://tinode/./src/topic.js","webpack://tinode/./src/fnd-topic.js","webpack://tinode/./src/me-topic.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"tinode\"] = factory();\n\telse\n\t\troot[\"tinode\"] = factory();\n})(this, () => {\nreturn ","/**\n * @copyright 2015-2022 Tinode LLC.\n * @summary Minimally rich text representation and formatting for Tinode.\n * @license Apache 2.0\n *\n * @file Basic parser and formatter for very simple text markup. Mostly targeted at\n * mobile use cases similar to Telegram, WhatsApp, and FB Messenger.\n *\n * \n *
\n * Also supports forms and buttons.\n *\n * Nested formatting is supported, e.g. *abc _def_* -> abc def\n * URLs, @mentions, and #hashtags are extracted and converted into links.\n * Forms and buttons can be added procedurally.\n * JSON data representation is inspired by Draft.js raw formatting.\n *\n *\n * @example\n * Text:\n * abc\n * this is *bold*, `code` and _italic_, ~strike~\n * combined *bold and _italic_*\n * an url: https://www.example.com/abc#fragment and another _www.tinode.co_\n * this is a @mention and a #hashtag in a string\n * second #hashtag\n *
\n *\n * Sample JSON representation of the text above:\n * {\n * \"txt\": \"this is bold, code and italic, strike combined bold and italic an url: https://www.example.com/abc#fragment \" +\n * \"and another www.tinode.co this is a @mention and a #hashtag in a string second #hashtag\",\n * \"fmt\": [\n * { \"at\":8, \"len\":4,\"tp\":\"ST\" },{ \"at\":14, \"len\":4, \"tp\":\"CO\" },{ \"at\":23, \"len\":6, \"tp\":\"EM\"},\n * { \"at\":31, \"len\":6, \"tp\":\"DL\" },{ \"tp\":\"BR\", \"len\":1, \"at\":37 },{ \"at\":56, \"len\":6, \"tp\":\"EM\" },\n * { \"at\":47, \"len\":15, \"tp\":\"ST\" },{ \"tp\":\"BR\", \"len\":1, \"at\":62 },{ \"at\":120, \"len\":13, \"tp\":\"EM\" },\n * { \"at\":71, \"len\":36, \"key\":0 },{ \"at\":120, \"len\":13, \"key\":1 },{ \"tp\":\"BR\", \"len\":1, \"at\":133 },\n * { \"at\":144, \"len\":8, \"key\":2 },{ \"at\":159, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":179 },\n * { \"at\":187, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":195 }\n * ],\n * \"ent\": [\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"https://www.example.com/abc#fragment\" } },\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"http://www.tinode.co\" } },\n * { \"tp\":\"MN\", \"data\":{ \"val\":\"mention\" } },\n * { \"tp\":\"HT\", \"data\":{ \"val\":\"hashtag\" } }\n * ]\n * }\n */\n\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nconst MAX_FORM_ELEMENTS = 8;\nconst MAX_PREVIEW_ATTACHMENTS = 3;\nconst MAX_PREVIEW_DATA_SIZE = 64;\nconst JSON_MIME_TYPE = 'application/json';\nconst DRAFTY_MIME_TYPE = 'text/x-drafty';\nconst ALLOWED_ENT_FIELDS = ['act', 'height', 'duration', 'incoming', 'mime', 'name', 'premime', 'preref', 'preview',\n 'ref', 'size', 'state', 'url', 'val', 'width'\n];\n\n// Regular expressions for parsing inline formats. Javascript does not support lookbehind,\n// so it's a bit messy.\nconst INLINE_STYLES = [\n // Strong = bold, *bold text*\n {\n name: 'ST',\n start: /(?:^|[\\W_])(\\*)[^\\s*]/,\n end: /[^\\s*](\\*)(?=$|[\\W_])/\n },\n // Emphesized = italic, _italic text_\n {\n name: 'EM',\n start: /(?:^|\\W)(_)[^\\s_]/,\n end: /[^\\s_](_)(?=$|\\W)/\n },\n // Deleted, ~strike this though~\n {\n name: 'DL',\n start: /(?:^|[\\W_])(~)[^\\s~]/,\n end: /[^\\s~](~)(?=$|[\\W_])/\n },\n // Code block `this is monospace`\n {\n name: 'CO',\n start: /(?:^|\\W)(`)[^`]/,\n end: /[^`](`)(?=$|\\W)/\n }\n];\n\n// Relative weights of formatting spans. Greater index in array means greater weight.\nconst FMT_WEIGHT = ['QQ'];\n\n// RegExps for entity extraction (RF = reference)\nconst ENTITY_TYPES = [\n // URLs\n {\n name: 'LN',\n dataName: 'url',\n pack: function(val) {\n // Check if the protocol is specified, if not use http\n if (!/^[a-z]+:\\/\\//i.test(val)) {\n val = 'http://' + val;\n }\n return {\n url: val\n };\n },\n re: /(?:(?:https?|ftp):\\/\\/|www\\.|ftp\\.)[-A-Z0-9+&@#\\/%=~_|$?!:,.]*[A-Z0-9+&@#\\/%=~_|$]/ig\n },\n // Mentions @user (must be 2 or more characters)\n {\n name: 'MN',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B@([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n },\n // Hashtags #hashtag, like metion 2 or more characters.\n {\n name: 'HT',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B#([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n }\n];\n\n// HTML tag name suggestions\nconst FORMAT_TAGS = {\n AU: {\n html_tag: 'audio',\n md_tag: undefined,\n isVoid: false\n },\n BN: {\n html_tag: 'button',\n md_tag: undefined,\n isVoid: false\n },\n BR: {\n html_tag: 'br',\n md_tag: '\\n',\n isVoid: true\n },\n CO: {\n html_tag: 'tt',\n md_tag: '`',\n isVoid: false\n },\n DL: {\n html_tag: 'del',\n md_tag: '~',\n isVoid: false\n },\n EM: {\n html_tag: 'i',\n md_tag: '_',\n isVoid: false\n },\n EX: {\n html_tag: '',\n md_tag: undefined,\n isVoid: true\n },\n FM: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n HD: {\n html_tag: '',\n md_tag: undefined,\n isVoid: false\n },\n HL: {\n html_tag: 'span',\n md_tag: undefined,\n isVoid: false\n },\n HT: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n IM: {\n html_tag: 'img',\n md_tag: undefined,\n isVoid: false\n },\n LN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n MN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n RW: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false,\n },\n QQ: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n ST: {\n html_tag: 'b',\n md_tag: '*',\n isVoid: false\n },\n VC: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n VD: {\n html_tag: 'video',\n md_tag: undefined,\n isVoid: false\n }\n};\n\n// Convert base64-encoded string into Blob.\nfunction base64toObjectUrl(b64, contentType, logger) {\n if (!b64) {\n return null;\n }\n\n try {\n const bin = atob(b64);\n const length = bin.length;\n const buf = new ArrayBuffer(length);\n const arr = new Uint8Array(buf);\n for (let i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n\n return URL.createObjectURL(new Blob([buf], {\n type: contentType\n }));\n } catch (err) {\n if (logger) {\n logger(\"Drafty: failed to convert object.\", err.message);\n }\n }\n\n return null;\n}\n\nfunction base64toDataUrl(b64, contentType) {\n if (!b64) {\n return null;\n }\n contentType = contentType || 'image/jpeg';\n return 'data:' + contentType + ';base64,' + b64;\n}\n\n// Helpers for converting Drafty to HTML.\nconst DECORATORS = {\n // Visial styles\n ST: {\n open: _ => '',\n close: _ => ''\n },\n EM: {\n open: _ => '',\n close: _ => ''\n },\n DL: {\n open: _ => '',\n close: _ => ''\n },\n CO: {\n open: _ => '',\n close: _ => ''\n },\n // Line break\n BR: {\n open: _ => '
',\n close: _ => ''\n },\n // Hidden element\n HD: {\n open: _ => '',\n close: _ => ''\n },\n // Highlighted element.\n HL: {\n open: _ => '',\n close: _ => ''\n },\n // Link (URL)\n LN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n href: data.url,\n target: '_blank'\n } : null;\n },\n },\n // Mention\n MN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Hashtag\n HT: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Button\n BN: {\n open: _ => '',\n props: (data) => {\n return data ? {\n 'data-act': data.act,\n 'data-val': data.val,\n 'data-name': data.name,\n 'data-ref': data.ref\n } : null;\n },\n },\n // Audio recording\n AU: {\n open: (data) => {\n const url = data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger);\n return '',\n props: (data) => {\n if (!data) return null;\n return {\n // Embedded data or external link.\n src: data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-duration': data.duration,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n // Image\n IM: {\n open: data => {\n // Don't use data.ref for preview: it's a security risk.\n const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime);\n const previewUrl = base64toObjectUrl(data.val, data.mime, Drafty.logger);\n const downloadUrl = data.ref || previewUrl;\n return (data.name ? '' : '') +\n '';\n },\n close: data => {\n return (data.name ? '' : '');\n },\n props: data => {\n if (!data) return null;\n return {\n // Temporary preview, or permanent preview, or external link.\n src: base64toDataUrl(data._tempPreview, data.mime) ||\n data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n title: data.name,\n alt: data.name,\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n },\n },\n // Form - structured layout of elements.\n FM: {\n open: _ => '
';\n },\n close: _ => '',\n props: data => {\n if (!data) return null;\n const poster = data.preref || base64toObjectUrl(data.preview, data.premime || 'image/jpeg', Drafty.logger);\n return {\n // Embedded data or external link.\n src: poster,\n 'data-src': data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-preview': poster,\n 'data-duration': data.duration | 0,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n};\n\n/**\n * The main object which performs all the formatting actions.\n * @class Drafty\n * @constructor\n */\nconst Drafty = function() {\n this.txt = '';\n this.fmt = [];\n this.ent = [];\n}\n\n/**\n * Initialize Drafty document to a plain text string.\n *\n * @param {string} plainText - string to use as Drafty content.\n *\n * @returns new Drafty document or null is plainText is not a string or undefined.\n */\nDrafty.init = function(plainText) {\n if (typeof plainText == 'undefined') {\n plainText = '';\n } else if (typeof plainText != 'string') {\n return null;\n }\n\n return {\n txt: plainText\n };\n}\n\n/**\n * Parse plain text into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} content - plain-text content to parse.\n * @return {Drafty} parsed document or null if the source is not plain text.\n */\nDrafty.parse = function(content) {\n // Make sure we are parsing strings only.\n if (typeof content != 'string') {\n return null;\n }\n\n // Split text into lines. It makes further processing easier.\n const lines = content.split(/\\r?\\n/);\n\n // Holds entities referenced from text\n const entityMap = [];\n const entityIndex = {};\n\n // Processing lines one by one, hold intermediate result in blx.\n const blx = [];\n lines.forEach((line) => {\n let spans = [];\n let entities;\n\n // Find formatted spans in the string.\n // Try to match each style.\n INLINE_STYLES.forEach((tag) => {\n // Each style could be matched multiple times.\n spans = spans.concat(spannify(line, tag.start, tag.end, tag.name));\n });\n\n let block;\n if (spans.length == 0) {\n block = {\n txt: line\n };\n } else {\n // Sort spans by style occurence early -> late, then by length: first long then short.\n spans.sort((a, b) => {\n const diff = a.at - b.at;\n return diff != 0 ? diff : b.end - a.end;\n });\n\n // Convert an array of possibly overlapping spans into a tree.\n spans = toSpanTree(spans);\n\n // Build a tree representation of the entire string, not\n // just the formatted parts.\n const chunks = chunkify(line, 0, line.length, spans);\n\n const drafty = draftify(chunks, 0);\n\n block = {\n txt: drafty.txt,\n fmt: drafty.fmt\n };\n }\n\n // Extract entities from the cleaned up string.\n entities = extractEntities(block.txt);\n if (entities.length > 0) {\n const ranges = [];\n for (let i in entities) {\n // {offset: match['index'], unique: match[0], len: match[0].length, data: ent.packer(), type: ent.name}\n const entity = entities[i];\n let index = entityIndex[entity.unique];\n if (!index) {\n index = entityMap.length;\n entityIndex[entity.unique] = index;\n entityMap.push({\n tp: entity.type,\n data: entity.data\n });\n }\n ranges.push({\n at: entity.offset,\n len: entity.len,\n key: index\n });\n }\n block.ent = ranges;\n }\n\n blx.push(block);\n });\n\n const result = {\n txt: ''\n };\n\n // Merge lines and save line breaks as BR inline formatting.\n if (blx.length > 0) {\n result.txt = blx[0].txt;\n result.fmt = (blx[0].fmt || []).concat(blx[0].ent || []);\n\n for (let i = 1; i < blx.length; i++) {\n const block = blx[i];\n const offset = result.txt.length + 1;\n\n result.fmt.push({\n tp: 'BR',\n len: 1,\n at: offset - 1\n });\n\n result.txt += ' ' + block.txt;\n if (block.fmt) {\n result.fmt = result.fmt.concat(block.fmt.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n if (block.ent) {\n result.fmt = result.fmt.concat(block.ent.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n }\n\n if (result.fmt.length == 0) {\n delete result.fmt;\n }\n\n if (entityMap.length > 0) {\n result.ent = entityMap;\n }\n }\n return result;\n}\n\n/**\n * Append one Drafty document to another.\n *\n * @param {Drafty} first - Drafty document to append to.\n * @param {Drafty|string} second - Drafty document or string being appended.\n *\n * @return {Drafty} first document with the second appended to it.\n */\nDrafty.append = function(first, second) {\n if (!first) {\n return second;\n }\n if (!second) {\n return first;\n }\n\n first.txt = first.txt || '';\n const len = first.txt.length;\n\n if (typeof second == 'string') {\n first.txt += second;\n } else if (second.txt) {\n first.txt += second.txt;\n }\n\n if (Array.isArray(second.fmt)) {\n first.fmt = first.fmt || [];\n if (Array.isArray(second.ent)) {\n first.ent = first.ent || [];\n }\n second.fmt.forEach(src => {\n const fmt = {\n at: (src.at | 0) + len,\n len: src.len | 0\n };\n // Special case for the outside of the normal rendering flow styles.\n if (src.at == -1) {\n fmt.at = -1;\n fmt.len = 0;\n }\n if (src.tp) {\n fmt.tp = src.tp;\n } else {\n fmt.key = first.ent.length;\n first.ent.push(second.ent[src.key || 0]);\n }\n first.fmt.push(fmt);\n });\n }\n\n return first;\n}\n\n/**\n * Description of an image to attach.\n * @typedef {Object} ImageDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the image, e.g. \"image/png\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded image content. Could be null/undefined.\n * @property {string} preview - base64-encoded thumbnail of the image.\n * @property {integer} width - width of the image.\n * @property {integer} height - height of the image.\n * @property {string} filename - file name suggestion for downloading the image.\n * @property {integer} size - size of the image in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded image preview used during upload process; not serializable.\n * @property {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {integer} at - index where the object is inserted. The length of the image is always 1.\n * @param {ImageDesc} imageDesc - object with image paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertImage = function(content, at, imageDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'IM',\n data: {\n mime: imageDesc.mime,\n ref: imageDesc.refurl,\n val: imageDesc.bits || imageDesc.preview,\n width: imageDesc.width,\n height: imageDesc.height,\n name: imageDesc.filename,\n size: imageDesc.size | 0,\n }\n };\n\n if (imageDesc.urlPromise) {\n ex.data._tempPreview = imageDesc._tempPreview;\n ex.data._processing = true;\n imageDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Description of a video to attach.\n * @typedef {Object} VideoDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the video, e.g. \"video/mpeg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - in-band base64-encoded image data. Could be null/undefined.\n * @property {string} preview - base64-encoded screencapture from the video. Could be null/undefined.\n * @property {string} preref - reference to screencapture from the video. Could be null/undefined.\n * @property {integer} width - width of the video.\n * @property {integer} height - height of the video.\n * @property {integer} duration - duration of the video.\n * @property {string} filename - file name suggestion for downloading the video.\n * @property {integer} size - size of the video in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded screencapture used during upload process; not serializable.\n * @property {Promise} urlPromise - array of two promises, which return URLs of video and preview uploads correspondingly\n * (either could be null).\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add video to.\n * @param {integer} at - index where the object is inserted. The length of the video is always 1.\n * @param {VideoDesc} videoDesc - object with video paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertVideo = function(content, at, videoDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'VD',\n data: {\n mime: videoDesc.mime,\n ref: videoDesc.refurl,\n val: videoDesc.bits,\n preref: videoDesc.preref,\n preview: videoDesc.preview,\n width: videoDesc.width,\n height: videoDesc.height,\n duration: videoDesc.duration | 0,\n name: videoDesc.filename,\n size: videoDesc.size | 0,\n }\n };\n\n if (videoDesc.urlPromise) {\n ex.data._tempPreview = videoDesc._tempPreview;\n ex.data._processing = true;\n videoDesc.urlPromise.then(\n urls => {\n ex.data.ref = urls[0];\n ex.data.preref = urls[1];\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Description of an audio recording to attach.\n * @typedef {Object} AudioDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the audio, e.g. \"audio/ogg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded audio content. Could be null/undefined.\n * @property {integer} duration - duration of the record in milliseconds.\n * @property {string} preview - base64 encoded short array of amplitude values 0..100.\n * @property {string} filename - file name suggestion for downloading the audio.\n * @property {integer} size - size of the recording in bytes. Treat is as an untrusted hint.\n * @property {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert audio recording into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add audio record to.\n * @param {integer} at - index where the object is inserted. The length of the record is always 1.\n * @param {AudioDesc} audioDesc - object with the audio paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertAudio = function(content, at, audioDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'AU',\n data: {\n mime: audioDesc.mime,\n val: audioDesc.bits,\n duration: audioDesc.duration | 0,\n preview: audioDesc.preview,\n name: audioDesc.filename,\n size: audioDesc.size | 0,\n ref: audioDesc.refurl\n }\n };\n\n if (audioDesc.urlPromise) {\n ex.data._processing = true;\n audioDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Create a (self-contained) video call Drafty document.\n * @memberof Drafty\n * @static\n * @param {boolean} audioOnly
true if the call is initially audio-only.\n * @returns Video Call drafty document.\n */\nDrafty.videoCall = function(audioOnly) {\n const content = {\n txt: ' ',\n fmt: [{\n at: 0,\n len: 1,\n key: 0\n }],\n ent: [{\n tp: 'VC',\n data: {\n aonly: audioOnly\n },\n }]\n };\n return content;\n}\n\n/**\n * Update video call (VC) entity with the new status and duration.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - VC document to update.\n * @param {object} params - new video call parameters.\n * @param {string} params.state - state of video call.\n * @param {number} params.duration - duration of the video call in milliseconds.\n *\n * @returns the same document with update applied.\n */\nDrafty.updateVideoCall = function(content, params) {\n // The video element could be just a format or a format + entity.\n // Must ensure it's the latter first.\n const fmt = ((content || {}).fmt || [])[0];\n if (!fmt) {\n // Unrecognized content.\n return content;\n }\n\n let ent;\n if (fmt.tp == 'VC') {\n // Just a format, convert to format + entity.\n delete fmt.tp;\n fmt.key = 0;\n ent = {\n tp: 'VC'\n };\n content.ent = [ent];\n } else {\n ent = (content.ent || [])[fmt.key | 0];\n if (!ent || ent.tp != 'VC') {\n // Not a VC entity.\n return content;\n }\n }\n ent.data = ent.data || {};\n Object.assign(ent.data, params);\n return content;\n}\n\n/**\n * Create a quote to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} header - Quote header (title, etc.).\n * @param {string} uid - UID of the author to mention.\n * @param {Drafty} body - Body of the quoted message.\n *\n * @returns Reply quote Drafty doc with the quote formatting.\n */\nDrafty.quote = function(header, uid, body) {\n const quote = Drafty.append(Drafty.appendLineBreak(Drafty.mention(header, uid)), body);\n\n // Wrap into a quote.\n quote.fmt.push({\n at: 0,\n len: quote.txt.length,\n tp: 'QQ'\n });\n\n return quote;\n}\n\n/**\n * Create a Drafty document with a mention.\n *\n * @param {string} name - mentioned name.\n * @param {string} uid - mentioned user ID.\n *\n * @returns {Drafty} document with the mention.\n */\nDrafty.mention = function(name, uid) {\n return {\n txt: name || '',\n fmt: [{\n at: 0,\n len: (name || '').length,\n key: 0\n }],\n ent: [{\n tp: 'MN',\n data: {\n val: uid\n }\n }]\n };\n}\n\n/**\n * Append a link to a Drafty document.\n *\n * @param {Drafty} content - Drafty document to append link to.\n * @param {Object} linkData - Link info in format {txt: 'ankor text', url: 'http://...'}.\n *\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLink = function(content, linkData) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: content.txt.length,\n len: linkData.txt.length,\n key: content.ent.length\n });\n content.txt += linkData.txt;\n\n const ex = {\n tp: 'LN',\n data: {\n url: linkData.url\n }\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Append image to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {ImageDesc} imageDesc - object with image paramenets.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendImage = function(content, imageDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertImage(content, content.txt.length - 1, imageDesc);\n}\n\n/**\n * Append audio recodring to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add recording to.\n * @param {AudioDesc} audioDesc - object with audio data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendAudio = function(content, audioDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertAudio(content, content.txt.length - 1, audioDesc);\n}\n\n/**\n * Description of a file to attach.\n * @typedef {Object} AttachmentDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the attachment, e.g. \"application/octet-stream\"\n * @property {string} data - base64-encoded in-band content of small attachments. Could be null/undefined.\n * @property {string} filename - file name suggestion for downloading the attachment.\n * @property {integer} size - size of the file in bytes. Treat is as an untrusted hint.\n * @property {string} refurl - reference to the out-of-band content. Could be null/undefined.\n * @property {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Attach file to Drafty content. Either as a blob or as a reference.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to attach file to.\n * @param {AttachmentDesc} object - containing attachment description and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.attachFile = function(content, attachmentDesc) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'EX',\n data: {\n mime: attachmentDesc.mime,\n val: attachmentDesc.data,\n name: attachmentDesc.filename,\n ref: attachmentDesc.refurl,\n size: attachmentDesc.size | 0\n }\n }\n if (attachmentDesc.urlPromise) {\n ex.data._processing = true;\n attachmentDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n /* catch the error, otherwise it will appear in the console. */\n ex.data._processing = undefined;\n }\n );\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Wraps drafty document into a simple formatting style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - document or string to wrap into a style.\n * @param {string} style - two-letter style to wrap into.\n * @param {number} at - index where the style starts, default 0.\n * @param {number} len - length of the form content, default all of it.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapInto = function(content, style, at, len) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at || 0,\n len: len || content.txt.length,\n tp: style,\n });\n\n return content;\n}\n\n/**\n * Wraps content into an interactive form.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - to wrap into a form.\n * @param {number} at - index where the forms starts.\n * @param {number} len - length of the form content.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapAsForm = function(content, at, len) {\n return Drafty.wrapInto(content, 'FM', at, len);\n}\n\n/**\n * Insert clickable button into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {number} at - location where the button is inserted.\n * @param {number} len - the length of the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertButton = function(content, at, len, name, actionType, actionValue, refUrl) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n\n if (!content || !content.txt || content.txt.length < at + len) {\n return null;\n }\n\n if (len <= 0 || ['url', 'pub'].indexOf(actionType) == -1) {\n return null;\n }\n // Ensure refUrl is a string.\n if (actionType == 'url' && !refUrl) {\n return null;\n }\n refUrl = '' + refUrl;\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: len,\n key: content.ent.length\n });\n content.ent.push({\n tp: 'BN',\n data: {\n act: actionType,\n val: actionValue,\n ref: refUrl,\n name: name\n }\n });\n\n return content;\n}\n\n/**\n * Append clickable button to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {string} title - the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendButton = function(content, title, name, actionType, actionValue, refUrl) {\n content = content || {\n txt: ''\n };\n const at = content.txt.length;\n content.txt += title;\n return Drafty.insertButton(content, at, title.length, name, actionType, actionValue, refUrl);\n}\n\n/**\n * Attach a generic JS object. The object is attached as a json string.\n * Intended for representing a form response.\n *\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to attach file to.\n * @param {Object} data - data to convert to json string and attach.\n * @returns {Drafty} the same document as content.\n */\nDrafty.attachJSON = function(content, data) {\n content = content || {\n txt: ''\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n content.ent.push({\n tp: 'EX',\n data: {\n mime: JSON_MIME_TYPE,\n val: data\n }\n });\n\n return content;\n}\n/**\n * Append line break to a Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to append linebreak to.\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLineBreak = function(content) {\n content = content || {\n txt: ''\n };\n content.fmt = content.fmt || [];\n content.fmt.push({\n at: content.txt.length,\n len: 1,\n tp: 'BR'\n });\n content.txt += ' ';\n\n return content;\n}\n/**\n * Given Drafty document, convert it to HTML.\n * No attempt is made to strip pre-existing html markup.\n * This is potentially unsafe because content.txt may contain malicious HTML\n * markup.\n * @memberof Tinode.Drafty\n * @static\n *\n * @param {Drafty} doc - document to convert.\n *\n * @returns {string} HTML-representation of content.\n */\nDrafty.UNSAFE_toHTML = function(doc) {\n const tree = draftyToTree(doc);\n const htmlFormatter = function(type, data, values) {\n const tag = DECORATORS[type];\n let result = values ? values.join('') : '';\n if (tag) {\n result = tag.open(data) + result + tag.close(data);\n }\n return result;\n };\n return treeBottomUp(tree, htmlFormatter, 0);\n}\n\n/**\n * Callback for applying custom formatting to a Drafty document.\n * Called once for each style span.\n * @memberof Drafty\n * @static\n *\n * @callback Formatter\n * @param {string} style - style code such as \"ST\" or \"IM\".\n * @param {Object} data - entity's data.\n * @param {Object} values - possibly styled subspans contained in this style span.\n * @param {number} index - index of the element guaranteed to be unique.\n */\n\n/**\n * Convert Drafty document to a representation suitable for display.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|Object} content - Drafty document to transform.\n * @param {Formatter} formatter - callback which formats individual elements.\n * @param {Object} context - context provided to formatter as this.\n *\n * @return {Object} transformed object\n */\nDrafty.format = function(original, formatter, context) {\n return treeBottomUp(draftyToTree(original), formatter, 0, [], context);\n}\n\n/**\n * Shorten Drafty document making the drafty text no longer than the limit.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characrets to shorten to.\n * @param {boolean} light - remove heavy data from entities.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.shorten = function(original, limit, light) {\n let tree = draftyToTree(original);\n tree = shortenTree(tree, limit, '…');\n if (tree && light) {\n tree = lightEntity(tree);\n }\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Transform Drafty doc for forwarding: strip leading @mention and any leading line breaks or whitespace.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.forwardedContent = function(original) {\n let tree = draftyToTree(original);\n const rmMention = function(node) {\n if (node.type == 'MN') {\n if (!node.parent || !node.parent.type) {\n return null;\n }\n }\n return node;\n }\n // Strip leading mention.\n tree = treeTopDown(tree, rmMention);\n // Remove leading whitespace.\n tree = lTrim(tree);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Prepare Drafty doc for wrapping into QQ as a reply:\n * - Replace forwarding mention with symbol '➦' and remove data (UID).\n * - Remove quoted text completely.\n * - Replace line breaks with spaces.\n * - Strip entities of heavy content.\n * - Move attachments to the end of the document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.replyContent = function(original, limit) {\n const convMNnQQnBR = function(node) {\n if (node.type == 'QQ') {\n return null;\n } else if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n delete node.data;\n }\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.type;\n delete node.children;\n }\n return node;\n }\n\n let tree = draftyToTree(original);\n if (!tree) {\n return original;\n }\n\n // Strip leading mention.\n tree = treeTopDown(tree, convMNnQQnBR);\n // Move attachments to the end of the doc.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n // Shorten the doc.\n tree = shortenTree(tree, limit, '…');\n // Strip heavy elements except IM.data['val'] and VD.data['preview'] (have to keep them to generate previews later).\n const filter = node => {\n switch (node.type) {\n case 'IM':\n return ['val'];\n case 'VD':\n return ['preview'];\n }\n return null;\n };\n tree = lightEntity(tree, filter);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n\n/**\n * Generate drafty preview:\n * - Shorten the document.\n * - Strip all heavy entity data leaving just inline styles and entity references.\n * - Replace line breaks with spaces.\n * - Replace content of QQ with a space.\n * - Replace forwarding mention with symbol '➦'.\n * move all attachments to the end of the document and make them visible.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @param {boolean} forwarding - this a forwarding message preview.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.preview = function(original, limit, forwarding) {\n let tree = draftyToTree(original);\n\n // Move attachments to the end.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n\n // Convert leading mention to '➦' and replace QQ and BR with a space ' '.\n const convMNnQQnBR = function(node) {\n if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n }\n } else if (node.type == 'QQ') {\n node.text = ' ';\n delete node.children;\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.children;\n delete node.type;\n }\n return node;\n }\n tree = treeTopDown(tree, convMNnQQnBR);\n\n tree = shortenTree(tree, limit, '…');\n if (forwarding) {\n // Keep some IM and VD data for preview.\n const filter = {\n IM: ['val'],\n VD: ['preview']\n };\n tree = lightEntity(tree, node => {\n return filter[node.type];\n });\n } else {\n tree = lightEntity(tree);\n }\n\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Given Drafty document, convert it to plain text.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text.\n * @returns {string} plain-text representation of the drafty document.\n */\nDrafty.toPlainText = function(content) {\n return typeof content == 'string' ? content : content.txt;\n}\n\n/**\n * Check if the document has no markup and no entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for presence of markup.\n * @returns true is content is plain text, false otherwise.\n */\nDrafty.isPlainText = function(content) {\n return typeof content == 'string' || !(content.fmt || content.ent);\n}\n\n/**\n * Convert document to plain text with markdown. All elements which cannot\n * be represented in markdown are stripped.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text with markdown.\n */\nDrafty.toMarkdown = function(content) {\n let tree = draftyToTree(content);\n const mdFormatter = function(type, _, values) {\n const def = FORMAT_TAGS[type];\n let result = (values ? values.join('') : '');\n if (def) {\n if (def.isVoid) {\n result = def.md_tag || '';\n } else if (def.md_tag) {\n result = def.md_tag + result + def.md_tag;\n }\n }\n return result;\n };\n return treeBottomUp(tree, mdFormatter, 0);\n}\n\n/**\n * Checks if the object represets is a valid Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for validity.\n * @returns true is content is valid, false otherwise.\n */\nDrafty.isValid = function(content) {\n if (!content) {\n return false;\n }\n\n const {\n txt,\n fmt,\n ent\n } = content;\n\n if (!txt && txt !== '' && !fmt && !ent) {\n return false;\n }\n\n const txt_type = typeof txt;\n if (txt_type != 'string' && txt_type != 'undefined' && txt !== null) {\n return false;\n }\n\n if (typeof fmt != 'undefined' && !Array.isArray(fmt) && fmt !== null) {\n return false;\n }\n\n if (typeof ent != 'undefined' && !Array.isArray(ent) && ent !== null) {\n return false;\n }\n return true;\n}\n\n/**\n * Check if the drafty document has attachments: style EX and outside of normal rendering flow,\n * i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for attachments.\n * @returns true if there are attachments.\n */\nDrafty.hasAttachments = function(content) {\n if (!Array.isArray(content.fmt)) {\n return false;\n }\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n return ent && ent.tp == 'EX' && ent.data;\n }\n }\n return false;\n}\n\n/**\n * Callback for enumerating entities in a Drafty document.\n * Called once for each entity.\n * @memberof Drafty\n * @static\n *\n * @callback EntityCallback\n * @param {Object} data entity data.\n * @param {string} entity type.\n * @param {number} index entity's index in `content.ent`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate attachments: style EX and outside of normal rendering flow, i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to process for attachments.\n * @param {EntityCallback} callback - callback to call for each attachment.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.attachments = function(content, callback, context) {\n if (!Array.isArray(content.fmt)) {\n return;\n }\n let count = 0;\n for (let i in content.ent) {\n let fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n if (ent && ent.tp == 'EX' && ent.data) {\n if (callback.call(context, ent.data, count++, 'EX')) {\n break;\n }\n }\n }\n };\n}\n\n/**\n * Check if the drafty document has entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for entities.\n * @returns true if there are entities.\n */\nDrafty.hasEntities = function(content) {\n return content.ent && content.ent.length > 0;\n}\n\n/**\n * Enumerate entities. Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @param {EntityCallback} callback - callback to call for each entity.\n * @param {Object} context - value of \"this\" for callback.\n *\n */\nDrafty.entities = function(content, callback, context) {\n if (content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n if (content.ent[i]) {\n if (callback.call(context, content.ent[i].data, i, content.ent[i].tp)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Callback for enumerating styles (inline formats) in a Drafty document.\n * Called once for each style.\n * @memberof Drafty\n * @static\n *\n * @callback StyleCallback\n * @param {string} tp - format type.\n * @param {number} at - starting position of the format in text.\n * @param {number} len - extent of the format in characters.\n * @param {number} key - index of the entity if format is a reference.\n * @param {number} index - style's index in `content.fmt`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate styles (inline formats). Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with styles (formats) to enumerate.\n * @param {StyleCallback} callback - callback to call for each format.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.styles = function(content, callback, context) {\n if (content.fmt && content.fmt.length > 0) {\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt) {\n if (callback.call(context, fmt.tp, fmt.at, fmt.len, fmt.key, i)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Remove unrecognized fields from entity data\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @returns content.\n */\nDrafty.sanitizeEntities = function(content) {\n if (content && content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n const ent = content.ent[i];\n if (ent && ent.data) {\n const data = copyEntData(ent.data);\n if (data) {\n content.ent[i].data = data;\n } else {\n delete content.ent[i].data;\n }\n }\n }\n }\n return content;\n}\n\n/**\n * Given the entity, get URL which can be used for downloading\n * entity data.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the URl from.\n * @returns {string} URL to download entity data or null.\n */\nDrafty.getDownloadUrl = function(entData) {\n let url = null;\n if (entData.mime != JSON_MIME_TYPE && entData.val) {\n url = base64toObjectUrl(entData.val, entData.mime, Drafty.logger);\n } else if (typeof entData.ref == 'string') {\n url = entData.ref;\n }\n return url;\n}\n\n/**\n * Check if the entity data is not ready for sending, such as being uploaded to the server.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n * @returns {boolean} true if upload is in progress, false otherwise.\n */\nDrafty.isProcessing = function(entData) {\n return !!entData._processing;\n}\n\n/**\n * Given the entity, get URL which can be used for previewing\n * the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n *\n * @returns {string} url for previewing or null if no such url is available.\n */\nDrafty.getPreviewUrl = function(entData) {\n return entData.val ? base64toObjectUrl(entData.val, entData.mime, Drafty.logger) : null;\n}\n\n/**\n * Get approximate size of the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the size for.\n * @returns {number} size of entity data in bytes.\n */\nDrafty.getEntitySize = function(entData) {\n // Either size hint or length of value. The value is base64 encoded,\n // the actual object size is smaller than the encoded length.\n return entData.size ? entData.size : entData.val ? (entData.val.length * 0.75) | 0 : 0;\n}\n\n/**\n * Get entity mime type.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the type for.\n * @returns {string} mime type of entity.\n */\nDrafty.getEntityMimeType = function(entData) {\n return entData.mime || 'text/plain';\n}\n\n/**\n * Get HTML tag for a given two-letter style name.\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style, like ST or LN.\n *\n * @returns {string} HTML tag name if style is found, {code: undefined} if style is falsish or not found.\n */\nDrafty.tagName = function(style) {\n return FORMAT_TAGS[style] && FORMAT_TAGS[style].html_tag;\n}\n\n/**\n * For a given data bundle generate an object with HTML attributes,\n * for instance, given {url: \"http://www.example.com/\"} return\n * {href: \"http://www.example.com/\"}\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style to generate attributes for.\n * @param {Object} data - data bundle to convert to attributes\n *\n * @returns {Object} object with HTML attributes.\n */\nDrafty.attrValue = function(style, data) {\n if (data && DECORATORS[style]) {\n return DECORATORS[style].props(data);\n }\n\n return undefined;\n}\n\n/**\n * Drafty MIME type.\n * @memberof Drafty\n * @static\n *\n * @returns {string} content-Type \"text/x-drafty\".\n */\nDrafty.getContentType = function() {\n return DRAFTY_MIME_TYPE;\n}\n\n// =================\n// Utility methods.\n// =================\n\n// Take a string and defined earlier style spans, re-compose them into a tree where each leaf is\n// a same-style (including unstyled) string. I.e. 'hello *bold _italic_* and ~more~ world' ->\n// ('hello ', (b: 'bold ', (i: 'italic')), ' and ', (s: 'more'), ' world');\n//\n// This is needed in order to clear markup, i.e. 'hello *world*' -> 'hello world' and convert\n// ranges from markup-ed offsets to plain text offsets.\nfunction chunkify(line, start, end, spans) {\n const chunks = [];\n\n if (spans.length == 0) {\n return [];\n }\n\n for (let i in spans) {\n // Get the next chunk from the queue\n const span = spans[i];\n\n // Grab the initial unstyled chunk\n if (span.at > start) {\n chunks.push({\n txt: line.slice(start, span.at)\n });\n }\n\n // Grab the styled chunk. It may include subchunks.\n const chunk = {\n tp: span.tp\n };\n const chld = chunkify(line, span.at + 1, span.end, span.children);\n if (chld.length > 0) {\n chunk.children = chld;\n } else {\n chunk.txt = span.txt;\n }\n chunks.push(chunk);\n start = span.end + 1; // '+1' is to skip the formatting character\n }\n\n // Grab the remaining unstyled chunk, after the last span\n if (start < end) {\n chunks.push({\n txt: line.slice(start, end)\n });\n }\n\n return chunks;\n}\n\n// Detect starts and ends of formatting spans. Unformatted spans are\n// ignored at this stage.\nfunction spannify(original, re_start, re_end, type) {\n const result = [];\n let index = 0;\n let line = original.slice(0); // make a copy;\n\n while (line.length > 0) {\n // match[0]; // match, like '*abc*'\n // match[1]; // match captured in parenthesis, like 'abc'\n // match['index']; // offset where the match started.\n\n // Find the opening token.\n const start = re_start.exec(line);\n if (start == null) {\n break;\n }\n\n // Because javascript RegExp does not support lookbehind, the actual offset may not point\n // at the markup character. Find it in the matched string.\n let start_offset = start['index'] + start[0].lastIndexOf(start[1]);\n // Clip the processed part of the string.\n line = line.slice(start_offset + 1);\n // start_offset is an offset within the clipped string. Convert to original index.\n start_offset += index;\n // Index now point to the beginning of 'line' within the 'original' string.\n index = start_offset + 1;\n\n // Find the matching closing token.\n const end = re_end ? re_end.exec(line) : null;\n if (end == null) {\n break;\n }\n let end_offset = end['index'] + end[0].indexOf(end[1]);\n // Clip the processed part of the string.\n line = line.slice(end_offset + 1);\n // Update offsets\n end_offset += index;\n // Index now points to the beginning of 'line' within the 'original' string.\n index = end_offset + 1;\n\n result.push({\n txt: original.slice(start_offset + 1, end_offset),\n children: [],\n at: start_offset,\n end: end_offset,\n tp: type\n });\n }\n\n return result;\n}\n\n// Convert linear array or spans into a tree representation.\n// Keep standalone and nested spans, throw away partially overlapping spans.\nfunction toSpanTree(spans) {\n if (spans.length == 0) {\n return [];\n }\n\n const tree = [spans[0]];\n let last = spans[0];\n for (let i = 1; i < spans.length; i++) {\n // Keep spans which start after the end of the previous span or those which\n // are complete within the previous span.\n if (spans[i].at > last.end) {\n // Span is completely outside of the previous span.\n tree.push(spans[i]);\n last = spans[i];\n } else if (spans[i].end <= last.end) {\n // Span is fully inside of the previous span. Push to subnode.\n last.children.push(spans[i]);\n }\n // Span could partially overlap, ignoring it as invalid.\n }\n\n // Recursively rearrange the subnodes.\n for (let i in tree) {\n tree[i].children = toSpanTree(tree[i].children);\n }\n\n return tree;\n}\n\n// Convert drafty document to a tree.\nfunction draftyToTree(doc) {\n if (!doc) {\n return null;\n }\n\n doc = (typeof doc == 'string') ? {\n txt: doc\n } : doc;\n let {\n txt,\n fmt,\n ent\n } = doc;\n\n txt = txt || '';\n if (!Array.isArray(ent)) {\n ent = [];\n }\n\n if (!Array.isArray(fmt) || fmt.length == 0) {\n if (ent.length == 0) {\n return {\n text: txt\n };\n }\n\n // Handle special case when all values in fmt are 0 and fmt therefore is skipped.\n fmt = [{\n at: 0,\n len: 0,\n key: 0\n }];\n }\n\n // Sanitize spans.\n const spans = [];\n const attachments = [];\n fmt.forEach((span) => {\n if (!span || typeof span != 'object') {\n return;\n }\n\n if (!['undefined', 'number'].includes(typeof span.at)) {\n // Present, but non-numeric 'at'.\n return;\n }\n if (!['undefined', 'number'].includes(typeof span.len)) {\n // Present, but non-numeric 'len'.\n return;\n }\n let at = span.at | 0;\n let len = span.len | 0;\n if (len < 0) {\n // Invalid span length.\n return;\n }\n\n let key = span.key || 0;\n if (ent.length > 0 && (typeof key != 'number' || key < 0 || key >= ent.length)) {\n // Invalid key value.\n return;\n }\n\n if (at <= -1) {\n // Attachment. Store attachments separately.\n attachments.push({\n start: -1,\n end: 0,\n key: key\n });\n return;\n } else if (at + len > txt.length) {\n // Span is out of bounds.\n return;\n }\n\n if (!span.tp) {\n if (ent.length > 0 && (typeof ent[key] == 'object')) {\n spans.push({\n start: at,\n end: at + len,\n key: key\n });\n }\n } else {\n spans.push({\n type: span.tp,\n start: at,\n end: at + len\n });\n }\n });\n\n // Sort spans first by start index (asc) then by length (desc), then by weight.\n spans.sort((a, b) => {\n let diff = a.start - b.start;\n if (diff != 0) {\n return diff;\n }\n diff = b.end - a.end;\n if (diff != 0) {\n return diff;\n }\n return FMT_WEIGHT.indexOf(b.type) - FMT_WEIGHT.indexOf(a.type);\n });\n\n // Move attachments to the end of the list.\n if (attachments.length > 0) {\n spans.push(...attachments);\n }\n\n spans.forEach((span) => {\n if (ent.length > 0 && !span.type && ent[span.key] && typeof ent[span.key] == 'object') {\n span.type = ent[span.key].tp;\n span.data = ent[span.key].data;\n }\n\n // Is type still undefined? Hide the invalid element!\n if (!span.type) {\n span.type = 'HD';\n }\n });\n\n let tree = spansToTree({}, txt, 0, txt.length, spans);\n\n // Flatten tree nodes.\n const flatten = function(node) {\n if (Array.isArray(node.children) && node.children.length == 1) {\n // Unwrap.\n const child = node.children[0];\n if (!node.type) {\n const parent = node.parent;\n node = child;\n node.parent = parent;\n } else if (!child.type && !child.children) {\n node.text = child.text;\n delete node.children;\n }\n }\n return node;\n }\n tree = treeTopDown(tree, flatten);\n\n return tree;\n}\n\n// Add tree node to a parent tree.\nfunction addNode(parent, n) {\n if (!n) {\n return parent;\n }\n\n if (!parent.children) {\n parent.children = [];\n }\n\n // If text is present, move it to a subnode.\n if (parent.text) {\n parent.children.push({\n text: parent.text,\n parent: parent\n });\n delete parent.text;\n }\n\n n.parent = parent;\n parent.children.push(n);\n\n return parent;\n}\n\n// Returns a tree of nodes.\nfunction spansToTree(parent, text, start, end, spans) {\n if (!spans || spans.length == 0) {\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n return parent;\n }\n\n // Process subspans.\n for (let i = 0; i < spans.length; i++) {\n const span = spans[i];\n if (span.start < 0 && span.type == 'EX') {\n addNode(parent, {\n type: span.type,\n data: span.data,\n key: span.key,\n att: true\n });\n continue;\n }\n\n // Add un-styled range before the styled span starts.\n if (start < span.start) {\n addNode(parent, {\n text: text.substring(start, span.start)\n });\n start = span.start;\n }\n\n // Get all spans which are within the current span.\n const subspans = [];\n while (i < spans.length - 1) {\n const inner = spans[i + 1];\n if (inner.start < 0) {\n // Attachments are in the end. Stop.\n break;\n } else if (inner.start < span.end) {\n if (inner.end <= span.end) {\n const tag = FORMAT_TAGS[inner.tp] || {};\n if (inner.start < inner.end || tag.isVoid) {\n // Valid subspan: completely within the current span and\n // either non-zero length or zero length is acceptable.\n subspans.push(inner);\n }\n }\n i++;\n // Overlapping subspans are ignored.\n } else {\n // Past the end of the current span. Stop.\n break;\n }\n }\n\n addNode(parent, spansToTree({\n type: span.type,\n data: span.data,\n key: span.key\n }, text, start, span.end, subspans));\n start = span.end;\n }\n\n // Add the last unformatted range.\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n\n return parent;\n}\n\n// Append a tree to a Drafty doc.\nfunction treeToDrafty(doc, tree, keymap) {\n if (!tree) {\n return doc;\n }\n\n doc.txt = doc.txt || '';\n\n // Checkpoint to measure length of the current tree node.\n const start = doc.txt.length;\n\n if (tree.text) {\n doc.txt += tree.text;\n } else if (Array.isArray(tree.children)) {\n tree.children.forEach((c) => {\n treeToDrafty(doc, c, keymap);\n });\n }\n\n if (tree.type) {\n const len = doc.txt.length - start;\n doc.fmt = doc.fmt || [];\n if (Object.keys(tree.data || {}).length > 0) {\n doc.ent = doc.ent || [];\n const newKey = (typeof keymap[tree.key] == 'undefined') ? doc.ent.length : keymap[tree.key];\n keymap[tree.key] = newKey;\n doc.ent[newKey] = {\n tp: tree.type,\n data: tree.data\n };\n if (tree.att) {\n // Attachment.\n doc.fmt.push({\n at: -1,\n len: 0,\n key: newKey\n });\n } else {\n doc.fmt.push({\n at: start,\n len: len,\n key: newKey\n });\n }\n } else {\n doc.fmt.push({\n tp: tree.type,\n at: start,\n len: len\n });\n }\n }\n return doc;\n}\n\n// Traverse the tree top down transforming the nodes: apply transformer to every tree node.\nfunction treeTopDown(src, transformer, context) {\n if (!src) {\n return null;\n }\n\n let dst = transformer.call(context, src);\n if (!dst || !dst.children) {\n return dst;\n }\n\n const children = [];\n for (let i in dst.children) {\n let n = dst.children[i];\n if (n) {\n n = treeTopDown(n, transformer, context);\n if (n) {\n children.push(n);\n }\n }\n }\n\n if (children.length == 0) {\n dst.children = null;\n } else {\n dst.children = children;\n }\n\n return dst;\n}\n\n// Traverse the tree bottom-up: apply formatter to every node.\n// The formatter must maintain its state through context.\nfunction treeBottomUp(src, formatter, index, stack, context) {\n if (!src) {\n return null;\n }\n\n if (stack && src.type) {\n stack.push(src.type);\n }\n\n let values = [];\n for (let i in src.children) {\n const n = treeBottomUp(src.children[i], formatter, i, stack, context);\n if (n) {\n values.push(n);\n }\n }\n if (values.length == 0) {\n if (src.text) {\n values = [src.text];\n } else {\n values = null;\n }\n }\n\n if (stack && src.type) {\n stack.pop();\n }\n\n return formatter.call(context, src.type, src.data, values, index, stack);\n}\n\n// Clip tree to the provided limit.\nfunction shortenTree(tree, limit, tail) {\n if (!tree) {\n return null;\n }\n\n if (tail) {\n limit -= tail.length;\n }\n\n const shortener = function(node) {\n if (limit <= -1) {\n // Limit -1 means the doc was already clipped.\n return null;\n }\n\n if (node.att) {\n // Attachments are unchanged.\n return node;\n }\n if (limit == 0) {\n node.text = tail;\n limit = -1;\n } else if (node.text) {\n const len = node.text.length;\n if (len > limit) {\n node.text = node.text.substring(0, limit) + tail;\n limit = -1;\n } else {\n limit -= len;\n }\n }\n return node;\n }\n\n return treeTopDown(tree, shortener);\n}\n\n// Strip heavy entities from a tree.\nfunction lightEntity(tree, allow) {\n const lightCopy = node => {\n const data = copyEntData(node.data, true, allow ? allow(node) : null);\n if (data) {\n node.data = data;\n } else {\n delete node.data;\n }\n return node;\n }\n return treeTopDown(tree, lightCopy);\n}\n\n// Remove spaces and breaks on the left.\nfunction lTrim(tree) {\n if (tree.type == 'BR') {\n tree = null;\n } else if (tree.text) {\n if (!tree.type) {\n tree.text = tree.text.trimStart();\n if (!tree.text) {\n tree = null;\n }\n }\n } else if (!tree.type && tree.children && tree.children.length > 0) {\n const c = lTrim(tree.children[0]);\n if (c) {\n tree.children[0] = c;\n } else {\n tree.children.shift();\n if (!tree.type && tree.children.length == 0) {\n tree = null;\n }\n }\n }\n return tree;\n}\n\n// Move attachments to the end. Attachments must be at the top level, no need to traverse the tree.\nfunction attachmentsToEnd(tree, limit) {\n if (!tree) {\n return null;\n }\n\n if (tree.att) {\n tree.text = ' ';\n delete tree.att;\n delete tree.children;\n } else if (tree.children) {\n const attachments = [];\n const children = [];\n for (let i in tree.children) {\n const c = tree.children[i];\n if (c.att) {\n if (attachments.length == limit) {\n // Too many attachments to preview;\n continue;\n }\n if (c.data['mime'] == JSON_MIME_TYPE) {\n // JSON attachments are not shown in preview.\n continue;\n }\n\n delete c.att;\n delete c.children;\n c.text = ' ';\n attachments.push(c);\n } else {\n children.push(c);\n }\n }\n tree.children = children.concat(attachments);\n }\n return tree;\n}\n\n// Get a list of entities from a text.\nfunction extractEntities(line) {\n let match;\n let extracted = [];\n ENTITY_TYPES.forEach((entity) => {\n while ((match = entity.re.exec(line)) !== null) {\n extracted.push({\n offset: match['index'],\n len: match[0].length,\n unique: match[0],\n data: entity.pack(match[0]),\n type: entity.name\n });\n }\n });\n\n if (extracted.length == 0) {\n return extracted;\n }\n\n // Remove entities detected inside other entities, like #hashtag in a URL.\n extracted.sort((a, b) => {\n return a.offset - b.offset;\n });\n\n let idx = -1;\n extracted = extracted.filter((el) => {\n const result = (el.offset > idx);\n idx = el.offset + el.len;\n return result;\n });\n\n return extracted;\n}\n\n// Convert the chunks into format suitable for serialization.\nfunction draftify(chunks, startAt) {\n let plain = '';\n let ranges = [];\n for (let i in chunks) {\n const chunk = chunks[i];\n if (!chunk.txt) {\n const drafty = draftify(chunk.children, plain.length + startAt);\n chunk.txt = drafty.txt;\n ranges = ranges.concat(drafty.fmt);\n }\n\n if (chunk.tp) {\n ranges.push({\n at: plain.length + startAt,\n len: chunk.txt.length,\n tp: chunk.tp\n });\n }\n\n plain += chunk.txt;\n }\n return {\n txt: plain,\n fmt: ranges\n };\n}\n\n// Create a copy of entity data with (light=false) or without (light=true) the large payload.\n// The array 'allow' contains a list of fields exempt from stripping.\nfunction copyEntData(data, light, allow) {\n if (data && Object.entries(data).length > 0) {\n allow = allow || [];\n const dc = {};\n ALLOWED_ENT_FIELDS.forEach(key => {\n if (data[key]) {\n if (light && !allow.includes(key) &&\n (typeof data[key] == 'string' || Array.isArray(data[key])) &&\n data[key].length > MAX_PREVIEW_DATA_SIZE) {\n return;\n }\n if (typeof data[key] == 'object') {\n return;\n }\n dc[key] = data[key];\n }\n });\n\n if (Object.entries(dc).length != 0) {\n return dc;\n }\n }\n return null;\n}\n\nif (typeof module != 'undefined') {\n module.exports = Drafty;\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * @file Access control model.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\n/**\n * Helper class for handling access mode.\n *\n * @class AccessMode\n * @memberof Tinode\n *\n * @param {AccessMode|Object=} acs - AccessMode to copy or access mode object received from the server.\n */\nexport default class AccessMode {\n constructor(acs) {\n if (acs) {\n this.given = typeof acs.given == 'number' ? acs.given : AccessMode.decode(acs.given);\n this.want = typeof acs.want == 'number' ? acs.want : AccessMode.decode(acs.want);\n this.mode = acs.mode ? (typeof acs.mode == 'number' ? acs.mode : AccessMode.decode(acs.mode)) :\n (this.given & this.want);\n }\n }\n\n static #checkFlag(val, side, flag) {\n side = side || 'mode';\n if (['given', 'want', 'mode'].includes(side)) {\n return ((val[side] & flag) != 0);\n }\n throw new Error(`Invalid AccessMode component '${side}'`);\n }\n /**\n * Parse string into an access mode value.\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {string | Number} mode - either a String representation of the access mode to parse or a set of bits to assign.\n * @returns {number} - Access mode as a numeric value.\n */\n static decode(str) {\n if (!str) {\n return null;\n } else if (typeof str == 'number') {\n return str & AccessMode._BITMASK;\n } else if (str === 'N' || str === 'n') {\n return AccessMode._NONE;\n }\n\n const bitmask = {\n 'J': AccessMode._JOIN,\n 'R': AccessMode._READ,\n 'W': AccessMode._WRITE,\n 'P': AccessMode._PRES,\n 'A': AccessMode._APPROVE,\n 'S': AccessMode._SHARE,\n 'D': AccessMode._DELETE,\n 'O': AccessMode._OWNER\n };\n\n let m0 = AccessMode._NONE;\n\n for (let i = 0; i < str.length; i++) {\n const bit = bitmask[str.charAt(i).toUpperCase()];\n if (!bit) {\n // Unrecognized bit, skip.\n continue;\n }\n m0 |= bit;\n }\n return m0;\n }\n /**\n * Convert numeric representation of the access mode into a string.\n *\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {number} val - access mode value to convert to a string.\n * @returns {string} - Access mode as a string.\n */\n static encode(val) {\n if (val === null || val === AccessMode._INVALID) {\n return null;\n } else if (val === AccessMode._NONE) {\n return 'N';\n }\n\n const bitmask = ['J', 'R', 'W', 'P', 'A', 'S', 'D', 'O'];\n let res = '';\n for (let i = 0; i < bitmask.length; i++) {\n if ((val & (1 << i)) != 0) {\n res = res + bitmask[i];\n }\n }\n return res;\n }\n /**\n * Update numeric representation of access mode with the new value. The value\n * is one of the following:\n * - a string starting with '+' or '-' then the bits to add or remove, e.g. '+R-W' or '-PS'.\n * - a new value of access mode\n *\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {number} val - access mode value to update.\n * @param {string} upd - update to apply to val.\n * @returns {number} - updated access mode.\n */\n static update(val, upd) {\n if (!upd || typeof upd != 'string') {\n return val;\n }\n\n let action = upd.charAt(0);\n if (action == '+' || action == '-') {\n let val0 = val;\n // Split delta-string like '+ABC-DEF+Z' into an array of parts including + and -.\n const parts = upd.split(/([-+])/);\n // Starting iteration from 1 because String.split() creates an array with the first empty element.\n // Iterating by 2 because we parse pairs +/- then data.\n for (let i = 1; i < parts.length - 1; i += 2) {\n action = parts[i];\n const m0 = AccessMode.decode(parts[i + 1]);\n if (m0 == AccessMode._INVALID) {\n return val;\n }\n if (m0 == null) {\n continue;\n }\n if (action === '+') {\n val0 |= m0;\n } else if (action === '-') {\n val0 &= ~m0;\n }\n }\n val = val0;\n } else {\n // The string is an explicit new value 'ABC' rather than delta.\n const val0 = AccessMode.decode(upd);\n if (val0 != AccessMode._INVALID) {\n val = val0;\n }\n }\n\n return val;\n }\n /**\n * Bits present in a1 but missing in a2.\n *\n * @static\n * @memberof Tinode\n *\n * @param {number | string} a1 - access mode to subtract from.\n * @param {number | string} a2 - access mode to subtract.\n * @returns {number} access mode with bits present in a1 but missing in a2.\n */\n static diff(a1, a2) {\n a1 = AccessMode.decode(a1);\n a2 = AccessMode.decode(a2);\n\n if (a1 == AccessMode._INVALID || a2 == AccessMode._INVALID) {\n return AccessMode._INVALID;\n }\n return a1 & ~a2;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Custom formatter\n */\n toString() {\n return '{\"mode\": \"' + AccessMode.encode(this.mode) +\n '\", \"given\": \"' + AccessMode.encode(this.given) +\n '\", \"want\": \"' + AccessMode.encode(this.want) + '\"}';\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Converts numeric values to strings.\n */\n jsonHelper() {\n return {\n mode: AccessMode.encode(this.mode),\n given: AccessMode.encode(this.given),\n want: AccessMode.encode(this.want)\n };\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign value to 'mode'.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} m - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setMode(m) {\n this.mode = AccessMode.decode(m);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update mode value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateMode(u) {\n this.mode = AccessMode.update(this.mode, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get mode value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - mode value.\n */\n getMode() {\n return AccessMode.encode(this.mode);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign given value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} g - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setGiven(g) {\n this.given = AccessMode.decode(g);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'given' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateGiven(u) {\n this.given = AccessMode.update(this.given, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'given' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - given value.\n */\n getGiven() {\n return AccessMode.encode(this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} w - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setWant(w) {\n this.want = AccessMode.decode(w);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateWant(u) {\n this.want = AccessMode.update(this.want, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'want' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - want value.\n */\n getWant() {\n return AccessMode.encode(this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'want' but missing in 'given'.\n * Inverse of {@link Tinode.AccessMode#getExcessive}\n *\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in want but missing in given.\n */\n getMissing() {\n return AccessMode.encode(this.want & ~this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'given' but missing in 'want'.\n * Inverse of {@link Tinode.AccessMode#getMissing}\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in given but missing in want.\n */\n getExcessive() {\n return AccessMode.encode(this.given & ~this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want', 'give', and 'mode' values.\n * @memberof Tinode.AccessMode\n *\n * @param {AccessMode} val - new access mode value.\n * @returns {AccessMode} - this AccessMode.\n */\n updateAll(val) {\n if (val) {\n this.updateGiven(val.given);\n this.updateWant(val.want);\n this.mode = this.given & this.want;\n }\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Owner (O) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isOwner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._OWNER);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isPresencer(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._PRES);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is NOT set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isMuted(side) {\n return !this.isPresencer(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Join (J) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isJoiner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._JOIN);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Reader (R) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isReader(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._READ);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Writer (W) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isWriter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._WRITE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Approver (A) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isApprover(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._APPROVE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O) or Approver (A) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isAdmin(side) {\n return this.isOwner(side) || this.isApprover(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O), Approver (A), or Sharer (S) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isSharer(side) {\n return this.isAdmin(side) || AccessMode.#checkFlag(this, side, AccessMode._SHARE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Deleter (D) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isDeleter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._DELETE);\n }\n}\n\nAccessMode._NONE = 0x00;\nAccessMode._JOIN = 0x01;\nAccessMode._READ = 0x02;\nAccessMode._WRITE = 0x04;\nAccessMode._PRES = 0x08;\nAccessMode._APPROVE = 0x10;\nAccessMode._SHARE = 0x20;\nAccessMode._DELETE = 0x40;\nAccessMode._OWNER = 0x80;\n\nAccessMode._BITMASK = AccessMode._JOIN | AccessMode._READ | AccessMode._WRITE | AccessMode._PRES |\n AccessMode._APPROVE | AccessMode._SHARE | AccessMode._DELETE | AccessMode._OWNER;\nAccessMode._INVALID = 0x100000;\n","export const PACKAGE_VERSION = \"0.23.0-rc1\";\n","/**\n * @file Global constants and configuration parameters.\n *\n * @copyright 2015-2023 Tinode LLC\n */\n'use strict';\n\nimport {\n PACKAGE_VERSION\n} from '../version.js';\n\n// Global constants\nexport const PROTOCOL_VERSION = '0'; // Major component of the version, e.g. '0' in '0.17.1'.\nexport const VERSION = PACKAGE_VERSION || '0.21';\nexport const LIBRARY = 'tinodejs/' + VERSION;\n\n// Topic name prefixes.\nexport const TOPIC_NEW = 'new';\nexport const TOPIC_NEW_CHAN = 'nch';\nexport const TOPIC_ME = 'me';\nexport const TOPIC_FND = 'fnd';\nexport const TOPIC_SYS = 'sys';\nexport const TOPIC_CHAN = 'chn';\nexport const TOPIC_GRP = 'grp';\nexport const TOPIC_P2P = 'p2p';\nexport const USER_NEW = 'new';\n\n// Starting value of a locally-generated seqId used for pending messages.\nexport const LOCAL_SEQID = 0xFFFFFFF;\n\n// Status codes.\nexport const MESSAGE_STATUS_NONE = 0; // Status not assigned.\nexport const MESSAGE_STATUS_QUEUED = 10; // Local ID assigned, in progress to be sent.\nexport const MESSAGE_STATUS_SENDING = 20; // Transmission started.\nexport const MESSAGE_STATUS_FAILED = 30; // At least one attempt was made to send the message.\nexport const MESSAGE_STATUS_FATAL = 40; // Message sending failed and it should not be retried.\nexport const MESSAGE_STATUS_SENT = 50; // Delivered to the server.\nexport const MESSAGE_STATUS_RECEIVED = 60; // Received by the client.\nexport const MESSAGE_STATUS_READ = 70; // Read by the user.\nexport const MESSAGE_STATUS_TO_ME = 80; // The message is received from another user.\n\n// Reject unresolved futures after this many milliseconds.\nexport const EXPIRE_PROMISES_TIMEOUT = 5_000;\n// Periodicity of garbage collection of unresolved futures.\nexport const EXPIRE_PROMISES_PERIOD = 1_000;\n\n// Delay before acknowledging that a message was recived.\nexport const RECV_TIMEOUT = 100;\n\n// Default number of messages to pull into memory from persistent cache.\nexport const DEFAULT_MESSAGES_PAGE = 24;\n\n// Unicode DEL character indicating data was deleted.\nexport const DEL_CHAR = '\\u2421';\n\n// Maximum number of pinnned messages;\nexport const MAX_PINNED_COUNT = 5;\n","/**\n * @file Throwable error with numeric error code.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nexport default class CommError extends Error {\n constructor(message, code) {\n super(`${message} (${code})`);\n this.name = 'CommError';\n this.code = code;\n }\n}\n","/**\n * @file Utilities used in multiple places.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport {\n DEL_CHAR,\n LOCAL_SEQID\n} from './config.js';\n\n// Attempt to convert date and AccessMode strings to objects.\nexport function jsonParseHelper(key, val) {\n // Try to convert string timestamps with optional milliseconds to Date,\n // e.g. 2015-09-02T01:45:43[.123]Z\n if (typeof val == 'string' && val.length >= 20 && val.length <= 24 && ['ts', 'touched', 'updated', 'created', 'when', 'deleted', 'expires'].includes(key)) {\n const date = new Date(val);\n if (!isNaN(date)) {\n return date;\n }\n } else if (key === 'acs' && typeof val === 'object') {\n return new AccessMode(val);\n }\n return val;\n}\n\n// Checks if URL is a relative url, i.e. has no 'scheme://', including the case of missing scheme '//'.\n// The scheme is expected to be RFC-compliant, e.g. [a-z][a-z0-9+.-]*\n// example.html - ok\n// https:example.com - not ok.\n// http:/example.com - not ok.\n// ' ↲ https://example.com' - not ok. (↲ means carriage return)\nexport function isUrlRelative(url) {\n return url && !/^\\s*([a-z][a-z0-9+.-]*:|\\/\\/)/im.test(url);\n}\n\nfunction isValidDate(d) {\n return (d instanceof Date) && !isNaN(d) && (d.getTime() != 0);\n}\n\n// RFC3339 formater of Date\nexport function rfc3339DateString(d) {\n if (!isValidDate(d)) {\n return undefined;\n }\n\n const pad = function(val, sp) {\n sp = sp || 2;\n return '0'.repeat(sp - ('' + val).length) + val;\n };\n\n const millis = d.getUTCMilliseconds();\n return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) +\n 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) +\n (millis ? '.' + pad(millis, 3) : '') + 'Z';\n}\n\n// Recursively merge src's own properties to dst.\n// Ignore properties where ignore[property] is true.\n// Array and Date objects are shallow-copied.\nexport function mergeObj(dst, src, ignore) {\n if (typeof src != 'object') {\n if (src === undefined) {\n return dst;\n }\n if (src === DEL_CHAR) {\n return undefined;\n }\n return src;\n }\n // JS is crazy: typeof null is 'object'.\n if (src === null) {\n return src;\n }\n\n // Handle Date\n if (src instanceof Date && !isNaN(src)) {\n return (!dst || !(dst instanceof Date) || isNaN(dst) || dst < src) ? src : dst;\n }\n\n // Access mode\n if (src instanceof AccessMode) {\n return new AccessMode(src);\n }\n\n // Handle Array\n if (src instanceof Array) {\n return src;\n }\n\n if (!dst || dst === DEL_CHAR) {\n dst = src.constructor();\n }\n\n for (let prop in src) {\n if (src.hasOwnProperty(prop) && (!ignore || !ignore[prop]) && (prop != '_noForwarding')) {\n try {\n dst[prop] = mergeObj(dst[prop], src[prop]);\n } catch (err) {\n // FIXME: probably need to log something here.\n }\n }\n }\n return dst;\n}\n\n// Update object stored in a cache. Returns updated value.\nexport function mergeToCache(cache, key, newval, ignore) {\n cache[key] = mergeObj(cache[key], newval, ignore);\n return cache[key];\n}\n\n// Strips all values from an object of they evaluate to false or if their name starts with '_'.\n// Used on all outgoing object before serialization to string.\nexport function simplify(obj) {\n Object.keys(obj).forEach((key) => {\n if (key[0] == '_') {\n // Strip fields like \"obj._key\".\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (Array.isArray(obj[key]) && obj[key].length == 0) {\n // Strip empty arrays.\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (obj[key] instanceof Date) {\n // Strip invalid or zero date.\n if (!isValidDate(obj[key])) {\n delete obj[key];\n }\n } else if (typeof obj[key] == 'object') {\n simplify(obj[key]);\n // Strip empty objects.\n if (Object.getOwnPropertyNames(obj[key]).length == 0) {\n delete obj[key];\n }\n }\n });\n return obj;\n};\n\n\n// Trim whitespace, strip empty and duplicate elements elements.\n// If the result is an empty array, add a single element \"\\u2421\" (Unicode Del character).\nexport function normalizeArray(arr) {\n let out = [];\n if (Array.isArray(arr)) {\n // Trim, throw away very short and empty tags.\n for (let i = 0, l = arr.length; i < l; i++) {\n let t = arr[i];\n if (t) {\n t = t.trim().toLowerCase();\n if (t.length > 1) {\n out.push(t);\n }\n }\n }\n out.sort().filter((item, pos, ary) => {\n return !pos || item != ary[pos - 1];\n });\n }\n if (out.length == 0) {\n // Add single tag with a Unicode Del character, otherwise an ampty array\n // is ambiguos. The Del tag will be stripped by the server.\n out.push(DEL_CHAR);\n }\n return out;\n}\n\n// Convert input to valid ranges of IDs.\nexport function normalizeRanges(ranges, maxSeq) {\n if (!Array.isArray(ranges)) {\n return [];\n }\n\n // Sort ranges in accending order by low, then descending by hi.\n ranges.sort((r1, r2) => {\n if (r1.low < r2.low) {\n return true;\n }\n if (r1.low == r2.low) {\n return !r2.hi || (r1.hi >= r2.hi);\n }\n return false;\n });\n\n // Remove pending messages from ranges possibly clipping some ranges.\n return ranges.reduce((out, r) => {\n if (r.low < LOCAL_SEQID && r.low > 0) {\n if (!r.hi || r.hi < LOCAL_SEQID) {\n out.push(r);\n } else {\n // Clip hi to max allowed value.\n out.push({\n low: r.low,\n hi: maxSeq + 1\n });\n }\n }\n return out;\n }, []);\n}\n\n// Convert array of IDs to array of ranges.\nexport function listToRanges(list) {\n // Sort the list in ascending order\n list.sort((a, b) => a - b);\n // Convert the array of IDs to ranges.\n return list.reduce((out, id) => {\n if (out.length == 0) {\n // First element.\n out.push({\n low: id\n });\n } else {\n let prev = out[out.length - 1];\n if ((!prev.hi && (id != prev.low + 1)) || (id > prev.hi)) {\n // New range.\n out.push({\n low: id\n });\n } else {\n // Expand existing range.\n prev.hi = prev.hi ? Math.max(prev.hi, id + 1) : id + 1;\n }\n }\n return out;\n }, []);\n}\n\n// Cuts 'clip' range out of the 'src' range.\n// Returns an array with 0, 1 or 2 elements.\nexport function clipRange(src, clip) {\n if (clip.hi < src.low || clip.low >= src.hi) {\n // Clip is completely outside of src, no intersection.\n return [src];\n }\n\n if (clip.low <= src.low) {\n if (clip.hi >= src.hi) {\n // The source range is completely inside the clipping range.\n return [];\n }\n // Partial clipping at the top.\n return [{\n low: src.low,\n hi: clip.hi\n }];\n }\n\n // Range on the lower end.\n const result = [{\n low: src.low,\n hi: clip.low\n }];\n if (clip.hi < src.hi) {\n // Maybe a range on the higher end, if clip is completely inside the source.\n result.push({\n low: clip.hi,\n hi: src.hi\n });\n }\n\n return result;\n}\n","/**\n * @file Abstraction layer for websocket and long polling connections.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n jsonParseHelper\n} from './utils.js';\n\nlet WebSocketProvider;\nlet XHRProvider;\n\n// Error code to return in case of a network problem.\nconst NETWORK_ERROR = 503;\nconst NETWORK_ERROR_TEXT = \"Connection failed\";\n\n// Error code to return when user disconnected from server.\nconst NETWORK_USER = 418;\nconst NETWORK_USER_TEXT = \"Disconnected by client\";\n\n// Settings for exponential backoff\nconst _BOFF_BASE = 2000; // 2000 milliseconds, minimum delay between reconnects\nconst _BOFF_MAX_ITER = 10; // Maximum delay between reconnects 2^10 * 2000 ~ 34 minutes\nconst _BOFF_JITTER = 0.3; // Add random delay\n\n// Helper function for creating an endpoint URL.\nfunction makeBaseUrl(host, protocol, version, apiKey) {\n let url = null;\n\n if (['http', 'https', 'ws', 'wss'].includes(protocol)) {\n url = `${protocol}://${host}`;\n if (url.charAt(url.length - 1) !== '/') {\n url += '/';\n }\n url += 'v' + version + '/channels';\n if (['http', 'https'].includes(protocol)) {\n // Long polling endpoint ends with \"lp\", i.e.\n // '/v0/channels/lp' vs just '/v0/channels' for ws\n url += '/lp';\n }\n url += '?apikey=' + apiKey;\n }\n return url;\n}\n\n/**\n * An abstraction for a websocket or a long polling connection.\n *\n * @class Connection\n * @memberof Tinode\n\n * @param {Object} config - configuration parameters.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - Network transport to use, either \"ws\"/\"wss\" for websocket or\n * lp for long polling.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} version_ - Major value of the protocol version, e.g. '0' in '0.17.1'.\n * @param {boolean} autoreconnect_ - If connection is lost, try to reconnect automatically.\n */\nexport default class Connection {\n // Logger, does nothing by default.\n static #log = _ => {};\n\n #boffTimer = null;\n #boffIteration = 0;\n #boffClosed = false; // Indicator if the socket was manually closed - don't autoreconnect if true.\n\n // Websocket.\n #socket = null;\n\n host;\n secure;\n apiKey;\n\n version;\n autoreconnect;\n\n initialized;\n\n // (config.host, config.apiKey, config.transport, config.secure), PROTOCOL_VERSION, true\n constructor(config, version_, autoreconnect_) {\n this.host = config.host;\n this.secure = config.secure;\n this.apiKey = config.apiKey;\n\n this.version = version_;\n this.autoreconnect = autoreconnect_;\n\n if (config.transport === 'lp') {\n // explicit request to use long polling\n this.#init_lp();\n this.initialized = 'lp';\n } else if (config.transport === 'ws') {\n // explicit request to use web socket\n // if websockets are not available, horrible things will happen\n this.#init_ws();\n this.initialized = 'ws';\n }\n\n if (!this.initialized) {\n // Invalid or undefined network transport.\n Connection.#log(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n throw new Error(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n }\n }\n\n /**\n * To use Connection in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n * @memberof Connection\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n }\n\n /**\n * Assign a non-default logger.\n * @static\n * @memberof Connection\n * @param {function} l variadic logging function.\n */\n static set logger(l) {\n Connection.#log = l;\n }\n\n /**\n * Initiate a new connection\n * @memberof Tinode.Connection#\n * @param {string} host_ Host name to connect to; if null the old host name will be used.\n * @param {boolean} force Force new connection even if one already exists.\n * @return {Promise} Promise resolved/rejected when the connection call completes, resolution is called without\n * parameters, rejection passes the {Error} as parameter.\n */\n connect(host_, force) {\n return Promise.reject(null);\n }\n\n /**\n * Try to restore a network connection, also reset backoff.\n * @memberof Tinode.Connection#\n *\n * @param {boolean} force - reconnect even if there is a live connection already.\n */\n reconnect(force) {}\n\n /**\n * Terminate the network connection\n * @memberof Tinode.Connection#\n */\n disconnect() {}\n\n /**\n * Send a string to the server.\n * @memberof Tinode.Connection#\n *\n * @param {string} msg - String to send.\n * @throws Throws an exception if the underlying connection is not live.\n */\n sendText(msg) {}\n\n /**\n * Check if connection is alive.\n * @memberof Tinode.Connection#\n * @returns {boolean} true if connection is live, false otherwise.\n */\n isConnected() {\n return false;\n }\n\n /**\n * Get the name of the current network transport.\n * @memberof Tinode.Connection#\n * @returns {string} name of the transport such as \"ws\" or \"lp\".\n */\n transport() {\n return this.initialized;\n }\n\n /**\n * Send network probe to check if connection is indeed live.\n * @memberof Tinode.Connection#\n */\n probe() {\n this.sendText('1');\n }\n\n /**\n * Reset autoreconnect counter to zero.\n * @memberof Tinode.Connection#\n */\n backoffReset() {\n this.#boffReset();\n }\n\n // Backoff implementation - reconnect after a timeout.\n #boffReconnect() {\n // Clear timer\n clearTimeout(this.#boffTimer);\n // Calculate when to fire the reconnect attempt\n const timeout = _BOFF_BASE * (Math.pow(2, this.#boffIteration) * (1.0 + _BOFF_JITTER * Math.random()));\n // Update iteration counter for future use\n this.#boffIteration = (this.#boffIteration >= _BOFF_MAX_ITER ? this.#boffIteration : this.#boffIteration + 1);\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(timeout);\n }\n\n this.#boffTimer = setTimeout(_ => {\n Connection.#log(`Reconnecting, iter=${this.#boffIteration}, timeout=${timeout}`);\n // Maybe the socket was closed while we waited for the timer?\n if (!this.#boffClosed) {\n const prom = this.connect();\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(0, prom);\n } else {\n // Suppress error if it's not used.\n prom.catch(_ => {\n /* do nothing */\n });\n }\n } else if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(-1);\n }\n }, timeout);\n }\n\n // Terminate auto-reconnect process.\n #boffStop() {\n clearTimeout(this.#boffTimer);\n this.#boffTimer = null;\n }\n\n // Reset auto-reconnect iteration counter.\n #boffReset() {\n this.#boffIteration = 0;\n }\n\n // Initialization for long polling.\n #init_lp() {\n const XDR_UNSENT = 0; // Client has been created. open() not called yet.\n const XDR_OPENED = 1; // open() has been called.\n const XDR_HEADERS_RECEIVED = 2; // send() has been called, and headers and status are available.\n const XDR_LOADING = 3; // Downloading; responseText holds partial data.\n const XDR_DONE = 4; // The operation is complete.\n\n // Fully composed endpoint URL, with API key & SID\n let _lpURL = null;\n\n let _poller = null;\n let _sender = null;\n\n let lp_sender = (url_) => {\n const sender = new XHRProvider();\n sender.onreadystatechange = (evt) => {\n if (sender.readyState == XDR_DONE && sender.status >= 400) {\n // Some sort of error response\n throw new CommError(\"LP sender failed\", sender.status);\n }\n };\n\n sender.open('POST', url_, true);\n return sender;\n }\n\n let lp_poller = (url_, resolve, reject) => {\n let poller = new XHRProvider();\n let promiseCompleted = false;\n\n poller.onreadystatechange = evt => {\n if (poller.readyState == XDR_DONE) {\n if (poller.status == 201) { // 201 == HTTP.Created, get SID\n let pkt = JSON.parse(poller.responseText, jsonParseHelper);\n _lpURL = url_ + '&sid=' + pkt.ctrl.params.sid;\n poller = lp_poller(_lpURL);\n poller.send(null);\n if (this.onOpen) {\n this.onOpen();\n }\n\n if (resolve) {\n promiseCompleted = true;\n resolve();\n }\n\n if (this.autoreconnect) {\n this.#boffStop();\n }\n } else if (poller.status > 0 && poller.status < 400) { // 0 = network error; 400 = HTTP.BadRequest\n if (this.onMessage) {\n this.onMessage(poller.responseText);\n }\n poller = lp_poller(_lpURL);\n poller.send(null);\n } else {\n // Don't throw an error here, gracefully handle server errors\n if (reject && !promiseCompleted) {\n promiseCompleted = true;\n reject(poller.responseText);\n }\n if (this.onMessage && poller.responseText) {\n this.onMessage(poller.responseText);\n }\n if (this.onDisconnect) {\n const code = poller.status || (this.#boffClosed ? NETWORK_USER : NETWORK_ERROR);\n const text = poller.responseText || (this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT);\n this.onDisconnect(new CommError(text, code), code);\n }\n\n // Polling has stopped. Indicate it by setting poller to null.\n poller = null;\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n }\n }\n };\n // Using POST to avoid caching response by service worker.\n poller.open('POST', url_, true);\n return poller;\n }\n\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (_poller) {\n if (!force) {\n return Promise.resolve();\n }\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'https' : 'http', this.version, this.apiKey);\n Connection.#log(\"LP connecting to:\", url);\n _poller = lp_poller(url, resolve, reject);\n _poller.send(null);\n }).catch(err => {\n Connection.#log(\"LP connection failed:\", err);\n });\n };\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (_sender) {\n _sender.onreadystatechange = undefined;\n _sender.abort();\n _sender = null;\n }\n if (_poller) {\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (this.onDisconnect) {\n this.onDisconnect(new CommError(NETWORK_USER_TEXT, NETWORK_USER), NETWORK_USER);\n }\n // Ensure it's reconstructed\n _lpURL = null;\n };\n\n this.sendText = (msg) => {\n _sender = lp_sender(_lpURL);\n if (_sender && (_sender.readyState == XDR_OPENED)) { // 1 == OPENED\n _sender.send(msg);\n } else {\n throw new Error(\"Long poller failed to connect\");\n }\n };\n\n this.isConnected = _ => {\n return (_poller && true);\n };\n }\n\n // Initialization for Websocket\n #init_ws() {\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (this.#socket) {\n if (!force && this.#socket.readyState == this.#socket.OPEN) {\n return Promise.resolve();\n }\n this.#socket.close();\n this.#socket = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'wss' : 'ws', this.version, this.apiKey);\n\n Connection.#log(\"WS connecting to: \", url);\n\n // It throws when the server is not accessible but the exception cannot be caught:\n // https://stackoverflow.com/questions/31002592/javascript-doesnt-catch-error-in-websocket-instantiation/31003057\n const conn = new WebSocketProvider(url);\n\n conn.onerror = err => {\n reject(err);\n };\n\n conn.onopen = _ => {\n if (this.autoreconnect) {\n this.#boffStop();\n }\n\n if (this.onOpen) {\n this.onOpen();\n }\n\n resolve();\n };\n\n conn.onclose = _ => {\n this.#socket = null;\n\n if (this.onDisconnect) {\n const code = this.#boffClosed ? NETWORK_USER : NETWORK_ERROR;\n this.onDisconnect(new CommError(this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT, code), code);\n }\n\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n };\n\n conn.onmessage = evt => {\n if (this.onMessage) {\n this.onMessage(evt.data);\n }\n };\n\n this.#socket = conn;\n });\n }\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (!this.#socket) {\n return;\n }\n this.#socket.close();\n this.#socket = null;\n };\n\n this.sendText = msg => {\n if (this.#socket && (this.#socket.readyState == this.#socket.OPEN)) {\n this.#socket.send(msg);\n } else {\n throw new Error(\"Websocket is not connected\");\n }\n };\n\n this.isConnected = _ => {\n return (this.#socket && (this.#socket.readyState == this.#socket.OPEN));\n };\n }\n\n // Callbacks:\n\n /**\n * A callback to pass incoming messages to. See {@link Tinode.Connection#onMessage}.\n * @callback Tinode.Connection.OnMessage\n * @memberof Tinode.Connection\n * @param {string} message - Message to process.\n */\n onMessage = undefined;\n\n /**\n * A callback for reporting a dropped connection.\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onDisconnect = undefined;\n\n /**\n * A callback called when the connection is ready to be used for sending. For websockets it's socket open,\n * for long polling it's readyState=1 (OPENED)\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onOpen = undefined;\n\n /**\n * A callback to notify of reconnection attempts. See {@link Tinode.Connection#onAutoreconnectIteration}.\n * @memberof Tinode.Connection\n * @callback AutoreconnectIterationType\n * @param {string} timeout - time till the next reconnect attempt in milliseconds. -1 means reconnect was skipped.\n * @param {Promise} promise resolved or rejected when the reconnect attemp completes.\n *\n */\n /**\n * A callback to inform when the next attampt to reconnect will happen and to receive connection promise.\n * @memberof Tinode.Connection#\n * @type {Tinode.Connection.AutoreconnectIterationType}\n */\n onAutoreconnectIteration = undefined;\n}\n\nConnection.NETWORK_ERROR = NETWORK_ERROR;\nConnection.NETWORK_ERROR_TEXT = NETWORK_ERROR_TEXT;\nConnection.NETWORK_USER = NETWORK_USER;\nConnection.NETWORK_USER_TEXT = NETWORK_USER_TEXT;\n","/**\n * @file Helper methods for dealing with IndexedDB cache of messages, users, and topics.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nimport {\n clipRange\n} from './utils.js';\n\nconst DB_VERSION = 3;\nconst DB_NAME = 'tinode-web';\n\nlet IDBProvider;\n\nexport default class DB {\n #onError = _ => {};\n #logger = _ => {};\n\n // Instance of IndexDB.\n db = null;\n // Indicator that the cache is disabled.\n disabled = false;\n\n constructor(onError, logger) {\n this.#onError = onError || this.#onError;\n this.#logger = logger || this.#logger;\n }\n\n #mapObjects(source, callback, context) {\n if (!this.db) {\n return disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction([source]);\n trx.onerror = event => {\n this.#logger('PCache', 'mapObjects', source, event.target.error);\n reject(event.target.error);\n };\n trx.objectStore(source).getAll().onsuccess = event => {\n if (callback) {\n event.target.result.forEach(topic => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n /**\n * Initialize persistent cache: open or create/upgrade if needed.\n * @returns {Promise} promise to be resolved/rejected when the DB is initialized.\n */\n initDatabase() {\n return new Promise((resolve, reject) => {\n // Open the database and initialize callbacks.\n const req = IDBProvider.open(DB_NAME, DB_VERSION);\n req.onsuccess = event => {\n this.db = event.target.result;\n this.disabled = false;\n resolve(this.db);\n };\n req.onerror = event => {\n this.#logger('PCache', \"failed to initialize\", event);\n reject(event.target.error);\n this.#onError(event.target.error);\n };\n req.onupgradeneeded = event => {\n this.db = event.target.result;\n\n this.db.onerror = event => {\n this.#logger('PCache', \"failed to create storage\", event);\n this.#onError(event.target.error);\n };\n\n // Individual object stores.\n // Object store (table) for topics. The primary key is topic name.\n this.db.createObjectStore('topic', {\n keyPath: 'name'\n });\n\n // Users object store. UID is the primary key.\n this.db.createObjectStore('user', {\n keyPath: 'uid'\n });\n\n // Subscriptions object store topic <-> user. Topic name + UID is the primary key.\n this.db.createObjectStore('subscription', {\n keyPath: ['topic', 'uid']\n });\n\n // Messages object store. The primary key is topic name + seq.\n this.db.createObjectStore('message', {\n keyPath: ['topic', 'seq']\n });\n\n // Records of deleted message ranges. The primary key is topic name + low seq.\n const dellog = this.db.createObjectStore('dellog', {\n keyPath: ['topic', 'low', 'hi']\n });\n dellog.createIndex('topic_clear', ['topic', 'clear'], {\n unique: false\n });\n };\n });\n }\n\n /**\n * Delete persistent cache.\n */\n deleteDatabase() {\n // Close connection, otherwise operations will fail with 'onblocked'.\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n return new Promise((resolve, reject) => {\n const req = IDBProvider.deleteDatabase(DB_NAME);\n req.onblocked = _ => {\n if (this.db) {\n this.db.close();\n }\n const err = new Error(\"blocked\");\n this.#logger('PCache', 'deleteDatabase', err);\n reject(err);\n };\n req.onsuccess = _ => {\n this.db = null;\n this.disabled = true;\n resolve(true);\n };\n req.onerror = event => {\n this.#logger('PCache', 'deleteDatabase', event.target.error);\n reject(event.target.error);\n };\n });\n }\n\n /**\n * Check if persistent cache is ready for use.\n * @memberOf DB\n * @returns {boolean} true if cache is ready, false otherwise.\n */\n isReady() {\n return !!this.db;\n }\n\n // Topics.\n\n /**\n * Save to cache or update topic in persistent cache.\n * @memberOf DB\n * @param {Topic} topic - topic to be added or updated.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updTopic(topic) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updTopic', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(topic.name);\n req.onsuccess = _ => {\n trx.objectStore('topic').put(DB.#serializeTopic(req.result, topic));\n trx.commit();\n };\n });\n }\n\n /**\n * Mark or unmark topic as deleted.\n * @memberOf DB\n * @param {string} name - name of the topic to mark or unmark.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n markTopicAsDeleted(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'markTopicAsDeleted', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(name);\n req.onsuccess = event => {\n const topic = event.target.result;\n topic._deleted = true;\n trx.objectStore('topic').put(topic);\n trx.commit();\n };\n });\n }\n\n /**\n * Remove topic from persistent cache.\n * @memberOf DB\n * @param {string} name - name of the topic to remove from database.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remTopic(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic', 'subscription', 'message'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remTopic', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('topic').delete(IDBKeyRange.only(name));\n trx.objectStore('subscription').delete(IDBKeyRange.bound([name, '-'], [name, '~']));\n trx.objectStore('message').delete(IDBKeyRange.bound([name, 0], [name, Number.MAX_SAFE_INTEGER]));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored topic.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapTopics(callback, context) {\n return this.#mapObjects('topic', callback, context);\n }\n\n /**\n * Copy data from serialized object to topic.\n * @memberOf DB\n * @param {Topic} topic - target to deserialize to.\n * @param {Object} src - serialized data to copy from.\n */\n deserializeTopic(topic, src) {\n DB.#deserializeTopic(topic, src);\n }\n\n // Users.\n /**\n * Add or update user object in the persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to save or update.\n * @param {Object} pub - user's public information.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updUser(uid, pub) {\n if (arguments.length < 2 || pub === undefined) {\n // No point inupdating user with invalid data.\n return;\n }\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').put({\n uid: uid,\n public: pub\n });\n trx.commit();\n });\n }\n\n /**\n * Remove user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to remove from the cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').delete(IDBKeyRange.only(uid));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored user.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapUsers(callback, context) {\n return this.#mapObjects('user', callback, context);\n }\n\n /**\n * Read a single user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to fetch from cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n getUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user']);\n trx.oncomplete = event => {\n const user = event.target.result;\n resolve({\n user: user.uid,\n public: user.public\n });\n };\n trx.onerror = event => {\n this.#logger('PCache', 'getUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').get(uid);\n });\n }\n\n // Subscriptions.\n /**\n * Add or update subscription in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {string} uid - ID of the subscribed user.\n * @param {Object} sub - subscription to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updSubscription(topicName, uid, sub) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updSubscription', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').get([topicName, uid]).onsuccess = (event) => {\n trx.objectStore('subscription').put(DB.#serializeSubscription(event.target.result, topicName, uid, sub));\n trx.commit();\n };\n });\n }\n\n /**\n * Execute a callback for each cached subscription in a given topic.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the subscriptions.\n * @param {function} callback - function to call for each subscription.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapSubscriptions(topicName, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription']);\n trx.onerror = (event) => {\n this.#logger('PCache', 'mapSubscriptions', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').getAll(IDBKeyRange.bound([topicName, '-'], [topicName, '~'])).onsuccess = (event) => {\n if (callback) {\n event.target.result.forEach((topic) => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n // Messages.\n\n /**\n * Save message to persistent cache.\n * @memberOf DB\n * @param {Object} msg - message to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n addMessage(msg) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'addMessage', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').add(DB.#serializeMessage(null, msg));\n trx.commit();\n });\n }\n\n /**\n * Update delivery status of a message stored in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} seq - ID of the message to update\n * @param {number} status - new delivery status of the message.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updMessageStatus(topicName, seq, status) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updMessageStatus', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('message').get(IDBKeyRange.only([topicName, seq]));\n req.onsuccess = event => {\n const src = req.result || event.target.result;\n if (!src || src._status == status) {\n trx.commit();\n return;\n }\n trx.objectStore('message').put(DB.#serializeMessage(src, {\n topic: topicName,\n seq: seq,\n _status: status\n }));\n trx.commit();\n };\n });\n }\n\n /**\n * Remove one or more messages from persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} from - id of the message to remove or lower boundary when removing range (inclusive).\n * @param {number=} to - upper boundary (exclusive) when removing a range of messages.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remMessages(topicName, from, to) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n if (!from && !to) {\n from = 0;\n to = Number.MAX_SAFE_INTEGER;\n }\n const range = to > 0 ? IDBKeyRange.bound([topicName, from], [topicName, to], false, true) :\n IDBKeyRange.only([topicName, from]);\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remMessages', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').delete(range);\n trx.commit();\n });\n }\n\n /**\n * Retrieve messages from persistent store.\n * @memberOf DB\n * @param {string} topicName - name of the topic to retrieve messages from.\n * @param {function} callback to call for each retrieved message.\n * @param {GetDataType} query - parameters of the message range to retrieve.\n *\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n readMessages(topicName, query, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n\n const trx = this.db.transaction(['message']);\n let result = [];\n\n // Handle individual message ranges.\n if (Array.isArray(query.ranges)) {\n return new Promise((resolve, reject) => {\n trx.onerror = event => {\n this.#logger('PCache', 'readMessages', event.target.error);\n reject(event.target.error);\n };\n\n let count = 0;\n query.ranges.forEach(range => {\n const key = range.hi ? IDBKeyRange.bound([topicName, range.low], [topicName, range.hi], false, true) :\n IDBKeyRange.only([topicName, range.low]);\n trx.objectStore('message').getAll(key).onsuccess = event => {\n const msgs = event.target.result;\n if (msgs) {\n if (callback) {\n callback.call(context, msgs);\n }\n if (Array.isArray(msgs)) {\n result = result.concat(msgs);\n } else {\n result.push(msgs);\n }\n }\n count++;\n if (count == query.ranges.length) {\n resolve(result);\n }\n };\n });\n });\n }\n\n return new Promise((resolve, reject) => {\n query = query || {};\n const since = query.since > 0 ? query.since : 0;\n const before = query.before > 0 ? query.before : Number.MAX_SAFE_INTEGER;\n const limit = query.limit | 0;\n\n trx.onerror = event => {\n this.#logger('PCache', 'readMessages', event.target.error);\n reject(event.target.error);\n };\n\n const range = IDBKeyRange.bound([topicName, since], [topicName, before], false, true);\n // Iterate in descending order.\n trx.objectStore('message').openCursor(range, 'prev')\n .onsuccess = event => {\n const cursor = event.target.result;\n if (cursor) {\n if (callback) {\n callback.call(context, cursor.value);\n }\n result.push(cursor.value);\n if (limit <= 0 || result.length < limit) {\n cursor.continue();\n } else {\n resolve(result);\n }\n } else {\n resolve(result);\n }\n };\n });\n }\n\n // Delete log\n\n /**\n * Add records of deleted messages.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} delId - id of the deletion transaction.\n * @param {Array.require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IDBProvider = idbProvider;\n }\n}\n","/**\n * @file Utilities for uploading and downloading files.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n isUrlRelative,\n jsonParseHelper\n} from './utils.js';\n\nlet XHRProvider;\n\nfunction addURLParam(relUrl, key, value) {\n const url = new URL(relUrl, window.location.origin);\n url.searchParams.append(key, value);\n return url.toString().substring(window.location.origin.length);\n}\n\n/**\n * @class LargeFileHelper - utilities for uploading and downloading files out of band.\n * Don't instantiate this class directly. Use {Tinode.getLargeFileHelper} instead.\n * @memberof Tinode\n *\n * @param {Tinode} tinode - the main Tinode object.\n * @param {string} version - protocol version, i.e. '0'.\n */\nexport default class LargeFileHelper {\n constructor(tinode, version) {\n this._tinode = tinode;\n this._version = version;\n\n this._apiKey = tinode._apiKey;\n this._authToken = tinode.getAuthToken();\n\n // Ongoing requests.\n this.xhr = [];\n }\n\n /**\n * Start uploading the file to an endpoint at baseUrl.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} baseUrl base URL of upload server.\n * @param {File|Blob} data data to upload.\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure) {\n let url = `/v${this._version}/file/u/`;\n if (baseUrl) {\n let base = baseUrl;\n if (base.endsWith('/')) {\n // Removing trailing slash.\n base = base.slice(0, -1);\n }\n if (base.startsWith('http://') || base.startsWith('https://')) {\n url = base + url;\n } else {\n throw new Error(`Invalid base URL '${baseUrl}'`);\n }\n }\n\n const instance = this;\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n xhr.open('POST', url, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n if (this._authToken) {\n xhr.setRequestHeader('X-Tinode-Auth', `Token ${this._authToken.token}`);\n }\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n xhr.upload.onprogress = e => {\n if (e.lengthComputable) {\n if (onProgress) {\n onProgress(e.loaded / e.total);\n }\n if (this.onProgress) {\n this.onProgress(e.loaded / e.total);\n }\n }\n };\n\n xhr.onload = function() {\n let pkt;\n try {\n pkt = JSON.parse(this.response, jsonParseHelper);\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.response);\n pkt = {\n ctrl: {\n code: this.status,\n text: this.statusText\n }\n };\n }\n\n if (this.status >= 200 && this.status < 300) {\n if (toResolve) {\n toResolve(pkt.ctrl.params.url);\n }\n if (onSuccess) {\n onSuccess(pkt.ctrl);\n }\n } else if (this.status >= 400) {\n if (toReject) {\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n }\n if (onFailure) {\n onFailure(pkt.ctrl);\n }\n } else {\n instance._tinode.logger(\"ERROR: Unexpected server response status\", this.status, this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(e || new Error(\"failed\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n xhr.onabort = function(e) {\n if (toReject) {\n toReject(new Error(\"upload cancelled by user\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n try {\n const form = new FormData();\n form.append('file', data);\n form.set('id', this._tinode.getNextUniqueId());\n if (avatarFor) {\n form.set('topic', avatarFor);\n }\n xhr.send(form);\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onFailure) {\n onFailure(null);\n }\n }\n\n return result;\n }\n /**\n * Start uploading the file to default endpoint.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {File|Blob} data to upload\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n upload(data, avatarFor, onProgress, onSuccess, onFailure) {\n const baseUrl = (this._tinode._secure ? 'https://' : 'http://') + this._tinode._host;\n return this.uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure);\n }\n /**\n * Download the file from a given URL using GET request. This method works with the Tinode server only.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} relativeUrl - URL to download the file from. Must be relative url, i.e. must not contain the host.\n * @param {string=} filename - file name to use for the downloaded file.\n *\n * @returns {Promise} resolved/rejected when the download is completed/failed.\n */\n download(relativeUrl, filename, mimetype, onProgress, onError) {\n if (!isUrlRelative(relativeUrl)) {\n // As a security measure refuse to download from an absolute URL.\n if (onError) {\n onError(`The URL '${relativeUrl}' must be relative, not absolute`);\n }\n return;\n }\n if (!this._authToken) {\n if (onError) {\n onError(\"Must authenticate first\");\n }\n return;\n }\n const instance = this;\n\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n // Add '&asatt=1' to URL to request 'Content-Disposition: attachment' response header.\n relativeUrl = addURLParam(relativeUrl, 'asatt', '1');\n\n // Get data as blob (stored by the browser as a temporary file).\n xhr.open('GET', relativeUrl, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n xhr.setRequestHeader('X-Tinode-Auth', 'Token ' + this._authToken.token);\n xhr.responseType = 'blob';\n\n xhr.onprogress = function(e) {\n if (onProgress) {\n // Passing e.loaded instead of e.loaded/e.total because e.total\n // is always 0 with gzip compression enabled by the server.\n onProgress(e.loaded);\n }\n };\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n // The blob needs to be saved as file. There is no known way to\n // save the blob as file other than to fake a click on an .\n xhr.onload = function() {\n if (this.status == 200) {\n const link = document.createElement('a');\n // URL.createObjectURL is not available in non-browser environment. This call will fail.\n link.href = window.URL.createObjectURL(new Blob([this.response], {\n type: mimetype\n }));\n link.style.display = 'none';\n link.setAttribute('download', filename);\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n window.URL.revokeObjectURL(link.href);\n if (toResolve) {\n toResolve();\n }\n } else if (this.status >= 400 && toReject) {\n // The this.responseText is undefined, must use this.response which is a blob.\n // Need to convert this.response to JSON. The blob can only be accessed by the\n // FileReader.\n const reader = new FileReader();\n reader.onload = function() {\n try {\n const pkt = JSON.parse(this.result, jsonParseHelper);\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.result);\n toReject(err);\n }\n };\n reader.readAsText(this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(new Error(\"failed\"));\n }\n if (onError) {\n onError(e);\n }\n };\n\n xhr.onabort = function() {\n if (toReject) {\n toReject(null);\n }\n };\n\n try {\n xhr.send();\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onError) {\n onError(err);\n }\n }\n\n return result;\n }\n /**\n * Try to cancel all ongoing uploads or downloads.\n * @memberof Tinode.LargeFileHelper#\n */\n cancel() {\n this.xhr.forEach(req => {\n if (req.readyState < 4) {\n req.abort();\n }\n });\n }\n /**\n * To use LargeFileHelper in a non browser context, supply XMLHttpRequest provider.\n * @static\n * @memberof LargeFileHelper\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProvider(xhrProvider) {\n XHRProvider = xhrProvider;\n }\n}\n","/**\n * @module tinode-sdk\n *\n * @copyright 2015-2022 Tinode LLC.\n * @summary Javascript bindings for Tinode.\n * @license Apache 2.0\n * @version 0.20\n *\n * See https://github.com/tinode/webapp for real-life usage.\n *\n * @example\n * \n * \n * \n *\n * \n * ...\n * \n * \n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nimport AccessMode from './access-mode.js';\nimport * as Const from './config.js';\nimport CommError from './comm-error.js';\nimport Connection from './connection.js';\nimport DBCache from './db.js';\nimport Drafty from './drafty.js';\nimport LargeFileHelper from './large-file.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport Topic from './topic.js';\nimport TopicFnd from './fnd-topic.js';\nimport TopicMe from './me-topic.js';\n\nimport {\n isUrlRelative,\n jsonParseHelper,\n mergeObj,\n rfc3339DateString,\n simplify\n} from './utils.js';\n\n// Re-export AccessMode\nexport {\n AccessMode\n};\n\nlet WebSocketProvider;\nif (typeof WebSocket != 'undefined') {\n WebSocketProvider = WebSocket;\n}\n\nlet XHRProvider;\nif (typeof XMLHttpRequest != 'undefined') {\n XHRProvider = XMLHttpRequest;\n}\n\nlet IndexedDBProvider;\nif (typeof indexedDB != 'undefined') {\n IndexedDBProvider = indexedDB;\n}\n\n// Re-export Drafty.\nexport {\n Drafty\n}\n\ninitForNonBrowserApp();\n\n// Utility functions\n\n// Polyfill for non-browser context, e.g. NodeJs.\nfunction initForNonBrowserApp() {\n // Tinode requirement in native mode because react native doesn't provide Base64 method\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\n if (typeof btoa == 'undefined') {\n global.btoa = function(input = '') {\n let str = input;\n let output = '';\n\n for (let block = 0, charCode, i = 0, map = chars; str.charAt(i | 0) || (map = '=', i % 1); output += map.charAt(63 & block >> 8 - i % 1 * 8)) {\n\n charCode = str.charCodeAt(i += 3 / 4);\n\n if (charCode > 0xFF) {\n throw new Error(\"'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.\");\n }\n block = block << 8 | charCode;\n }\n\n return output;\n };\n }\n\n if (typeof atob == 'undefined') {\n global.atob = function(input = '') {\n let str = input.replace(/=+$/, '');\n let output = '';\n\n if (str.length % 4 == 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (let bc = 0, bs = 0, buffer, i = 0; buffer = str.charAt(i++);\n\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n }\n\n if (typeof window == 'undefined') {\n global.window = {\n WebSocket: WebSocketProvider,\n XMLHttpRequest: XHRProvider,\n indexedDB: IndexedDBProvider,\n URL: {\n createObjectURL: function() {\n throw new Error(\"Unable to use URL.createObjectURL in a non-browser application\");\n }\n }\n }\n }\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n DBCache.setDatabaseProvider(IndexedDBProvider);\n}\n\n// Detect find most useful network transport.\nfunction detectTransport() {\n if (typeof window == 'object') {\n if (window['WebSocket']) {\n return 'ws';\n } else if (window['XMLHttpRequest']) {\n // The browser or node has no websockets, using long polling.\n return 'lp';\n }\n }\n return null;\n}\n\n// btoa replacement. Stock btoa fails on on non-Latin1 strings.\nfunction b64EncodeUnicode(str) {\n // The encodeURIComponent percent-encodes UTF-8 string,\n // then the percent encoding is converted into raw bytes which\n // can be fed into btoa.\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,\n function toSolidBytes(match, p1) {\n return String.fromCharCode('0x' + p1);\n }));\n}\n\n// JSON stringify helper - pre-processor for JSON.stringify\nfunction jsonBuildHelper(key, val) {\n if (val instanceof Date) {\n // Convert javascript Date objects to rfc3339 strings\n val = rfc3339DateString(val);\n } else if (val instanceof AccessMode) {\n val = val.jsonHelper();\n } else if (val === undefined || val === null || val === false ||\n (Array.isArray(val) && val.length == 0) ||\n ((typeof val == 'object') && (Object.keys(val).length == 0))) {\n // strip out empty elements while serializing objects to JSON\n return undefined;\n }\n\n return val;\n};\n\n// Trims very long strings (encoded images) to make logged packets more readable.\nfunction jsonLoggerHelper(key, val) {\n if (typeof val == 'string' && val.length > 128) {\n return '<' + val.length + ', bytes: ' + val.substring(0, 12) + '...' + val.substring(val.length - 12) + '>';\n }\n return jsonBuildHelper(key, val);\n};\n\n// Parse browser user agent to extract browser name and version.\nfunction getBrowserInfo(ua, product) {\n ua = ua || '';\n let reactnative = '';\n // Check if this is a ReactNative app.\n if (/reactnative/i.test(product)) {\n reactnative = 'ReactNative; ';\n }\n let result;\n // Remove useless string.\n ua = ua.replace(' (KHTML, like Gecko)', '');\n // Test for WebKit-based browser.\n let m = ua.match(/(AppleWebKit\\/[.\\d]+)/i);\n if (m) {\n // List of common strings, from more useful to less useful.\n // All unknown strings get the highest (-1) priority.\n const priority = ['edg', 'chrome', 'safari', 'mobile', 'version'];\n let tmp = ua.substr(m.index + m[0].length).split(' ');\n let tokens = [];\n let version; // 1.0 in Version/1.0 or undefined;\n // Split string like 'Name/0.0.0' into ['Name', '0.0.0', 3] where the last element is the priority.\n for (let i = 0; i < tmp.length; i++) {\n let m2 = /([\\w.]+)[\\/]([\\.\\d]+)/.exec(tmp[i]);\n if (m2) {\n // Unknown values are highest priority (-1).\n tokens.push([m2[1], m2[2], priority.findIndex((e) => {\n return m2[1].toLowerCase().startsWith(e);\n })]);\n if (m2[1] == 'Version') {\n version = m2[2];\n }\n }\n }\n // Sort by priority: more interesting is earlier than less interesting.\n tokens.sort((a, b) => {\n return a[2] - b[2];\n });\n if (tokens.length > 0) {\n // Return the least common browser string and version.\n if (tokens[0][0].toLowerCase().startsWith('edg')) {\n tokens[0][0] = 'Edge';\n } else if (tokens[0][0] == 'OPR') {\n tokens[0][0] = 'Opera';\n } else if (tokens[0][0] == 'Safari' && version) {\n tokens[0][1] = version;\n }\n result = tokens[0][0] + '/' + tokens[0][1];\n } else {\n // Failed to ID the browser. Return the webkit version.\n result = m[1];\n }\n } else if (/firefox/i.test(ua)) {\n m = /Firefox\\/([.\\d]+)/g.exec(ua);\n if (m) {\n result = 'Firefox/' + m[1];\n } else {\n result = 'Firefox/?';\n }\n } else {\n // Neither AppleWebKit nor Firefox. Try the last resort.\n m = /([\\w.]+)\\/([.\\d]+)/.exec(ua);\n if (m) {\n result = m[1] + '/' + m[2];\n } else {\n m = ua.split(' ');\n result = m[0];\n }\n }\n\n // Shorten the version to one dot 'a.bb.ccc.d -> a.bb' at most.\n m = result.split('/');\n if (m.length > 1) {\n const v = m[1].split('.');\n const minor = v[1] ? '.' + v[1].substr(0, 2) : '';\n result = `${m[0]}/${v[0]}${minor}`;\n }\n return reactnative + result;\n}\n\n/**\n * The main class for interacting with Tinode server.\n */\nexport class Tinode {\n _host;\n _secure;\n\n _appName;\n\n // API Key.\n _apiKey;\n\n // Name and version of the browser.\n _browser = '';\n _platform;\n // Hardware\n _hwos = 'undefined';\n _humanLanguage = 'xx';\n\n // Logging to console enabled\n _loggingEnabled = false;\n // When logging, trip long strings (base64-encoded images) for readability\n _trimLongStrings = false;\n // UID of the currently authenticated user.\n _myUID = null;\n // Status of connection: authenticated or not.\n _authenticated = false;\n // Login used in the last successful basic authentication\n _login = null;\n // Token which can be used for login instead of login/password.\n _authToken = null;\n // Counter of received packets\n _inPacketCount = 0;\n // Counter for generating unique message IDs\n _messageId = Math.floor((Math.random() * 0xFFFF) + 0xFFFF);\n // Information about the server, if connected\n _serverInfo = null;\n // Push notification token. Called deviceToken for consistency with the Android SDK.\n _deviceToken = null;\n\n // Cache of pending promises by message id.\n _pendingPromises = {};\n // The Timeout object returned by the reject expired promises setInterval.\n _expirePromises = null;\n\n // Websocket or long polling connection.\n _connection = null;\n\n // Use indexDB for caching topics and messages.\n _persist = false;\n // IndexedDB wrapper object.\n _db = null;\n\n // Tinode's cache of objects\n _cache = {};\n\n /**\n * Create Tinode object.\n *\n * @param {Object} config - configuration parameters.\n * @param {string} config.appName - Name of the calling application to be reported in the User Agent.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - See {@link Tinode.Connection#transport}.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} config.platform - Optional platform identifier, one of \"ios\", \"web\", \"android\".\n * @param {boolen} config.persist - Use IndexedDB persistent storage.\n * @param {function} onComplete - callback to call when initialization is completed.\n */\n constructor(config, onComplete) {\n this._host = config.host;\n this._secure = config.secure;\n\n // Client-provided application name, format null if no valid credentials were given.\n */\n static credential(meth, val, params, resp) {\n if (typeof meth == 'object') {\n ({\n val,\n params,\n resp,\n meth\n } = meth);\n }\n if (meth && (val || resp)) {\n return [{\n 'meth': meth,\n 'val': val,\n 'resp': resp,\n 'params': params\n }];\n }\n return null;\n }\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n return Topic.topicType(name);\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.isMeTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a group topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.isGroupTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.isP2PTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isCommTopicName(name);\n }\n /**\n * Check if the topic name is a name of a new topic.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return Topic.isNewGroupTopicName(name);\n }\n /**\n * Check if the topic name is a name of a channel.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return Topic.isChannelTopicName(name);\n }\n /**\n * Get information about the current version of this Tinode client library.\n * @returns {string} semantic version of the library, e.g. \"0.15.5-rc1\".\n */\n static getVersion() {\n return Const.VERSION;\n }\n /**\n * To use Tinode in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n *\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n }\n /**\n * To use Tinode in a non browser context, supply indexedDB provider.\n * @static\n *\n * @param idbProvider indexedDB provider, e.g. for nodeJS , require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IndexedDBProvider = idbProvider;\n\n DBCache.setDatabaseProvider(IndexedDBProvider);\n }\n /**\n * Return information about the current name and version of this Tinode library.\n * @static\n *\n * @returns {string} the name of the library and it's version.\n */\n static getLibrary() {\n return Const.LIBRARY;\n }\n /**\n * Check if the given string represents NULL value as defined by Tinode ('\\u2421').\n * @param {string} str - string to check for NULL value.\n * @returns {boolean} true if string represents NULL value, false otherwise.\n */\n static isNullValue(str) {\n return str === Const.DEL_CHAR;\n }\n\n // Instance methods.\n\n // Generates unique message IDs\n getNextUniqueId() {\n return (this._messageId != 0) ? '' + this._messageId++ : undefined;\n };\n\n /**\n * Connect to the server.\n *\n * @param {string} host_ - name of the host to connect to.\n * @return {Promise} Promise resolved/rejected when the connection call completes:\n * resolve() is called without parameters, reject() receives the\n * Error as a single parameter.\n */\n connect(host_) {\n return this._connection.connect(host_);\n }\n\n /**\n * Attempt to reconnect to the server immediately.\n *\n * @param {string} force - if true, reconnect even if there is a connection already.\n */\n reconnect(force) {\n this._connection.reconnect(force);\n }\n\n /**\n * Disconnect from the server.\n */\n disconnect() {\n this._connection.disconnect();\n }\n\n /**\n * Clear persistent cache: remove IndexedDB.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n clearStorage() {\n if (this._db.isReady()) {\n return this._db.deleteDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Initialize persistent cache: create IndexedDB cache.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n initStorage() {\n if (!this._db.isReady()) {\n return this._db.initDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Send a network probe message to make sure the connection is alive.\n */\n networkProbe() {\n this._connection.probe();\n }\n\n /**\n * Check for live connection to server.\n *\n * @returns {boolean} true if there is a live connection, false otherwise.\n */\n isConnected() {\n return this._connection.isConnected();\n }\n\n /**\n * Check if connection is authenticated (last login was successful).\n *\n * @returns {boolean} true if authenticated, false otherwise.\n */\n isAuthenticated() {\n return this._authenticated;\n }\n\n /**\n * Add API key and auth token to the relative URL making it usable for getting data\n * from the server in a simple HTTP GET request.\n *\n * @param {string} URL - URL to wrap.\n * @returns {string} URL with appended API key and token, if valid token is present.\n */\n authorizeURL(url) {\n if (typeof url != 'string') {\n return url;\n }\n\n if (isUrlRelative(url)) {\n // Fake base to make the relative URL parseable.\n const base = 'scheme://host/';\n const parsed = new URL(url, base);\n if (this._apiKey) {\n parsed.searchParams.append('apikey', this._apiKey);\n }\n if (this._authToken && this._authToken.token) {\n parsed.searchParams.append('auth', 'token');\n parsed.searchParams.append('secret', this._authToken.token);\n }\n // Convert back to string and strip fake base URL except for the root slash.\n url = parsed.toString().substring(base.length - 1);\n }\n return url;\n }\n\n /**\n * @typedef AccountParams\n * @type {Object}\n * @property {DefAcs=} defacs - Default access parameters for user's me topic.\n * @property {Object=} public - Public application-defined data exposed on me topic.\n * @property {Object=} private - Private application-defined data accessible on me topic.\n * @property {Object=} trusted - Trusted user data which can be set by a root user only.\n * @property {Array.me for authenticated users.\n * @property {string=} anon - Access mode for me for anonymous users.\n */\n\n /**\n * Create or update an account.\n *\n * @param {string} uid - User id to update\n * @param {string} scheme - Authentication scheme; \"basic\" and \"anonymous\" are the currently supported schemes.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n account(uid, scheme, secret, login, params) {\n const pkt = this.#initPacket('acc');\n pkt.acc.user = uid;\n pkt.acc.scheme = scheme;\n pkt.acc.secret = secret;\n // Log in to the new account using selected scheme\n pkt.acc.login = login;\n\n if (params) {\n pkt.acc.desc.defacs = params.defacs;\n pkt.acc.desc.public = params.public;\n pkt.acc.desc.private = params.private;\n pkt.acc.desc.trusted = params.trusted;\n\n pkt.acc.tags = params.tags;\n pkt.acc.cred = params.cred;\n\n pkt.acc.tmpscheme = params.scheme;\n pkt.acc.tmpsecret = params.secret;\n\n if (Array.isArray(params.attachments) && params.attachments.length > 0) {\n pkt.extra = {\n attachments: params.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n }\n\n return this.#send(pkt, pkt.acc.id);\n }\n\n /**\n * Create a new user. Wrapper for {@link Tinode#account}.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccount(scheme, secret, login, params) {\n let promise = this.account(Const.USER_NEW, scheme, secret, login, params);\n if (login) {\n promise = promise.then(ctrl => this.#loginSuccessful(ctrl));\n }\n return promise;\n }\n\n /**\n * Create user with 'basic' authentication scheme and immediately\n * use it for authentication. Wrapper for {@link Tinode#account}.\n *\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccountBasic(username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.createAccount('basic',\n b64EncodeUnicode(username + ':' + password), true, params);\n }\n\n /**\n * Update user's credentials for 'basic' authentication scheme. Wrapper for {@link Tinode#account}.\n *\n * @param {string} uid - User ID to update.\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n updateAccountBasic(uid, username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.account(uid, 'basic',\n b64EncodeUnicode(username + ':' + password), false, params);\n }\n\n /**\n * Send handshake to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n hello() {\n const pkt = this.#initPacket('hi');\n\n return this.#send(pkt, pkt.hi.id)\n .then(ctrl => {\n // Reset backoff counter on successful connection.\n this._connection.backoffReset();\n\n // Server response contains server protocol version, build, constraints,\n // session ID for long polling. Save them.\n if (ctrl.params) {\n this._serverInfo = ctrl.params;\n }\n\n if (this.onConnect) {\n this.onConnect();\n }\n\n return ctrl;\n }).catch(err => {\n this._connection.reconnect(true);\n\n if (this.onDisconnect) {\n this.onDisconnect(err);\n }\n });\n }\n\n /**\n * Set or refresh the push notifications/device token. If the client is connected,\n * the deviceToken can be sent to the server.\n *\n * @param {string} dt - token obtained from the provider or false,\n * null or undefined to clear the token.\n *\n * @returns true if attempt was made to send the update to the server.\n */\n setDeviceToken(dt) {\n let sent = false;\n // Convert any falsish value to null.\n dt = dt || null;\n if (dt != this._deviceToken) {\n this._deviceToken = dt;\n if (this.isConnected() && this.isAuthenticated()) {\n this.#send({\n 'hi': {\n 'dev': dt || Tinode.DEL_CHAR\n }\n });\n sent = true;\n }\n }\n return sent;\n }\n\n /**\n * @typedef Credential\n * @type {Object}\n * @property {string} meth - validation method.\n * @property {string} val - value to validate (e.g. email or phone number).\n * @property {string} resp - validation response.\n * @property {Object} params - validation parameters.\n */\n /**\n * Authenticate current session.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n login(scheme, secret, cred) {\n const pkt = this.#initPacket('login');\n pkt.login.scheme = scheme;\n pkt.login.secret = secret;\n pkt.login.cred = cred;\n\n return this.#send(pkt, pkt.login.id)\n .then(ctrl => this.#loginSuccessful(ctrl));\n }\n\n /**\n * Wrapper for {@link Tinode#login} with basic authentication\n *\n * @param {string} uname - User name.\n * @param {string} password - Password.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginBasic(uname, password, cred) {\n return this.login('basic', b64EncodeUnicode(uname + ':' + password), cred)\n .then(ctrl => {\n this._login = uname;\n return ctrl;\n });\n }\n\n /**\n * Wrapper for {@link Tinode#login} with token authentication\n *\n * @param {string} token - Token received in response to earlier login.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginToken(token, cred) {\n return this.login('token', token, cred);\n }\n\n /**\n * Send a request for resetting an authentication secret.\n *\n * @param {string} scheme - authentication scheme to reset.\n * @param {string} method - method to use for resetting the secret, such as \"email\" or \"tel\".\n * @param {string} value - value of the credential to use, a specific email address or a phone number.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving the server reply.\n */\n requestResetAuthSecret(scheme, method, value) {\n return this.login('reset', b64EncodeUnicode(scheme + ':' + method + ':' + value));\n }\n\n /**\n * @typedef AuthToken\n * @type {Object}\n * @property {string} token - Token value.\n * @property {Date} expires - Token expiration time.\n */\n /**\n * Get stored authentication token.\n *\n * @returns {AuthToken} authentication token.\n */\n getAuthToken() {\n if (this._authToken && (this._authToken.expires.getTime() > Date.now())) {\n return this._authToken;\n } else {\n this._authToken = null;\n }\n return null;\n }\n\n /**\n * Application may provide a saved authentication token.\n *\n * @param {AuthToken} token - authentication token.\n */\n setAuthToken(token) {\n this._authToken = token;\n }\n\n /**\n * @typedef SetParams\n * @type {Object}\n * @property {SetDesc=} desc - Topic initialization parameters when creating a new topic or a new subscription.\n * @property {SetSub=} sub - Subscription initialization parameters.\n * @property {Array.true, detach and unsubscribe, otherwise just detach.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n leave(topic, unsub) {\n const pkt = this.#initPacket('leave', topic);\n pkt.leave.unsub = unsub;\n\n return this.#send(pkt, pkt.leave.id);\n }\n\n /**\n * Create message draft without sending it to the server.\n *\n * @param {string} topic - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Object} new message which can be sent to the server or otherwise used.\n */\n createMessage(topic, content, noEcho) {\n const pkt = this.#initPacket('pub', topic);\n\n let dft = typeof content == 'string' ? Drafty.parse(content) : content;\n if (dft && !Drafty.isPlainText(dft)) {\n pkt.pub.head = {\n mime: Drafty.getContentType()\n };\n content = dft;\n }\n pkt.pub.noecho = noEcho;\n pkt.pub.content = content;\n\n return pkt.pub;\n }\n\n /**\n * Publish {data} message to topic.\n *\n * @param {string} topicName - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n publish(topicName, content, noEcho) {\n return this.publishMessage(\n this.createMessage(topicName, content, noEcho)\n );\n }\n\n /**\n * Publish message to topic. The message should be created by {@link Tinode#createMessage}.\n *\n * @param {Object} pub - Message to publish.\n * @param {Array.'me' topic.\n *\n * @param {string} method - validation method such as 'email' or 'tel'.\n * @param {string} value - validation value, i.e. 'alice@example.com'.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n const pkt = this.#initPacket('del', Const.TOPIC_ME);\n pkt.del.what = 'cred';\n pkt.del.cred = {\n meth: method,\n val: value\n };\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Request to delete account of the current user.\n *\n * @param {boolean} hard - hard-delete user.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCurrentUser(hard) {\n const pkt = this.#initPacket('del', null);\n pkt.del.what = 'user';\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id).then(_ => {\n this._myUID = null;\n });\n }\n\n /**\n * Notify server that a message or messages were read or received. Does NOT return promise.\n *\n * @param {string} topicName - Name of the topic where the mesage is being aknowledged.\n * @param {string} what - Action being aknowledged, either \"read\" or \"recv\".\n * @param {number} seq - Maximum id of the message being acknowledged.\n */\n note(topicName, what, seq) {\n if (seq <= 0 || seq >= Const.LOCAL_SEQID) {\n throw new Error(`Invalid message id ${seq}`);\n }\n\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = what;\n pkt.note.seq = seq;\n this.#send(pkt);\n }\n\n /**\n * Broadcast a key-press notification to topic subscribers. Used to show\n * typing notifications \"user X is typing...\".\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {string=} type - notification to send, default is 'kp'.\n */\n noteKeyPress(topicName, type) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = type || 'kp';\n this.#send(pkt);\n }\n\n /**\n * Send a video call notification to topic subscribers (including dialing,\n * hangup, etc.).\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} evt - Call event.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(topicName, seq, evt, payload) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.seq = seq;\n pkt.note.what = 'call';\n pkt.note.event = evt;\n pkt.note.payload = payload;\n this.#send(pkt, pkt.note.id);\n }\n\n /**\n * Get a named topic, either pull it from cache or create a new instance.\n * There is a single instance of topic for each name.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested or newly created topic or undefined if topic name is invalid.\n */\n getTopic(topicName) {\n let topic = this.#cacheGet('topic', topicName);\n if (!topic && topicName) {\n if (topicName == Const.TOPIC_ME) {\n topic = new TopicMe();\n } else if (topicName == Const.TOPIC_FND) {\n topic = new TopicFnd();\n } else {\n topic = new Topic(topicName);\n }\n // Cache management.\n this.#attachCacheToTopic(topic);\n topic._cachePutSelf();\n // Don't save to DB here: a record will be added when the topic is subscribed.\n }\n return topic;\n }\n\n /**\n * Get a named topic from cache.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested topic or undefined if topic is not found in cache.\n */\n cacheGetTopic(topicName) {\n return this.#cacheGet('topic', topicName);\n }\n\n /**\n * Remove named topic from cache.\n *\n * @param {string} topicName - Name of the topic to remove from cache.\n */\n cacheRemTopic(topicName) {\n this.#cacheDel('topic', topicName);\n }\n\n /**\n * Iterate over cached topics.\n *\n * @param {Function} func - callback to call for each topic.\n * @param {Object} context - 'this' inside the 'func'.\n */\n mapTopics(func, context) {\n this.#cacheMap('topic', func, context);\n }\n\n /**\n * Check if named topic is already present in cache.\n *\n * @param {string} topicName - Name of the topic to check.\n * @returns {boolean} true if topic is found in cache, false otherwise.\n */\n isTopicCached(topicName) {\n return !!this.#cacheGet('topic', topicName);\n }\n\n /**\n * Generate unique name like 'new123456' suitable for creating a new group topic.\n *\n * @param {boolean} isChan - if the topic is channel-enabled.\n * @returns {string} name which can be used for creating a new group topic.\n */\n newGroupTopicName(isChan) {\n return (isChan ? Const.TOPIC_NEW_CHAN : Const.TOPIC_NEW) + this.getNextUniqueId();\n }\n\n /**\n * Instantiate 'me' topic or get it from cache.\n *\n * @returns {TopicMe} Instance of 'me' topic.\n */\n getMeTopic() {\n return this.getTopic(Const.TOPIC_ME);\n }\n\n /**\n * Instantiate 'fnd' (find) topic or get it from cache.\n *\n * @returns {Topic} Instance of 'fnd' topic.\n */\n getFndTopic() {\n return this.getTopic(Const.TOPIC_FND);\n }\n\n /**\n * Create a new {@link LargeFileHelper} instance\n *\n * @returns {LargeFileHelper} instance of a {@link Tinode.LargeFileHelper}.\n */\n getLargeFileHelper() {\n return new LargeFileHelper(this, Const.PROTOCOL_VERSION);\n }\n\n /**\n * Get the UID of the the current authenticated user.\n *\n * @returns {string} UID of the current user or undefined if the session is not yet\n * authenticated or if there is no session.\n */\n getCurrentUserID() {\n return this._myUID;\n }\n\n /**\n * Check if the given user ID is equal to the current user's UID.\n *\n * @param {string} uid - UID to check.\n *\n * @returns {boolean} true if the given UID belongs to the current logged in user.\n */\n isMe(uid) {\n return this._myUID === uid;\n }\n\n /**\n * Get login used for last successful authentication.\n *\n * @returns {string} login last used successfully or undefined.\n */\n getCurrentLogin() {\n return this._login;\n }\n\n /**\n * Return information about the server: protocol version and build timestamp.\n *\n * @returns {Object} build and version of the server or null if there is no connection or\n * if the first server response has not been received yet.\n */\n getServerInfo() {\n return this._serverInfo;\n }\n\n /**\n * Report a topic for abuse. Wrapper for {@link Tinode#publish}.\n *\n * @param {string} action - the only supported action is 'report'.\n * @param {string} target - name of the topic being reported.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n report(action, target) {\n return this.publish(Const.TOPIC_SYS, Drafty.attachJSON(null, {\n 'action': action,\n 'target': target\n }));\n }\n\n /**\n * Return server-provided configuration value.\n *\n * @param {string} name of the value to return.\n * @param {Object} defaultValue to return in case the parameter is not set or not found.\n *\n * @returns {Object} named value.\n */\n getServerParam(name, defaultValue) {\n return this._serverInfo && this._serverInfo[name] || defaultValue;\n }\n\n /**\n * Toggle console logging. Logging is off by default.\n *\n * @param {boolean} enabled - Set to true to enable logging to console.\n * @param {boolean} trimLongStrings - Set to true to trim long strings.\n */\n enableLogging(enabled, trimLongStrings) {\n this._loggingEnabled = enabled;\n this._trimLongStrings = enabled && trimLongStrings;\n }\n\n /**\n * Set UI language to report to the server. Must be called before 'hi' is sent, otherwise it will not be used.\n *\n * @param {string} hl - human (UI) language, like \"en_US\" or \"zh-Hans\".\n */\n setHumanLanguage(hl) {\n if (hl) {\n this._humanLanguage = hl;\n }\n }\n\n /**\n * Check if given topic is online.\n *\n * @param {string} name of the topic to test.\n * @returns {boolean} true if topic is online, false otherwise.\n */\n isTopicOnline(name) {\n const topic = this.#cacheGet('topic', name);\n return topic && topic.online;\n }\n\n /**\n * Get access mode for the given contact.\n *\n * @param {string} name of the topic to query.\n * @returns {AccessMode} access mode if topic is found, null otherwise.\n */\n getTopicAccessMode(name) {\n const topic = this.#cacheGet('topic', name);\n return topic ? topic.acs : null;\n }\n\n /**\n * Include message ID into all subsequest messages to server instructin it to send aknowledgemens.\n * Required for promises to function. Default is \"on\".\n *\n * @param {boolean} status - Turn aknowledgemens on or off.\n * @deprecated\n */\n wantAkn(status) {\n if (status) {\n this._messageId = Math.floor((Math.random() * 0xFFFFFF) + 0xFFFFFF);\n } else {\n this._messageId = 0;\n }\n }\n\n // Callbacks:\n /**\n * Callback to report when the websocket is opened. The callback has no parameters.\n *\n * @type {onWebsocketOpen}\n */\n onWebsocketOpen = undefined;\n\n /**\n * @typedef ServerParams\n *\n * @type {Object}\n * @property {string} ver - Server version\n * @property {string} build - Server build\n * @property {string=} sid - Session ID, long polling connections only.\n */\n\n /**\n * @callback onConnect\n * @param {number} code - Result code\n * @param {string} text - Text epxplaining the completion, i.e \"OK\" or an error message.\n * @param {ServerParams} params - Parameters returned by the server.\n */\n /**\n * Callback to report when connection with Tinode server is established.\n * @type {onConnect}\n */\n onConnect = undefined;\n\n /**\n * Callback to report when connection is lost. The callback has no parameters.\n * @type {onDisconnect}\n */\n onDisconnect = undefined;\n\n /**\n * @callback onLogin\n * @param {number} code - NUmeric completion code, same as HTTP status codes.\n * @param {string} text - Explanation of the completion code.\n */\n /**\n * Callback to report login completion.\n * @type {onLogin}\n */\n onLogin = undefined;\n\n /**\n * Callback to receive {ctrl} (control) messages.\n * @type {onCtrlMessage}\n */\n onCtrlMessage = undefined;\n\n /**\n * Callback to recieve {data} (content) messages.\n * @type {onDataMessage}\n */\n onDataMessage = undefined;\n\n /**\n * Callback to receive {pres} (presence) messages.\n * @type {onPresMessage}\n */\n onPresMessage = undefined;\n\n /**\n * Callback to receive all messages as objects.\n * @type {onMessage}\n */\n onMessage = undefined;\n\n /**\n * Callback to receive all messages as unparsed text.\n * @type {onRawMessage}\n */\n onRawMessage = undefined;\n\n /**\n * Callback to receive server responses to network probes. See {@link Tinode#networkProbe}\n * @type {onNetworkProbe}\n */\n onNetworkProbe = undefined;\n\n /**\n * Callback to be notified when exponential backoff is iterating.\n * @type {onAutoreconnectIteration}\n */\n onAutoreconnectIteration = undefined;\n};\n\n// Exported constants\nTinode.MESSAGE_STATUS_NONE = Const.MESSAGE_STATUS_NONE;\nTinode.MESSAGE_STATUS_QUEUED = Const.MESSAGE_STATUS_QUEUED;\nTinode.MESSAGE_STATUS_SENDING = Const.MESSAGE_STATUS_SENDING;\nTinode.MESSAGE_STATUS_FAILED = Const.MESSAGE_STATUS_FAILED;\nTinode.MESSAGE_STATUS_FATAL = Const.MESSAGE_STATUS_FATAL;\nTinode.MESSAGE_STATUS_SENT = Const.MESSAGE_STATUS_SENT;\nTinode.MESSAGE_STATUS_RECEIVED = Const.MESSAGE_STATUS_RECEIVED;\nTinode.MESSAGE_STATUS_READ = Const.MESSAGE_STATUS_READ;\nTinode.MESSAGE_STATUS_TO_ME = Const.MESSAGE_STATUS_TO_ME;\n\n// Unicode [del] symbol.\nTinode.DEL_CHAR = Const.DEL_CHAR;\n\n// Names of keys to server-provided configuration limits.\nTinode.MAX_MESSAGE_SIZE = 'maxMessageSize';\nTinode.MAX_SUBSCRIBER_COUNT = 'maxSubscriberCount';\nTinode.MAX_TAG_COUNT = 'maxTagCount';\nTinode.MAX_FILE_UPLOAD_SIZE = 'maxFileUploadSize';\nTinode.REQ_CRED_VALIDATORS = 'reqCred';\n","/**\n * @file Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport {\n listToRanges,\n normalizeRanges\n} from './utils';\n\n/**\n * Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @class MetaGetBuilder\n * @memberof Tinode\n *\n * @param {Tinode.Topic} parent topic which instantiated this builder.\n */\nexport default class MetaGetBuilder {\n constructor(parent) {\n this.topic = parent;\n this.what = {};\n }\n\n // Get timestamp of the most recent desc update.\n #get_desc_ims() {\n return this.topic.updated;\n }\n\n // Get timestamp of the most recent subs update.\n #get_subs_ims() {\n if (this.topic.isP2PType()) {\n return this.#get_desc_ims();\n }\n return this.topic._lastSubsUpdate;\n }\n /**\n * Add query parameters to fetch messages within explicit limits.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - messages newer than this (inclusive);\n * @param {number=} before - older than this (exclusive)\n * @param {number=} limit - number of messages to fetch\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withData(since, before, limit) {\n this.what['data'] = {\n since: since,\n before: before,\n limit: limit\n };\n return this;\n }\n /**\n * Add query parameters to fetch messages newer than the latest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of messages to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterData(limit) {\n return this.withData(this.topic._maxSeq > 0 ? this.topic._maxSeq + 1 : undefined, undefined, limit);\n }\n /**\n * Add query parameters to fetch messages within ID ranges.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Array.this object.\n */\n withDataRanges(ranges, limit) {\n this.what['data'] = {\n ranges: normalizeRanges(ranges, this.topic._maxSeq),\n limit: limit\n };\n return this;\n }\n /**\n * Add query parameters to fetch messages by an array of IDs.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number[]} list - array of seq IDs to fetch.\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDataList(list) {\n return this.withDataRanges(listToRanges(list));\n }\n /**\n * Add query parameters to fetch messages older than the earliest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of messages to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withEarlierData(limit) {\n return this.withData(undefined, this.topic._minSeq > 0 ? this.topic._minSeq : undefined, limit);\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the given timestamp.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch messages newer than this timestamp.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDesc(ims) {\n this.what['desc'] = {\n ims: ims\n };\n return this;\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDesc() {\n return this.withDesc(this.#get_desc_ims());\n }\n /**\n * Add query parameters to fetch subscriptions.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {number=} limit - maximum number of subscriptions to fetch.\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withSub(ims, limit, userOrTopic) {\n const opts = {\n ims: ims,\n limit: limit\n };\n if (this.topic.getType() == 'me') {\n opts.topic = userOrTopic;\n } else {\n opts.user = userOrTopic;\n }\n this.what['sub'] = opts;\n return this;\n }\n /**\n * Add query parameters to fetch a single subscription.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withOneSub(ims, userOrTopic) {\n return this.withSub(ims, undefined, userOrTopic);\n }\n /**\n * Add query parameters to fetch a single subscription if it's been updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterOneSub(userOrTopic) {\n return this.withOneSub(this.topic._lastSubsUpdate, userOrTopic);\n }\n /**\n * Add query parameters to fetch subscriptions updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of subscriptions to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterSub(limit) {\n return this.withSub(this.#get_subs_ims(), limit);\n }\n /**\n * Add query parameters to fetch topic tags.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withTags() {\n this.what['tags'] = true;\n return this;\n }\n /**\n * Add query parameters to fetch user's credentials. 'me' topic only.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withCred() {\n if (this.topic.getType() == 'me') {\n this.what['cred'] = true;\n } else {\n this.topic._tinode.logger(\"ERROR: Invalid topic type for MetaGetBuilder:withCreds\", this.topic.getType());\n }\n return this;\n }\n /**\n * Add query parameters to fetch topic tags.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withAux() {\n this.what['aux'] = true;\n return this;\n }\n /**\n * Add query parameters to fetch deleted messages within explicit limits. Any/all parameters can be null.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - ids of messages deleted since this 'del' id (inclusive)\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDel(since, limit) {\n if (since || limit) {\n this.what['del'] = {\n since: since,\n limit: limit\n };\n }\n return this;\n }\n /**\n * Add query parameters to fetch messages deleted after the saved 'del' id.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDel(limit) {\n // Specify 'since' only if we have already received some messages. If\n // we have no locally cached messages then we don't care if any messages were deleted.\n return this.withDel(this.topic._maxSeq > 0 ? this.topic._maxDel + 1 : undefined, limit);\n }\n\n /**\n * Extract subquery: get an object that contains specified subquery.\n * @memberof Tinode.MetaGetBuilder#\n * @param {string} what - subquery to return: one of 'data', 'sub', 'desc', 'tags', 'cred', 'del'.\n * @returns {Object} requested subquery or undefined.\n */\n extract(what) {\n return this.what[what];\n }\n\n /**\n * Construct parameters.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.GetQuery} Get query\n */\n build() {\n const what = [];\n let params = {};\n ['data', 'sub', 'desc', 'tags', 'cred', 'aux', 'del'].forEach((key) => {\n if (this.what.hasOwnProperty(key)) {\n what.push(key);\n if (Object.getOwnPropertyNames(this.what[key]).length > 0) {\n params[key] = this.what[key];\n }\n }\n });\n if (what.length > 0) {\n params.what = what.join(' ');\n } else {\n params = undefined;\n }\n return params;\n }\n}\n","/**\n * @file In-memory sorted cache of objects.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n/**\n * In-memory sorted cache of objects.\n *\n * @class CBuffer\n * @memberof Tinode\n * @protected\n *\n * @param {function} compare custom comparator of objects. Takes two parameters a and b;\n * returns -1 if a < b, 0 if a == b, 1 otherwise.\n * @param {boolean} unique enforce element uniqueness: when true replace existing element with a new\n * one on conflict; when false keep both elements.\n */\nexport default class CBuffer {\n #comparator = undefined;\n #unique = false;\n buffer = [];\n\n constructor(compare_, unique_) {\n this.#comparator = compare_ || ((a, b) => {\n return a === b ? 0 : a < b ? -1 : 1;\n });\n this.#unique = unique_;\n }\n\n #findNearest(elem, arr, exact) {\n let start = 0;\n let end = arr.length - 1;\n let pivot = 0;\n let diff = 0;\n let found = false;\n\n while (start <= end) {\n pivot = (start + end) / 2 | 0;\n diff = this.#comparator(arr[pivot], elem);\n if (diff < 0) {\n start = pivot + 1;\n } else if (diff > 0) {\n end = pivot - 1;\n } else {\n found = true;\n break;\n }\n }\n if (found) {\n return {\n idx: pivot,\n exact: true\n };\n }\n if (exact) {\n return {\n idx: -1\n };\n }\n // Not exact - insertion point\n return {\n idx: diff < 0 ? pivot + 1 : pivot\n };\n }\n\n // Insert element into a sorted array.\n #insertSorted(elem, arr) {\n const found = this.#findNearest(elem, arr, false);\n const count = (found.exact && this.#unique) ? 1 : 0;\n arr.splice(found.idx, count, elem);\n return arr;\n }\n\n /**\n * Get an element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to fetch from.\n * @returns {Object} Element at the given position or undefined.\n */\n getAt(at) {\n return this.buffer[at];\n }\n\n /**\n * Convenience method for getting the element from the end of the buffer.\n * @memberof Tinode.CBuffer#\n * @param {number} at - position to fetch from, counting from the end;\n * undefined or null mean \"last\".\n * @returns {Object} The last element in the buffer or undefined if buffer is empty.\n */\n getLast(at) {\n at |= 0;\n return this.buffer.length > at ? this.buffer[this.buffer.length - 1 - at] : undefined;\n }\n\n /**\n * Insert new element(s) to the buffer at the correct position according to the sort method.\n * Variadic: takes one or more arguments. If an array is passed as a single argument, its\n * elements are inserted individually.\n * @memberof Tinode.CBuffer#\n *\n * @param {...Object|Array} - One or more objects to insert.\n */\n put() {\n let insert;\n // inspect arguments: if array, insert its elements, if one or more non-array arguments, insert them one by one\n if (arguments.length == 1 && Array.isArray(arguments[0])) {\n insert = arguments[0];\n } else {\n insert = arguments;\n }\n for (let idx in insert) {\n this.#insertSorted(insert[idx], this.buffer);\n }\n }\n\n /**\n * Remove element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to delete at.\n * @returns {Object} Element at the given position or undefined.\n */\n delAt(at) {\n at |= 0;\n let r = this.buffer.splice(at, 1);\n if (r && r.length > 0) {\n return r[0];\n }\n return undefined;\n }\n\n /**\n * Remove elements between two positions.\n * @memberof Tinode.CBuffer#\n * @param {number} since - Position to delete from (inclusive).\n * @param {number} before - Position to delete to (exclusive).\n *\n * @returns {Array} array of removed elements (could be zero length).\n */\n delRange(since, before) {\n return this.buffer.splice(since, before - since);\n }\n\n /**\n * Return the number of elements the buffer holds.\n * @memberof Tinode.CBuffer#\n * @return {number} Number of elements in the buffer.\n */\n length() {\n return this.buffer.length;\n }\n\n /**\n * Reset the buffer discarding all elements\n * @memberof Tinode.CBuffer#\n */\n reset() {\n this.buffer = [];\n }\n\n /**\n * Callback for iterating contents of buffer. See {@link Tinode.CBuffer#forEach}.\n * @callback ForEachCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {Object} prev - Previous element of the buffer.\n * @param {Object} next - Next element of the buffer.\n * @param {number} index - Index of the current element.\n */\n\n /**\n * Apply given callback to all elements of the buffer.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.ForEachCallbackType} callback - Function to call for each element.\n * @param {number} startIdx - Optional index to start iterating from (inclusive), default: 0.\n * @param {number} beforeIdx - Optional index to stop iterating before (exclusive), default: length of the buffer.\n * @param {Object} context - calling context (i.e. value of this in callback)\n */\n forEach(callback, startIdx, beforeIdx, context) {\n startIdx = Math.max(0, startIdx | 0);\n beforeIdx = Math.min(beforeIdx || this.buffer.length, this.buffer.length);\n\n for (let i = startIdx; i < beforeIdx; i++) {\n callback.call(context, this.buffer[i],\n (i > startIdx ? this.buffer[i - 1] : undefined),\n (i < beforeIdx - 1 ? this.buffer[i + 1] : undefined), i);\n }\n }\n\n /**\n * Find element in buffer using buffer's comparison function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Object} elem - element to find.\n * @param {boolean=} nearest - when true and exact match is not found, return the nearest element (insertion point).\n * @returns {number} index of the element in the buffer or -1.\n */\n find(elem, nearest) {\n const {\n idx\n } = this.#findNearest(elem, this.buffer, !nearest);\n return idx;\n }\n\n /**\n * Callback for filtering the buffer. See {@link Tinode.CBuffer#filter}.\n * @callback FilterCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {number} index - Index of the current element.\n * @returns {boolen} true to keep the element, false to remove.\n */\n\n /**\n * Remove all elements that do not pass the test implemented by the provided callback function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.FilterCallbackType} callback - Function to call for each element.\n * @param {Object} context - calling context (i.e. value of this in the callback)\n */\n filter(callback, context) {\n let count = 0;\n for (let i = 0; i < this.buffer.length; i++) {\n if (callback.call(context, this.buffer[i], i)) {\n this.buffer[count] = this.buffer[i];\n count++;\n }\n }\n\n this.buffer.splice(count);\n }\n\n /**\n * Check if buffer is empty.\n * @returns {boolean} true if the buffer is empty, false otherwise.\n */\n isEmpty() {\n return this.buffer.length == 0;\n }\n}\n","/**\n * @file Topic management.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport CBuffer from './cbuffer.js';\nimport CommError from './comm-error.js';\nimport * as Const from './config.js';\nimport Drafty from './drafty.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport {\n listToRanges,\n mergeObj,\n mergeToCache,\n normalizeArray,\n normalizeRanges\n} from './utils.js';\n\n/**\n * Topic is a class representing a logical communication channel.\n */\nexport default class Topic {\n /**\n * @callback onData\n * @param {Data} data - Data packet\n */\n\n /**\n * Create topic.\n * @param {string} name - Name of the topic to create.\n * @param {Object=} callbacks - Object with various event callbacks.\n * @param {onData} callbacks.onData - Callback which receives a {data} message.\n * @param {callback} callbacks.onMeta - Callback which receives a {meta} message.\n * @param {callback} callbacks.onPres - Callback which receives a {pres} message.\n * @param {callback} callbacks.onInfo - Callback which receives an {info} message.\n * @param {callback} callbacks.onMetaDesc - Callback which receives changes to topic desctioption {@link desc}.\n * @param {callback} callbacks.onMetaSub - Called for a single subscription record change.\n * @param {callback} callbacks.onSubsUpdated - Called after a batch of subscription changes have been recieved and cached.\n * @param {callback} callbacks.onDeleteTopic - Called after the topic is deleted.\n * @param {callback} callbacls.onAllMessagesReceived - Called when all requested {data} messages have been recived.\n */\n constructor(name, callbacks) {\n // Parent Tinode object.\n this._tinode = null;\n\n // Server-provided data, locally immutable.\n // topic name\n this.name = name;\n // Timestamp when the topic was created.\n this.created = null;\n // Timestamp when the topic was last updated.\n this.updated = null;\n // Timestamp of the last messages\n this.touched = new Date(0);\n // Access mode, see AccessMode\n this.acs = new AccessMode(null);\n // Per-topic private data (accessible by current user only).\n this.private = null;\n // Per-topic public data (accessible by all users).\n this.public = null;\n // Per-topic system-provided data (accessible by all users).\n this.trusted = null;\n\n // Locally cached data\n // Subscribed users, for tracking read/recv/msg notifications.\n this._users = {};\n\n // Current value of locally issued seqId, used for pending messages.\n this._queuedSeqId = Const.LOCAL_SEQID;\n\n // The maximum known {data.seq} value.\n this._maxSeq = 0;\n // The minimum known {data.seq} value.\n this._minSeq = 0;\n // Indicator that the last request for earlier messages returned 0.\n this._noEarlierMsgs = false;\n // The maximum known deletion ID.\n this._maxDel = 0;\n // Timer object used to send 'recv' notifications.\n this._recvNotificationTimer = null;\n\n // User discovery tags\n this._tags = [];\n // Credentials such as email or phone number.\n this._credentials = [];\n // Auxiliary data\n this._aux = {};\n\n // Message versions cache (e.g. for edited messages).\n // Keys: original message seq ID.\n // Values: CBuffers containing newer versions of the original message\n // ordered by seq id.\n this._messageVersions = {};\n // Message cache, sorted by message seq values, from old to new.\n this._messages = new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n // Boolean, true if the topic is currently live\n this._attached = false;\n // Timestap of the most recently updated subscription.\n this._lastSubsUpdate = new Date(0);\n // Topic created but not yet synced with the server. Used only during initialization.\n this._new = true;\n // The topic is deleted at the server, this is a local copy.\n this._deleted = false;\n\n // Timer used to trgger {leave} request after a delay.\n this._delayedLeaveTimer = null;\n\n // Callbacks\n if (callbacks) {\n this.onData = callbacks.onData;\n this.onMeta = callbacks.onMeta;\n this.onPres = callbacks.onPres;\n this.onInfo = callbacks.onInfo;\n // A single desc update;\n this.onMetaDesc = callbacks.onMetaDesc;\n // A single subscription record;\n this.onMetaSub = callbacks.onMetaSub;\n // All subscription records received;\n this.onSubsUpdated = callbacks.onSubsUpdated;\n this.onTagsUpdated = callbacks.onTagsUpdated;\n this.onCredsUpdated = callbacks.onCredsUpdated;\n this.onAuxUpdated = callbacks.onAuxUpdated;\n this.onDeleteTopic = callbacks.onDeleteTopic;\n this.onAllMessagesReceived = callbacks.onAllMessagesReceived;\n }\n }\n\n // Static methods.\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n *\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n const types = {\n 'me': Const.TOPIC_ME,\n 'fnd': Const.TOPIC_FND,\n 'grp': Const.TOPIC_GRP,\n 'new': Const.TOPIC_GRP,\n 'nch': Const.TOPIC_GRP,\n 'chn': Const.TOPIC_GRP,\n 'usr': Const.TOPIC_P2P,\n 'sys': Const.TOPIC_SYS\n };\n return types[(typeof name == 'string') ? name.substring(0, 3) : 'xxx'];\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_ME;\n }\n\n /**\n * Check if the given topic name is a name of a group topic.\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_GRP;\n }\n\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_P2P;\n }\n\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isP2PTopicName(name) || Topic.isGroupTopicName(name);\n }\n\n /**\n * Check if the topic name is a name of a new topic.\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_NEW || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n /**\n * Check if the topic name is a name of a channel.\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_CHAN || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n // Returns true if pub is meant to replace another message (e.g. original message was edited).\n static #isReplacementMsg(pub) {\n return pub.head && pub.head.replace;\n }\n\n /**\n * Check if the topic is subscribed.\n * @returns {boolean} True is topic is attached/subscribed, false otherwise.\n */\n isSubscribed() {\n return this._attached;\n }\n\n /**\n * Request topic to subscribe. Wrapper for {@link Tinode#subscribe}.\n *\n * @param {Tinode.GetQuery=} getParams - get query parameters.\n * @param {Tinode.SetParams=} setParams - set parameters.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n subscribe(getParams, setParams) {\n // Clear request to leave topic.\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = null;\n\n // If the topic is already subscribed, return resolved promise\n if (this._attached) {\n return Promise.resolve(this);\n }\n\n // If the topic is deleted, reject subscription requests.\n if (this._deleted) {\n return Promise.reject(new Error(\"Conversation deleted\"));\n }\n\n // Send subscribe message, handle async response.\n // If topic name is explicitly provided, use it. If no name, then it's a new group topic,\n // use \"new\".\n return this._tinode.subscribe(this.name || Const.TOPIC_NEW, getParams, setParams).then(ctrl => {\n if (ctrl.code >= 300) {\n // Do nothing if subscription status has not changed.\n return ctrl;\n }\n\n this._attached = true;\n this._deleted = false;\n this.acs = (ctrl.params && ctrl.params.acs) ? ctrl.params.acs : this.acs;\n\n // Set topic name for new topics and add it to cache.\n if (this._new) {\n delete this._new;\n\n if (this.name != ctrl.topic) {\n // Name may change new123456 -> grpAbCdEf. Remove from cache under the old name.\n this._cacheDelSelf();\n this.name = ctrl.topic;\n }\n this._cachePutSelf();\n\n this.created = ctrl.ts;\n this.updated = ctrl.ts;\n\n if (this.name != Const.TOPIC_ME && this.name != Const.TOPIC_FND) {\n // Add the new topic to the list of contacts maintained by the 'me' topic.\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (setParams && setParams.desc) {\n setParams.desc._noForwarding = true;\n this._processMetaDesc(setParams.desc);\n }\n }\n return ctrl;\n });\n }\n\n /**\n * Create a draft of a message without sending it to the server.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Content to wrap in a draft.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * session. Otherwise the server will send a copy of the message to sender.\n *\n * @returns {Object} message draft.\n */\n createMessage(data, noEcho) {\n return this._tinode.createMessage(this.name, data, noEcho);\n }\n\n /**\n * Immediately publish data to topic. Wrapper for {@link Tinode#publish}.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Message to publish, either plain string or a Drafty object.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publish(data, noEcho) {\n return this.publishMessage(this.createMessage(data, noEcho));\n }\n\n /**\n * Publish message created by {@link Tinode.Topic#createMessage}.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - {data} object to publish. Must be created by {@link Tinode.Topic#createMessage}\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publishMessage(pub) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot publish on inactive topic\"));\n }\n if (this._sending) {\n return Promise.reject(new Error(\"The message is already being sent\"));\n }\n\n // Send data.\n pub._sending = true;\n pub._failed = false;\n\n // Extract refereces to attachments and out of band image records.\n let attachments = null;\n if (Drafty.hasEntities(pub.content)) {\n attachments = [];\n Drafty.entities(pub.content, data => {\n if (data) {\n if (data.ref) {\n attachments.push(data.ref);\n }\n if (data.preref) {\n attachments.push(data.preref);\n }\n }\n });\n if (attachments.length == 0) {\n attachments = null;\n }\n }\n\n return this._tinode.publishMessage(pub, attachments).then(ctrl => {\n pub._sending = false;\n pub.ts = ctrl.ts;\n this.swapMessageId(pub, ctrl.params.seq);\n this._maybeUpdateMessageVersionsCache(pub);\n this._routeData(pub);\n return ctrl;\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message rejected by the server\", err);\n pub._sending = false;\n pub._failed = true;\n if (this.onData) {\n this.onData();\n }\n });\n }\n\n /**\n * Add message to local message cache, send to the server when the promise is resolved.\n * If promise is null or undefined, the message will be sent immediately.\n * The message is sent when the\n * The message should be created by {@link Tinode.Topic#createMessage}.\n * This is probably not the final API.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - Message to use as a draft.\n * @param {Promise} prom - Message will be sent when this promise is resolved, discarded if rejected.\n *\n * @returns {Promise} derived promise.\n */\n publishDraft(pub, prom) {\n const seq = pub.seq || this._getQueuedSeqId();\n if (!pub._noForwarding) {\n // The 'seq', 'ts', and 'from' are added to mimic {data}. They are removed later\n // before the message is sent.\n pub._noForwarding = true;\n pub.seq = seq;\n pub.ts = new Date();\n pub.from = this._tinode.getCurrentUserID();\n\n // Don't need an echo message because the message is added to local cache right away.\n pub.noecho = true;\n // Add to cache.\n this._messages.put(pub);\n this._tinode._db.addMessage(pub);\n\n if (this.onData) {\n this.onData(pub);\n }\n }\n // If promise is provided, send the queued message when it's resolved.\n // If no promise is provided, create a resolved one and send immediately.\n return (prom || Promise.resolve())\n .then(_ => {\n if (pub._cancelled) {\n return {\n code: 300,\n text: \"cancelled\"\n };\n }\n return this.publishMessage(pub);\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message draft rejected\", err);\n pub._sending = false;\n pub._failed = true;\n pub._fatal = err instanceof CommError ? (err.code >= 400 && err.code < 500) : false;\n if (this.onData) {\n this.onData();\n }\n // Rethrow to let caller know that the operation failed.\n throw err;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean=} unsub - If true, unsubscribe, otherwise just leave.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n leave(unsub) {\n // It's possible to unsubscribe (unsub==true) from inactive topic.\n if (!this._attached && !unsub) {\n return Promise.reject(new Error(\"Cannot leave inactive topic\"));\n }\n\n // Send a 'leave' message, handle async response\n return this._tinode.leave(this.name, unsub).then(ctrl => {\n this._resetSub();\n if (unsub) {\n this._gone();\n }\n return ctrl;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe after a delay. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} unsub - If true, unsubscribe, otherwise just leave.\n * @param {number} delay - time in milliseconds to delay leave request.\n */\n leaveDelayed(unsub, delay) {\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = setTimeout(_ => {\n this._delayedLeaveTimer = null;\n this.leave(unsub)\n }, delay);\n }\n\n /**\n * Request topic metadata from the local cache or from the server.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.GetQuery} request parameters\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n getMeta(params) {\n // Send {get} message, return promise.\n return this._tinode.getMeta(this.name, params);\n }\n\n /**\n * Request more messages from the server. The goal is to load continous range of messages\n * covering at least between 'min' and 'max' + one full page forward (newer = true) or backwards\n * (newer=false).\n * @memberof Tinode.Topic#\n *\n * @param {number} limit number of messages to get.\n * @param {Array.null means to use default.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n invite(uid, mode) {\n return this.setMeta({\n sub: {\n user: uid,\n mode: mode\n }\n });\n }\n /**\n * Archive or un-archive the topic. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} arch - true to archive the topic, false otherwise.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n archive(arch) {\n if (this.private && (!this.private.arch == !arch)) {\n return Promise.resolve(arch);\n }\n return this.setMeta({\n desc: {\n private: {\n arch: arch ? true : Const.DEL_CHAR\n }\n }\n });\n }\n /**\n * Set message as pinned or unpinned by adding it to aux.pins array. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - seq ID of the message to pin or un-pin.\n * @param {boolean} pin - true to pin the message, false to un-pin.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n pinMessage(seq, pin) {\n let pinned = this.aux('pins');\n if (!Array.isArray(pinned)) {\n pinned = [];\n }\n let changed = false;\n if (pin) {\n if (!pinned.includes(seq)) {\n changed = true;\n if (pinned.length == Const.MAX_PINNED_COUNT) {\n pinned.shift();\n }\n pinned.push(seq);\n }\n } else {\n if (pinned.includes(seq)) {\n changed = true;\n pinned = pinned.filter(id => id != seq);\n if (pinned.length == 0) {\n pinned = Const.DEL_CHAR;\n }\n }\n }\n if (changed) {\n return this.setMeta({\n aux: {\n pins: pinned\n }\n });\n }\n return Promise.resolve();\n }\n /**\n * Delete messages. Hard-deleting messages requires Owner permission.\n * Wrapper for {@link Tinode#delMessages}.\n * @memberof Tinode.Topic#\n *\n * @param {Array.recv, read.\n * @param {number} seq - ID or the message read or received.\n */\n note(what, seq) {\n if (!this._attached) {\n // Cannot sending {note} on an inactive topic\".\n return;\n }\n\n // Update local cache with the new count.\n const user = this._users[this._tinode.getCurrentUserID()];\n let update = false;\n if (user) {\n // Self-subscription is found.\n if (!user[what] || user[what] < seq) {\n user[what] = seq;\n update = true;\n }\n } else {\n // Self-subscription is not found.\n update = (this[what] | 0) < seq;\n }\n\n if (update) {\n // Send notification to the server.\n this._tinode.note(this.name, what, seq);\n // Update locally cached contact with the new count.\n this._updateReadRecv(what, seq);\n\n if (this.acs != null && !this.acs.isMuted()) {\n const me = this._tinode.getMeTopic();\n // Sent a notification to 'me' listeners.\n me._refreshContact(what, this);\n }\n }\n }\n\n /**\n * Send a 'recv' receipt. Wrapper for {@link Tinode#noteRecv}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge.\n */\n noteRecv(seq) {\n this.note('recv', seq);\n }\n /**\n * Send a 'read' receipt. Wrapper for {@link Tinode#noteRead}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge or 0/undefined to acknowledge the latest messages.\n */\n noteRead(seq) {\n seq = seq || this._maxSeq;\n if (seq > 0) {\n this.note('read', seq);\n }\n }\n /**\n * Send a key-press notification. Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n */\n noteKeyPress() {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name);\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n /**\n * Send a notification than a video or audio message is . Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n * @param audioOnly - true if the recording is audio-only, false if it's a video recording.\n */\n noteRecording(audioOnly) {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name, audioOnly ? 'kpa' : 'kpv');\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n\n /**\n * Send a {note what='call'}. Wrapper for {@link Tinode#videoCall}.\n * @memberof Tinode#\n *\n * @param {string} evt - Call event.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(evt, seq, payload) {\n if (!this._attached && !['ringing', 'hang-up'].includes(evt)) {\n // Cannot {call} on an inactive topic\".\n return;\n }\n return this._tinode.videoCall(this.name, seq, evt, payload);\n }\n\n // Update cached read/recv/unread counts.\n _updateReadRecv(what, seq, ts) {\n let oldVal, doUpdate = false;\n\n seq = seq | 0;\n this.seq = this.seq | 0;\n this.read = this.read | 0;\n this.recv = this.recv | 0;\n switch (what) {\n case 'recv':\n oldVal = this.recv;\n this.recv = Math.max(this.recv, seq);\n doUpdate = (oldVal != this.recv);\n break;\n case 'read':\n oldVal = this.read;\n this.read = Math.max(this.read, seq);\n doUpdate = (oldVal != this.read);\n break;\n case 'msg':\n oldVal = this.seq;\n this.seq = Math.max(this.seq, seq);\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = (oldVal != this.seq);\n break;\n }\n\n // Sanity checks.\n if (this.recv < this.read) {\n this.recv = this.read;\n doUpdate = true;\n }\n if (this.seq < this.recv) {\n this.seq = this.recv;\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = true;\n }\n this.unread = this.seq - this.read;\n return doUpdate;\n }\n /**\n * Get user description from global cache. The user does not need to be a\n * subscriber of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - ID of the user to fetch.\n * @return {Object} user description or undefined.\n */\n userDesc(uid) {\n // TODO: handle asynchronous requests\n const user = this._cacheGetUser(uid);\n if (user) {\n return user; // Promise.resolve(user)\n }\n }\n /**\n * Get description of the p2p peer from subscription cache.\n * @memberof Tinode.Topic#\n *\n * @return {Object} peer's description or undefined.\n */\n p2pPeerDesc() {\n if (!this.isP2PType()) {\n return undefined;\n }\n return this._users[this.name];\n }\n /**\n * Iterate over cached subscribers. If callback is undefined, use this.onMetaSub.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive subscribers one by one.\n * @param {Object=} context - Value of `this` inside the `callback`.\n */\n subscribers(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._users) {\n cb.call(context, this._users[idx], idx, this._users);\n }\n }\n }\n /**\n * Get a copy of cached tags.\n * @memberof Tinode.Topic#\n *\n * @return {Array.key or undefined.\n */\n aux(key) {\n return this._aux[key];\n }\n /**\n * Get cached subscription for the given user ID.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - id of the user to query for\n * @return user description or undefined.\n */\n subscriber(uid) {\n return this._users[uid];\n }\n /**\n * Iterate over versions of a message: call callback for each version (excluding original).\n * If callback is undefined, does nothing.\n * @memberof Tinode.Topic#\n *\n * @param {number} origSeq - seq ID of the original message.\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messageVersions(origSeq, callback, context) {\n if (!callback) {\n // No callback? We are done then.\n return;\n }\n const versions = this._messageVersions[origSeq];\n if (!versions) {\n return;\n }\n versions.forEach(callback, undefined, undefined, context);\n }\n /**\n * Iterate over cached messages: call callback for each message in the range [sinceIdx, beforeIdx).\n * If callback is undefined, use this.onData.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {number} sinceId - Optional seqId to start iterating from (inclusive).\n * @param {number} beforeId - Optional seqId to stop iterating before it is reached (exclusive).\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messages(callback, sinceId, beforeId, context) {\n const cb = (callback || this.onData);\n if (cb) {\n const startIdx = typeof sinceId == 'number' ? this._messages.find({\n seq: sinceId\n }, true) : undefined;\n const beforeIdx = typeof beforeId == 'number' ? this._messages.find({\n seq: beforeId\n }, true) : undefined;\n if (startIdx != -1 && beforeIdx != -1) {\n // Step 1. Filter out all replacement messages and\n // save displayable messages in a temporary buffer.\n let msgs = [];\n this._messages.forEach((msg, unused1, unused2, i) => {\n if (Topic.#isReplacementMsg(msg)) {\n // Skip replacements.\n return;\n }\n if (msg._deleted) {\n // Skip deleted ranges.\n return;\n }\n // In case the massage was edited, replace timestamp of the version with the original's timestamp.\n const latest = this.latestMsgVersion(msg.seq) || msg;\n if (!latest._origTs) {\n latest._origTs = latest.ts;\n latest._origSeq = latest.seq;\n latest.ts = msg.ts;\n latest.seq = msg.seq;\n }\n msgs.push({\n data: latest,\n idx: i\n });\n }, startIdx, beforeIdx, {});\n // Step 2. Loop over displayble messages invoking cb on each of them.\n msgs.forEach((val, i) => {\n cb.call(context, val.data,\n (i > 0 ? msgs[i - 1].data : undefined),\n (i < msgs.length - 1 ? msgs[i + 1].data : undefined), val.idx);\n });\n }\n }\n }\n /**\n * Get the message from cache by literal seq (does not resolve message edits).\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message seqId to search for.\n * @returns {Object} the message with the given seq or undefined, if no such message is found.\n */\n findMessage(seq) {\n const idx = this._messages.find({\n seq: seq\n });\n if (idx >= 0) {\n return this._messages.getAt(idx);\n }\n return undefined;\n }\n /**\n * Get the most recent message from cache. This method counts all messages, including deleted ranges.\n * @memberof Tinode.Topic#\n *\n * @returns {Object} the most recent cached message or undefined, if no messages are cached.\n */\n latestMessage() {\n return this._messages.getLast();\n }\n /**\n * Get the latest version for message.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - original seq ID of the message.\n * @returns {Object} the latest version of the message or null if message not found.\n */\n latestMsgVersion(seq) {\n const versions = this._messageVersions[seq];\n return versions ? versions.getLast() : null;\n }\n /**\n * Get the maximum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest seq ID in cache.\n */\n maxMsgSeq() {\n return this._maxSeq;\n }\n /**\n * Get the minimum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the smallest seq ID in cache or 0.\n */\n minMsgSeq() {\n return this._minSeq;\n }\n /**\n * Get the maximum deletion ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest deletion ID.\n */\n maxClearId() {\n return this._maxDel;\n }\n /**\n * Get the number of messages in the cache.\n * @memberof Tinode.Topic#\n *\n * @returns {number} count of cached messages.\n */\n messageCount() {\n return this._messages.length();\n }\n /**\n * Iterate over cached unsent messages. Wraps {@link Tinode.Topic#messages}.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of this inside the callback.\n */\n queuedMessages(callback, context) {\n if (!callback) {\n throw new Error(\"Callback must be provided\");\n }\n this.messages(callback, Const.LOCAL_SEQID, undefined, context);\n }\n /**\n * Get the number of topic subscribers who marked this message as either recv or read\n * Current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {string} what - what action to consider: received \"recv\" or read \"read\".\n * @param {number} seq - ID or the message read or received.\n *\n * @returns {number} the number of subscribers who marked the message with the given ID as read or received.\n */\n msgReceiptCount(what, seq) {\n let count = 0;\n if (seq > 0) {\n const me = this._tinode.getCurrentUserID();\n for (let idx in this._users) {\n const user = this._users[idx];\n if (user.user !== me && user[what] >= seq) {\n count++;\n }\n }\n }\n return count;\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as read.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message id to check.\n * @returns {number} number of subscribers who claim to have received the message.\n */\n msgReadCount(seq) {\n return this.msgReceiptCount('read', seq);\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as received.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - Message id to check.\n * @returns {number} Number of subscribers who claim to have received the message.\n */\n msgRecvCount(seq) {\n return this.msgReceiptCount('recv', seq);\n }\n /**\n * Check if cached message IDs indicate that the server may have more messages.\n * @memberof Tinode.Topic#\n *\n * @param {number} min - smallest seq ID loaded range.\n * @param {number} max - greatest seq ID in loaded range.\n * @param {boolean} newer - if true, check for newer messages only.\n * @returns {Array.true if message was cancelled, false otherwise.\n */\n cancelSend(seqId) {\n const idx = this._messages.find({\n seq: seqId\n });\n if (idx >= 0) {\n const msg = this._messages.getAt(idx);\n const status = this.msgStatus(msg);\n if (status == Const.MESSAGE_STATUS_QUEUED ||\n status == Const.MESSAGE_STATUS_FAILED ||\n status == Const.MESSAGE_STATUS_FATAL) {\n this._tinode._db.remMessages(this.name, seqId);\n msg._cancelled = true;\n this._messages.delAt(idx);\n if (this.onData) {\n // Calling with no parameters to indicate the message was deleted.\n this.onData();\n }\n return true;\n }\n }\n return false;\n }\n /**\n * Get type of the topic: me, p2p, grp, fnd...\n * @memberof Tinode.Topic#\n *\n * @returns {string} One of 'me', 'p2p', 'grp', 'fnd', 'sys' or undefined.\n */\n getType() {\n return Topic.topicType(this.name);\n }\n /**\n * Get current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.AccessMode} - user's access mode\n */\n getAccessMode() {\n return this.acs;\n }\n /**\n * Set current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @param {AccessMode | Object} acs - access mode to set.\n */\n setAccessMode(acs) {\n return this.acs = new AccessMode(acs);\n }\n /**\n * Get topic's default access mode.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.DefAcs} - access mode, such as {auth: `RWP`, anon: `N`}.\n */\n getDefaultAccess() {\n return this.defacs;\n }\n /**\n * Initialize new meta {@link Tinode.GetQuery} builder. The query is attched to the current topic.\n * It will not work correctly if used with a different topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.MetaGetBuilder} query attached to the current topic.\n */\n startMetaQuery() {\n return new MetaGetBuilder(this);\n }\n /**\n * Check if topic is archived, i.e. private.arch == true.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is archived, false otherwise.\n */\n isArchived() {\n return this.private && !!this.private.arch;\n }\n /**\n * Check if topic is a 'me' topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a 'me' topic, false otherwise.\n */\n isMeType() {\n return Topic.isMeTopicName(this.name);\n }\n /**\n * Check if topic is a channel.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a channel, false otherwise.\n */\n isChannelType() {\n return Topic.isChannelTopicName(this.name);\n }\n /**\n * Check if topic is a group topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a group, false otherwise.\n */\n isGroupType() {\n return Topic.isGroupTopicName(this.name);\n }\n /**\n * Check if topic is a p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p topic, false otherwise.\n */\n isP2PType() {\n return Topic.isP2PTopicName(this.name);\n }\n /**\n * Check if topic is a communication topic, i.e. a group or p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p or group topic, false otherwise.\n */\n isCommType() {\n return Topic.isCommTopicName(this.name);\n }\n /**\n * Get status (queued, sent, received etc) of a given message in the context\n * of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {Message} msg - message to check for status.\n * @param {boolean} upd - update chached message status.\n *\n * @returns message status constant.\n */\n msgStatus(msg, upd) {\n let status = Const.MESSAGE_STATUS_NONE;\n if (this._tinode.isMe(msg.from)) {\n if (msg._sending) {\n status = Const.MESSAGE_STATUS_SENDING;\n } else if (msg._fatal || msg._cancelled) {\n status = Const.MESSAGE_STATUS_FATAL;\n } else if (msg._failed) {\n status = Const.MESSAGE_STATUS_FAILED;\n } else if (msg.seq >= Const.LOCAL_SEQID) {\n status = Const.MESSAGE_STATUS_QUEUED;\n } else if (this.msgReadCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_READ;\n } else if (this.msgRecvCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_RECEIVED;\n } else if (msg.seq > 0) {\n status = Const.MESSAGE_STATUS_SENT;\n }\n } else {\n status = Const.MESSAGE_STATUS_TO_ME;\n }\n\n if (upd && msg._status != status) {\n msg._status = status;\n this._tinode._db.updMessageStatus(this.name, msg.seq, status);\n }\n\n return status;\n }\n\n // If msg is a replacement for another message, save the msg in the message versions cache\n // as a newer version for the message it's supposed to replace.\n _maybeUpdateMessageVersionsCache(msg) {\n if (!Topic.#isReplacementMsg(msg)) {\n // Check if this message is the original in the chain of edits and if so\n // ensure all version have the same sender.\n if (this._messageVersions[msg.seq]) {\n // Remove versions with different 'from'.\n this._messageVersions[msg.seq].filter(version => version.from == msg.from);\n if (this._messageVersions[msg.seq].isEmpty()) {\n delete this._messageVersions[msg.seq];\n }\n }\n return;\n }\n\n const targetSeq = parseInt(msg.head.replace.split(':')[1]);\n if (targetSeq > msg.seq) {\n // Substitutes are supposed to have higher seq ids.\n return;\n }\n const targetMsg = this.findMessage(targetSeq);\n if (targetMsg && targetMsg.from != msg.from) {\n // Substitute cannot change the sender.\n return;\n }\n const versions = this._messageVersions[targetSeq] || new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n versions.put(msg);\n this._messageVersions[targetSeq] = versions;\n }\n\n // Process data message\n _routeData(data) {\n if (data.content) {\n if (!this.touched || this.touched < data.ts) {\n this.touched = data.ts;\n this._tinode._db.updTopic(this);\n }\n }\n\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n this.msgStatus(data, true);\n // Ackn receiving the message.\n clearTimeout(this._recvNotificationTimer);\n this._recvNotificationTimer = setTimeout(_ => {\n this._recvNotificationTimer = null;\n this.noteRecv(this._maxSeq);\n }, Const.RECV_TIMEOUT);\n }\n\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n\n const outgoing = ((!this.isChannelType() && !data.from) || this._tinode.isMe(data.from));\n\n if (data.head && data.head.webrtc && data.head.mime == Drafty.getContentType() && data.content) {\n // Rewrite VC body with info from the headers.\n data.content = Drafty.updateVideoCall(data.content, {\n state: data.head.webrtc,\n duration: data.head['webrtc-duration'],\n incoming: !outgoing,\n });\n }\n\n if (!data._noForwarding) {\n this._messages.put(data);\n this._tinode._db.addMessage(data);\n this._maybeUpdateMessageVersionsCache(data);\n }\n\n if (this.onData) {\n this.onData(data);\n }\n\n // Update locally cached contact with the new message count.\n const what = outgoing ? 'read' : 'msg';\n this._updateReadRecv(what, data.seq, data.ts);\n // Notify 'me' listeners of the change.\n this._tinode.getMeTopic()._refreshContact(what, this);\n }\n\n // Process metadata message\n _routeMeta(meta) {\n if (meta.desc) {\n this._processMetaDesc(meta.desc);\n }\n if (meta.sub && meta.sub.length > 0) {\n this._processMetaSub(meta.sub);\n }\n if (meta.del) {\n this._processDelMessages(meta.del.clear, meta.del.delseq);\n }\n if (meta.tags) {\n this._processMetaTags(meta.tags);\n }\n if (meta.cred) {\n this._processMetaCreds(meta.cred);\n }\n if (meta.aux) {\n this._processMetaAux(meta.aux);\n }\n if (this.onMeta) {\n this.onMeta(meta);\n }\n }\n // Process presence change message\n _routePres(pres) {\n let user, uid;\n switch (pres.what) {\n case 'del':\n // Delete cached messages.\n this._processDelMessages(pres.clear, pres.delseq);\n break;\n case 'on':\n case 'off':\n // Update online status of a subscription.\n user = this._users[pres.src];\n if (user) {\n user.online = pres.what == 'on';\n } else {\n this._tinode.logger(\"WARNING: Presence update for an unknown user\", this.name, pres.src);\n }\n break;\n case 'term':\n // Attachment to topic is terminated probably due to cluster rehashing.\n this._resetSub();\n break;\n case 'upd':\n // A topic subscriber has updated his description.\n // Issue {get sub} only if the current user has no p2p topics with the updated user (p2p name is not in cache).\n // Otherwise 'me' will issue a {get desc} request.\n if (pres.src && !this._tinode.isTopicCached(pres.src)) {\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n }\n break;\n case 'aux':\n // Auxiliary data updated.\n this.getMeta(this.startMetaQuery().withAux().build());\n break;\n case 'acs':\n uid = pres.src || this._tinode.getCurrentUserID();\n user = this._users[uid];\n if (!user) {\n // Update for an unknown user: notification of a new subscription.\n const acs = new AccessMode().updateAll(pres.dacs);\n if (acs && acs.mode != AccessMode._NONE) {\n user = this._cacheGetUser(uid);\n if (!user) {\n user = {\n user: uid,\n acs: acs\n };\n this.getMeta(this.startMetaQuery().withOneSub(undefined, uid).build());\n } else {\n user.acs = acs;\n }\n user.updated = new Date();\n this._processMetaSub([user]);\n }\n } else {\n // Known user\n user.acs.updateAll(pres.dacs);\n // Update user's access mode.\n this._processMetaSub([{\n user: uid,\n updated: new Date(),\n acs: user.acs\n }]);\n }\n break;\n default:\n this._tinode.logger(\"INFO: Ignored presence update\", pres.what);\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n // Process {info} message\n _routeInfo(info) {\n switch (info.what) {\n case 'recv':\n case 'read':\n const user = this._users[info.from];\n if (user) {\n user[info.what] = info.seq;\n if (user.recv < user.read) {\n user.recv = user.read;\n }\n }\n const msg = this.latestMessage();\n if (msg) {\n this.msgStatus(msg, true);\n }\n\n // If this is an update from the current user, update the cache with the new count.\n if (this._tinode.isMe(info.from)) {\n this._updateReadRecv(info.what, info.seq);\n }\n\n // Notify 'me' listener of the status change.\n this._tinode.getMeTopic()._refreshContact(info.what, this);\n break;\n case 'kp':\n // Do nothing.\n break;\n case 'call':\n // Do nothing here.\n break;\n default:\n this._tinode.logger(\"INFO: Ignored info update\", info.what);\n }\n\n if (this.onInfo) {\n this.onInfo(info);\n }\n }\n // Called by Tinode when meta.desc packet is received.\n // Called by 'me' topic on contact update (desc._noForwarding is true).\n _processMetaDesc(desc) {\n if (this.isP2PType()) {\n // Synthetic desc may include defacs for p2p topics which is useless.\n // Remove it.\n delete desc.defacs;\n\n // Update to p2p desc is the same as user update. Update cached user.\n this._tinode._db.updUser(this.name, desc.public);\n }\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n // Update persistent cache.\n this._tinode._db.updTopic(this);\n\n // Notify 'me' listener, if available:\n if (this.name !== Const.TOPIC_ME && !desc._noForwarding) {\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n // Called by Tinode when meta.sub is recived or in response to received\n // {ctrl} after setMeta-sub.\n _processMetaSub(subs) {\n for (let idx in subs) {\n const sub = subs[idx];\n\n // Fill defaults.\n sub.online = !!sub.online;\n // Update timestamp of the most recent subscription update.\n this._lastSubsUpdate = new Date(Math.max(this._lastSubsUpdate, sub.updated));\n\n let user = null;\n if (!sub.deleted) {\n // If this is a change to user's own permissions, update them in topic too.\n // Desc will update 'me' topic.\n if (this._tinode.isMe(sub.user) && sub.acs) {\n this._processMetaDesc({\n updated: sub.updated,\n touched: sub.touched,\n acs: sub.acs\n });\n }\n user = this._updateCachedUser(sub.user, sub);\n } else {\n // Subscription is deleted, remove it from topic (but leave in Users cache)\n delete this._users[sub.user];\n user = sub;\n }\n\n if (this.onMetaSub) {\n this.onMetaSub(user);\n }\n }\n\n if (this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._users));\n }\n }\n // Called by Tinode when meta.tags is recived.\n _processMetaTags(tags) {\n if (tags == Const.DEL_CHAR || (tags.length == 1 && tags[0] == Const.DEL_CHAR)) {\n tags = [];\n }\n this._tags = tags;\n this._tinode._db.updTopic(this);\n if (this.onTagsUpdated) {\n this.onTagsUpdated(tags);\n }\n }\n // Do nothing for topics other than 'me'\n _processMetaCreds(creds) {}\n\n // Called by Tinode when meta.aux is recived.\n _processMetaAux(aux) {\n aux = (!aux || aux == Const.DEL_CHAR) ? {} : aux;\n this._aux = mergeObj(this._aux, aux);\n this._tinode._db.updTopic(this);\n if (this.onAuxUpdated) {\n this.onAuxUpdated(this._aux);\n }\n }\n\n // Delete cached messages and update cached transaction IDs\n _processDelMessages(clear, delseq) {\n this._maxDel = Math.max(clear, this._maxDel);\n this.clear = Math.max(clear, this.clear);\n let count = 0;\n if (Array.isArray(delseq)) {\n delseq.forEach(rec => {\n if (!rec.hi) {\n count++;\n this.flushMessage(rec.low);\n } else {\n count += rec.hi - rec.low;\n this.flushMessageRange(rec.low, rec.hi);\n }\n this._messages.put({\n seq: rec.low,\n low: rec.low,\n hi: rec.hi,\n _deleted: true\n });\n });\n\n this._tinode._db.addDelLog(this.name, clear, delseq);\n }\n\n if (count > 0) {\n if (this.onData) {\n this.onData();\n }\n }\n }\n // Topic is informed that the entire response to {get what=data} has been received.\n _allMessagesReceived(count) {\n\n if (this.onAllMessagesReceived) {\n this.onAllMessagesReceived(count);\n }\n }\n // Reset subscribed state\n _resetSub() {\n this._attached = false;\n }\n // This topic is either deleted or unsubscribed from.\n _gone() {\n this._messages.reset();\n this._tinode._db.remMessages(this.name);\n this._users = {};\n this.acs = new AccessMode(null);\n this.private = null;\n this.public = null;\n this.trusted = null;\n this._maxSeq = 0;\n this._minSeq = 0;\n this._attached = false;\n\n const me = this._tinode.getMeTopic();\n if (me) {\n me._routePres({\n _noForwarding: true,\n what: 'gone',\n topic: Const.TOPIC_ME,\n src: this.name\n });\n }\n if (this.onDeleteTopic) {\n this.onDeleteTopic();\n }\n }\n // Update global user cache and local subscribers cache.\n // Don't call this method for non-subscribers.\n _updateCachedUser(uid, obj) {\n // Fetch user object from the global cache.\n // This is a clone of the stored object\n let cached = this._cacheGetUser(uid);\n cached = mergeObj(cached || {}, obj);\n // Save to global cache\n this._cachePutUser(uid, cached);\n // Save to the list of topic subsribers.\n return mergeToCache(this._users, uid, cached);\n }\n // Get local seqId for a queued message.\n _getQueuedSeqId() {\n return this._queuedSeqId++;\n }\n\n // Load most recent messages from persistent cache.\n _loadMessages(db, query) {\n query = query || {};\n query.limit = query.limit || Const.DEFAULT_MESSAGES_PAGE;\n\n // Count of message loaded from DB.\n let count = 0;\n return db.readMessages(this.name, query)\n .then(msgs => {\n msgs.forEach(data => {\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n }\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n this._messages.put(data);\n this._maybeUpdateMessageVersionsCache(data);\n });\n count = msgs.length;\n })\n .then(_ => db.readDelLog(this.name, query))\n .then(dellog => {\n return dellog.forEach(rec => {\n this._messages.put({\n seq: rec.low,\n low: rec.low,\n hi: rec.hi,\n _deleted: true\n });\n });\n })\n .then(_ => {\n // DEBUG\n return count;\n });\n }\n\n // Push or {pres}: message received.\n _updateReceived(seq, act) {\n this.touched = new Date();\n this.seq = seq | 0;\n // Check if message is sent by the current user. If so it's been read already.\n if (!act || this._tinode.isMe(act)) {\n this.read = this.read ? Math.max(this.read, this.seq) : this.seq;\n this.recv = this.recv ? Math.max(this.read, this.recv) : this.read;\n }\n this.unread = this.seq - (this.read | 0);\n this._tinode._db.updTopic(this);\n }\n}\n","/**\n * @file Definition of 'fnd' topic.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport * as Const from './config.js';\nimport Topic from './topic.js';\nimport {\n mergeToCache\n} from './utils.js';\n\n\n/**\n * Special case of {@link Tinode.Topic} for searching for contacts and group topics\n * @extends Tinode.Topic\n *\n */\nexport default class TopicFnd extends Topic {\n // List of users and topics uid or topic_name -> Contact object)\n _contacts = {};\n\n /**\n * Create TopicFnd.\n *\n * @param {TopicFnd.Callbacks} callbacks - Callbacks to receive various events.\n */\n constructor(callbacks) {\n super(Const.TOPIC_FND, callbacks);\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = Object.getOwnPropertyNames(this._contacts).length;\n // Reset contact list.\n this._contacts = {};\n for (let idx in subs) {\n let sub = subs[idx];\n const indexBy = sub.topic ? sub.topic : sub.user;\n\n sub = mergeToCache(this._contacts, indexBy, sub);\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(sub);\n }\n }\n\n if (updateCount > 0 && this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._contacts));\n }\n }\n\n /**\n * Publishing to TopicFnd is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicFnd#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'fnd' is not supported\"));\n }\n\n /**\n * setMeta to TopicFnd resets contact list in addition to sending the message.\n * @memberof Tinode.TopicFnd#\n * @param {Tinode.SetParams} params parameters to update.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n setMeta(params) {\n return Object.getPrototypeOf(TopicFnd.prototype).setMeta.call(this, params).then(_ => {\n if (Object.keys(this._contacts).length > 0) {\n this._contacts = {};\n if (this.onSubsUpdated) {\n this.onSubsUpdated([]);\n }\n }\n });\n }\n\n /**\n * Iterate over found contacts. If callback is undefined, use {@link this.onMetaSub}.\n * @function\n * @memberof Tinode.TopicFnd#\n * @param {TopicFnd.ContactCallback} callback - Callback to call for each contact.\n * @param {Object} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._contacts) {\n cb.call(context, this._contacts[idx], idx, this._contacts);\n }\n }\n }\n}\n","/**\n * @file Definition of 'me' topic.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport * as Const from './config.js';\nimport Topic from './topic.js';\nimport {\n mergeObj\n} from './utils.js';\n\n/**\n * @class TopicMe - special case of {@link Tinode.Topic} for\n * managing data of the current user, including contact list.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicMe.Callbacks} callbacks - Callbacks to receive various events.\n */\nexport default class TopicMe extends Topic {\n onContactUpdate;\n\n constructor(callbacks) {\n super(Const.TOPIC_ME, callbacks);\n\n // me-specific callbacks\n if (callbacks) {\n this.onContactUpdate = callbacks.onContactUpdate;\n }\n }\n\n // Override the original Topic._processMetaDesc.\n _processMetaDesc(desc) {\n // Check if online contacts need to be turned off because P permission was removed.\n const turnOff = (desc.acs && !desc.acs.isPresencer()) && (this.acs && this.acs.isPresencer());\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n this._tinode._db.updTopic(this);\n // Update current user's record in the global cache.\n this._updateCachedUser(this._tinode._myUID, desc);\n\n // 'P' permission was removed. All topics are offline now.\n if (turnOff) {\n this._tinode.mapTopics((cont) => {\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n this._refreshContact('off', cont);\n }\n });\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = 0;\n subs.forEach((sub) => {\n const topicName = sub.topic;\n // Don't show 'me' and 'fnd' topics in the list of contacts.\n if (topicName == Const.TOPIC_FND || topicName == Const.TOPIC_ME) {\n return;\n }\n sub.online = !!sub.online;\n\n let cont = null;\n if (sub.deleted) {\n cont = sub;\n this._tinode.cacheRemTopic(topicName);\n this._tinode._db.remTopic(topicName);\n } else {\n // Ensure the values are defined and are integers.\n if (typeof sub.seq != 'undefined') {\n sub.seq = sub.seq | 0;\n sub.recv = sub.recv | 0;\n sub.read = sub.read | 0;\n sub.unread = sub.seq - sub.read;\n }\n\n const topic = this._tinode.getTopic(topicName);\n if (topic._new) {\n delete topic._new;\n }\n\n cont = mergeObj(topic, sub);\n this._tinode._db.updTopic(cont);\n\n if (Topic.isP2PTopicName(topicName)) {\n this._cachePutUser(topicName, cont);\n this._tinode._db.updUser(topicName, cont.public);\n }\n // Notify topic of the update if it's an external update.\n if (!sub._noForwarding && topic) {\n sub._noForwarding = true;\n topic._processMetaDesc(sub);\n }\n }\n\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(cont);\n }\n });\n\n if (this.onSubsUpdated && updateCount > 0) {\n const keys = [];\n subs.forEach((s) => {\n keys.push(s.topic);\n });\n this.onSubsUpdated(keys, updateCount);\n }\n }\n\n // Called by Tinode when meta.sub is recived.\n _processMetaCreds(creds, upd) {\n if (creds.length == 1 && creds[0] == Const.DEL_CHAR) {\n creds = [];\n }\n if (upd) {\n creds.forEach((cr) => {\n if (cr.val) {\n // Adding a credential.\n let idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && el.val == cr.val;\n });\n if (idx < 0) {\n // Not found.\n if (!cr.done) {\n // Unconfirmed credential replaces previous unconfirmed credential of the same method.\n idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n // Remove previous unconfirmed credential.\n this._credentials.splice(idx, 1);\n }\n }\n this._credentials.push(cr);\n } else {\n // Found. Maybe change 'done' status.\n this._credentials[idx].done = cr.done;\n }\n } else if (cr.resp) {\n // Handle credential confirmation.\n const idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n this._credentials[idx].done = true;\n }\n }\n });\n } else {\n this._credentials = creds;\n }\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n }\n\n // Process presence change message\n _routePres(pres) {\n if (pres.what == 'term') {\n // The 'me' topic itself is detached. Mark as unsubscribed.\n this._resetSub();\n return;\n }\n\n if (pres.what == 'upd' && pres.src == Const.TOPIC_ME) {\n // Update to me's description. Request updated value.\n this.getMeta(this.startMetaQuery().withDesc().build());\n return;\n }\n\n const cont = this._tinode.cacheGetTopic(pres.src);\n if (cont) {\n switch (pres.what) {\n case 'on': // topic came online\n cont.online = true;\n break;\n case 'off': // topic went offline\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n }\n break;\n case 'msg': // new message received\n cont._updateReceived(pres.seq, pres.act);\n break;\n case 'upd': // desc updated\n // Request updated subscription.\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n break;\n case 'acs': // access mode changed\n if (cont.acs) {\n cont.acs.updateAll(pres.dacs);\n } else {\n cont.acs = new AccessMode().updateAll(pres.dacs);\n }\n cont.touched = new Date();\n break;\n case 'ua':\n // user agent changed.\n cont.seen = {\n when: new Date(),\n ua: pres.ua\n };\n break;\n case 'recv':\n // user's other session marked some messges as received.\n pres.seq = pres.seq | 0;\n cont.recv = cont.recv ? Math.max(cont.recv, pres.seq) : pres.seq;\n break;\n case 'read':\n // user's other session marked some messages as read.\n pres.seq = pres.seq | 0;\n cont.read = cont.read ? Math.max(cont.read, pres.seq) : pres.seq;\n cont.recv = cont.recv ? Math.max(cont.read, cont.recv) : cont.recv;\n cont.unread = cont.seq - cont.read;\n break;\n case 'gone':\n // topic deleted or unsubscribed from.\n if (!cont._deleted) {\n cont._deleted = true;\n cont._attached = false;\n this._tinode._db.markTopicAsDeleted(pres.src);\n } else {\n this._tinode._db.remTopic(pres.src);\n }\n break;\n case 'del':\n // Update topic.del value.\n break;\n default:\n this._tinode.logger(\"INFO: Unsupported presence update in 'me'\", pres.what);\n }\n\n this._refreshContact(pres.what, cont);\n } else {\n if (pres.what == 'acs') {\n // New subscriptions and deleted/banned subscriptions have full\n // access mode (no + or - in the dacs string). Changes to known subscriptions are sent as\n // deltas, but they should not happen here.\n const acs = new AccessMode(pres.dacs);\n if (!acs || acs.mode == AccessMode._INVALID) {\n this._tinode.logger(\"ERROR: Invalid access mode update\", pres.src, pres.dacs);\n return;\n } else if (acs.mode == AccessMode._NONE) {\n this._tinode.logger(\"WARNING: Removing non-existent subscription\", pres.src, pres.dacs);\n return;\n } else {\n // New subscription. Send request for the full description.\n // Using .withOneSub (not .withLaterOneSub) to make sure IfModifiedSince is not set.\n this.getMeta(this.startMetaQuery().withOneSub(undefined, pres.src).build());\n // Create a dummy entry to catch online status update.\n const dummy = this._tinode.getTopic(pres.src);\n dummy.topic = pres.src;\n dummy.online = false;\n dummy.acs = acs;\n this._tinode._db.updTopic(dummy);\n }\n } else if (pres.what == 'tags') {\n this.getMeta(this.startMetaQuery().withTags().build());\n }\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n\n // Contact is updated, execute callbacks.\n _refreshContact(what, cont) {\n if (this.onContactUpdate) {\n this.onContactUpdate(what, cont);\n }\n }\n\n /**\n * Publishing to TopicMe is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicMe#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'me' is not supported\"));\n }\n\n /**\n * Delete validation credential.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} topic - Name of the topic to delete\n * @param {string} user - User ID to remove.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete credential in inactive 'me' topic\"));\n }\n // Send {del} message, return promise\n return this._tinode.delCredential(method, value).then(ctrl => {\n // Remove deleted credential from the cache.\n const index = this._credentials.findIndex((el) => {\n return el.meth == method && el.val == value;\n });\n if (index > -1) {\n this._credentials.splice(index, 1);\n }\n // Notify listeners\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n return ctrl;\n });\n }\n\n /**\n * @callback contactFilter\n * @param {Object} contact to check for inclusion.\n * @returns {boolean} true if contact should be processed, false to exclude it.\n */\n /**\n * Iterate over cached contacts.\n *\n * @function\n * @memberof Tinode.TopicMe#\n * @param {TopicMe.ContactCallback} callback - Callback to call for each contact.\n * @param {contactFilter=} filter - Optionally filter contacts; include all if filter is false-ish, otherwise\n * include those for which filter returns true-ish.\n * @param {Object=} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, filter, context) {\n this._tinode.mapTopics((c, idx) => {\n if (c.isCommType() && (!filter || filter(c))) {\n callback.call(context, c, idx);\n }\n });\n }\n\n /**\n * Get a contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get, either a UID (for p2p topics) or a topic name.\n * @returns {Tinode.Contact} - Contact or `undefined`.\n */\n getContact(name) {\n return this._tinode.cacheGetTopic(name);\n }\n\n /**\n * Get access mode of a given contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get access mode for, either a UID (for p2p topics)\n * or a topic name; if missing, access mode for the 'me' topic itself.\n * @returns {string} - access mode, such as `RWP`.\n */\n getAccessMode(name) {\n if (name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont ? cont.acs : null;\n }\n return this.acs;\n }\n\n /**\n * Check if contact is archived, i.e. contact.private.arch == true.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to check archived status, either a UID (for p2p topics) or a topic name.\n * @returns {boolean} - true if contact is archived, false otherwise.\n */\n isArchived(name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont && cont.private && !!cont.private.arch;\n }\n\n /**\n * @typedef Tinode.Credential\n * @memberof Tinode\n * @type Object\n * @property {string} meth - validation method such as 'email' or 'tel'.\n * @property {string} val - credential value, i.e. 'jdoe@example.com' or '+17025551234'\n * @property {boolean} done - true if credential is validated.\n */\n /**\n * Get the user's credentials: email, phone, etc.\n * @memberof Tinode.TopicMe#\n *\n * @returns {Tinode.Credential[]} - array of credentials.\n */\n getCredentials() {\n return this._credentials;\n }\n}\n"],"names":["root","factory","exports","module","define","amd","this","MAX_PREVIEW_DATA_SIZE","JSON_MIME_TYPE","ALLOWED_ENT_FIELDS","INLINE_STYLES","name","start","end","FMT_WEIGHT","ENTITY_TYPES","dataName","pack","val","test","url","re","slice","FORMAT_TAGS","AU","html_tag","md_tag","undefined","isVoid","BN","BR","CO","DL","EM","EX","FM","HD","HL","HT","IM","LN","MN","RW","QQ","ST","VC","VD","base64toObjectUrl","b64","contentType","logger","bin","atob","length","buf","ArrayBuffer","arr","Uint8Array","i","charCodeAt","URL","createObjectURL","Blob","type","err","message","base64toDataUrl","DECORATORS","open","_","close","data","props","href","target","id","act","ref","mime","Drafty","src","duration","size","tmpPreviewUrl","_tempPreview","previewUrl","downloadUrl","width","height","title","alt","state","preview","premime","poster","preref","txt","fmt","ent","chunkify","line","spans","chunks","span","at","push","chunk","tp","chld","children","toSpanTree","tree","last","draftyToTree","doc","Array","isArray","text","len","key","attachments","forEach","includes","sort","a","b","diff","indexOf","spansToTree","treeTopDown","node","child","parent","addNode","n","substring","att","subspans","inner","tag","treeToDrafty","keymap","c","Object","keys","newKey","transformer","context","dst","call","treeBottomUp","formatter","index","stack","values","pop","shortenTree","limit","tail","lightEntity","allow","copyEntData","lTrim","trimStart","shift","attachmentsToEnd","concat","draftify","startAt","plain","ranges","drafty","light","entries","dc","init","plainText","parse","content","lines","split","entityMap","entityIndex","blx","entities","block","original","re_start","re_end","result","exec","start_offset","lastIndexOf","end_offset","spannify","match","extracted","entity","offset","unique","idx","filter","el","extractEntities","map","s","append","first","second","insertImage","imageDesc","ex","refurl","bits","filename","urlPromise","_processing","then","insertVideo","videoDesc","urls","insertAudio","audioDesc","videoCall","audioOnly","aonly","updateVideoCall","params","assign","quote","header","uid","body","appendLineBreak","mention","appendLink","linkData","appendImage","appendAudio","attachFile","attachmentDesc","wrapInto","style","wrapAsForm","insertButton","actionType","actionValue","refUrl","appendButton","attachJSON","UNSAFE_toHTML","join","format","shorten","forwardedContent","replyContent","startsWith","forwarding","toPlainText","isPlainText","toMarkdown","def","isValid","txt_type","hasAttachments","callback","count","hasEntities","styles","sanitizeEntities","getDownloadUrl","entData","isProcessing","getPreviewUrl","getEntitySize","getEntityMimeType","tagName","attrValue","getContentType","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","getter","__esModule","d","definition","o","defineProperty","enumerable","get","g","globalThis","Function","e","window","obj","prop","prototype","hasOwnProperty","r","Symbol","toStringTag","value","AccessMode","constructor","acs","given","decode","want","mode","static","side","flag","Error","str","_BITMASK","_NONE","bitmask","_JOIN","_READ","_WRITE","_PRES","_APPROVE","_SHARE","_DELETE","_OWNER","m0","bit","charAt","toUpperCase","_INVALID","res","upd","action","val0","parts","a1","a2","toString","encode","jsonHelper","setMode","m","updateMode","u","update","getMode","setGiven","updateGiven","getGiven","setWant","w","updateWant","getWant","getMissing","getExcessive","updateAll","isOwner","isPresencer","isMuted","isJoiner","isReader","isWriter","isApprover","isAdmin","isSharer","isDeleter","VERSION","LIBRARY","TOPIC_NEW","TOPIC_NEW_CHAN","TOPIC_ME","TOPIC_FND","TOPIC_GRP","LOCAL_SEQID","DEL_CHAR","CommError","code","super","jsonParseHelper","date","Date","isNaN","isUrlRelative","isValidDate","getTime","mergeObj","ignore","mergeToCache","cache","newval","simplify","getOwnPropertyNames","normalizeRanges","maxSeq","r1","r2","low","hi","reduce","out","listToRanges","list","prev","Math","max","WebSocketProvider","XHRProvider","NETWORK_ERROR_TEXT","NETWORK_USER","NETWORK_USER_TEXT","makeBaseUrl","host","protocol","version","apiKey","Connection","secure","autoreconnect","initialized","config","version_","autoreconnect_","transport","wsProvider","xhrProvider","l","connect","host_","force","Promise","reject","reconnect","disconnect","sendText","msg","isConnected","probe","backoffReset","clearTimeout","timeout","pow","random","onAutoreconnectIteration","setTimeout","prom","catch","_lpURL","_poller","_sender","lp_poller","url_","resolve","poller","promiseCompleted","onreadystatechange","evt","readyState","status","pkt","JSON","responseText","ctrl","sid","send","onOpen","onMessage","onDisconnect","abort","sender","lp_sender","OPEN","conn","onerror","onopen","onclose","onmessage","NETWORK_ERROR","DB_NAME","IDBProvider","DB","db","disabled","onError","source","trx","transaction","event","error","objectStore","getAll","onsuccess","topic","initDatabase","req","onupgradeneeded","createObjectStore","keyPath","createIndex","deleteDatabase","onblocked","isReady","updTopic","oncomplete","put","commit","markTopicAsDeleted","_deleted","remTopic","delete","IDBKeyRange","only","bound","Number","MAX_SAFE_INTEGER","mapTopics","deserializeTopic","updUser","pub","arguments","public","remUser","mapUsers","getUser","user","updSubscription","topicName","sub","mapSubscriptions","addMessage","add","updMessageStatus","seq","_status","remMessages","from","to","range","readMessages","query","msgs","since","before","openCursor","cursor","continue","addDelLog","delId","clear","readDelLog","maxDelId","f","tags","_tags","setAccessMode","read","unread","getAccessMode","idbProvider","IndexedDBProvider","LargeFileHelper","tinode","_tinode","_version","_apiKey","_authToken","getAuthToken","xhr","uploadWithBaseUrl","baseUrl","avatarFor","onProgress","onSuccess","onFailure","base","endsWith","instance","setRequestHeader","token","toResolve","toReject","upload","onprogress","lengthComputable","loaded","total","onload","response","statusText","onabort","form","FormData","set","getNextUniqueId","_secure","_host","download","relativeUrl","mimetype","relUrl","location","origin","searchParams","addURLParam","responseType","link","document","createElement","display","setAttribute","appendChild","click","removeChild","revokeObjectURL","reader","FileReader","readAsText","cancel","MetaGetBuilder","what","updated","isP2PType","_lastSubsUpdate","withData","withLaterData","_maxSeq","withDataRanges","withDataList","withEarlierData","_minSeq","withDesc","ims","withLaterDesc","withSub","userOrTopic","opts","getType","withOneSub","withLaterOneSub","withLaterSub","withTags","withCred","withAux","withDel","withLaterDel","_maxDel","extract","build","CBuffer","buffer","compare_","unique_","elem","exact","pivot","found","splice","getAt","getLast","insert","delAt","delRange","reset","startIdx","beforeIdx","min","find","nearest","isEmpty","Topic","callbacks","created","touched","private","trusted","_users","_queuedSeqId","Const","_noEarlierMsgs","_recvNotificationTimer","_credentials","_aux","_messageVersions","_messages","_attached","_new","_delayedLeaveTimer","onData","onMeta","onPres","onInfo","onMetaDesc","onMetaSub","onSubsUpdated","onTagsUpdated","onCredsUpdated","onAuxUpdated","onDeleteTopic","onAllMessagesReceived","topicType","isP2PTopicName","isGroupTopicName","head","replace","isSubscribed","subscribe","getParams","setParams","_cacheDelSelf","_cachePutSelf","ts","me","getMeTopic","desc","_noForwarding","_processMetaDesc","createMessage","noEcho","publish","publishMessage","_sending","_failed","swapMessageId","_maybeUpdateMessageVersionsCache","_routeData","publishDraft","_getQueuedSeqId","getCurrentUserID","noecho","_db","_cancelled","_fatal","leave","unsub","_resetSub","_gone","leaveDelayed","delay","getMeta","getMessagesPage","gaps","newer","startMetaQuery","_loadMessages","msgHasMoreMessages","getPinnedMessages","pins","aux","remains","setMeta","t","trim","toLowerCase","item","pos","ary","normalizeArray","_processMetaSub","_processMetaTags","cred","_processMetaCreds","_processMetaAux","subscriber","am","invite","archive","arch","pinMessage","pin","pinned","changed","delMessages","hard","tosend","del","rec","flushMessageRange","flushMessage","delMessagesAll","hardDel","_all","delMessagesList","delMessagesEdits","messageVersions","delTopic","delSubscription","note","_updateReadRecv","_refreshContact","noteRecv","noteRead","noteKeyPress","noteRecording","payload","oldVal","doUpdate","recv","userDesc","_cacheGetUser","p2pPeerDesc","subscribers","cb","origSeq","versions","messages","sinceId","beforeId","unused1","unused2","latest","latestMsgVersion","_origTs","_origSeq","findMessage","latestMessage","maxMsgSeq","minMsgSeq","maxClearId","messageCount","queuedMessages","msgReceiptCount","msgReadCount","msgRecvCount","gap","p","expected","isNewMessage","seqId","fromId","untilId","newSeqId","numMessages","cancelSend","msgStatus","getDefaultAccess","defacs","isArchived","isMeType","isMeTopicName","isChannelType","isChannelTopicName","isGroupType","isCommType","isCommTopicName","isMe","targetSeq","parseInt","targetMsg","outgoing","webrtc","incoming","_routeMeta","meta","_processDelMessages","delseq","_routePres","pres","online","isTopicCached","dacs","_routeInfo","info","subs","deleted","_updateCachedUser","creds","_allMessagesReceived","cached","_cachePutUser","dellog","_updateReceived","TopicFnd","_contacts","updateCount","indexBy","getPrototypeOf","contacts","TopicMe","onContactUpdate","turnOff","_myUID","cont","seen","when","cacheRemTopic","getTopic","cr","findIndex","meth","done","resp","cacheGetTopic","ua","dummy","delCredential","method","getContact","getCredentials","b64EncodeUnicode","btoa","encodeURIComponent","p1","String","fromCharCode","jsonBuildHelper","pad","sp","repeat","millis","getUTCMilliseconds","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","rfc3339DateString","jsonLoggerHelper","WebSocket","XMLHttpRequest","indexedDB","chars","global","output","charCode","bc","bs","setNetworkProviders","setNetworkProvider","DBCache","initForNonBrowserApp","Tinode","_appName","_browser","_platform","_hwos","_humanLanguage","_loggingEnabled","_trimLongStrings","_authenticated","_login","_inPacketCount","_messageId","floor","_serverInfo","_deviceToken","_pendingPromises","_expirePromises","_connection","_persist","_cache","onComplete","appName","platform","navigator","product","reactnative","priority","tmp","substr","tokens","m2","v","minor","getBrowserInfo","userAgent","language","detectTransport","promise","persist","all","dateString","_len","args","_key","console","log","onOK","errorText","stringify","onRawMessage","onNetworkProbe","onCtrlMessage","onMetaMessage","onDataMessage","onPresMessage","onInfoMessage","setInterval","expires","hello","clearInterval","func","_cacheDelUser","onLogin","isNewGroupTopicName","clearStorage","initStorage","networkProbe","isAuthenticated","authorizeURL","parsed","account","scheme","secret","login","acc","tmpscheme","tmpsecret","extra","createAccount","createAccountBasic","username","password","updateAccountBasic","onConnect","setDeviceToken","dt","sent","loginBasic","uname","loginToken","requestResetAuthSecret","now","setAuthToken","dft","oobNotification","xfrom","finally","modeGiven","modeWant","delCurrentUser","newGroupTopicName","isChan","getFndTopic","getLargeFileHelper","getCurrentLogin","getServerInfo","report","getServerParam","defaultValue","enableLogging","enabled","trimLongStrings","setHumanLanguage","hl","isTopicOnline","getTopicAccessMode","wantAkn","onWebsocketOpen","MESSAGE_STATUS_NONE","MESSAGE_STATUS_QUEUED","MESSAGE_STATUS_SENDING","MESSAGE_STATUS_FAILED","MESSAGE_STATUS_FATAL","MESSAGE_STATUS_SENT","MESSAGE_STATUS_RECEIVED","MESSAGE_STATUS_READ","MESSAGE_STATUS_TO_ME","MAX_MESSAGE_SIZE","MAX_SUBSCRIBER_COUNT","MAX_TAG_COUNT","MAX_FILE_UPLOAD_SIZE","REQ_CRED_VALIDATORS"],"sourceRoot":""}
\ No newline at end of file