diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c3124d..03d7de6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 0.1.1 + +- Add `THIRD-PARTY-NOTICES` with the copyright and MIT license texts of + pusher-js, @stablelib/base64, @stablelib/utf8 and qrcode-generator, which + `dist/cp.js` bundles, and a short notice at the top of `dist/cp.js`. +- Events are sent after the response, so a save never waits on Hibira. +- Comment events carry only the comment's ID and pages fetch the comment, + so long comments in any script appear live on every plan. +- The comment file is encoded before it is rewritten, and comments with + invalid UTF-8 are refused, so a failed write can't empty it. +- The comments card shows when loading failed, with a retry button, and + clears an old error after a later success. +- README: Statamic Pro, what passes through Hibira (hosted in Hong Kong), + plan limits and support contact. + ## 0.1.0 - Avatars of everyone who has the same entry open, and a warning when one diff --git a/README.md b/README.md index 2acb880..de62fa1 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,11 @@ Realtime teamwork for the [Statamic](https://statamic.com) control panel, on Works with Statamic 5 and 6, flat file or database. Comments need no database, and there is nothing to publish or build. +Avatars, saved warnings and shared comments are about several people +working in the same control panel, so they need more than one control panel +user, which in Statamic generally means [Statamic Pro](https://statamic.com/pricing). +Live preview on another device is useful on Statamic Solo too. + ![The dock, comments and a saved warning](art/comments-light.png) ## Install @@ -88,8 +93,12 @@ don't use such an addon. - Each entry has a presence channel. The control panel signs subscriptions on its own route, for users who may view the entry, so you don't have to change your app's broadcasting setup. -- Comments are stored first, then sent to the others on the entry's channel. - A page that lost its connection fetches them again when it reconnects. +- Comments are stored first. The others on the entry's channel get only the + comment's ID and fetch the comment from the control panel, so long + comments in any script go live. A page that lost its connection fetches + them again when it reconnects. +- Events are sent after the response, so saving never waits on Hibira, even + if it can't be reached. - A live preview page opened outside the control panel listens on a public channel named after a keyed hash of its preview token, so only someone with the link can find it, and its events carry no content. Events are sent only @@ -97,6 +106,34 @@ don't use such an addon. - Each open edit page is one connection, and each preview page opened on another device is one more. +## Your data and Hibira + +Events go through [Hibira](https://hibira.io), a hosted WebSocket service +whose servers are in Hong Kong. What passes through it: + +- the name (or email, when no name is set), initials and avatar URL of each + control panel user who has an entry open, and the name of whoever saved + it; +- entry and comment IDs, so open pages know to fetch comments again. The + comment text itself stays on your server and is fetched from your own + control panel; +- for live preview on another device, a reload signal with no content. + +See the [privacy policy](https://hibira.io/legal/privacy). + +## Plan limits + +Each open edit page is one connection, and each preview page opened on +another device is one more. The free plan allows 100 concurrent connections +and one app, which fits a small team; paid plans raise the connection, daily +message and message size limits. Comments are never limited by message size, +because only their IDs are sent. See [hibira.io/pricing](https://hibira.io/pricing). + +## Support + +Open an issue at [github.com/hibira-io/statamic/issues](https://github.com/hibira-io/statamic/issues) +or write to [support@hibira.io](mailto:support@hibira.io). + ## Testing ```sh @@ -108,12 +145,16 @@ with `npm ci && npm run build`. ## License -MIT +MIT. `dist/cp.js` includes pusher-js, @stablelib/base64, @stablelib/utf8 and +qrcode-generator, all MIT licensed; their notices are in +[THIRD-PARTY-NOTICES](THIRD-PARTY-NOTICES). ## 中文摘要 在 Statamic 控制台加上即時協作:同一篇內容誰也開著(頭像),有人儲存時立刻提醒重新載入; 即時留言(可標記已解決,只能看不能改的審稿人也能留言);用手機掃 QR Code 開即時預覽, 每次修改內容手機頁面就自動重新載入。支援 Statamic 5 與 6,留言存成 JSON 檔不需要資料庫。 +多人協作功能需要多個控制台使用者(通常是 Statamic Pro)。使用者名稱、頭像網址與留言 ID 會經過位於香港的 Hibira; +留言內容留在你的伺服器上。免費方案 100 個同時連線、1 個 App。客服:support@hibira.io。 安裝:`composer require hibira-io/statamic`,`php artisan hibira:install` 填入 [hibira.io/portal](https://hibira.io/portal) 的 App ID、Key、Secret,並把網站網址加到 Allowed origins。 diff --git a/THIRD-PARTY-NOTICES b/THIRD-PARTY-NOTICES new file mode 100644 index 0000000..f5a33ba --- /dev/null +++ b/THIRD-PARTY-NOTICES @@ -0,0 +1,81 @@ +THIRD-PARTY NOTICES + +dist/cp.js, the control panel script of this addon, includes code from the +open source projects below. Each is distributed under the MIT License, whose +text follows each notice. + +------------------------------------------------------------------------------- +pusher-js 8.6.0 +https://github.com/pusher/pusher-js + +Copyright (c) 2020 Pusher, Ltd (https://pusher.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +------------------------------------------------------------------------------- +@stablelib/base64 and @stablelib/utf8 (bundled inside pusher-js) +https://github.com/StableLib/stablelib + +Copyright (C) 2016 Dmitry Chestnykh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +------------------------------------------------------------------------------- +qrcode-generator 1.5.2 +https://github.com/kazuhikoarase/qrcode-generator + +Copyright (c) 2009 Kazuhiko Arase + +URL: http://www.d-project.com/ + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +The word "QR Code" is a registered trademark of DENSO WAVE INCORPORATED. diff --git a/dist/cp.js b/dist/cp.js index 1c33dd5..69b1a3c 100644 --- a/dist/cp.js +++ b/dist/cp.js @@ -1,7 +1,8 @@ -(()=>{var Un=Object.create;var Le=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Fn=Object.getPrototypeOf,$n=Object.prototype.hasOwnProperty;var Ee=(A,o)=>()=>(o||A((o={exports:{}}).exports,o),o.exports);var Xn=(A,o,g,P)=>{if(o&&typeof o=="object"||typeof o=="function")for(let E of zn(o))!$n.call(A,E)&&E!==g&&Le(A,E,{get:()=>o[E],enumerable:!(P=qn(o,E))||P.enumerable});return A};var Re=(A,o,g)=>(g=A!=null?Un(Fn(A)):{},Xn(o||!A||!A.__esModule?Le(g,"default",{value:A,enumerable:!0}):g,A));var Me=Ee((zt,ne)=>{(function(o,g){typeof zt=="object"&&typeof ne=="object"?ne.exports=g():typeof define=="function"&&define.amd?define([],g):typeof zt=="object"?zt.Pusher=g():o.Pusher=g()})(self,()=>(()=>{var A={594(E,L){"use strict";var z=this&&this.__extends||(function(){var M=function(S,c){return M=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,v){b.__proto__=v}||function(b,v){for(var x in v)v.hasOwnProperty(x)&&(b[x]=v[x])},M(S,c)};return function(S,c){M(S,c);function b(){this.constructor=S}S.prototype=c===null?Object.create(c):(b.prototype=c.prototype,new b)}})();Object.defineProperty(L,"__esModule",{value:!0});var W=256,it=(function(){function M(S){S===void 0&&(S="="),this._paddingCharacter=S}return M.prototype.encodedLength=function(S){return this._paddingCharacter?(S+2)/3*4|0:(S*8+5)/6|0},M.prototype.encode=function(S){for(var c="",b=0;b>>18&63),c+=this._encodeByte(v>>>12&63),c+=this._encodeByte(v>>>6&63),c+=this._encodeByte(v>>>0&63)}var x=S.length-b;if(x>0){var v=S[b]<<16|(x===2?S[b+1]<<8:0);c+=this._encodeByte(v>>>18&63),c+=this._encodeByte(v>>>12&63),x===2?c+=this._encodeByte(v>>>6&63):c+=this._paddingCharacter||"",c+=this._paddingCharacter||""}return c},M.prototype.maxDecodedLength=function(S){return this._paddingCharacter?S/4*3|0:(S*6+7)/8|0},M.prototype.decodedLength=function(S){return this.maxDecodedLength(S.length-this._getPaddingLength(S))},M.prototype.decode=function(S){if(S.length===0)return new Uint8Array(0);for(var c=this._getPaddingLength(S),b=S.length-c,v=new Uint8Array(this.maxDecodedLength(b)),x=0,u=0,_=0,a=0,s=0,y=0,d=0;u>>4,v[x++]=s<<4|y>>>2,v[x++]=y<<6|d,_|=a&W,_|=s&W,_|=y&W,_|=d&W;if(u>>4,_|=a&W,_|=s&W),u>>2,_|=y&W),u>>8&6,c+=51-S>>>8&-75,c+=61-S>>>8&-15,c+=62-S>>>8&3,String.fromCharCode(c)},M.prototype._decodeChar=function(S){var c=W;return c+=(42-S&S-44)>>>8&-W+S-43+62,c+=(46-S&S-48)>>>8&-W+S-47+63,c+=(47-S&S-58)>>>8&-W+S-48+52,c+=(64-S&S-91)>>>8&-W+S-65+0,c+=(96-S&S-123)>>>8&-W+S-97+26,c},M.prototype._getPaddingLength=function(S){var c=0;if(this._paddingCharacter){for(var b=S.length-1;b>=0&&S[b]===this._paddingCharacter;b--)c++;if(S.length<4||c>2)throw new Error("Base64Coder: incorrect padding")}return c},M})();L.Coder=it;var ut=new it;function G(M){return ut.encode(M)}L.encode=G;function wt(M){return ut.decode(M)}L.decode=wt;var Z=(function(M){z(S,M);function S(){return M!==null&&M.apply(this,arguments)||this}return S.prototype._encodeByte=function(c){var b=c;return b+=65,b+=25-c>>>8&6,b+=51-c>>>8&-75,b+=61-c>>>8&-13,b+=62-c>>>8&49,String.fromCharCode(b)},S.prototype._decodeChar=function(c){var b=W;return b+=(44-c&c-46)>>>8&-W+c-45+62,b+=(94-c&c-96)>>>8&-W+c-95+63,b+=(47-c&c-58)>>>8&-W+c-48+52,b+=(64-c&c-91)>>>8&-W+c-65+0,b+=(96-c&c-123)>>>8&-W+c-97+26,b},S})(it);L.URLSafeCoder=Z;var K=new Z;function F(M){return K.encode(M)}L.encodeURLSafe=F;function $(M){return K.decode(M)}L.decodeURLSafe=$,L.encodedLength=function(M){return ut.encodedLength(M)},L.maxDecodedLength=function(M){return ut.maxDecodedLength(M)},L.decodedLength=function(M){return ut.decodedLength(M)}},978(E,L){"use strict";var z;z={value:!0};var W="utf8: invalid string",it="utf8: invalid source encoding";function ut(Z){for(var K=new Uint8Array(G(Z)),F=0,$=0;$>6,K[F++]=128|M&63):M<55296?(K[F++]=224|M>>12,K[F++]=128|M>>6&63,K[F++]=128|M&63):($++,M=(M&1023)<<10,M|=Z.charCodeAt($)&1023,M+=65536,K[F++]=240|M>>18,K[F++]=128|M>>12&63,K[F++]=128|M>>6&63,K[F++]=128|M&63)}return K}z=ut;function G(Z){for(var K=0,F=0;F=Z.length-1)throw new Error(W);F++,K+=4}else throw new Error(W)}return K}z=G;function wt(Z){for(var K=[],F=0;F=Z.length)throw new Error(it);var S=Z[++F];if((S&192)!==128)throw new Error(it);$=($&31)<<6|S&63,M=128}else if($<240){if(F>=Z.length-1)throw new Error(it);var S=Z[++F],c=Z[++F];if((S&192)!==128||(c&192)!==128)throw new Error(it);$=($&15)<<12|(S&63)<<6|c&63,M=2048}else if($<248){if(F>=Z.length-2)throw new Error(it);var S=Z[++F],c=Z[++F],b=Z[++F];if((S&192)!==128||(c&192)!==128||(b&192)!==128)throw new Error(it);$=($&15)<<18|(S&63)<<12|(c&63)<<6|b&63,M=65536}else throw new Error(it);if($=55296&&$<=57343)throw new Error(it);if($>=65536){if($>1114111)throw new Error(it);$-=65536,K.push(String.fromCharCode(55296|$>>10)),$=56320|$&1023}}K.push(String.fromCharCode($))}return K.join("")}L.D4=wt},721(E,L,z){E.exports=z(207).default},207(E,L,z){"use strict";z.d(L,{default:()=>Ut});class W{constructor(t,e){this.lastId=0,this.prefix=t,this.name=e}create(t){this.lastId++;var e=this.lastId,n=this.prefix+e,i=this.name+"["+e+"]",l=!1,k=function(){l||(t.apply(null,arguments),l=!0)};return this[e]=k,{number:e,id:n,name:i,callback:k}}remove(t){delete this[t.number]}}var it=new W("_pusher_script_","Pusher.ScriptReceivers"),ut={VERSION:"8.6.0",PROTOCOL:7,wsPort:80,wssPort:443,wsPath:"",httpHost:"sockjs.pusher.com",httpPort:80,httpsPort:443,httpPath:"/pusher",stats_host:"stats.pusher.com",authEndpoint:"/pusher/auth",authTransport:"ajax",activityTimeout:12e4,pongTimeout:3e4,unavailableTimeout:1e4,userAuthentication:{endpoint:"/pusher/user-auth",transport:"ajax"},channelAuthorization:{endpoint:"/pusher/auth",transport:"ajax"},cdn_http:"http://js.pusher.com",cdn_https:"https://js.pusher.com",dependency_suffix:""};let G=ut;class wt{constructor(t){this.options=t,this.receivers=t.receivers||it,this.loading={}}load(t,e,n){var i=this;if(i.loading[t]&&i.loading[t].length>0)i.loading[t].push(n);else{i.loading[t]=[n];var l=j.createScriptRequest(i.getPath(t,e)),k=i.receivers.create(function(O){if(i.receivers.remove(k),i.loading[t]){var H=i.loading[t];delete i.loading[t];for(var J=function(st){st||l.cleanup()},V=0;V>>6)+N(128|t&63):N(224|t>>>12&15)+N(128|t>>>6&63)+N(128|t&63)},dt=function(r){return r.replace(/[^\x00-\x7F]/g,lt)},bt=function(r){var t=[0,2,1][r.length%3],e=r.charCodeAt(0)<<16|(r.length>1?r.charCodeAt(1):0)<<8|(r.length>2?r.charCodeAt(2):0),n=[X.charAt(e>>>18),X.charAt(e>>>12&63),t>=2?"=":X.charAt(e>>>6&63),t>=1?"=":X.charAt(e&63)];return n.join("")},$t=typeof window!="undefined"&&window.btoa||function(r){return r.replace(/[\s\S]{1,3}/g,bt)};class mt{constructor(t,e,n,i){this.clear=e,this.timer=t(()=>{this.timer&&(this.timer=i(this.timer))},n)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}let It=mt;function f(r){window.clearTimeout(r)}function p(r){window.clearInterval(r)}class h extends It{constructor(t,e){super(setTimeout,f,t,function(n){return e(),null})}}class m extends It{constructor(t,e){super(setInterval,p,t,function(n){return e(),n})}}var w={now(){return Date.now?Date.now():new Date().valueOf()},defer(r){return new h(0,r)},method(r,...t){var e=Array.prototype.slice.call(arguments,1);return function(n){return n[r].apply(n,e.concat(arguments))}}};let T=w;function R(r,...t){for(var e=0;e{window.console&&window.console.log&&window.console.log(t)}}debug(...t){this.log(this.globalLog,t)}warn(...t){this.log(this.globalLogWarn,t)}error(...t){this.log(this.globalLogError,t)}globalLogWarn(t){window.console&&window.console.warn?window.console.warn(t):this.globalLog(t)}globalLogError(t){window.console&&window.console.error?window.console.error(t):this.globalLogWarn(t)}log(t,...e){var n=I.apply(this,arguments);Ut.log?Ut.log(n):Ut.logToConsole&&t.bind(this)(n)}}let et=new Ge;var Qe=function(r,t,e,n,i){(e.headers!==void 0||e.headersProvider!=null)&&et.warn(`To send headers with the ${n.toString()} request, you must use AJAX, rather than JSONP.`);var l=r.nextAuthCallbackID.toString();r.nextAuthCallbackID++;var k=r.getDocument(),O=k.createElement("script");r.auth_callbacks[l]=function(V){i(null,V)};var H="Pusher.auth_callbacks['"+l+"']";O.src=e.endpoint+"?callback="+encodeURIComponent(H)+"&"+t;var J=k.getElementsByTagName("head")[0]||k.documentElement;J.insertBefore(O,J.firstChild)};let Ve=Qe;class Ye{constructor(t){this.src=t}send(t){var e=this,n="Error loading "+e.src;e.script=document.createElement("script"),e.script.id=t.id,e.script.src=e.src,e.script.type="text/javascript",e.script.charset="UTF-8",e.script.addEventListener?(e.script.onerror=function(){t.callback(n)},e.script.onload=function(){t.callback(null)}):e.script.onreadystatechange=function(){(e.script.readyState==="loaded"||e.script.readyState==="complete")&&t.callback(null)},e.script.async===void 0&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(e.errorScript=document.createElement("script"),e.errorScript.id=t.id+"_error",e.errorScript.text=t.name+"('"+n+"');",e.script.async=e.errorScript.async=!1):e.script.async=!0;var i=document.getElementsByTagName("head")[0];i.insertBefore(e.script,i.firstChild),e.errorScript&&i.insertBefore(e.errorScript,e.script.nextSibling)}cleanup(){this.script&&(this.script.onload=this.script.onerror=null,this.script.onreadystatechange=null),this.script&&this.script.parentNode&&this.script.parentNode.removeChild(this.script),this.errorScript&&this.errorScript.parentNode&&this.errorScript.parentNode.removeChild(this.errorScript),this.script=null,this.errorScript=null}}class Ze{constructor(t,e){this.url=t,this.data=e}send(t){if(!this.request){var e=We(this.data),n=this.url+"/"+t.number+"?"+e;this.request=j.createScriptRequest(n),this.request.send(t)}}cleanup(){this.request&&this.request.cleanup()}}var tr=function(r,t){return function(e,n){var i="http"+(t?"s":"")+"://",l=i+(r.host||r.options.host)+r.options.path,k=j.createJSONPRequest(l,e),O=j.ScriptReceivers.create(function(H,J){it.remove(O),k.cleanup(),J&&J.host&&(r.host=J.host),n&&n(H,J)});k.send(O)}},er={name:"jsonp",getAgent:tr};let rr=er;function Xt(r,t,e){var n=r+(t.useTLS?"s":""),i=t.useTLS?t.hostTLS:t.hostNonTLS;return n+"://"+i+e}function Jt(r,t){var e="/app/"+r,n="?protocol="+G.PROTOCOL+"&client=js&version="+G.VERSION+(t?"&"+t:"");return e+n}var nr={getInitial:function(r,t){var e=(t.httpPath||"")+Jt(r,"flash=false");return Xt("ws",t,e)}},ir={getInitial:function(r,t){var e=(t.httpPath||"/pusher")+Jt(r);return Xt("http",t,e)}},sr={getInitial:function(r,t){return Xt("http",t,t.httpPath||"/pusher")},getPath:function(r,t){return Jt(r)}};class or{constructor(){this._callbacks={}}get(t){return this._callbacks[Wt(t)]}add(t,e,n){var i=Wt(t);this._callbacks[i]=this._callbacks[i]||[],this._callbacks[i].push({fn:e,context:n})}remove(t,e,n){if(!t&&!e&&!n){this._callbacks={};return}var i=t?[Wt(t)]:D(this._callbacks);e||n?this.removeCallback(i,e,n):this.removeAllCallbacks(i)}removeCallback(t,e,n){ot(t,function(i){this._callbacks[i]=Lt(this._callbacks[i]||[],function(l){return e&&e!==l.fn||n&&n!==l.context}),this._callbacks[i].length===0&&delete this._callbacks[i]},this)}removeAllCallbacks(t){ot(t,function(e){delete this._callbacks[e]},this)}}function Wt(r){return"_"+r}class gt{constructor(t){this.callbacks=new or,this.global_callbacks=[],this.failThrough=t}bind(t,e,n){return this.callbacks.add(t,e,n),this}bind_global(t){return this.global_callbacks.push(t),this}unbind(t,e,n){return this.callbacks.remove(t,e,n),this}unbind_global(t){return t?(this.global_callbacks=Lt(this.global_callbacks||[],e=>e!==t),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(t,e,n){for(var i=0;i0)for(var i=0;i{this.onError(e),this.changeState("closed")}),!1}return this.bindListeners(),et.debug("Connecting",{transport:this.name,url:t}),this.changeState("connecting"),!0}close(){return this.socket?(this.socket.close(),!0):!1}send(t){return this.state==="open"?(T.defer(()=>{this.socket&&this.socket.send(t)}),!0):!1}ping(){this.state==="open"&&this.supportsPing()&&this.socket.ping()}onOpen(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0}onError(t){this.emit("error",{type:"WebSocketError",error:t}),this.timeline.error(this.buildTimelineMessage({error:t.toString()}))}onClose(t){t?this.changeState("closed",{code:t.code,reason:t.reason,wasClean:t.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(t){this.emit("message",t)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=t=>{this.onError(t)},this.socket.onclose=t=>{this.onClose(t)},this.socket.onmessage=t=>{this.onMessage(t)},this.supportsPing()&&(this.socket.onactivity=()=>{this.onActivity()})}unbindListeners(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))}changeState(t,e){this.state=t,this.timeline.info(this.buildTimelineMessage({state:t,params:e})),this.emit(t,e)}buildTimelineMessage(t){return R({cid:this.id},t)}}class kt{constructor(t){this.hooks=t}isSupported(t){return this.hooks.isSupported(t)}createConnection(t,e,n,i){return new ar(this.hooks,t,e,n,i)}}var hr=new kt({urls:nr,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!j.getWebSocketAPI()},isSupported:function(){return!!j.getWebSocketAPI()},getSocket:function(r){return j.createWebSocket(r)}}),ae={urls:ir,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},he=R({getSocket:function(r){return j.HTTPFactory.createStreamingSocket(r)}},ae),ce=R({getSocket:function(r){return j.HTTPFactory.createPollingSocket(r)}},ae),ue={isSupported:function(){return j.isXHRSupported()}},cr=new kt(R({},he,ue)),ur=new kt(R({},ce,ue)),lr={ws:hr,xhr_streaming:cr,xhr_polling:ur};let Nt=lr;var dr=new kt({file:"sockjs",urls:sr,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return window.SockJS!==void 0},getSocket:function(r,t){return new window.SockJS(r,null,{js_path:K.getPath("sockjs",{useTLS:t.useTLS}),ignore_null_origin:t.ignoreNullOrigin})},beforeOpen:function(r,t){r.send(JSON.stringify({path:t}))}}),le={isSupported:function(r){var t=j.isXDRSupported(r.useTLS);return t}},fr=new kt(R({},he,le)),pr=new kt(R({},ce,le));Nt.xdr_streaming=fr,Nt.xdr_polling=pr,Nt.sockjs=dr;let gr=Nt;class vr extends gt{constructor(){super();var t=this;typeof window!="undefined"&&window.addEventListener!==void 0&&(window.addEventListener("online",function(){t.emit("online")},!1),window.addEventListener("offline",function(){t.emit("offline")},!1))}isOnline(){return window.navigator.onLine===void 0?!0:window.navigator.onLine}}var br=new vr;class mr{constructor(t,e,n){this.manager=t,this.transport=e,this.minPingDelay=n.minPingDelay,this.maxPingDelay=n.maxPingDelay,this.pingDelay=void 0}createConnection(t,e,n,i){i=R({},i,{activityTimeout:this.pingDelay});var l=this.transport.createConnection(t,e,n,i),k=null,O=function(){l.unbind("open",O),l.bind("closed",H),k=T.now()},H=J=>{if(l.unbind("closed",H),J.code===1002||J.code===1003)this.manager.reportDeath();else if(!J.wasClean&&k){var V=T.now()-k;V<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(V/2,this.minPingDelay))}};return l.bind("open",O),l}isSupported(t){return this.manager.isAlive()&&this.transport.isSupported(t)}}let de={decodeMessage:function(r){try{var t=JSON.parse(r.data),e=t.data;if(typeof e=="string")try{e=JSON.parse(t.data)}catch{}var n={event:t.event,channel:t.channel,data:e};return t.user_id&&(n.user_id=t.user_id),n}catch(i){throw{type:"MessageParseError",error:i,data:r.data}}},encodeMessage:function(r){return JSON.stringify(r)},processHandshake:function(r){var t=de.decodeMessage(r);if(t.event==="pusher:connection_established"){if(!t.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:t.data.socket_id,activityTimeout:t.data.activity_timeout*1e3}}else{if(t.event==="pusher:error")return{action:this.getCloseAction(t.data),error:this.getCloseError(t.data)};throw"Invalid handshake"}},getCloseAction:function(r){return r.code<4e3?r.code>=1002&&r.code<=1004?"backoff":null:r.code===4e3?"tls_only":r.code<4100?"refused":r.code<4200?"backoff":r.code<4300?"retry":"refused"},getCloseError:function(r){return r.code!==1e3&&r.code!==1001?{type:"PusherError",data:{code:r.code,message:r.reason||r.message}}:null}},yt=de;class wr extends gt{constructor(t,e){super(),this.id=t,this.transport=e,this.activityTimeout=e.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(t){return this.transport.send(t)}send_event(t,e,n){var i={event:t,data:e};return n&&(i.channel=n),et.debug("Event sent",i),this.send(yt.encodeMessage(i))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var t={message:n=>{var i;try{i=yt.decodeMessage(n)}catch(l){this.emit("error",{type:"MessageParseError",error:l,data:n.data})}if(i!==void 0){switch(et.debug("Event recd",i),i.event){case"pusher:error":this.emit("error",{type:"PusherError",data:i.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong");break}this.emit("message",i)}},activity:()=>{this.emit("activity")},error:n=>{this.emit("error",n)},closed:n=>{e(),n&&n.code&&this.handleCloseEvent(n),this.transport=null,this.emit("closed")}},e=()=>{Q(t,(n,i)=>{this.transport.unbind(i,n)})};Q(t,(n,i)=>{this.transport.bind(i,n)})}handleCloseEvent(t){var e=yt.getCloseAction(t),n=yt.getCloseError(t);n&&this.emit("error",n),e&&this.emit(e,{action:e,error:n})}}class yr{constructor(t,e){this.transport=t,this.callback=e,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=t=>{this.unbindListeners();var e;try{e=yt.processHandshake(t)}catch(n){this.finish("error",{error:n}),this.transport.close();return}e.action==="connected"?this.finish("connected",{connection:new wr(e.id,this.transport),activityTimeout:e.activityTimeout}):(this.finish(e.action,{error:e.error}),this.transport.close())},this.onClosed=t=>{this.unbindListeners();var e=yt.getCloseAction(t)||"backoff",n=yt.getCloseError(t);this.finish(e,{error:n})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)}unbindListeners(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)}finish(t,e){this.callback(R({transport:this.transport,action:t},e))}}class xr{constructor(t,e){this.timeline=t,this.options=e||{}}send(t,e){this.timeline.isEmpty()||this.timeline.send(j.TimelineTransport.getAgent(this,t),e)}}class Kt extends gt{constructor(t,e){super(function(n,i){et.debug("No callbacks on "+t+" for "+n)}),this.name=t,this.pusher=e,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(t,e){return e(null,{auth:""})}trigger(t,e){if(t.indexOf("client-")!==0)throw new c("Event '"+t+"' does not start with 'client-'");if(!this.subscribed){var n=M.buildLogSuffix("triggeringClientEvents");et.warn(`Client event triggered before channel 'subscription_succeeded' event . ${n}`)}return this.pusher.send_event(t,e,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(t){var e=t.event,n=t.data;if(e==="pusher_internal:subscription_succeeded")this.handleSubscriptionSucceededEvent(t);else if(e==="pusher_internal:subscription_count")this.handleSubscriptionCountEvent(t);else if(e.indexOf("pusher_internal:")!==0){var i={};this.emit(e,n,i)}}handleSubscriptionSucceededEvent(t){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",t.data)}handleSubscriptionCountEvent(t){t.data.subscription_count&&(this.subscriptionCount=t.data.subscription_count),this.emit("pusher:subscription_count",t.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(t,e)=>{t?(this.subscriptionPending=!1,et.error(t.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:t.message},t instanceof y?{status:t.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:e.auth,channel_data:e.channel_data,channel:this.name})}))}unsubscribe(){this.subscribed=!1,this.pusher.send_event("pusher:unsubscribe",{channel:this.name})}cancelSubscription(){this.subscriptionCancelled=!0}reinstateSubscription(){this.subscriptionCancelled=!1}}class Gt extends Kt{authorize(t,e){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:t},e)}}class _r{constructor(){this.reset()}get(t){return Object.prototype.hasOwnProperty.call(this.members,t)?{id:t,info:this.members[t]}:null}each(t){Q(this.members,(e,n)=>{t(this.get(n))})}setMyID(t){this.myID=t}onSubscription(t){this.members=t.presence.hash,this.count=t.presence.count,this.me=this.get(this.myID)}addMember(t){return this.get(t.user_id)===null&&this.count++,this.members[t.user_id]=t.user_info,this.get(t.user_id)}removeMember(t){var e=this.get(t.user_id);return e&&(delete this.members[t.user_id],this.count--),e}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var Cr=function(r,t,e,n){function i(l){return l instanceof e?l:new e(function(k){k(l)})}return new(e||(e=Promise))(function(l,k){function O(V){try{J(n.next(V))}catch(st){k(st)}}function H(V){try{J(n.throw(V))}catch(st){k(st)}}function J(V){V.done?l(V.value):i(V.value).then(O,H)}J((n=n.apply(r,t||[])).next())})};class Sr extends Gt{constructor(t,e){super(t,e),this.members=new _r}authorize(t,e){super.authorize(t,(n,i)=>Cr(this,void 0,void 0,function*(){if(!n)if(i=i,i.channel_data!=null){var l=JSON.parse(i.channel_data);this.members.setMyID(l.user_id)}else if(yield this.pusher.user.signinDonePromise,this.pusher.user.user_data!=null)this.members.setMyID(this.pusher.user.user_data.id);else{let k=M.buildLogSuffix("authorizationEndpoint");et.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${k}, or the user should be signed in.`),e("Invalid auth response");return}e(n,i)}))}handleEvent(t){var e=t.event;if(e.indexOf("pusher_internal:")===0)this.handleInternalEvent(t);else{var n=t.data,i={};t.user_id&&(i.user_id=t.user_id),this.emit(e,n,i)}}handleInternalEvent(t){var e=t.event,n=t.data;switch(e){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(t);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(t);break;case"pusher_internal:member_added":var i=this.members.addMember(n);this.emit("pusher:member_added",i);break;case"pusher_internal:member_removed":var l=this.members.removeMember(n);l&&this.emit("pusher:member_removed",l);break}}handleSubscriptionSucceededEvent(t){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(t.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var Tr=z(978),Qt=z(594);class kr extends Gt{constructor(t,e,n){super(t,e),this.key=null,this.nacl=n}authorize(t,e){super.authorize(t,(n,i)=>{if(n){e(n,i);return}let l=i.shared_secret;if(!l){e(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=(0,Qt.decode)(l),delete i.shared_secret,e(null,i)})}trigger(t,e){throw new _("Client events are not currently supported for encrypted channels")}handleEvent(t){var e=t.event,n=t.data;if(e.indexOf("pusher_internal:")===0||e.indexOf("pusher:")===0){super.handleEvent(t);return}this.handleEncryptedEvent(e,n)}handleEncryptedEvent(t,e){if(!this.key){et.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!e.ciphertext||!e.nonce){et.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+e);return}let n=(0,Qt.decode)(e.ciphertext);if(n.length{if(k){et.error(`Failed to make a request to the authEndpoint: ${O}. Unable to fetch new key, so dropping encrypted event`);return}if(l=this.nacl.secretbox.open(n,i,this.key),l===null){et.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(t,this.getDataToEmit(l))});return}this.emit(t,this.getDataToEmit(l))}getDataToEmit(t){let e=(0,Tr.D4)(t);try{return JSON.parse(e)}catch{return e}}}class Ar extends gt{constructor(t,e){super(),this.state="initialized",this.connection=null,this.key=t,this.options=e,this.timeline=this.options.timeline,this.usingTLS=this.options.useTLS,this.errorCallbacks=this.buildErrorCallbacks(),this.connectionCallbacks=this.buildConnectionCallbacks(this.errorCallbacks),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var n=j.getNetwork();n.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),n.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}switchCluster(t){this.key=t,this.updateStrategy(),this.retryIn(0)}connect(){if(!(this.connection||this.runner)){if(!this.strategy.isSupported()){this.updateState("failed");return}this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()}}send(t){return this.connection?this.connection.send(t):!1}send_event(t,e,n){return this.connection?this.connection.send_event(t,e,n):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var t=(e,n)=>{e?this.runner=this.strategy.connect(0,t):n.action==="error"?(this.emit("error",{type:"HandshakeError",error:n.error}),this.timeline.error({handshakeError:n.error})):(this.abortConnecting(),this.handshakeCallbacks[n.action](n))};this.runner=this.strategy.connect(0,t)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){if(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection){var t=this.abandonConnection();t.close()}}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(t){this.timeline.info({action:"retry",delay:t}),t>0&&this.emit("connecting_in",Math.round(t/1e3)),this.retryTimer=new h(t||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new h(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new h(this.options.pongTimeout,()=>{this.timeline.error({pong_timed_out:this.options.pongTimeout}),this.retryIn(0)})}resetActivityCheck(){this.stopActivityCheck(),this.connection&&!this.connection.handlesActivityChecks()&&(this.activityTimer=new h(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(t){return R({},t,{message:e=>{this.resetActivityCheck(),this.emit("message",e)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:e=>{this.emit("error",e)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(t){return R({},t,{connected:e=>{this.activityTimeout=Math.min(this.options.activityTimeout,e.activityTimeout,e.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(e.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let t=e=>n=>{n.error&&this.emit("error",{type:"WebSocketError",error:n.error}),e(n)};return{tls_only:t(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:t(()=>{this.disconnect()}),backoff:t(()=>{this.retryIn(1e3)}),retry:t(()=>{this.retryIn(0)})}}setConnection(t){this.connection=t;for(var e in this.connectionCallbacks)this.connection.bind(e,this.connectionCallbacks[e]);this.resetActivityCheck()}abandonConnection(){if(this.connection){this.stopActivityCheck();for(var t in this.connectionCallbacks)this.connection.unbind(t,this.connectionCallbacks[t]);var e=this.connection;return this.connection=null,e}}updateState(t,e){var n=this.state;if(this.state=t,n!==t){var i=t;i==="connected"&&(i+=" with new socket ID "+e.socket_id),et.debug("State changed",n+" -> "+i),this.timeline.info({state:t,params:e}),this.emit("state_change",{previous:n,current:t}),this.emit(t,e)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class Pr{constructor(){this.channels={}}add(t,e){return this.channels[t]||(this.channels[t]=Lr(t,e)),this.channels[t]}all(){return ht(this.channels)}find(t){return this.channels[t]}remove(t){var e=this.channels[t];return delete this.channels[t],e}disconnect(){Q(this.channels,function(t){t.disconnect()})}}function Lr(r,t){if(r.indexOf("private-encrypted-")===0){if(t.config.nacl)return vt.createEncryptedChannel(r,t,t.config.nacl);let e="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",n=M.buildLogSuffix("encryptedChannelSupport");throw new _(`${e}. ${n}`)}else{if(r.indexOf("private-")===0)return vt.createPrivateChannel(r,t);if(r.indexOf("presence-")===0)return vt.createPresenceChannel(r,t);if(r.indexOf("#")===0)throw new b('Cannot create a channel with name "'+r+'".');return vt.createChannel(r,t)}}var Er={createChannels(){return new Pr},createConnectionManager(r,t){return new Ar(r,t)},createChannel(r,t){return new Kt(r,t)},createPrivateChannel(r,t){return new Gt(r,t)},createPresenceChannel(r,t){return new Sr(r,t)},createEncryptedChannel(r,t,e){return new kr(r,t,e)},createTimelineSender(r,t){return new xr(r,t)},createHandshake(r,t){return new yr(r,t)},createAssistantToTheTransportManager(r,t,e){return new mr(r,t,e)}};let vt=Er;class fe{constructor(t){this.options=t||{},this.livesLeft=this.options.lives||1/0}getAssistant(t){return vt.createAssistantToTheTransportManager(this,t,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class xt{constructor(t,e){this.strategies=t,this.loop=!!e.loop,this.failFast=!!e.failFast,this.timeout=e.timeout,this.timeoutLimit=e.timeoutLimit}isSupported(){return oe(this.strategies,T.method("isSupported"))}connect(t,e){var n=this.strategies,i=0,l=this.timeout,k=null,O=(H,J)=>{J?e(null,J):(i=i+1,this.loop&&(i=i%n.length),i0&&(l=new h(n.timeout,function(){k.abort(),i(!0)})),k=t.connect(e,function(O,H){O&&l&&l.isRunning()&&!n.failFast||(l&&l.ensureAborted(),i(O,H))}),{abort:function(){l&&l.ensureAborted(),k.abort()},forceMinPriority:function(O){k.forceMinPriority(O)}}}}class Vt{constructor(t){this.strategies=t}isSupported(){return oe(this.strategies,T.method("isSupported"))}connect(t,e){return Rr(this.strategies,t,function(n,i){return function(l,k){if(i[n].error=l,l){Mr(i)&&e(!0);return}ot(i,function(O){O.forceMinPriority(k.transport.priority)}),e(null,k)}})}}function Rr(r,t,e){var n=Pt(r,function(i,l,k,O){return i.connect(t,e(l,O))});return{abort:function(){ot(n,Or)},forceMinPriority:function(i){ot(n,function(l){l.forceMinPriority(i)})}}}function Mr(r){return Xe(r,function(t){return!!t.error})}function Or(r){!r.error&&!r.aborted&&(r.abort(),r.aborted=!0)}class Ir{constructor(t,e,n){this.strategy=t,this.transports=e,this.ttl=n.ttl||18e5,this.usingTLS=n.useTLS,this.timeline=n.timeline}isSupported(){return this.strategy.isSupported()}connect(t,e){var n=this.usingTLS,i=Br(n),l=i&&i.cacheSkipCount?i.cacheSkipCount:0,k=[this.strategy];if(i&&i.timestamp+this.ttl>=T.now()){var O=this.transports[i.transport];O&&(["ws","wss"].includes(i.transport)||l>3?(this.timeline.info({cached:!0,transport:i.transport,latency:i.latency}),k.push(new xt([O],{timeout:i.latency*2+1e3,failFast:!0}))):l++)}var H=T.now(),J=k.pop().connect(t,function V(st,qt){st?(pe(n),k.length>0?(H=T.now(),J=k.pop().connect(t,V)):e(st)):(Dr(n,qt.transport.name,T.now()-H,l),e(null,qt))});return{abort:function(){J.abort()},forceMinPriority:function(V){t=V,J&&J.forceMinPriority(V)}}}}function Yt(r){return"pusherTransport"+(r?"TLS":"NonTLS")}function Br(r){var t=j.getLocalStorage();if(t)try{var e=t[Yt(r)];if(e)return JSON.parse(e)}catch{pe(r)}return null}function Dr(r,t,e,n){var i=j.getLocalStorage();if(i)try{i[Yt(r)]=Dt({timestamp:T.now(),transport:t,latency:e,cacheSkipCount:n})}catch{}}function pe(r){var t=j.getLocalStorage();if(t)try{delete t[Yt(r)]}catch{}}class Ht{constructor(t,{delay:e}){this.strategy=t,this.options={delay:e}}isSupported(){return this.strategy.isSupported()}connect(t,e){var n=this.strategy,i,l=new h(this.options.delay,function(){i=n.connect(t,e)});return{abort:function(){l.ensureAborted(),i&&i.abort()},forceMinPriority:function(k){t=k,i&&i.forceMinPriority(k)}}}}class Et{constructor(t,e,n){this.test=t,this.trueBranch=e,this.falseBranch=n}isSupported(){var t=this.test()?this.trueBranch:this.falseBranch;return t.isSupported()}connect(t,e){var n=this.test()?this.trueBranch:this.falseBranch;return n.connect(t,e)}}class Nr{constructor(t){this.strategy=t}isSupported(){return this.strategy.isSupported()}connect(t,e){var n=this.strategy.connect(t,function(i,l){l&&n.abort(),e(i,l)});return n}}function Rt(r){return function(){return r.isSupported()}}var Hr=function(r,t,e){var n={};function i(Ae,Dn,Nn,Hn,jn){var Pe=e(r,Ae,Dn,Nn,Hn,jn);return n[Ae]=Pe,Pe}var l=Object.assign({},t,{hostNonTLS:r.wsHost+":"+r.wsPort,hostTLS:r.wsHost+":"+r.wssPort,httpPath:r.wsPath}),k=Object.assign({},l,{useTLS:!0}),O=Object.assign({},t,{hostNonTLS:r.httpHost+":"+r.httpPort,hostTLS:r.httpHost+":"+r.httpsPort,httpPath:r.httpPath}),H={loop:!0,timeout:15e3,timeoutLimit:6e4},J=new fe({minPingDelay:1e4,maxPingDelay:r.activityTimeout}),V=new fe({lives:2,minPingDelay:1e4,maxPingDelay:r.activityTimeout}),st=i("ws","ws",3,l,J),qt=i("wss","ws",3,k,J),Rn=i("sockjs","sockjs",1,O),xe=i("xhr_streaming","xhr_streaming",1,O,V),Mn=i("xdr_streaming","xdr_streaming",1,O,V),_e=i("xhr_polling","xhr_polling",1,O),On=i("xdr_polling","xdr_polling",1,O),Ce=new xt([st],H),In=new xt([qt],H),Bn=new xt([Rn],H),Se=new xt([new Et(Rt(xe),xe,Mn)],H),Te=new xt([new Et(Rt(_e),_e,On)],H),ke=new xt([new Et(Rt(Se),new Vt([Se,new Ht(Te,{delay:4e3})]),Te)],H),ee=new Et(Rt(ke),ke,Bn),re;return t.useTLS?re=new Vt([Ce,new Ht(ee,{delay:2e3})]):re=new Vt([Ce,new Ht(In,{delay:2e3}),new Ht(ee,{delay:5e3})]),new Ir(new Nr(new Et(Rt(st),re,ee)),n,{ttl:18e5,timeline:t.timeline,useTLS:t.useTLS})};let jr=Hr;function Ur(){var r=this;r.timeline.info(r.buildTimelineMessage({transport:r.name+(r.options.useTLS?"s":"")})),r.hooks.isInitialized()?r.changeState("initialized"):r.hooks.file?(r.changeState("initializing"),K.load(r.hooks.file,{useTLS:r.options.useTLS},function(t,e){r.hooks.isInitialized()?(r.changeState("initialized"),e(!0)):(t&&r.onError(t),r.onClose(),e(!1))})):r.onClose()}var qr={getRequest:function(r){var t=new window.XDomainRequest;return t.ontimeout=function(){r.emit("error",new v),r.close()},t.onerror=function(e){r.emit("error",e),r.close()},t.onprogress=function(){t.responseText&&t.responseText.length>0&&r.onChunk(200,t.responseText)},t.onload=function(){t.responseText&&t.responseText.length>0&&r.onChunk(200,t.responseText),r.emit("finished",200),r.close()},t},abortRequest:function(r){r.ontimeout=r.onerror=r.onprogress=r.onload=null,r.abort()}};let zr=qr,Fr=256*1024;class $r extends gt{constructor(t,e,n){super(),this.hooks=t,this.method=e,this.url=n}start(t){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},j.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(t)}close(){this.unloader&&(j.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(t,e){for(;;){var n=this.advanceBuffer(e);if(n)this.emit("chunk",{status:t,data:n});else break}this.isBufferTooLong(e)&&this.emit("buffer_too_long")}advanceBuffer(t){var e=t.slice(this.position),n=e.indexOf(` -`);return n!==-1?(this.position+=n+1,e.slice(0,n)):null}isBufferTooLong(t){return this.position===t.length&&t.length>Fr}}var Zt;(function(r){r[r.CONNECTING=0]="CONNECTING",r[r.OPEN=1]="OPEN",r[r.CLOSED=3]="CLOSED"})(Zt||(Zt={}));let _t=Zt;var Xr=1;class Jr{constructor(t,e){this.hooks=t,this.session=ve(1e3)+"/"+Qr(8),this.location=Wr(e),this.readyState=_t.CONNECTING,this.openStream()}send(t){return this.sendRaw(JSON.stringify([t]))}ping(){this.hooks.sendHeartbeat(this)}close(t,e){this.onClose(t,e,!0)}sendRaw(t){if(this.readyState===_t.OPEN)try{return j.createSocketRequest("POST",ge(Kr(this.location,this.session))).start(t),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(t,e,n){this.closeStream(),this.readyState=_t.CLOSED,this.onclose&&this.onclose({code:t,reason:e,wasClean:n})}onChunk(t){if(t.status===200){this.readyState===_t.OPEN&&this.onActivity();var e,n=t.data.slice(0,1);switch(n){case"o":e=JSON.parse(t.data.slice(1)||"{}"),this.onOpen(e);break;case"a":e=JSON.parse(t.data.slice(1)||"[]");for(var i=0;i{this.onChunk(t)}),this.stream.bind("finished",t=>{this.hooks.onFinished(this,t)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(t){T.defer(()=>{this.onError(t),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}}function Wr(r){var t=/([^\?]*)\/*(\??.*)/.exec(r);return{base:t[1],queryString:t[2]}}function Kr(r,t){return r.base+"/"+t+"/xhr_send"}function ge(r){var t=r.indexOf("?")===-1?"?":"&";return r+t+"t="+ +new Date+"&n="+Xr++}function Gr(r,t){var e=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(r);return e[1]+t+e[3]}function ve(r){return j.randomInt(r)}function Qr(r){for(var t=[],e=0;e0&&r.onChunk(e.status,e.responseText);break;case 4:e.responseText&&e.responseText.length>0&&r.onChunk(e.status,e.responseText),r.emit("finished",e.status),r.close();break}},e},abortRequest:function(r){r.onreadystatechange=null,r.abort()}};let nn=rn;var sn={createStreamingSocket(r){return this.createSocket(Zr,r)},createPollingSocket(r){return this.createSocket(en,r)},createSocket(r,t){return new Vr(r,t)},createXHR(r,t){return this.createRequest(nn,r,t)},createRequest(r,t,e){return new $r(r,t,e)}};let be=sn;be.createXDR=function(r,t){return this.createRequest(zr,r,t)};var on={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:it,DependenciesReceivers:Z,getDefaultStrategy:jr,Transports:gr,transportConnectionInitializer:Ur,HTTPFactory:be,TimelineTransport:rr,getXHRAPI(){return window.XMLHttpRequest},getWebSocketAPI(){return window.WebSocket||window.MozWebSocket},setup(r){if(typeof window!="undefined"){window.Pusher=r;var t=()=>{this.onDocumentBody(r.ready)};window.JSON?t():K.load("json2",{},t)}},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:C,jsonp:Ve}},onDocumentBody(r){document.body?r():setTimeout(()=>{this.onDocumentBody(r)},0)},createJSONPRequest(r,t){return new Ze(r,t)},createScriptRequest(r){return new Ye(r)},getLocalStorage(){try{return window.localStorage}catch{return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){var r=this.getXHRAPI();return new r},createMicrosoftXHR(){return new ActiveXObject("Microsoft.XMLHTTP")},getNetwork(){return br},createWebSocket(r){var t=this.getWebSocketAPI();return new t(r)},createSocketRequest(r,t){if(this.isXHRSupported())return this.HTTPFactory.createXHR(r,t);if(this.isXDRSupported(t.indexOf("https:")===0))return this.HTTPFactory.createXDR(r,t);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var r=this.getXHRAPI();return!!r&&new r().withCredentials!==void 0},isXDRSupported(r){var t=r?"https:":"http:",e=this.getProtocol();return!!window.XDomainRequest&&e===t},addUnloadListener(r){window.addEventListener!==void 0?window.addEventListener("pagehide",r,!1):window.attachEvent!==void 0&&window.attachEvent("onunload",r)},removeUnloadListener(r){window.addEventListener!==void 0?window.removeEventListener("pagehide",r,!1):window.detachEvent!==void 0&&window.detachEvent("onunload",r)},randomInt(r){let t=window.crypto||window.msCrypto,e=Math.floor(Math.pow(2,32)/r)*r,n;do n=t.getRandomValues(new Uint32Array(1))[0];while(n>=e);return n%r}};let j=on;var te;(function(r){r[r.ERROR=3]="ERROR",r[r.INFO=6]="INFO",r[r.DEBUG=7]="DEBUG"})(te||(te={}));let jt=te;class an{constructor(t,e,n){this.key=t,this.session=e,this.events=[],this.options=n||{},this.sent=0,this.uniqueID=0}log(t,e){t<=this.options.level&&(this.events.push(R({},e,{timestamp:T.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(t){this.log(jt.ERROR,t)}info(t){this.log(jt.INFO,t)}debug(t){this.log(jt.DEBUG,t)}isEmpty(){return this.events.length===0}send(t,e){var n=R({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],t(n,(i,l)=>{i||this.sent++,e&&e(i,l)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class hn{constructor(t,e,n,i){this.name=t,this.priority=e,this.transport=n,this.options=i||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(t,e){if(this.isSupported()){if(this.priority{n||(V(),l?l.close():i.close())},forceMinPriority:st=>{n||this.priority{var e="socket_id="+encodeURIComponent(r.socketId);for(var n in t.params)e+="&"+encodeURIComponent(n)+"="+encodeURIComponent(t.params[n]);if(t.paramsProvider!=null){let i=t.paramsProvider();for(var n in i)e+="&"+encodeURIComponent(n)+"="+encodeURIComponent(i[n])}return e},pn=r=>{if(typeof j.getAuthorizers()[r.transport]=="undefined")throw`'${r.transport}' is not a recognized auth transport`;return(t,e)=>{let n=fn(t,r);j.getAuthorizers()[r.transport](j,n,r,S.UserAuthentication,e)}},gn=(r,t)=>{var e="socket_id="+encodeURIComponent(r.socketId);e+="&channel_name="+encodeURIComponent(r.channelName);for(var n in t.params)e+="&"+encodeURIComponent(n)+"="+encodeURIComponent(t.params[n]);if(t.paramsProvider!=null){let i=t.paramsProvider();for(var n in i)e+="&"+encodeURIComponent(n)+"="+encodeURIComponent(i[n])}return e},vn=r=>{if(typeof j.getAuthorizers()[r.transport]=="undefined")throw`'${r.transport}' is not a recognized auth transport`;return(t,e)=>{let n=gn(t,r);j.getAuthorizers()[r.transport](j,n,r,S.ChannelAuthorization,e)}},bn=(r,t,e)=>{let n={authTransport:t.transport,authEndpoint:t.endpoint,auth:{params:t.params,headers:t.headers}};return(i,l)=>{let k=r.channel(i.channelName);e(k,n).authorize(i.socketId,l)}};function we(r,t){let e={activityTimeout:r.activityTimeout||G.activityTimeout,cluster:r.cluster,httpPath:r.httpPath||G.httpPath,httpPort:r.httpPort||G.httpPort,httpsPort:r.httpsPort||G.httpsPort,pongTimeout:r.pongTimeout||G.pongTimeout,statsHost:r.statsHost||G.stats_host,unavailableTimeout:r.unavailableTimeout||G.unavailableTimeout,wsPath:r.wsPath||G.wsPath,wsPort:r.wsPort||G.wsPort,wssPort:r.wssPort||G.wssPort,enableStats:_n(r),httpHost:mn(r),useTLS:xn(r),wsHost:wn(r),userAuthenticator:Cn(r),channelAuthorizer:Tn(r,t)};return"disabledTransports"in r&&(e.disabledTransports=r.disabledTransports),"enabledTransports"in r&&(e.enabledTransports=r.enabledTransports),"ignoreNullOrigin"in r&&(e.ignoreNullOrigin=r.ignoreNullOrigin),"timelineParams"in r&&(e.timelineParams=r.timelineParams),"nacl"in r&&(e.nacl=r.nacl),e}function mn(r){return r.httpHost?r.httpHost:r.cluster?`sockjs-${r.cluster}.pusher.com`:G.httpHost}function wn(r){return r.wsHost?r.wsHost:yn(r.cluster)}function yn(r){return`ws-${r}.pusher.com`}function xn(r){return j.getProtocol()==="https:"?!0:r.forceTLS!==!1}function _n(r){return"enableStats"in r?r.enableStats:"disableStats"in r?!r.disableStats:!1}let ye=r=>"customHandler"in r&&r.customHandler!=null;function Cn(r){let t=Object.assign(Object.assign({},G.userAuthentication),r.userAuthentication);return ye(t)?t.customHandler:pn(t)}function Sn(r,t){let e;return"channelAuthorization"in r?e=Object.assign(Object.assign({},G.channelAuthorization),r.channelAuthorization):(e={transport:r.authTransport||G.authTransport,endpoint:r.authEndpoint||G.authEndpoint},"auth"in r&&("params"in r.auth&&(e.params=r.auth.params),"headers"in r.auth&&(e.headers=r.auth.headers)),"authorizer"in r&&(e.customHandler=bn(t,e,r.authorizer))),e}function Tn(r,t){let e=Sn(r,t);return ye(e)?e.customHandler:vn(e)}class kn extends gt{constructor(t){super(function(e,n){et.debug(`No callbacks on watchlist events for ${e}`)}),this.pusher=t,this.bindWatchlistInternalEvent()}handleEvent(t){t.data.events.forEach(e=>{this.emit(e.name,e)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",t=>{var e=t.event;e==="pusher_internal:watchlist_events"&&this.handleEvent(t)})}}function An(){let r,t;return{promise:new Promise((n,i)=>{r=n,t=i}),resolve:r,reject:t}}let Pn=An;class Ln extends gt{constructor(t){super(function(e,n){et.debug("No callbacks on user for "+e)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(e,n)=>{if(e){et.warn(`Error during signin: ${e}`),this.emit("pusher:signin_error",Object.assign({},{type:"AuthError",error:e.message},e instanceof y?{status:e.status}:{})),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:n.auth,user_data:n.user_data})},this.pusher=t,this.pusher.connection.bind("state_change",({previous:e,current:n})=>{e!=="connected"&&n==="connected"&&this._signin(),e==="connected"&&n!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new kn(t),this.pusher.connection.bind("message",e=>{var n=e.event;n==="pusher:signin_success"&&this._onSigninSuccess(e.data),this.serverToUserChannel&&this.serverToUserChannel.name===e.channel&&this.serverToUserChannel.handleEvent(e)})}signin(){this.signin_requested||(this.signin_requested=!0,this._signin())}_signin(){this.signin_requested&&(this._newSigninPromiseIfNeeded(),this.pusher.connection.state==="connected"&&this.pusher.config.userAuthenticator({socketId:this.pusher.connection.socket_id},this._onAuthorize))}_onSigninSuccess(t){try{this.user_data=JSON.parse(t.user_data)}catch{et.error(`Failed parsing user data after signin: ${t.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){et.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),this._cleanup();return}this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){let t=e=>{e.subscriptionPending&&e.subscriptionCancelled?e.reinstateSubscription():!e.subscriptionPending&&this.pusher.connection.state==="connected"&&e.subscribe()};this.serverToUserChannel=new Kt(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((e,n)=>{e.indexOf("pusher_internal:")===0||e.indexOf("pusher:")===0||this.emit(e,n)}),t(this.serverToUserChannel)}_cleanup(){this.user_data=null,this.serverToUserChannel&&(this.serverToUserChannel.unbind_all(),this.serverToUserChannel.disconnect(),this.serverToUserChannel=null),this.signin_requested&&this._signinDoneResolve()}_newSigninPromiseIfNeeded(){if(!this.signin_requested||this.signinDonePromise&&!this.signinDonePromise.done)return;let{promise:t,resolve:e,reject:n}=Pn();t.done=!1;let i=()=>{t.done=!0};t.then(i).catch(i),this.signinDonePromise=t,this._signinDoneResolve=e}}class at{static ready(){at.isReady=!0;for(var t=0,e=at.instances.length;tj.getDefaultStrategy(this.config,i,un);this.connection=vt.createConnectionManager(this.key,{getStrategy:n,timeline:this.timeline,activityTimeout:this.config.activityTimeout,pongTimeout:this.config.pongTimeout,unavailableTimeout:this.config.unavailableTimeout,useTLS:!!this.config.useTLS}),this.connection.bind("connected",()=>{this.subscribeAll(),this.timelineSender&&this.timelineSender.send(this.connection.isUsingTLS())}),this.connection.bind("message",i=>{var l=i.event,k=l.indexOf("pusher_internal:")===0;if(i.channel){var O=this.channel(i.channel);O&&O.handleEvent(i)}k||this.global_emitter.emit(i.event,i.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",i=>{et.warn(i)}),at.instances.push(this),this.timeline.info({instances:at.instances.length}),this.user=new Ln(this),at.isReady&&this.connect()}switchCluster(t){let{appKey:e,cluster:n}=t;this.key=e,this.options=Object.assign(Object.assign({},this.options),{cluster:n}),this.config=we(this.options,this),this.connection.switchCluster(this.key)}channel(t){return this.channels.find(t)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var t=this.connection.isUsingTLS(),e=this.timelineSender;this.timelineSenderTimer=new m(6e4,function(){e.send(t)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(t,e,n){return this.global_emitter.bind(t,e,n),this}unbind(t,e,n){return this.global_emitter.unbind(t,e,n),this}bind_global(t){return this.global_emitter.bind_global(t),this}unbind_global(t){return this.global_emitter.unbind_global(t),this}unbind_all(t){return this.global_emitter.unbind_all(),this}subscribeAll(){var t;for(t in this.channels.channels)this.channels.channels.hasOwnProperty(t)&&this.subscribe(t)}subscribe(t){var e=this.channels.add(t,this);return e.subscriptionPending&&e.subscriptionCancelled?e.reinstateSubscription():!e.subscriptionPending&&this.connection.state==="connected"&&e.subscribe(),e}unsubscribe(t){var e=this.channels.find(t);e&&e.subscriptionPending?e.cancelSubscription():(e=this.channels.remove(t),e&&e.subscribed&&e.unsubscribe())}send_event(t,e,n){return this.connection.send_event(t,e,n)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}at.instances=[],at.isReady=!1,at.logToConsole=!1,at.Runtime=j,at.ScriptReceivers=j.ScriptReceivers,at.DependenciesReceivers=j.DependenciesReceivers,at.auth_callbacks=j.auth_callbacks;let Ut=at;function En(r){if(r==null)throw"You must pass your app key when you instantiate Pusher."}j.setup(at)}},o={};function g(E){var L=o[E];if(L!==void 0)return L.exports;var z=o[E]={exports:{}};return A[E].call(z.exports,z,z.exports,g),z.exports}g.d=(E,L)=>{for(var z in L)g.o(L,z)&&!g.o(E,z)&&Object.defineProperty(E,z,{enumerable:!0,get:L[z]})},g.o=(E,L)=>Object.prototype.hasOwnProperty.call(E,L);var P=g(721);return P})())});var De=Ee((Ie,Be)=>{var Oe=(function(){var A=function(c,b){var v=236,x=17,u=c,_=g[b],a=null,s=0,y=null,d=[],C={},U=function(f,p){s=u*4+17,a=(function(h){for(var m=new Array(h),w=0;w=7&&ct(f),y==null&&(y=$t(u,_,d)),dt(y,p)},N=function(f,p){for(var h=-1;h<=7;h+=1)if(!(f+h<=-1||s<=f+h))for(var m=-1;m<=7;m+=1)p+m<=-1||s<=p+m||(0<=h&&h<=6&&(m==0||m==6)||0<=m&&m<=6&&(h==0||h==6)||2<=h&&h<=4&&2<=m&&m<=4?a[f+h][p+m]=!0:a[f+h][p+m]=!1)},X=function(){for(var f=0,p=0,h=0;h<8;h+=1){U(!0,h);var m=E.getLostPoint(C);(h==0||f>m)&&(f=m,p=h)}return p},rt=function(){for(var f=8;f>h&1)==1;a[Math.floor(h/3)][h%3+s-8-3]=m}for(var h=0;h<18;h+=1){var m=!f&&(p>>h&1)==1;a[h%3+s-8-3][Math.floor(h/3)]=m}},lt=function(f,p){for(var h=_<<3|p,m=E.getBCHTypeInfo(h),w=0;w<15;w+=1){var T=!f&&(m>>w&1)==1;w<6?a[w][8]=T:w<8?a[w+1][8]=T:a[s-15+w][8]=T}for(var w=0;w<15;w+=1){var T=!f&&(m>>w&1)==1;w<8?a[8][s-w-1]=T:w<9?a[8][15-w-1+1]=T:a[8][15-w-1]=T}a[s-8][8]=!f},dt=function(f,p){for(var h=-1,m=s-1,w=7,T=0,R=E.getMaskFunction(p),I=s-1;I>0;I-=2)for(I==6&&(I-=1);;){for(var tt=0;tt<2;tt+=1)if(a[m][I-tt]==null){var Q=!1;T>>w&1)==1);var D=R(m,I-tt);D&&(Q=!Q),a[m][I-tt]=Q,w-=1,w==-1&&(T+=1,w=7)}if(m+=h,m<0||s<=m){m-=h,h=-h;break}}},bt=function(f,p){for(var h=0,m=0,w=0,T=new Array(p.length),R=new Array(p.length),I=0;I=0?Pt.getAt(Bt):0}}for(var Lt=0,D=0;DI*8)throw"code length overflow. ("+w.getLengthInBits()+">"+I*8+")";for(w.getLengthInBits()+4<=I*8&&w.put(0,4);w.getLengthInBits()%8!=0;)w.putBit(!1);for(;!(w.getLengthInBits()>=I*8||(w.put(v,8),w.getLengthInBits()>=I*8));)w.put(x,8);return bt(w,m)};C.addData=function(f,p){p=p||"Byte";var h=null;switch(p){case"Numeric":h=ut(f);break;case"Alphanumeric":h=G(f);break;case"Byte":h=wt(f);break;case"Kanji":h=Z(f);break;default:throw"mode:"+p}d.push(h),y=null},C.isDark=function(f,p){if(f<0||s<=f||p<0||s<=p)throw f+","+p;return a[f][p]},C.getModuleCount=function(){return s},C.make=function(){if(u<1){for(var f=1;f<40;f++){for(var p=W.getRSBlocks(f,_),h=it(),m=0;m";for(var w=0;w';h+=""}return h+="",h+="",h},C.createSvgTag=function(f,p,h,m){var w={};typeof arguments[0]=="object"&&(w=arguments[0],f=w.cellSize,p=w.margin,h=w.alt,m=w.title),f=f||2,p=typeof p=="undefined"?f*4:p,h=typeof h=="string"?{text:h}:h||{},h.text=h.text||null,h.id=h.text?h.id||"qrcode-description":null,m=typeof m=="string"?{text:m}:m||{},m.text=m.text||null,m.id=m.text?m.id||"qrcode-title":null;var T=C.getModuleCount()*f+p*2,R,I,tt,Q,D="",ht;for(ht="l"+f+",0 0,"+f+" -"+f+",0 0,-"+f+"z ",D+=''+mt(m.text)+"":"",D+=h.text?''+mt(h.text)+"":"",D+='',D+='":p+=">";break;case"&":p+="&";break;case'"':p+=""";break;default:p+=m;break}}return p},It=function(f){var p=1;f=typeof f=="undefined"?p*2:f;var h=C.getModuleCount()*p+f*2,m=f,w=h-f,T,R,I,tt,Q,D={"\u2588\u2588":"\u2588","\u2588 ":"\u2580"," \u2588":"\u2584"," ":" "},ht={"\u2588\u2588":"\u2580","\u2588 ":"\u2580"," \u2588":" "," ":" "},ot="";for(T=0;T=w?ht[Q]:D[Q];ot+=` -`}return h%2&&f>0?ot.substring(0,ot.length-h-1)+Array(h+1).join("\u2580"):ot.substring(0,ot.length-1)};return C.createASCII=function(f,p){if(f=f||1,f<2)return It(p);f-=1,p=typeof p=="undefined"?f*2:p;var h=C.getModuleCount()*f+p*2,m=p,w=h-p,T,R,I,tt,Q=Array(f+1).join("\u2588\u2588"),D=Array(f+1).join(" "),ht="",ot="";for(T=0;T>>8),_.push(y&255)):_.push(x)}}return _}};var o={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},g={L:1,M:0,Q:3,H:2},P={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},E=(function(){var c=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],b=1335,v=7973,x=21522,u={},_=function(a){for(var s=0;a!=0;)s+=1,a>>>=1;return s};return u.getBCHTypeInfo=function(a){for(var s=a<<10;_(s)-_(b)>=0;)s^=b<<_(s)-_(b);return(a<<10|s)^x},u.getBCHTypeNumber=function(a){for(var s=a<<12;_(s)-_(v)>=0;)s^=v<<_(s)-_(v);return a<<12|s},u.getPatternPosition=function(a){return c[a-1]},u.getMaskFunction=function(a){switch(a){case P.PATTERN000:return function(s,y){return(s+y)%2==0};case P.PATTERN001:return function(s,y){return s%2==0};case P.PATTERN010:return function(s,y){return y%3==0};case P.PATTERN011:return function(s,y){return(s+y)%3==0};case P.PATTERN100:return function(s,y){return(Math.floor(s/2)+Math.floor(y/3))%2==0};case P.PATTERN101:return function(s,y){return s*y%2+s*y%3==0};case P.PATTERN110:return function(s,y){return(s*y%2+s*y%3)%2==0};case P.PATTERN111:return function(s,y){return(s*y%3+(s+y)%2)%2==0};default:throw"bad maskPattern:"+a}},u.getErrorCorrectPolynomial=function(a){for(var s=z([1],0),y=0;y5&&(y+=3+U-5)}for(var d=0;d=256;)u-=255;return c[u]},x})();function z(c,b){if(typeof c.length=="undefined")throw c.length+"/"+b;var v=(function(){for(var u=0;u>>7-x%8&1)==1},v.put=function(x,u){for(var _=0;_>>u-_-1&1)==1)},v.getLengthInBits=function(){return b},v.putBit=function(x){var u=Math.floor(b/8);c.length<=u&&c.push(0),x&&(c[u]|=128>>>b%8),b+=1},v},ut=function(c){var b=o.MODE_NUMBER,v=c,x={};x.getMode=function(){return b},x.getLength=function(a){return v.length},x.write=function(a){for(var s=v,y=0;y+2>>8&255)*192+(d&255),a.put(d,13),y+=2}if(y>>8)},b.writeBytes=function(v,x,u){x=x||0,u=u||v.length;for(var _=0;_0&&(v+=","),v+=c[x];return v+="]",v},b},F=function(){var c=0,b=0,v=0,x="",u={},_=function(s){x+=String.fromCharCode(a(s&63))},a=function(s){if(!(s<0)){if(s<26)return 65+s;if(s<52)return 97+(s-26);if(s<62)return 48+(s-52);if(s==62)return 43;if(s==63)return 47}throw"n:"+s};return u.writeByte=function(s){for(c=c<<8|s&255,b+=8,v+=1;b>=6;)_(c>>>b-6),b-=6},u.flush=function(){if(b>0&&(_(c<<6-b),c=0,b=0),v%3!=0)for(var s=3-v%3,y=0;y=b.length){if(u==0)return-1;throw"unexpected end of file./"+u}var s=b.charAt(v);if(v+=1,s=="=")return u=0,-1;if(s.match(/^\s$/))continue;x=x<<6|a(s.charCodeAt(0)),u+=6}var y=x>>>u-8&255;return u-=8,y};var a=function(s){if(65<=s&&s<=90)return s-65;if(97<=s&&s<=122)return s-97+26;if(48<=s&&s<=57)return s-48+52;if(s==43)return 62;if(s==47)return 63;throw"c:"+s};return _},M=function(c,b){var v=c,x=b,u=new Array(c*b),_={};_.setPixel=function(d,C,U){u[C*v+d]=U},_.write=function(d){d.writeString("GIF87a"),d.writeShort(v),d.writeShort(x),d.writeByte(128),d.writeByte(0),d.writeByte(0),d.writeByte(0),d.writeByte(0),d.writeByte(0),d.writeByte(255),d.writeByte(255),d.writeByte(255),d.writeString(","),d.writeShort(0),d.writeShort(0),d.writeShort(v),d.writeShort(x),d.writeByte(0);var C=2,U=s(C);d.writeByte(C);for(var N=0;U.length-N>255;)d.writeByte(255),d.writeBytes(U,N,255),N+=255;d.writeByte(U.length-N),d.writeBytes(U,N,U.length-N),d.writeByte(0),d.writeString(";")};var a=function(d){var C=d,U=0,N=0,X={};return X.write=function(rt,nt){if(rt>>>nt)throw"length over";for(;U+nt>=8;)C.writeByte(255&(rt<>>=8-U,N=0,U=0;N=rt<0&&C.writeByte(N)},X},s=function(d){for(var C=1<>6,128|L&63):L<55296||L>=57344?P.push(224|L>>12,128|L>>6&63,128|L&63):(E++,L=65536+((L&1023)<<10|g.charCodeAt(E)&1023),P.push(240|L>>18,128|L>>12&63,128|L>>6&63,128|L&63))}return P}return o(A)}})();(function(A){typeof define=="function"&&define.amd?define([],A):typeof Ie=="object"&&(Be.exports=A())})(function(){return Oe})});var ze=Re(Me()),Fe=Re(De());var Ne=`.hibira-st { +/*! Hibira Realtime for Statamic. MIT License. Includes pusher-js (MIT, Copyright (c) 2020 Pusher, Ltd), @stablelib/base64 and @stablelib/utf8 (MIT, Copyright (C) 2016 Dmitry Chestnykh) and qrcode-generator (MIT, Copyright (c) 2009 Kazuhiko Arase). Full license texts: THIRD-PARTY-NOTICES. */ +(()=>{var Un=Object.create;var Le=Object.defineProperty;var Fn=Object.getOwnPropertyDescriptor;var qn=Object.getOwnPropertyNames;var zn=Object.getPrototypeOf,$n=Object.prototype.hasOwnProperty;var Ee=(A,o)=>()=>(o||A((o={exports:{}}).exports,o),o.exports);var Xn=(A,o,p,P)=>{if(o&&typeof o=="object"||typeof o=="function")for(let E of qn(o))!$n.call(A,E)&&E!==p&&Le(A,E,{get:()=>o[E],enumerable:!(P=Fn(o,E))||P.enumerable});return A};var Re=(A,o,p)=>(p=A!=null?Un(zn(A)):{},Xn(o||!A||!A.__esModule?Le(p,"default",{value:A,enumerable:!0}):p,A));var Me=Ee((qt,ne)=>{(function(o,p){typeof qt=="object"&&typeof ne=="object"?ne.exports=p():typeof define=="function"&&define.amd?define([],p):typeof qt=="object"?qt.Pusher=p():o.Pusher=p()})(self,()=>(()=>{var A={594(E,L){"use strict";var q=this&&this.__extends||(function(){var M=function(S,c){return M=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,v){b.__proto__=v}||function(b,v){for(var x in v)v.hasOwnProperty(x)&&(b[x]=v[x])},M(S,c)};return function(S,c){M(S,c);function b(){this.constructor=S}S.prototype=c===null?Object.create(c):(b.prototype=c.prototype,new b)}})();Object.defineProperty(L,"__esModule",{value:!0});var X=256,it=(function(){function M(S){S===void 0&&(S="="),this._paddingCharacter=S}return M.prototype.encodedLength=function(S){return this._paddingCharacter?(S+2)/3*4|0:(S*8+5)/6|0},M.prototype.encode=function(S){for(var c="",b=0;b>>18&63),c+=this._encodeByte(v>>>12&63),c+=this._encodeByte(v>>>6&63),c+=this._encodeByte(v>>>0&63)}var x=S.length-b;if(x>0){var v=S[b]<<16|(x===2?S[b+1]<<8:0);c+=this._encodeByte(v>>>18&63),c+=this._encodeByte(v>>>12&63),x===2?c+=this._encodeByte(v>>>6&63):c+=this._paddingCharacter||"",c+=this._paddingCharacter||""}return c},M.prototype.maxDecodedLength=function(S){return this._paddingCharacter?S/4*3|0:(S*6+7)/8|0},M.prototype.decodedLength=function(S){return this.maxDecodedLength(S.length-this._getPaddingLength(S))},M.prototype.decode=function(S){if(S.length===0)return new Uint8Array(0);for(var c=this._getPaddingLength(S),b=S.length-c,v=new Uint8Array(this.maxDecodedLength(b)),x=0,u=0,_=0,a=0,s=0,w=0,d=0;u>>4,v[x++]=s<<4|w>>>2,v[x++]=w<<6|d,_|=a&X,_|=s&X,_|=w&X,_|=d&X;if(u>>4,_|=a&X,_|=s&X),u>>2,_|=w&X),u>>8&6,c+=51-S>>>8&-75,c+=61-S>>>8&-15,c+=62-S>>>8&3,String.fromCharCode(c)},M.prototype._decodeChar=function(S){var c=X;return c+=(42-S&S-44)>>>8&-X+S-43+62,c+=(46-S&S-48)>>>8&-X+S-47+63,c+=(47-S&S-58)>>>8&-X+S-48+52,c+=(64-S&S-91)>>>8&-X+S-65+0,c+=(96-S&S-123)>>>8&-X+S-97+26,c},M.prototype._getPaddingLength=function(S){var c=0;if(this._paddingCharacter){for(var b=S.length-1;b>=0&&S[b]===this._paddingCharacter;b--)c++;if(S.length<4||c>2)throw new Error("Base64Coder: incorrect padding")}return c},M})();L.Coder=it;var ut=new it;function G(M){return ut.encode(M)}L.encode=G;function yt(M){return ut.decode(M)}L.decode=yt;var Z=(function(M){q(S,M);function S(){return M!==null&&M.apply(this,arguments)||this}return S.prototype._encodeByte=function(c){var b=c;return b+=65,b+=25-c>>>8&6,b+=51-c>>>8&-75,b+=61-c>>>8&-13,b+=62-c>>>8&49,String.fromCharCode(b)},S.prototype._decodeChar=function(c){var b=X;return b+=(44-c&c-46)>>>8&-X+c-45+62,b+=(94-c&c-96)>>>8&-X+c-95+63,b+=(47-c&c-58)>>>8&-X+c-48+52,b+=(64-c&c-91)>>>8&-X+c-65+0,b+=(96-c&c-123)>>>8&-X+c-97+26,b},S})(it);L.URLSafeCoder=Z;var K=new Z;function z(M){return K.encode(M)}L.encodeURLSafe=z;function $(M){return K.decode(M)}L.decodeURLSafe=$,L.encodedLength=function(M){return ut.encodedLength(M)},L.maxDecodedLength=function(M){return ut.maxDecodedLength(M)},L.decodedLength=function(M){return ut.decodedLength(M)}},978(E,L){"use strict";var q;q={value:!0};var X="utf8: invalid string",it="utf8: invalid source encoding";function ut(Z){for(var K=new Uint8Array(G(Z)),z=0,$=0;$>6,K[z++]=128|M&63):M<55296?(K[z++]=224|M>>12,K[z++]=128|M>>6&63,K[z++]=128|M&63):($++,M=(M&1023)<<10,M|=Z.charCodeAt($)&1023,M+=65536,K[z++]=240|M>>18,K[z++]=128|M>>12&63,K[z++]=128|M>>6&63,K[z++]=128|M&63)}return K}q=ut;function G(Z){for(var K=0,z=0;z=Z.length-1)throw new Error(X);z++,K+=4}else throw new Error(X)}return K}q=G;function yt(Z){for(var K=[],z=0;z=Z.length)throw new Error(it);var S=Z[++z];if((S&192)!==128)throw new Error(it);$=($&31)<<6|S&63,M=128}else if($<240){if(z>=Z.length-1)throw new Error(it);var S=Z[++z],c=Z[++z];if((S&192)!==128||(c&192)!==128)throw new Error(it);$=($&15)<<12|(S&63)<<6|c&63,M=2048}else if($<248){if(z>=Z.length-2)throw new Error(it);var S=Z[++z],c=Z[++z],b=Z[++z];if((S&192)!==128||(c&192)!==128||(b&192)!==128)throw new Error(it);$=($&15)<<18|(S&63)<<12|(c&63)<<6|b&63,M=65536}else throw new Error(it);if($=55296&&$<=57343)throw new Error(it);if($>=65536){if($>1114111)throw new Error(it);$-=65536,K.push(String.fromCharCode(55296|$>>10)),$=56320|$&1023}}K.push(String.fromCharCode($))}return K.join("")}L.D4=yt},721(E,L,q){E.exports=q(207).default},207(E,L,q){"use strict";q.d(L,{default:()=>Ut});class X{constructor(t,e){this.lastId=0,this.prefix=t,this.name=e}create(t){this.lastId++;var e=this.lastId,n=this.prefix+e,i=this.name+"["+e+"]",l=!1,k=function(){l||(t.apply(null,arguments),l=!0)};return this[e]=k,{number:e,id:n,name:i,callback:k}}remove(t){delete this[t.number]}}var it=new X("_pusher_script_","Pusher.ScriptReceivers"),ut={VERSION:"8.6.0",PROTOCOL:7,wsPort:80,wssPort:443,wsPath:"",httpHost:"sockjs.pusher.com",httpPort:80,httpsPort:443,httpPath:"/pusher",stats_host:"stats.pusher.com",authEndpoint:"/pusher/auth",authTransport:"ajax",activityTimeout:12e4,pongTimeout:3e4,unavailableTimeout:1e4,userAuthentication:{endpoint:"/pusher/user-auth",transport:"ajax"},channelAuthorization:{endpoint:"/pusher/auth",transport:"ajax"},cdn_http:"http://js.pusher.com",cdn_https:"https://js.pusher.com",dependency_suffix:""};let G=ut;class yt{constructor(t){this.options=t,this.receivers=t.receivers||it,this.loading={}}load(t,e,n){var i=this;if(i.loading[t]&&i.loading[t].length>0)i.loading[t].push(n);else{i.loading[t]=[n];var l=j.createScriptRequest(i.getPath(t,e)),k=i.receivers.create(function(O){if(i.receivers.remove(k),i.loading[t]){var H=i.loading[t];delete i.loading[t];for(var W=function(st){st||l.cleanup()},V=0;V>>6)+N(128|t&63):N(224|t>>>12&15)+N(128|t>>>6&63)+N(128|t&63)},dt=function(r){return r.replace(/[^\x00-\x7F]/g,lt)},bt=function(r){var t=[0,2,1][r.length%3],e=r.charCodeAt(0)<<16|(r.length>1?r.charCodeAt(1):0)<<8|(r.length>2?r.charCodeAt(2):0),n=[J.charAt(e>>>18),J.charAt(e>>>12&63),t>=2?"=":J.charAt(e>>>6&63),t>=1?"=":J.charAt(e&63)];return n.join("")},$t=typeof window!="undefined"&&window.btoa||function(r){return r.replace(/[\s\S]{1,3}/g,bt)};class mt{constructor(t,e,n,i){this.clear=e,this.timer=t(()=>{this.timer&&(this.timer=i(this.timer))},n)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}let It=mt;function f(r){window.clearTimeout(r)}function g(r){window.clearInterval(r)}class h extends It{constructor(t,e){super(setTimeout,f,t,function(n){return e(),null})}}class m extends It{constructor(t,e){super(setInterval,g,t,function(n){return e(),n})}}var y={now(){return Date.now?Date.now():new Date().valueOf()},defer(r){return new h(0,r)},method(r,...t){var e=Array.prototype.slice.call(arguments,1);return function(n){return n[r].apply(n,e.concat(arguments))}}};let T=y;function R(r,...t){for(var e=0;e{window.console&&window.console.log&&window.console.log(t)}}debug(...t){this.log(this.globalLog,t)}warn(...t){this.log(this.globalLogWarn,t)}error(...t){this.log(this.globalLogError,t)}globalLogWarn(t){window.console&&window.console.warn?window.console.warn(t):this.globalLog(t)}globalLogError(t){window.console&&window.console.error?window.console.error(t):this.globalLogWarn(t)}log(t,...e){var n=B.apply(this,arguments);Ut.log?Ut.log(n):Ut.logToConsole&&t.bind(this)(n)}}let et=new Ge;var Qe=function(r,t,e,n,i){(e.headers!==void 0||e.headersProvider!=null)&&et.warn(`To send headers with the ${n.toString()} request, you must use AJAX, rather than JSONP.`);var l=r.nextAuthCallbackID.toString();r.nextAuthCallbackID++;var k=r.getDocument(),O=k.createElement("script");r.auth_callbacks[l]=function(V){i(null,V)};var H="Pusher.auth_callbacks['"+l+"']";O.src=e.endpoint+"?callback="+encodeURIComponent(H)+"&"+t;var W=k.getElementsByTagName("head")[0]||k.documentElement;W.insertBefore(O,W.firstChild)};let Ve=Qe;class Ye{constructor(t){this.src=t}send(t){var e=this,n="Error loading "+e.src;e.script=document.createElement("script"),e.script.id=t.id,e.script.src=e.src,e.script.type="text/javascript",e.script.charset="UTF-8",e.script.addEventListener?(e.script.onerror=function(){t.callback(n)},e.script.onload=function(){t.callback(null)}):e.script.onreadystatechange=function(){(e.script.readyState==="loaded"||e.script.readyState==="complete")&&t.callback(null)},e.script.async===void 0&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(e.errorScript=document.createElement("script"),e.errorScript.id=t.id+"_error",e.errorScript.text=t.name+"('"+n+"');",e.script.async=e.errorScript.async=!1):e.script.async=!0;var i=document.getElementsByTagName("head")[0];i.insertBefore(e.script,i.firstChild),e.errorScript&&i.insertBefore(e.errorScript,e.script.nextSibling)}cleanup(){this.script&&(this.script.onload=this.script.onerror=null,this.script.onreadystatechange=null),this.script&&this.script.parentNode&&this.script.parentNode.removeChild(this.script),this.errorScript&&this.errorScript.parentNode&&this.errorScript.parentNode.removeChild(this.errorScript),this.script=null,this.errorScript=null}}class Ze{constructor(t,e){this.url=t,this.data=e}send(t){if(!this.request){var e=We(this.data),n=this.url+"/"+t.number+"?"+e;this.request=j.createScriptRequest(n),this.request.send(t)}}cleanup(){this.request&&this.request.cleanup()}}var tr=function(r,t){return function(e,n){var i="http"+(t?"s":"")+"://",l=i+(r.host||r.options.host)+r.options.path,k=j.createJSONPRequest(l,e),O=j.ScriptReceivers.create(function(H,W){it.remove(O),k.cleanup(),W&&W.host&&(r.host=W.host),n&&n(H,W)});k.send(O)}},er={name:"jsonp",getAgent:tr};let rr=er;function Xt(r,t,e){var n=r+(t.useTLS?"s":""),i=t.useTLS?t.hostTLS:t.hostNonTLS;return n+"://"+i+e}function Jt(r,t){var e="/app/"+r,n="?protocol="+G.PROTOCOL+"&client=js&version="+G.VERSION+(t?"&"+t:"");return e+n}var nr={getInitial:function(r,t){var e=(t.httpPath||"")+Jt(r,"flash=false");return Xt("ws",t,e)}},ir={getInitial:function(r,t){var e=(t.httpPath||"/pusher")+Jt(r);return Xt("http",t,e)}},sr={getInitial:function(r,t){return Xt("http",t,t.httpPath||"/pusher")},getPath:function(r,t){return Jt(r)}};class or{constructor(){this._callbacks={}}get(t){return this._callbacks[Wt(t)]}add(t,e,n){var i=Wt(t);this._callbacks[i]=this._callbacks[i]||[],this._callbacks[i].push({fn:e,context:n})}remove(t,e,n){if(!t&&!e&&!n){this._callbacks={};return}var i=t?[Wt(t)]:D(this._callbacks);e||n?this.removeCallback(i,e,n):this.removeAllCallbacks(i)}removeCallback(t,e,n){ot(t,function(i){this._callbacks[i]=Lt(this._callbacks[i]||[],function(l){return e&&e!==l.fn||n&&n!==l.context}),this._callbacks[i].length===0&&delete this._callbacks[i]},this)}removeAllCallbacks(t){ot(t,function(e){delete this._callbacks[e]},this)}}function Wt(r){return"_"+r}class gt{constructor(t){this.callbacks=new or,this.global_callbacks=[],this.failThrough=t}bind(t,e,n){return this.callbacks.add(t,e,n),this}bind_global(t){return this.global_callbacks.push(t),this}unbind(t,e,n){return this.callbacks.remove(t,e,n),this}unbind_global(t){return t?(this.global_callbacks=Lt(this.global_callbacks||[],e=>e!==t),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(t,e,n){for(var i=0;i0)for(var i=0;i{this.onError(e),this.changeState("closed")}),!1}return this.bindListeners(),et.debug("Connecting",{transport:this.name,url:t}),this.changeState("connecting"),!0}close(){return this.socket?(this.socket.close(),!0):!1}send(t){return this.state==="open"?(T.defer(()=>{this.socket&&this.socket.send(t)}),!0):!1}ping(){this.state==="open"&&this.supportsPing()&&this.socket.ping()}onOpen(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0}onError(t){this.emit("error",{type:"WebSocketError",error:t}),this.timeline.error(this.buildTimelineMessage({error:t.toString()}))}onClose(t){t?this.changeState("closed",{code:t.code,reason:t.reason,wasClean:t.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(t){this.emit("message",t)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=t=>{this.onError(t)},this.socket.onclose=t=>{this.onClose(t)},this.socket.onmessage=t=>{this.onMessage(t)},this.supportsPing()&&(this.socket.onactivity=()=>{this.onActivity()})}unbindListeners(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))}changeState(t,e){this.state=t,this.timeline.info(this.buildTimelineMessage({state:t,params:e})),this.emit(t,e)}buildTimelineMessage(t){return R({cid:this.id},t)}}class kt{constructor(t){this.hooks=t}isSupported(t){return this.hooks.isSupported(t)}createConnection(t,e,n,i){return new ar(this.hooks,t,e,n,i)}}var hr=new kt({urls:nr,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!j.getWebSocketAPI()},isSupported:function(){return!!j.getWebSocketAPI()},getSocket:function(r){return j.createWebSocket(r)}}),ae={urls:ir,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},he=R({getSocket:function(r){return j.HTTPFactory.createStreamingSocket(r)}},ae),ce=R({getSocket:function(r){return j.HTTPFactory.createPollingSocket(r)}},ae),ue={isSupported:function(){return j.isXHRSupported()}},cr=new kt(R({},he,ue)),ur=new kt(R({},ce,ue)),lr={ws:hr,xhr_streaming:cr,xhr_polling:ur};let Nt=lr;var dr=new kt({file:"sockjs",urls:sr,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return window.SockJS!==void 0},getSocket:function(r,t){return new window.SockJS(r,null,{js_path:K.getPath("sockjs",{useTLS:t.useTLS}),ignore_null_origin:t.ignoreNullOrigin})},beforeOpen:function(r,t){r.send(JSON.stringify({path:t}))}}),le={isSupported:function(r){var t=j.isXDRSupported(r.useTLS);return t}},fr=new kt(R({},he,le)),pr=new kt(R({},ce,le));Nt.xdr_streaming=fr,Nt.xdr_polling=pr,Nt.sockjs=dr;let gr=Nt;class vr extends gt{constructor(){super();var t=this;typeof window!="undefined"&&window.addEventListener!==void 0&&(window.addEventListener("online",function(){t.emit("online")},!1),window.addEventListener("offline",function(){t.emit("offline")},!1))}isOnline(){return window.navigator.onLine===void 0?!0:window.navigator.onLine}}var br=new vr;class mr{constructor(t,e,n){this.manager=t,this.transport=e,this.minPingDelay=n.minPingDelay,this.maxPingDelay=n.maxPingDelay,this.pingDelay=void 0}createConnection(t,e,n,i){i=R({},i,{activityTimeout:this.pingDelay});var l=this.transport.createConnection(t,e,n,i),k=null,O=function(){l.unbind("open",O),l.bind("closed",H),k=T.now()},H=W=>{if(l.unbind("closed",H),W.code===1002||W.code===1003)this.manager.reportDeath();else if(!W.wasClean&&k){var V=T.now()-k;V<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(V/2,this.minPingDelay))}};return l.bind("open",O),l}isSupported(t){return this.manager.isAlive()&&this.transport.isSupported(t)}}let de={decodeMessage:function(r){try{var t=JSON.parse(r.data),e=t.data;if(typeof e=="string")try{e=JSON.parse(t.data)}catch{}var n={event:t.event,channel:t.channel,data:e};return t.user_id&&(n.user_id=t.user_id),n}catch(i){throw{type:"MessageParseError",error:i,data:r.data}}},encodeMessage:function(r){return JSON.stringify(r)},processHandshake:function(r){var t=de.decodeMessage(r);if(t.event==="pusher:connection_established"){if(!t.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:t.data.socket_id,activityTimeout:t.data.activity_timeout*1e3}}else{if(t.event==="pusher:error")return{action:this.getCloseAction(t.data),error:this.getCloseError(t.data)};throw"Invalid handshake"}},getCloseAction:function(r){return r.code<4e3?r.code>=1002&&r.code<=1004?"backoff":null:r.code===4e3?"tls_only":r.code<4100?"refused":r.code<4200?"backoff":r.code<4300?"retry":"refused"},getCloseError:function(r){return r.code!==1e3&&r.code!==1001?{type:"PusherError",data:{code:r.code,message:r.reason||r.message}}:null}},wt=de;class yr extends gt{constructor(t,e){super(),this.id=t,this.transport=e,this.activityTimeout=e.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(t){return this.transport.send(t)}send_event(t,e,n){var i={event:t,data:e};return n&&(i.channel=n),et.debug("Event sent",i),this.send(wt.encodeMessage(i))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var t={message:n=>{var i;try{i=wt.decodeMessage(n)}catch(l){this.emit("error",{type:"MessageParseError",error:l,data:n.data})}if(i!==void 0){switch(et.debug("Event recd",i),i.event){case"pusher:error":this.emit("error",{type:"PusherError",data:i.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong");break}this.emit("message",i)}},activity:()=>{this.emit("activity")},error:n=>{this.emit("error",n)},closed:n=>{e(),n&&n.code&&this.handleCloseEvent(n),this.transport=null,this.emit("closed")}},e=()=>{Q(t,(n,i)=>{this.transport.unbind(i,n)})};Q(t,(n,i)=>{this.transport.bind(i,n)})}handleCloseEvent(t){var e=wt.getCloseAction(t),n=wt.getCloseError(t);n&&this.emit("error",n),e&&this.emit(e,{action:e,error:n})}}class wr{constructor(t,e){this.transport=t,this.callback=e,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=t=>{this.unbindListeners();var e;try{e=wt.processHandshake(t)}catch(n){this.finish("error",{error:n}),this.transport.close();return}e.action==="connected"?this.finish("connected",{connection:new yr(e.id,this.transport),activityTimeout:e.activityTimeout}):(this.finish(e.action,{error:e.error}),this.transport.close())},this.onClosed=t=>{this.unbindListeners();var e=wt.getCloseAction(t)||"backoff",n=wt.getCloseError(t);this.finish(e,{error:n})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)}unbindListeners(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)}finish(t,e){this.callback(R({transport:this.transport,action:t},e))}}class xr{constructor(t,e){this.timeline=t,this.options=e||{}}send(t,e){this.timeline.isEmpty()||this.timeline.send(j.TimelineTransport.getAgent(this,t),e)}}class Kt extends gt{constructor(t,e){super(function(n,i){et.debug("No callbacks on "+t+" for "+n)}),this.name=t,this.pusher=e,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(t,e){return e(null,{auth:""})}trigger(t,e){if(t.indexOf("client-")!==0)throw new c("Event '"+t+"' does not start with 'client-'");if(!this.subscribed){var n=M.buildLogSuffix("triggeringClientEvents");et.warn(`Client event triggered before channel 'subscription_succeeded' event . ${n}`)}return this.pusher.send_event(t,e,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(t){var e=t.event,n=t.data;if(e==="pusher_internal:subscription_succeeded")this.handleSubscriptionSucceededEvent(t);else if(e==="pusher_internal:subscription_count")this.handleSubscriptionCountEvent(t);else if(e.indexOf("pusher_internal:")!==0){var i={};this.emit(e,n,i)}}handleSubscriptionSucceededEvent(t){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",t.data)}handleSubscriptionCountEvent(t){t.data.subscription_count&&(this.subscriptionCount=t.data.subscription_count),this.emit("pusher:subscription_count",t.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(t,e)=>{t?(this.subscriptionPending=!1,et.error(t.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:t.message},t instanceof w?{status:t.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:e.auth,channel_data:e.channel_data,channel:this.name})}))}unsubscribe(){this.subscribed=!1,this.pusher.send_event("pusher:unsubscribe",{channel:this.name})}cancelSubscription(){this.subscriptionCancelled=!0}reinstateSubscription(){this.subscriptionCancelled=!1}}class Gt extends Kt{authorize(t,e){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:t},e)}}class _r{constructor(){this.reset()}get(t){return Object.prototype.hasOwnProperty.call(this.members,t)?{id:t,info:this.members[t]}:null}each(t){Q(this.members,(e,n)=>{t(this.get(n))})}setMyID(t){this.myID=t}onSubscription(t){this.members=t.presence.hash,this.count=t.presence.count,this.me=this.get(this.myID)}addMember(t){return this.get(t.user_id)===null&&this.count++,this.members[t.user_id]=t.user_info,this.get(t.user_id)}removeMember(t){var e=this.get(t.user_id);return e&&(delete this.members[t.user_id],this.count--),e}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var Cr=function(r,t,e,n){function i(l){return l instanceof e?l:new e(function(k){k(l)})}return new(e||(e=Promise))(function(l,k){function O(V){try{W(n.next(V))}catch(st){k(st)}}function H(V){try{W(n.throw(V))}catch(st){k(st)}}function W(V){V.done?l(V.value):i(V.value).then(O,H)}W((n=n.apply(r,t||[])).next())})};class Sr extends Gt{constructor(t,e){super(t,e),this.members=new _r}authorize(t,e){super.authorize(t,(n,i)=>Cr(this,void 0,void 0,function*(){if(!n)if(i=i,i.channel_data!=null){var l=JSON.parse(i.channel_data);this.members.setMyID(l.user_id)}else if(yield this.pusher.user.signinDonePromise,this.pusher.user.user_data!=null)this.members.setMyID(this.pusher.user.user_data.id);else{let k=M.buildLogSuffix("authorizationEndpoint");et.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${k}, or the user should be signed in.`),e("Invalid auth response");return}e(n,i)}))}handleEvent(t){var e=t.event;if(e.indexOf("pusher_internal:")===0)this.handleInternalEvent(t);else{var n=t.data,i={};t.user_id&&(i.user_id=t.user_id),this.emit(e,n,i)}}handleInternalEvent(t){var e=t.event,n=t.data;switch(e){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(t);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(t);break;case"pusher_internal:member_added":var i=this.members.addMember(n);this.emit("pusher:member_added",i);break;case"pusher_internal:member_removed":var l=this.members.removeMember(n);l&&this.emit("pusher:member_removed",l);break}}handleSubscriptionSucceededEvent(t){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(t.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var Tr=q(978),Qt=q(594);class kr extends Gt{constructor(t,e,n){super(t,e),this.key=null,this.nacl=n}authorize(t,e){super.authorize(t,(n,i)=>{if(n){e(n,i);return}let l=i.shared_secret;if(!l){e(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=(0,Qt.decode)(l),delete i.shared_secret,e(null,i)})}trigger(t,e){throw new _("Client events are not currently supported for encrypted channels")}handleEvent(t){var e=t.event,n=t.data;if(e.indexOf("pusher_internal:")===0||e.indexOf("pusher:")===0){super.handleEvent(t);return}this.handleEncryptedEvent(e,n)}handleEncryptedEvent(t,e){if(!this.key){et.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!e.ciphertext||!e.nonce){et.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+e);return}let n=(0,Qt.decode)(e.ciphertext);if(n.length{if(k){et.error(`Failed to make a request to the authEndpoint: ${O}. Unable to fetch new key, so dropping encrypted event`);return}if(l=this.nacl.secretbox.open(n,i,this.key),l===null){et.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(t,this.getDataToEmit(l))});return}this.emit(t,this.getDataToEmit(l))}getDataToEmit(t){let e=(0,Tr.D4)(t);try{return JSON.parse(e)}catch{return e}}}class Ar extends gt{constructor(t,e){super(),this.state="initialized",this.connection=null,this.key=t,this.options=e,this.timeline=this.options.timeline,this.usingTLS=this.options.useTLS,this.errorCallbacks=this.buildErrorCallbacks(),this.connectionCallbacks=this.buildConnectionCallbacks(this.errorCallbacks),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var n=j.getNetwork();n.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),n.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}switchCluster(t){this.key=t,this.updateStrategy(),this.retryIn(0)}connect(){if(!(this.connection||this.runner)){if(!this.strategy.isSupported()){this.updateState("failed");return}this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()}}send(t){return this.connection?this.connection.send(t):!1}send_event(t,e,n){return this.connection?this.connection.send_event(t,e,n):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var t=(e,n)=>{e?this.runner=this.strategy.connect(0,t):n.action==="error"?(this.emit("error",{type:"HandshakeError",error:n.error}),this.timeline.error({handshakeError:n.error})):(this.abortConnecting(),this.handshakeCallbacks[n.action](n))};this.runner=this.strategy.connect(0,t)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){if(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection){var t=this.abandonConnection();t.close()}}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(t){this.timeline.info({action:"retry",delay:t}),t>0&&this.emit("connecting_in",Math.round(t/1e3)),this.retryTimer=new h(t||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new h(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new h(this.options.pongTimeout,()=>{this.timeline.error({pong_timed_out:this.options.pongTimeout}),this.retryIn(0)})}resetActivityCheck(){this.stopActivityCheck(),this.connection&&!this.connection.handlesActivityChecks()&&(this.activityTimer=new h(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(t){return R({},t,{message:e=>{this.resetActivityCheck(),this.emit("message",e)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:e=>{this.emit("error",e)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(t){return R({},t,{connected:e=>{this.activityTimeout=Math.min(this.options.activityTimeout,e.activityTimeout,e.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(e.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let t=e=>n=>{n.error&&this.emit("error",{type:"WebSocketError",error:n.error}),e(n)};return{tls_only:t(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:t(()=>{this.disconnect()}),backoff:t(()=>{this.retryIn(1e3)}),retry:t(()=>{this.retryIn(0)})}}setConnection(t){this.connection=t;for(var e in this.connectionCallbacks)this.connection.bind(e,this.connectionCallbacks[e]);this.resetActivityCheck()}abandonConnection(){if(this.connection){this.stopActivityCheck();for(var t in this.connectionCallbacks)this.connection.unbind(t,this.connectionCallbacks[t]);var e=this.connection;return this.connection=null,e}}updateState(t,e){var n=this.state;if(this.state=t,n!==t){var i=t;i==="connected"&&(i+=" with new socket ID "+e.socket_id),et.debug("State changed",n+" -> "+i),this.timeline.info({state:t,params:e}),this.emit("state_change",{previous:n,current:t}),this.emit(t,e)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class Pr{constructor(){this.channels={}}add(t,e){return this.channels[t]||(this.channels[t]=Lr(t,e)),this.channels[t]}all(){return ht(this.channels)}find(t){return this.channels[t]}remove(t){var e=this.channels[t];return delete this.channels[t],e}disconnect(){Q(this.channels,function(t){t.disconnect()})}}function Lr(r,t){if(r.indexOf("private-encrypted-")===0){if(t.config.nacl)return vt.createEncryptedChannel(r,t,t.config.nacl);let e="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",n=M.buildLogSuffix("encryptedChannelSupport");throw new _(`${e}. ${n}`)}else{if(r.indexOf("private-")===0)return vt.createPrivateChannel(r,t);if(r.indexOf("presence-")===0)return vt.createPresenceChannel(r,t);if(r.indexOf("#")===0)throw new b('Cannot create a channel with name "'+r+'".');return vt.createChannel(r,t)}}var Er={createChannels(){return new Pr},createConnectionManager(r,t){return new Ar(r,t)},createChannel(r,t){return new Kt(r,t)},createPrivateChannel(r,t){return new Gt(r,t)},createPresenceChannel(r,t){return new Sr(r,t)},createEncryptedChannel(r,t,e){return new kr(r,t,e)},createTimelineSender(r,t){return new xr(r,t)},createHandshake(r,t){return new wr(r,t)},createAssistantToTheTransportManager(r,t,e){return new mr(r,t,e)}};let vt=Er;class fe{constructor(t){this.options=t||{},this.livesLeft=this.options.lives||1/0}getAssistant(t){return vt.createAssistantToTheTransportManager(this,t,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class xt{constructor(t,e){this.strategies=t,this.loop=!!e.loop,this.failFast=!!e.failFast,this.timeout=e.timeout,this.timeoutLimit=e.timeoutLimit}isSupported(){return oe(this.strategies,T.method("isSupported"))}connect(t,e){var n=this.strategies,i=0,l=this.timeout,k=null,O=(H,W)=>{W?e(null,W):(i=i+1,this.loop&&(i=i%n.length),i0&&(l=new h(n.timeout,function(){k.abort(),i(!0)})),k=t.connect(e,function(O,H){O&&l&&l.isRunning()&&!n.failFast||(l&&l.ensureAborted(),i(O,H))}),{abort:function(){l&&l.ensureAborted(),k.abort()},forceMinPriority:function(O){k.forceMinPriority(O)}}}}class Vt{constructor(t){this.strategies=t}isSupported(){return oe(this.strategies,T.method("isSupported"))}connect(t,e){return Rr(this.strategies,t,function(n,i){return function(l,k){if(i[n].error=l,l){Mr(i)&&e(!0);return}ot(i,function(O){O.forceMinPriority(k.transport.priority)}),e(null,k)}})}}function Rr(r,t,e){var n=Pt(r,function(i,l,k,O){return i.connect(t,e(l,O))});return{abort:function(){ot(n,Or)},forceMinPriority:function(i){ot(n,function(l){l.forceMinPriority(i)})}}}function Mr(r){return Xe(r,function(t){return!!t.error})}function Or(r){!r.error&&!r.aborted&&(r.abort(),r.aborted=!0)}class Ir{constructor(t,e,n){this.strategy=t,this.transports=e,this.ttl=n.ttl||18e5,this.usingTLS=n.useTLS,this.timeline=n.timeline}isSupported(){return this.strategy.isSupported()}connect(t,e){var n=this.usingTLS,i=Br(n),l=i&&i.cacheSkipCount?i.cacheSkipCount:0,k=[this.strategy];if(i&&i.timestamp+this.ttl>=T.now()){var O=this.transports[i.transport];O&&(["ws","wss"].includes(i.transport)||l>3?(this.timeline.info({cached:!0,transport:i.transport,latency:i.latency}),k.push(new xt([O],{timeout:i.latency*2+1e3,failFast:!0}))):l++)}var H=T.now(),W=k.pop().connect(t,function V(st,Ft){st?(pe(n),k.length>0?(H=T.now(),W=k.pop().connect(t,V)):e(st)):(Dr(n,Ft.transport.name,T.now()-H,l),e(null,Ft))});return{abort:function(){W.abort()},forceMinPriority:function(V){t=V,W&&W.forceMinPriority(V)}}}}function Yt(r){return"pusherTransport"+(r?"TLS":"NonTLS")}function Br(r){var t=j.getLocalStorage();if(t)try{var e=t[Yt(r)];if(e)return JSON.parse(e)}catch{pe(r)}return null}function Dr(r,t,e,n){var i=j.getLocalStorage();if(i)try{i[Yt(r)]=Dt({timestamp:T.now(),transport:t,latency:e,cacheSkipCount:n})}catch{}}function pe(r){var t=j.getLocalStorage();if(t)try{delete t[Yt(r)]}catch{}}class Ht{constructor(t,{delay:e}){this.strategy=t,this.options={delay:e}}isSupported(){return this.strategy.isSupported()}connect(t,e){var n=this.strategy,i,l=new h(this.options.delay,function(){i=n.connect(t,e)});return{abort:function(){l.ensureAborted(),i&&i.abort()},forceMinPriority:function(k){t=k,i&&i.forceMinPriority(k)}}}}class Et{constructor(t,e,n){this.test=t,this.trueBranch=e,this.falseBranch=n}isSupported(){var t=this.test()?this.trueBranch:this.falseBranch;return t.isSupported()}connect(t,e){var n=this.test()?this.trueBranch:this.falseBranch;return n.connect(t,e)}}class Nr{constructor(t){this.strategy=t}isSupported(){return this.strategy.isSupported()}connect(t,e){var n=this.strategy.connect(t,function(i,l){l&&n.abort(),e(i,l)});return n}}function Rt(r){return function(){return r.isSupported()}}var Hr=function(r,t,e){var n={};function i(Ae,Dn,Nn,Hn,jn){var Pe=e(r,Ae,Dn,Nn,Hn,jn);return n[Ae]=Pe,Pe}var l=Object.assign({},t,{hostNonTLS:r.wsHost+":"+r.wsPort,hostTLS:r.wsHost+":"+r.wssPort,httpPath:r.wsPath}),k=Object.assign({},l,{useTLS:!0}),O=Object.assign({},t,{hostNonTLS:r.httpHost+":"+r.httpPort,hostTLS:r.httpHost+":"+r.httpsPort,httpPath:r.httpPath}),H={loop:!0,timeout:15e3,timeoutLimit:6e4},W=new fe({minPingDelay:1e4,maxPingDelay:r.activityTimeout}),V=new fe({lives:2,minPingDelay:1e4,maxPingDelay:r.activityTimeout}),st=i("ws","ws",3,l,W),Ft=i("wss","ws",3,k,W),Rn=i("sockjs","sockjs",1,O),xe=i("xhr_streaming","xhr_streaming",1,O,V),Mn=i("xdr_streaming","xdr_streaming",1,O,V),_e=i("xhr_polling","xhr_polling",1,O),On=i("xdr_polling","xdr_polling",1,O),Ce=new xt([st],H),In=new xt([Ft],H),Bn=new xt([Rn],H),Se=new xt([new Et(Rt(xe),xe,Mn)],H),Te=new xt([new Et(Rt(_e),_e,On)],H),ke=new xt([new Et(Rt(Se),new Vt([Se,new Ht(Te,{delay:4e3})]),Te)],H),ee=new Et(Rt(ke),ke,Bn),re;return t.useTLS?re=new Vt([Ce,new Ht(ee,{delay:2e3})]):re=new Vt([Ce,new Ht(In,{delay:2e3}),new Ht(ee,{delay:5e3})]),new Ir(new Nr(new Et(Rt(st),re,ee)),n,{ttl:18e5,timeline:t.timeline,useTLS:t.useTLS})};let jr=Hr;function Ur(){var r=this;r.timeline.info(r.buildTimelineMessage({transport:r.name+(r.options.useTLS?"s":"")})),r.hooks.isInitialized()?r.changeState("initialized"):r.hooks.file?(r.changeState("initializing"),K.load(r.hooks.file,{useTLS:r.options.useTLS},function(t,e){r.hooks.isInitialized()?(r.changeState("initialized"),e(!0)):(t&&r.onError(t),r.onClose(),e(!1))})):r.onClose()}var Fr={getRequest:function(r){var t=new window.XDomainRequest;return t.ontimeout=function(){r.emit("error",new v),r.close()},t.onerror=function(e){r.emit("error",e),r.close()},t.onprogress=function(){t.responseText&&t.responseText.length>0&&r.onChunk(200,t.responseText)},t.onload=function(){t.responseText&&t.responseText.length>0&&r.onChunk(200,t.responseText),r.emit("finished",200),r.close()},t},abortRequest:function(r){r.ontimeout=r.onerror=r.onprogress=r.onload=null,r.abort()}};let qr=Fr,zr=256*1024;class $r extends gt{constructor(t,e,n){super(),this.hooks=t,this.method=e,this.url=n}start(t){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},j.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(t)}close(){this.unloader&&(j.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(t,e){for(;;){var n=this.advanceBuffer(e);if(n)this.emit("chunk",{status:t,data:n});else break}this.isBufferTooLong(e)&&this.emit("buffer_too_long")}advanceBuffer(t){var e=t.slice(this.position),n=e.indexOf(` +`);return n!==-1?(this.position+=n+1,e.slice(0,n)):null}isBufferTooLong(t){return this.position===t.length&&t.length>zr}}var Zt;(function(r){r[r.CONNECTING=0]="CONNECTING",r[r.OPEN=1]="OPEN",r[r.CLOSED=3]="CLOSED"})(Zt||(Zt={}));let _t=Zt;var Xr=1;class Jr{constructor(t,e){this.hooks=t,this.session=ve(1e3)+"/"+Qr(8),this.location=Wr(e),this.readyState=_t.CONNECTING,this.openStream()}send(t){return this.sendRaw(JSON.stringify([t]))}ping(){this.hooks.sendHeartbeat(this)}close(t,e){this.onClose(t,e,!0)}sendRaw(t){if(this.readyState===_t.OPEN)try{return j.createSocketRequest("POST",ge(Kr(this.location,this.session))).start(t),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(t,e,n){this.closeStream(),this.readyState=_t.CLOSED,this.onclose&&this.onclose({code:t,reason:e,wasClean:n})}onChunk(t){if(t.status===200){this.readyState===_t.OPEN&&this.onActivity();var e,n=t.data.slice(0,1);switch(n){case"o":e=JSON.parse(t.data.slice(1)||"{}"),this.onOpen(e);break;case"a":e=JSON.parse(t.data.slice(1)||"[]");for(var i=0;i{this.onChunk(t)}),this.stream.bind("finished",t=>{this.hooks.onFinished(this,t)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(t){T.defer(()=>{this.onError(t),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}}function Wr(r){var t=/([^\?]*)\/*(\??.*)/.exec(r);return{base:t[1],queryString:t[2]}}function Kr(r,t){return r.base+"/"+t+"/xhr_send"}function ge(r){var t=r.indexOf("?")===-1?"?":"&";return r+t+"t="+ +new Date+"&n="+Xr++}function Gr(r,t){var e=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(r);return e[1]+t+e[3]}function ve(r){return j.randomInt(r)}function Qr(r){for(var t=[],e=0;e0&&r.onChunk(e.status,e.responseText);break;case 4:e.responseText&&e.responseText.length>0&&r.onChunk(e.status,e.responseText),r.emit("finished",e.status),r.close();break}},e},abortRequest:function(r){r.onreadystatechange=null,r.abort()}};let nn=rn;var sn={createStreamingSocket(r){return this.createSocket(Zr,r)},createPollingSocket(r){return this.createSocket(en,r)},createSocket(r,t){return new Vr(r,t)},createXHR(r,t){return this.createRequest(nn,r,t)},createRequest(r,t,e){return new $r(r,t,e)}};let be=sn;be.createXDR=function(r,t){return this.createRequest(qr,r,t)};var on={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:it,DependenciesReceivers:Z,getDefaultStrategy:jr,Transports:gr,transportConnectionInitializer:Ur,HTTPFactory:be,TimelineTransport:rr,getXHRAPI(){return window.XMLHttpRequest},getWebSocketAPI(){return window.WebSocket||window.MozWebSocket},setup(r){if(typeof window!="undefined"){window.Pusher=r;var t=()=>{this.onDocumentBody(r.ready)};window.JSON?t():K.load("json2",{},t)}},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:C,jsonp:Ve}},onDocumentBody(r){document.body?r():setTimeout(()=>{this.onDocumentBody(r)},0)},createJSONPRequest(r,t){return new Ze(r,t)},createScriptRequest(r){return new Ye(r)},getLocalStorage(){try{return window.localStorage}catch{return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){var r=this.getXHRAPI();return new r},createMicrosoftXHR(){return new ActiveXObject("Microsoft.XMLHTTP")},getNetwork(){return br},createWebSocket(r){var t=this.getWebSocketAPI();return new t(r)},createSocketRequest(r,t){if(this.isXHRSupported())return this.HTTPFactory.createXHR(r,t);if(this.isXDRSupported(t.indexOf("https:")===0))return this.HTTPFactory.createXDR(r,t);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var r=this.getXHRAPI();return!!r&&new r().withCredentials!==void 0},isXDRSupported(r){var t=r?"https:":"http:",e=this.getProtocol();return!!window.XDomainRequest&&e===t},addUnloadListener(r){window.addEventListener!==void 0?window.addEventListener("pagehide",r,!1):window.attachEvent!==void 0&&window.attachEvent("onunload",r)},removeUnloadListener(r){window.addEventListener!==void 0?window.removeEventListener("pagehide",r,!1):window.detachEvent!==void 0&&window.detachEvent("onunload",r)},randomInt(r){let t=window.crypto||window.msCrypto,e=Math.floor(Math.pow(2,32)/r)*r,n;do n=t.getRandomValues(new Uint32Array(1))[0];while(n>=e);return n%r}};let j=on;var te;(function(r){r[r.ERROR=3]="ERROR",r[r.INFO=6]="INFO",r[r.DEBUG=7]="DEBUG"})(te||(te={}));let jt=te;class an{constructor(t,e,n){this.key=t,this.session=e,this.events=[],this.options=n||{},this.sent=0,this.uniqueID=0}log(t,e){t<=this.options.level&&(this.events.push(R({},e,{timestamp:T.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(t){this.log(jt.ERROR,t)}info(t){this.log(jt.INFO,t)}debug(t){this.log(jt.DEBUG,t)}isEmpty(){return this.events.length===0}send(t,e){var n=R({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],t(n,(i,l)=>{i||this.sent++,e&&e(i,l)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class hn{constructor(t,e,n,i){this.name=t,this.priority=e,this.transport=n,this.options=i||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(t,e){if(this.isSupported()){if(this.priority{n||(V(),l?l.close():i.close())},forceMinPriority:st=>{n||this.priority{var e="socket_id="+encodeURIComponent(r.socketId);for(var n in t.params)e+="&"+encodeURIComponent(n)+"="+encodeURIComponent(t.params[n]);if(t.paramsProvider!=null){let i=t.paramsProvider();for(var n in i)e+="&"+encodeURIComponent(n)+"="+encodeURIComponent(i[n])}return e},pn=r=>{if(typeof j.getAuthorizers()[r.transport]=="undefined")throw`'${r.transport}' is not a recognized auth transport`;return(t,e)=>{let n=fn(t,r);j.getAuthorizers()[r.transport](j,n,r,S.UserAuthentication,e)}},gn=(r,t)=>{var e="socket_id="+encodeURIComponent(r.socketId);e+="&channel_name="+encodeURIComponent(r.channelName);for(var n in t.params)e+="&"+encodeURIComponent(n)+"="+encodeURIComponent(t.params[n]);if(t.paramsProvider!=null){let i=t.paramsProvider();for(var n in i)e+="&"+encodeURIComponent(n)+"="+encodeURIComponent(i[n])}return e},vn=r=>{if(typeof j.getAuthorizers()[r.transport]=="undefined")throw`'${r.transport}' is not a recognized auth transport`;return(t,e)=>{let n=gn(t,r);j.getAuthorizers()[r.transport](j,n,r,S.ChannelAuthorization,e)}},bn=(r,t,e)=>{let n={authTransport:t.transport,authEndpoint:t.endpoint,auth:{params:t.params,headers:t.headers}};return(i,l)=>{let k=r.channel(i.channelName);e(k,n).authorize(i.socketId,l)}};function ye(r,t){let e={activityTimeout:r.activityTimeout||G.activityTimeout,cluster:r.cluster,httpPath:r.httpPath||G.httpPath,httpPort:r.httpPort||G.httpPort,httpsPort:r.httpsPort||G.httpsPort,pongTimeout:r.pongTimeout||G.pongTimeout,statsHost:r.statsHost||G.stats_host,unavailableTimeout:r.unavailableTimeout||G.unavailableTimeout,wsPath:r.wsPath||G.wsPath,wsPort:r.wsPort||G.wsPort,wssPort:r.wssPort||G.wssPort,enableStats:_n(r),httpHost:mn(r),useTLS:xn(r),wsHost:yn(r),userAuthenticator:Cn(r),channelAuthorizer:Tn(r,t)};return"disabledTransports"in r&&(e.disabledTransports=r.disabledTransports),"enabledTransports"in r&&(e.enabledTransports=r.enabledTransports),"ignoreNullOrigin"in r&&(e.ignoreNullOrigin=r.ignoreNullOrigin),"timelineParams"in r&&(e.timelineParams=r.timelineParams),"nacl"in r&&(e.nacl=r.nacl),e}function mn(r){return r.httpHost?r.httpHost:r.cluster?`sockjs-${r.cluster}.pusher.com`:G.httpHost}function yn(r){return r.wsHost?r.wsHost:wn(r.cluster)}function wn(r){return`ws-${r}.pusher.com`}function xn(r){return j.getProtocol()==="https:"?!0:r.forceTLS!==!1}function _n(r){return"enableStats"in r?r.enableStats:"disableStats"in r?!r.disableStats:!1}let we=r=>"customHandler"in r&&r.customHandler!=null;function Cn(r){let t=Object.assign(Object.assign({},G.userAuthentication),r.userAuthentication);return we(t)?t.customHandler:pn(t)}function Sn(r,t){let e;return"channelAuthorization"in r?e=Object.assign(Object.assign({},G.channelAuthorization),r.channelAuthorization):(e={transport:r.authTransport||G.authTransport,endpoint:r.authEndpoint||G.authEndpoint},"auth"in r&&("params"in r.auth&&(e.params=r.auth.params),"headers"in r.auth&&(e.headers=r.auth.headers)),"authorizer"in r&&(e.customHandler=bn(t,e,r.authorizer))),e}function Tn(r,t){let e=Sn(r,t);return we(e)?e.customHandler:vn(e)}class kn extends gt{constructor(t){super(function(e,n){et.debug(`No callbacks on watchlist events for ${e}`)}),this.pusher=t,this.bindWatchlistInternalEvent()}handleEvent(t){t.data.events.forEach(e=>{this.emit(e.name,e)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",t=>{var e=t.event;e==="pusher_internal:watchlist_events"&&this.handleEvent(t)})}}function An(){let r,t;return{promise:new Promise((n,i)=>{r=n,t=i}),resolve:r,reject:t}}let Pn=An;class Ln extends gt{constructor(t){super(function(e,n){et.debug("No callbacks on user for "+e)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(e,n)=>{if(e){et.warn(`Error during signin: ${e}`),this.emit("pusher:signin_error",Object.assign({},{type:"AuthError",error:e.message},e instanceof w?{status:e.status}:{})),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:n.auth,user_data:n.user_data})},this.pusher=t,this.pusher.connection.bind("state_change",({previous:e,current:n})=>{e!=="connected"&&n==="connected"&&this._signin(),e==="connected"&&n!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new kn(t),this.pusher.connection.bind("message",e=>{var n=e.event;n==="pusher:signin_success"&&this._onSigninSuccess(e.data),this.serverToUserChannel&&this.serverToUserChannel.name===e.channel&&this.serverToUserChannel.handleEvent(e)})}signin(){this.signin_requested||(this.signin_requested=!0,this._signin())}_signin(){this.signin_requested&&(this._newSigninPromiseIfNeeded(),this.pusher.connection.state==="connected"&&this.pusher.config.userAuthenticator({socketId:this.pusher.connection.socket_id},this._onAuthorize))}_onSigninSuccess(t){try{this.user_data=JSON.parse(t.user_data)}catch{et.error(`Failed parsing user data after signin: ${t.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){et.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),this._cleanup();return}this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){let t=e=>{e.subscriptionPending&&e.subscriptionCancelled?e.reinstateSubscription():!e.subscriptionPending&&this.pusher.connection.state==="connected"&&e.subscribe()};this.serverToUserChannel=new Kt(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((e,n)=>{e.indexOf("pusher_internal:")===0||e.indexOf("pusher:")===0||this.emit(e,n)}),t(this.serverToUserChannel)}_cleanup(){this.user_data=null,this.serverToUserChannel&&(this.serverToUserChannel.unbind_all(),this.serverToUserChannel.disconnect(),this.serverToUserChannel=null),this.signin_requested&&this._signinDoneResolve()}_newSigninPromiseIfNeeded(){if(!this.signin_requested||this.signinDonePromise&&!this.signinDonePromise.done)return;let{promise:t,resolve:e,reject:n}=Pn();t.done=!1;let i=()=>{t.done=!0};t.then(i).catch(i),this.signinDonePromise=t,this._signinDoneResolve=e}}class at{static ready(){at.isReady=!0;for(var t=0,e=at.instances.length;tj.getDefaultStrategy(this.config,i,un);this.connection=vt.createConnectionManager(this.key,{getStrategy:n,timeline:this.timeline,activityTimeout:this.config.activityTimeout,pongTimeout:this.config.pongTimeout,unavailableTimeout:this.config.unavailableTimeout,useTLS:!!this.config.useTLS}),this.connection.bind("connected",()=>{this.subscribeAll(),this.timelineSender&&this.timelineSender.send(this.connection.isUsingTLS())}),this.connection.bind("message",i=>{var l=i.event,k=l.indexOf("pusher_internal:")===0;if(i.channel){var O=this.channel(i.channel);O&&O.handleEvent(i)}k||this.global_emitter.emit(i.event,i.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",i=>{et.warn(i)}),at.instances.push(this),this.timeline.info({instances:at.instances.length}),this.user=new Ln(this),at.isReady&&this.connect()}switchCluster(t){let{appKey:e,cluster:n}=t;this.key=e,this.options=Object.assign(Object.assign({},this.options),{cluster:n}),this.config=ye(this.options,this),this.connection.switchCluster(this.key)}channel(t){return this.channels.find(t)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var t=this.connection.isUsingTLS(),e=this.timelineSender;this.timelineSenderTimer=new m(6e4,function(){e.send(t)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(t,e,n){return this.global_emitter.bind(t,e,n),this}unbind(t,e,n){return this.global_emitter.unbind(t,e,n),this}bind_global(t){return this.global_emitter.bind_global(t),this}unbind_global(t){return this.global_emitter.unbind_global(t),this}unbind_all(t){return this.global_emitter.unbind_all(),this}subscribeAll(){var t;for(t in this.channels.channels)this.channels.channels.hasOwnProperty(t)&&this.subscribe(t)}subscribe(t){var e=this.channels.add(t,this);return e.subscriptionPending&&e.subscriptionCancelled?e.reinstateSubscription():!e.subscriptionPending&&this.connection.state==="connected"&&e.subscribe(),e}unsubscribe(t){var e=this.channels.find(t);e&&e.subscriptionPending?e.cancelSubscription():(e=this.channels.remove(t),e&&e.subscribed&&e.unsubscribe())}send_event(t,e,n){return this.connection.send_event(t,e,n)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}at.instances=[],at.isReady=!1,at.logToConsole=!1,at.Runtime=j,at.ScriptReceivers=j.ScriptReceivers,at.DependenciesReceivers=j.DependenciesReceivers,at.auth_callbacks=j.auth_callbacks;let Ut=at;function En(r){if(r==null)throw"You must pass your app key when you instantiate Pusher."}j.setup(at)}},o={};function p(E){var L=o[E];if(L!==void 0)return L.exports;var q=o[E]={exports:{}};return A[E].call(q.exports,q,q.exports,p),q.exports}p.d=(E,L)=>{for(var q in L)p.o(L,q)&&!p.o(E,q)&&Object.defineProperty(E,q,{enumerable:!0,get:L[q]})},p.o=(E,L)=>Object.prototype.hasOwnProperty.call(E,L);var P=p(721);return P})())});var De=Ee((Ie,Be)=>{var Oe=(function(){var A=function(c,b){var v=236,x=17,u=c,_=p[b],a=null,s=0,w=null,d=[],C={},F=function(f,g){s=u*4+17,a=(function(h){for(var m=new Array(h),y=0;y=7&&ct(f),w==null&&(w=$t(u,_,d)),dt(w,g)},N=function(f,g){for(var h=-1;h<=7;h+=1)if(!(f+h<=-1||s<=f+h))for(var m=-1;m<=7;m+=1)g+m<=-1||s<=g+m||(0<=h&&h<=6&&(m==0||m==6)||0<=m&&m<=6&&(h==0||h==6)||2<=h&&h<=4&&2<=m&&m<=4?a[f+h][g+m]=!0:a[f+h][g+m]=!1)},J=function(){for(var f=0,g=0,h=0;h<8;h+=1){F(!0,h);var m=E.getLostPoint(C);(h==0||f>m)&&(f=m,g=h)}return g},rt=function(){for(var f=8;f>h&1)==1;a[Math.floor(h/3)][h%3+s-8-3]=m}for(var h=0;h<18;h+=1){var m=!f&&(g>>h&1)==1;a[h%3+s-8-3][Math.floor(h/3)]=m}},lt=function(f,g){for(var h=_<<3|g,m=E.getBCHTypeInfo(h),y=0;y<15;y+=1){var T=!f&&(m>>y&1)==1;y<6?a[y][8]=T:y<8?a[y+1][8]=T:a[s-15+y][8]=T}for(var y=0;y<15;y+=1){var T=!f&&(m>>y&1)==1;y<8?a[8][s-y-1]=T:y<9?a[8][15-y-1+1]=T:a[8][15-y-1]=T}a[s-8][8]=!f},dt=function(f,g){for(var h=-1,m=s-1,y=7,T=0,R=E.getMaskFunction(g),B=s-1;B>0;B-=2)for(B==6&&(B-=1);;){for(var tt=0;tt<2;tt+=1)if(a[m][B-tt]==null){var Q=!1;T>>y&1)==1);var D=R(m,B-tt);D&&(Q=!Q),a[m][B-tt]=Q,y-=1,y==-1&&(T+=1,y=7)}if(m+=h,m<0||s<=m){m-=h,h=-h;break}}},bt=function(f,g){for(var h=0,m=0,y=0,T=new Array(g.length),R=new Array(g.length),B=0;B=0?Pt.getAt(Bt):0}}for(var Lt=0,D=0;DB*8)throw"code length overflow. ("+y.getLengthInBits()+">"+B*8+")";for(y.getLengthInBits()+4<=B*8&&y.put(0,4);y.getLengthInBits()%8!=0;)y.putBit(!1);for(;!(y.getLengthInBits()>=B*8||(y.put(v,8),y.getLengthInBits()>=B*8));)y.put(x,8);return bt(y,m)};C.addData=function(f,g){g=g||"Byte";var h=null;switch(g){case"Numeric":h=ut(f);break;case"Alphanumeric":h=G(f);break;case"Byte":h=yt(f);break;case"Kanji":h=Z(f);break;default:throw"mode:"+g}d.push(h),w=null},C.isDark=function(f,g){if(f<0||s<=f||g<0||s<=g)throw f+","+g;return a[f][g]},C.getModuleCount=function(){return s},C.make=function(){if(u<1){for(var f=1;f<40;f++){for(var g=X.getRSBlocks(f,_),h=it(),m=0;m";for(var y=0;y';h+=""}return h+="",h+="",h},C.createSvgTag=function(f,g,h,m){var y={};typeof arguments[0]=="object"&&(y=arguments[0],f=y.cellSize,g=y.margin,h=y.alt,m=y.title),f=f||2,g=typeof g=="undefined"?f*4:g,h=typeof h=="string"?{text:h}:h||{},h.text=h.text||null,h.id=h.text?h.id||"qrcode-description":null,m=typeof m=="string"?{text:m}:m||{},m.text=m.text||null,m.id=m.text?m.id||"qrcode-title":null;var T=C.getModuleCount()*f+g*2,R,B,tt,Q,D="",ht;for(ht="l"+f+",0 0,"+f+" -"+f+",0 0,-"+f+"z ",D+=''+mt(m.text)+"":"",D+=h.text?''+mt(h.text)+"":"",D+='',D+='":g+=">";break;case"&":g+="&";break;case'"':g+=""";break;default:g+=m;break}}return g},It=function(f){var g=1;f=typeof f=="undefined"?g*2:f;var h=C.getModuleCount()*g+f*2,m=f,y=h-f,T,R,B,tt,Q,D={"\u2588\u2588":"\u2588","\u2588 ":"\u2580"," \u2588":"\u2584"," ":" "},ht={"\u2588\u2588":"\u2580","\u2588 ":"\u2580"," \u2588":" "," ":" "},ot="";for(T=0;T=y?ht[Q]:D[Q];ot+=` +`}return h%2&&f>0?ot.substring(0,ot.length-h-1)+Array(h+1).join("\u2580"):ot.substring(0,ot.length-1)};return C.createASCII=function(f,g){if(f=f||1,f<2)return It(g);f-=1,g=typeof g=="undefined"?f*2:g;var h=C.getModuleCount()*f+g*2,m=g,y=h-g,T,R,B,tt,Q=Array(f+1).join("\u2588\u2588"),D=Array(f+1).join(" "),ht="",ot="";for(T=0;T>>8),_.push(w&255)):_.push(x)}}return _}};var o={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},p={L:1,M:0,Q:3,H:2},P={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},E=(function(){var c=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],b=1335,v=7973,x=21522,u={},_=function(a){for(var s=0;a!=0;)s+=1,a>>>=1;return s};return u.getBCHTypeInfo=function(a){for(var s=a<<10;_(s)-_(b)>=0;)s^=b<<_(s)-_(b);return(a<<10|s)^x},u.getBCHTypeNumber=function(a){for(var s=a<<12;_(s)-_(v)>=0;)s^=v<<_(s)-_(v);return a<<12|s},u.getPatternPosition=function(a){return c[a-1]},u.getMaskFunction=function(a){switch(a){case P.PATTERN000:return function(s,w){return(s+w)%2==0};case P.PATTERN001:return function(s,w){return s%2==0};case P.PATTERN010:return function(s,w){return w%3==0};case P.PATTERN011:return function(s,w){return(s+w)%3==0};case P.PATTERN100:return function(s,w){return(Math.floor(s/2)+Math.floor(w/3))%2==0};case P.PATTERN101:return function(s,w){return s*w%2+s*w%3==0};case P.PATTERN110:return function(s,w){return(s*w%2+s*w%3)%2==0};case P.PATTERN111:return function(s,w){return(s*w%3+(s+w)%2)%2==0};default:throw"bad maskPattern:"+a}},u.getErrorCorrectPolynomial=function(a){for(var s=q([1],0),w=0;w5&&(w+=3+F-5)}for(var d=0;d=256;)u-=255;return c[u]},x})();function q(c,b){if(typeof c.length=="undefined")throw c.length+"/"+b;var v=(function(){for(var u=0;u>>7-x%8&1)==1},v.put=function(x,u){for(var _=0;_>>u-_-1&1)==1)},v.getLengthInBits=function(){return b},v.putBit=function(x){var u=Math.floor(b/8);c.length<=u&&c.push(0),x&&(c[u]|=128>>>b%8),b+=1},v},ut=function(c){var b=o.MODE_NUMBER,v=c,x={};x.getMode=function(){return b},x.getLength=function(a){return v.length},x.write=function(a){for(var s=v,w=0;w+2>>8&255)*192+(d&255),a.put(d,13),w+=2}if(w>>8)},b.writeBytes=function(v,x,u){x=x||0,u=u||v.length;for(var _=0;_0&&(v+=","),v+=c[x];return v+="]",v},b},z=function(){var c=0,b=0,v=0,x="",u={},_=function(s){x+=String.fromCharCode(a(s&63))},a=function(s){if(!(s<0)){if(s<26)return 65+s;if(s<52)return 97+(s-26);if(s<62)return 48+(s-52);if(s==62)return 43;if(s==63)return 47}throw"n:"+s};return u.writeByte=function(s){for(c=c<<8|s&255,b+=8,v+=1;b>=6;)_(c>>>b-6),b-=6},u.flush=function(){if(b>0&&(_(c<<6-b),c=0,b=0),v%3!=0)for(var s=3-v%3,w=0;w=b.length){if(u==0)return-1;throw"unexpected end of file./"+u}var s=b.charAt(v);if(v+=1,s=="=")return u=0,-1;if(s.match(/^\s$/))continue;x=x<<6|a(s.charCodeAt(0)),u+=6}var w=x>>>u-8&255;return u-=8,w};var a=function(s){if(65<=s&&s<=90)return s-65;if(97<=s&&s<=122)return s-97+26;if(48<=s&&s<=57)return s-48+52;if(s==43)return 62;if(s==47)return 63;throw"c:"+s};return _},M=function(c,b){var v=c,x=b,u=new Array(c*b),_={};_.setPixel=function(d,C,F){u[C*v+d]=F},_.write=function(d){d.writeString("GIF87a"),d.writeShort(v),d.writeShort(x),d.writeByte(128),d.writeByte(0),d.writeByte(0),d.writeByte(0),d.writeByte(0),d.writeByte(0),d.writeByte(255),d.writeByte(255),d.writeByte(255),d.writeString(","),d.writeShort(0),d.writeShort(0),d.writeShort(v),d.writeShort(x),d.writeByte(0);var C=2,F=s(C);d.writeByte(C);for(var N=0;F.length-N>255;)d.writeByte(255),d.writeBytes(F,N,255),N+=255;d.writeByte(F.length-N),d.writeBytes(F,N,F.length-N),d.writeByte(0),d.writeString(";")};var a=function(d){var C=d,F=0,N=0,J={};return J.write=function(rt,nt){if(rt>>>nt)throw"length over";for(;F+nt>=8;)C.writeByte(255&(rt<>>=8-F,N=0,F=0;N=rt<0&&C.writeByte(N)},J},s=function(d){for(var C=1<>6,128|L&63):L<55296||L>=57344?P.push(224|L>>12,128|L>>6&63,128|L&63):(E++,L=65536+((L&1023)<<10|p.charCodeAt(E)&1023),P.push(240|L>>18,128|L>>12&63,128|L>>6&63,128|L&63))}return P}return o(A)}})();(function(A){typeof define=="function"&&define.amd?define([],A):typeof Ie=="object"&&(Be.exports=A())})(function(){return Oe})});var qe=Re(Me()),ze=Re(De());var Ne=`.hibira-st { --h-bg: #ffffff; --h-fg: #1f2937; --h-muted: #6b7280; @@ -161,6 +162,7 @@ .hibira-st-text-button:hover { background: var(--h-soft); color: var(--h-fg); } .hibira-st-list { max-height: min(55vh, 460px); overflow-y: auto; padding: 4px 0; } .hibira-st-empty { padding: 20px 16px; color: var(--h-muted); text-align: center; } +.hibira-st-empty .hibira-st-text-button { margin-top: 8px; } .hibira-st-comment { display: flex; gap: 10px; padding: 10px 14px; } .hibira-st-comment + .hibira-st-comment { border-top: 1px solid var(--h-soft); } .hibira-st-comment.hibira-st-resolved { opacity: .65; } @@ -259,4 +261,15 @@ .hibira-st { right: 8px; bottom: 8px; max-width: calc(100vw - 16px); } .hibira-st-label { display: none; } } -`;var He=document.currentScript,$e=He?He.src.replace(/cp\.js(\?.*)?$/,""):null,Wn=/\/collections\/[^/]+\/entries\/([A-Za-z0-9_-]{1,100})\/?$/,Kn=["create","actions","reorder"],ie=null,Y=null,ft=null,pt=null;function q(A,o={}){let g=Y&&Y.strings&&Y.strings[A]||A;for(let[P,E]of Object.entries(o))g=g.split(":"+P).join(String(E));return g}function B(A,o={},...g){let P=document.createElement(A);for(let[E,L]of Object.entries(o))L==null||L===!1||(E==="class"?P.className=L:E.startsWith("on")?P.addEventListener(E.slice(2),L):P.setAttribute(E,L===!0?"":L));for(let E of g.flat())E==null||E===!1||P.append(E instanceof Node?E:document.createTextNode(String(E)));return P}var Gn={comment:'',phone:'',close:'',check:'',undo:'',trash:'',send:'',copy:'',open:'',warn:''};function Ot(A,o=18){let g=document.createElement("span");return g.innerHTML=``,g.firstChild}function At(A,o,g,P=""){return B("button",{type:"button",class:"hibira-st-icon "+P,"aria-label":o,"data-tip":o,onclick:g},Ot(A))}function je(A){let o=B("span",{class:"hibira-st-avatar",style:`background:${A.color||"#6b7280"}`});if(A.avatar){let g=B("img",{src:A.avatar,alt:""});g.addEventListener("error",()=>g.replaceWith(document.createTextNode(A.initials||"?"))),o.append(g)}else o.append(A.initials||"?");return o}function Qn(A){let o=Math.round((new Date(A).getTime()-Date.now())/1e3);try{let g=new Intl.RelativeTimeFormat(Y.locale,{numeric:"auto"}),P=[[60,"second"],[3600,"minute",60],[86400,"hour",3600],[604800,"day",86400]];if(Math.abs(o)<45)return g.format(0,"second");for(let[E,L,z=1]of P)if(Math.abs(o)Y=A).catch(()=>Y={enabled:!1})),ie}function Zn(){if(ft)return ft;let A=Y.connection;return ft=new ze.default(A.key,{cluster:"hkg",wsHost:A.host,wsPort:A.port,wssPort:A.port,forceTLS:A.tls,enabledTransports:["ws","wss"],disableStats:!0,channelAuthorization:{customHandler:({socketId:o,channelName:g},P)=>{Ct(Y.routes.auth,{method:"POST",body:{socket_id:o,channel_name:g}}).then(E=>P(null,E)).catch(E=>P(E,null))}}}),ft.connection.bind("state_change",({current:o})=>pt&&pt.setState(o)),ft}var se=class{constructor(o){this.entryId=o,this.channelName="presence-hibira-statamic.entry."+o,this.comments=[],this.loaded=!1,this.showResolved=!1,this.open=null,this.unread=!1,this.subscribed=!1,this.confirming=null,this.build(),this.subscribe(),Y.features.comments&&this.loadComments()}build(){let o=Y.features;this.avatars=B("span",{class:"hibira-st-avatars"}),this.label=B("span",{class:"hibira-st-label"}),this.people=B("span",{class:"hibira-st-people",hidden:!0},this.avatars,this.label),this.separator=B("span",{class:"hibira-st-sep",hidden:!0}),this.status=B("span",{class:"hibira-st-status","data-state":"connecting"}),this.commentsButton=o.comments?At("comment",q("comments"),()=>this.toggle("comments")):null,this.commentsButton&&(this.count=B("span",{class:"hibira-st-count"}),this.commentsButton.append(this.count),this.commentsButton.setAttribute("aria-expanded","false")),this.previewButton=o.livePreview?At("phone",q("preview"),()=>this.toggle("preview")):null,this.previewButton&&this.previewButton.setAttribute("aria-expanded","false"),this.dock=B("div",{class:"hibira-st-dock"},this.people,this.separator,this.commentsButton,this.previewButton,this.status),this.banner=B("div",{class:"hibira-st-banner",role:"status",hidden:!0}),this.card=B("div",{class:"hibira-st-card",hidden:!0}),this.root=B("div",{class:"hibira-st"},this.banner,this.card,this.dock),this.applyTheme(),this.themeObserver=new MutationObserver(()=>this.applyTheme()),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),this.onKey=g=>{g.key==="Escape"&&this.open&&this.toggle(null)},document.addEventListener("keydown",this.onKey),document.body.append(this.root)}applyTheme(){this.root.classList.toggle("hibira-st-dark",Vn())}setState(o){this.status.dataset.state=o;let g=o==="connected"?"Hibira":q("reconnecting");this.status.setAttribute("title",g)}toggle(o){this.open=this.open===o?null:o,this.commentsButton&&this.commentsButton.setAttribute("aria-expanded",String(this.open==="comments")),this.previewButton&&this.previewButton.setAttribute("aria-expanded",String(this.open==="preview")),this.card.hidden=!this.open,this.open==="comments"?(this.unread=!1,this.renderCount(),this.renderComments(),setTimeout(()=>this.textarea.focus(),0)):this.open==="preview"&&this.renderPreview()}head(o,...g){return B("div",{class:"hibira-st-head"},B("span",{},o),B("span",{class:"hibira-st-head-actions"},...g,At("close",q("close"),()=>this.toggle(null),"hibira-st-sm")))}subscribe(){this.setState(Zn().connection.state),this.channel=ft.subscribe(this.channelName),this.channel.bind("pusher:subscription_succeeded",()=>{this.subscribed&&Y.features.comments&&this.loadComments(),this.subscribed=!0,this.renderPeople()}),this.channel.bind("pusher:member_added",()=>this.renderPeople()),this.channel.bind("pusher:member_removed",()=>this.renderPeople()),this.channel.bind("saved",o=>this.onSaved(o)),this.channel.bind("comment",o=>this.onComment(o))}others(){let o=[];return!this.channel||!this.channel.members||this.channel.members.each(g=>{String(g.id)!==String(Y.user.id)&&o.push({id:g.id,...g.info})}),o}renderPeople(){if(!Y.features.presence)return;let o=this.others();this.people.hidden=o.length===0,this.separator.hidden=o.length===0||!this.commentsButton&&!this.previewButton,this.avatars.replaceChildren(...o.slice(0,3).map(g=>{let P=je(g);return P.setAttribute("data-tip",g.name),P.setAttribute("aria-label",g.name),P})),o.length>3&&this.avatars.append(B("span",{class:"hibira-st-avatar hibira-st-more"},"+"+(o.length-3))),this.label.textContent=o.length===0?"":o.length===1?q("here_one",{name:o[0].name}):q("here_many",{name:o[0].name,count:o.length-1})}onSaved(o){if(!Y.features.presence||o&&o.by&&String(o.by.id)===String(Y.user.id))return;let g=o&&o.by?q("saved_by",{name:o.by.name}):q("saved_elsewhere");this.banner.replaceChildren(B("span",{style:"flex:none;margin-top:1px"},Ot("warn",18)),B("div",{class:"hibira-st-banner-text"},g,B("div",{class:"hibira-st-row"},B("button",{type:"button",class:"hibira-st-button",onclick:()=>location.reload()},q("reload")),B("button",{type:"button",class:"hibira-st-button",onclick:()=>this.banner.hidden=!0},q("dismiss"))))),this.banner.hidden=!1}async loadComments(){try{let o=await Ct(Mt("comments",this.entryId));this.comments=o.comments||[],this.loaded=!0,this.renderCount(),this.open==="comments"&&this.renderComments()}catch{}}onComment({action:o,comment:g}){o==="added"?(this.comments.some(P=>P.id===g.id)||this.comments.push(g),this.open!=="comments"&&String(g.author.id)!==String(Y.user.id)&&(this.unread=!0)):o==="updated"?this.comments=this.comments.map(P=>P.id===g.id?g:P):o==="deleted"&&(this.comments=this.comments.filter(P=>P.id!==g.id)),this.renderCount(),this.open==="comments"&&this.renderComments()}open_(){return this.comments.filter(o=>!o.resolved_at)}renderCount(){if(!this.commentsButton)return;let o=this.open_().length;this.count.textContent=o?String(o):"",this.commentsButton.classList.toggle("hibira-st-new",this.unread);let g=o?q("comments_count",{count:o}):q("comments");this.commentsButton.setAttribute("aria-label",g),this.commentsButton.setAttribute("data-tip",this.unread?g+" \u2022":g)}renderComments(){(!this.compose||!this.card.contains(this.compose))&&this.buildCommentsCard();let o=this.comments.filter(z=>z.resolved_at),g=this.showResolved?this.comments:this.open_();this.resolvedToggle.hidden=o.length===0,this.resolvedToggle.textContent=this.showResolved?q("hide_resolved"):q("show_resolved",{count:o.length});let P=this.list,E=P.scrollTop+P.clientHeight>=P.scrollHeight-8,L=P.scrollTop;P.replaceChildren(...g.length?g.map(z=>this.renderComment(z)):[B("div",{class:"hibira-st-empty"},this.loaded?q("empty"):"\u2026")]),P.scrollTop=E?P.scrollHeight:L}buildCommentsCard(){this.resolvedToggle=B("button",{type:"button",class:"hibira-st-text-button",onclick:()=>{this.showResolved=!this.showResolved,this.renderComments()}}),this.list=B("div",{class:"hibira-st-list"}),this.textarea=B("textarea",{rows:1,placeholder:q("placeholder"),"aria-label":q("placeholder"),maxlength:Y.maxLength,oninput:()=>this.resize(),onkeydown:o=>{o.key==="Enter"&&(o.metaKey||o.ctrlKey)&&(o.preventDefault(),this.send())}}),this.sendButton=B("button",{type:"button",class:"hibira-st-send","aria-label":q("send"),"data-tip":q("send_hint"),onclick:()=>this.send()},Ot("send",18)),this.error=B("div",{class:"hibira-st-error",role:"alert"}),this.compose=B("div",{class:"hibira-st-compose"},this.textarea,this.sendButton),this.card.replaceChildren(this.head(q("comments"),this.resolvedToggle),this.list,this.compose,this.error),this.resize()}renderComment(o){let g=String(o.author.id)===String(Y.user.id),P=g||Y.user.super,E=B("span",{class:"hibira-st-comment-actions"},o.resolved_at?At("undo",q("reopen"),()=>this.resolve(o,!1),"hibira-st-sm"):At("check",q("resolve"),()=>this.resolve(o,!0),"hibira-st-sm"),P?At("trash",q("delete"),()=>{this.confirming=o.id,this.renderComments()},"hibira-st-sm"):null),L=this.confirming===o.id?B("div",{class:"hibira-st-confirm"},B("span",{},q("delete_confirm")),B("button",{type:"button",class:"hibira-st-text-button hibira-st-danger",onclick:()=>this.remove(o)},q("delete")),B("button",{type:"button",class:"hibira-st-text-button",onclick:()=>{this.confirming=null,this.renderComments()}},q("dismiss"))):null;return B("div",{class:"hibira-st-comment"+(o.resolved_at?" hibira-st-resolved":"")},je(o.author),B("div",{class:"hibira-st-comment-main"},B("div",{class:"hibira-st-comment-meta"},B("span",{class:"hibira-st-comment-name"},g?q("you"):o.author.name),B("time",{class:"hibira-st-comment-time",datetime:o.created_at,title:new Date(o.created_at).toLocaleString(Y.locale)},Qn(o.created_at)),E),B("div",{class:"hibira-st-comment-body"},o.body),o.resolved_by?B("div",{class:"hibira-st-comment-note"},q("resolved_by",{name:o.resolved_by.name})):null,L))}resize(){this.textarea&&(this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight+2,160)+"px",this.sendButton.disabled=this.textarea.value.trim()==="")}async send(){let o=this.textarea.value.trim();if(!(!o||this.sending)){if(o.length>Y.maxLength){this.error.textContent=q("too_long",{max:Y.maxLength});return}this.sending=!0,this.sendButton.disabled=!0;try{let{comment:g}=await Ct(Mt("comments",this.entryId),{method:"POST",body:{body:o}});this.textarea.value="",this.onComment({action:"added",comment:g}),this.list&&(this.list.scrollTop=this.list.scrollHeight)}catch{this.error.textContent=q("failed")}finally{this.sending=!1,this.resize()}}}async resolve(o,g){try{let P=await Ct(Mt("resolve",this.entryId,o.id),{method:"POST",body:{resolved:g}});this.onComment({action:"updated",comment:P.comment})}catch{this.error.textContent=q("failed")}}async remove(o){this.confirming=null;try{await Ct(Mt("comment",this.entryId,o.id),{method:"DELETE"}),this.onComment({action:"deleted",comment:{id:o.id}})}catch{this.renderComments(),this.error.textContent=q("failed")}}async renderPreview(){let o=B("div",{class:"hibira-st-preview"},B("div",{class:"hibira-st-hint"},"\u2026"));this.card.replaceChildren(this.head(q("preview")),o);let g=null;try{({url:g}=await Ct(Mt("previewLink",this.entryId)))}catch{g=null}if(this.open!=="preview")return;if(!g){o.replaceChildren(B("div",{class:"hibira-st-hint"},q("preview_none")));return}let P=(0,Fe.default)(0,"M");P.addData(g),P.make();let E=B("div",{class:"hibira-st-qr",role:"img","aria-label":g});E.innerHTML=P.createSvgTag({cellSize:4,margin:0,scalable:!0});let L=B("button",{type:"button",class:"hibira-st-button",onclick:async()=>{try{await navigator.clipboard.writeText(g),L.lastChild.textContent=q("copied"),setTimeout(()=>L.lastChild.textContent=q("copy"),1500)}catch{window.getSelection().selectAllChildren(z)}}},Ot("copy",16),B("span",{},q("copy"))),z=B("div",{class:"hibira-st-link",title:g},g);o.replaceChildren(E,B("div",{class:"hibira-st-hint"},q("preview_scan")),z,B("div",{class:"hibira-st-row"},L,B("a",{class:"hibira-st-button",href:g,target:"_blank",rel:"noopener"},Ot("open",16),B("span",{},q("open")))))}destroy(){ft&&ft.unsubscribe(this.channelName),this.themeObserver.disconnect(),document.removeEventListener("keydown",this.onKey),this.root.remove()}};function Ue(){let A=location.pathname.match(Wn);return A&&!Kn.includes(A[1])?A[1]:null}async function Ft(){let A=Ue();if(pt&&pt.entryId===A||(pt&&(pt.destroy(),pt=null),!A))return;await Yn();let{features:o}=Y;!Y.enabled||!(o.presence||o.comments||o.livePreview)||Ue()!==A||pt||(pt=new se(A))}function qe(){if(!$e||window.HibiraStatamic)return;window.HibiraStatamic={get page(){return pt}};let A=document.createElement("style");A.textContent=Ne,document.head.append(A);for(let o of["pushState","replaceState"]){let g=history[o];history[o]=function(...P){let E=g.apply(this,P);return setTimeout(Ft,0),E}}window.addEventListener("popstate",()=>setTimeout(Ft,0)),setInterval(Ft,1500),Ft()}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",qe):qe();})(); +`;var He=document.currentScript,$e=He?He.src.replace(/cp\.js(\?.*)?$/,""):null,Wn=/\/collections\/[^/]+\/entries\/([A-Za-z0-9_-]{1,100})\/?$/,Kn=["create","actions","reorder"],ie=null,Y=null,ft=null,pt=null;function U(A,o={}){let p=Y&&Y.strings&&Y.strings[A]||A;for(let[P,E]of Object.entries(o))p=p.split(":"+P).join(String(E));return p}function I(A,o={},...p){let P=document.createElement(A);for(let[E,L]of Object.entries(o))L==null||L===!1||(E==="class"?P.className=L:E.startsWith("on")?P.addEventListener(E.slice(2),L):P.setAttribute(E,L===!0?"":L));for(let E of p.flat())E==null||E===!1||P.append(E instanceof Node?E:document.createTextNode(String(E)));return P}var Gn={comment:'',phone:'',close:'',check:'',undo:'',trash:'',send:'',copy:'',open:'',warn:''};function Ot(A,o=18){let p=document.createElement("span");return p.innerHTML=``,p.firstChild}function At(A,o,p,P=""){return I("button",{type:"button",class:"hibira-st-icon "+P,"aria-label":o,"data-tip":o,onclick:p},Ot(A))}function je(A){let o=I("span",{class:"hibira-st-avatar",style:`background:${A.color||"#6b7280"}`});if(A.avatar){let p=I("img",{src:A.avatar,alt:""});p.addEventListener("error",()=>p.replaceWith(document.createTextNode(A.initials||"?"))),o.append(p)}else o.append(A.initials||"?");return o}function Qn(A){let o=Math.round((new Date(A).getTime()-Date.now())/1e3);try{let p=new Intl.RelativeTimeFormat(Y.locale,{numeric:"auto"}),P=[[60,"second"],[3600,"minute",60],[86400,"hour",3600],[604800,"day",86400]];if(Math.abs(o)<45)return p.format(0,"second");for(let[E,L,q=1]of P)if(Math.abs(o)Y=A).catch(()=>Y={enabled:!1})),ie}function Zn(){if(ft)return ft;let A=Y.connection;return ft=new qe.default(A.key,{cluster:"hkg",wsHost:A.host,wsPort:A.port,wssPort:A.port,forceTLS:A.tls,enabledTransports:["ws","wss"],disableStats:!0,channelAuthorization:{customHandler:({socketId:o,channelName:p},P)=>{Ct(Y.routes.auth,{method:"POST",body:{socket_id:o,channel_name:p}}).then(E=>P(null,E)).catch(E=>P(E,null))}}}),ft.connection.bind("state_change",({current:o})=>pt&&pt.setState(o)),ft}var se=class{constructor(o){this.entryId=o,this.channelName="presence-hibira-statamic.entry."+o,this.comments=[],this.loaded=!1,this.loadFailed=!1,this.loading=null,this.reloadAfter=!1,this.showResolved=!1,this.open=null,this.unread=!1,this.subscribed=!1,this.confirming=null,this.build(),this.subscribe(),Y.features.comments&&this.loadComments()}build(){let o=Y.features;this.avatars=I("span",{class:"hibira-st-avatars"}),this.label=I("span",{class:"hibira-st-label"}),this.people=I("span",{class:"hibira-st-people",hidden:!0},this.avatars,this.label),this.separator=I("span",{class:"hibira-st-sep",hidden:!0}),this.status=I("span",{class:"hibira-st-status","data-state":"connecting"}),this.commentsButton=o.comments?At("comment",U("comments"),()=>this.toggle("comments")):null,this.commentsButton&&(this.count=I("span",{class:"hibira-st-count"}),this.commentsButton.append(this.count),this.commentsButton.setAttribute("aria-expanded","false")),this.previewButton=o.livePreview?At("phone",U("preview"),()=>this.toggle("preview")):null,this.previewButton&&this.previewButton.setAttribute("aria-expanded","false"),this.dock=I("div",{class:"hibira-st-dock"},this.people,this.separator,this.commentsButton,this.previewButton,this.status),this.banner=I("div",{class:"hibira-st-banner",role:"status",hidden:!0}),this.card=I("div",{class:"hibira-st-card",hidden:!0}),this.root=I("div",{class:"hibira-st"},this.banner,this.card,this.dock),this.applyTheme(),this.themeObserver=new MutationObserver(()=>this.applyTheme()),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),this.onKey=p=>{p.key==="Escape"&&this.open&&this.toggle(null)},document.addEventListener("keydown",this.onKey),document.body.append(this.root)}applyTheme(){this.root.classList.toggle("hibira-st-dark",Vn())}setState(o){this.status.dataset.state=o;let p=o==="connected"?"Hibira":U("reconnecting");this.status.setAttribute("title",p)}toggle(o){this.open=this.open===o?null:o,this.commentsButton&&this.commentsButton.setAttribute("aria-expanded",String(this.open==="comments")),this.previewButton&&this.previewButton.setAttribute("aria-expanded",String(this.open==="preview")),this.card.hidden=!this.open,this.open==="comments"?(this.unread=!1,this.renderCount(),this.renderComments(),setTimeout(()=>this.textarea.focus(),0)):this.open==="preview"&&this.renderPreview()}head(o,...p){return I("div",{class:"hibira-st-head"},I("span",{},o),I("span",{class:"hibira-st-head-actions"},...p,At("close",U("close"),()=>this.toggle(null),"hibira-st-sm")))}subscribe(){this.setState(Zn().connection.state),this.channel=ft.subscribe(this.channelName),this.channel.bind("pusher:subscription_succeeded",()=>{this.subscribed&&Y.features.comments&&this.loadComments(),this.subscribed=!0,this.renderPeople()}),this.channel.bind("pusher:member_added",()=>this.renderPeople()),this.channel.bind("pusher:member_removed",()=>this.renderPeople()),this.channel.bind("saved",o=>this.onSaved(o)),this.channel.bind("comment",o=>this.onRemoteComment(o))}others(){let o=[];return!this.channel||!this.channel.members||this.channel.members.each(p=>{String(p.id)!==String(Y.user.id)&&o.push({id:p.id,...p.info})}),o}renderPeople(){if(!Y.features.presence)return;let o=this.others();this.people.hidden=o.length===0,this.separator.hidden=o.length===0||!this.commentsButton&&!this.previewButton,this.avatars.replaceChildren(...o.slice(0,3).map(p=>{let P=je(p);return P.setAttribute("data-tip",p.name),P.setAttribute("aria-label",p.name),P})),o.length>3&&this.avatars.append(I("span",{class:"hibira-st-avatar hibira-st-more"},"+"+(o.length-3))),this.label.textContent=o.length===0?"":o.length===1?U("here_one",{name:o[0].name}):U("here_many",{name:o[0].name,count:o.length-1})}onSaved(o){if(!Y.features.presence||o&&o.by&&String(o.by.id)===String(Y.user.id))return;let p=o&&o.by?U("saved_by",{name:o.by.name}):U("saved_elsewhere");this.banner.replaceChildren(I("span",{style:"flex:none;margin-top:1px"},Ot("warn",18)),I("div",{class:"hibira-st-banner-text"},p,I("div",{class:"hibira-st-row"},I("button",{type:"button",class:"hibira-st-button",onclick:()=>location.reload()},U("reload")),I("button",{type:"button",class:"hibira-st-button",onclick:()=>this.banner.hidden=!0},U("dismiss"))))),this.banner.hidden=!1}loadComments(){return this.loading?(this.reloadAfter=!0,this.loading):(this.loading=(async()=>{try{let o=await Ct(Mt("comments",this.entryId)),p=new Set(this.comments.map(P=>P.id));this.comments=o.comments||[],this.loaded&&this.open!=="comments"&&this.comments.some(P=>!p.has(P.id)&&String(P.author.id)!==String(Y.user.id))&&(this.unread=!0),this.loaded=!0,this.loadFailed=!1}catch{this.loadFailed=!0}finally{this.loading=null}this.renderCount(),this.open==="comments"&&this.renderComments(),this.reloadAfter&&(this.reloadAfter=!1,this.loadComments())})(),this.loading)}onRemoteComment({action:o,id:p}){o==="deleted"?this.onComment({action:o,comment:{id:p}}):this.loadComments()}onComment({action:o,comment:p}){o==="added"?this.comments.some(P=>P.id===p.id)||this.comments.push(p):o==="updated"?this.comments=this.comments.map(P=>P.id===p.id?p:P):o==="deleted"&&(this.comments=this.comments.filter(P=>P.id!==p.id)),this.renderCount(),this.open==="comments"&&this.renderComments()}open_(){return this.comments.filter(o=>!o.resolved_at)}renderCount(){if(!this.commentsButton)return;let o=this.open_().length;this.count.textContent=o?String(o):"",this.commentsButton.classList.toggle("hibira-st-new",this.unread);let p=o?U("comments_count",{count:o}):U("comments");this.commentsButton.setAttribute("aria-label",p),this.commentsButton.setAttribute("data-tip",this.unread?p+" \u2022":p)}renderComments(){(!this.compose||!this.card.contains(this.compose))&&this.buildCommentsCard();let o=this.comments.filter(X=>X.resolved_at),p=this.showResolved?this.comments:this.open_();this.resolvedToggle.hidden=o.length===0,this.resolvedToggle.textContent=this.showResolved?U("hide_resolved"):U("show_resolved",{count:o.length});let P=this.list,E=P.scrollTop+P.clientHeight>=P.scrollHeight-8,L=P.scrollTop,q;this.loadFailed&&!this.loaded?q=I("div",{class:"hibira-st-empty"},I("div",{},U("load_failed")),I("button",{type:"button",class:"hibira-st-text-button",onclick:()=>this.retryLoad()},U("retry"))):q=I("div",{class:"hibira-st-empty","aria-busy":this.loaded?"false":"true"},this.loaded?U("empty"):"\u2026"),P.replaceChildren(...p.length?p.map(X=>this.renderComment(X)):[q]),P.scrollTop=E?P.scrollHeight:L}retryLoad(){this.loadFailed=!1,this.renderComments(),this.loadComments()}clearError(){this.error&&(this.error.textContent="")}buildCommentsCard(){this.resolvedToggle=I("button",{type:"button",class:"hibira-st-text-button",onclick:()=>{this.showResolved=!this.showResolved,this.renderComments()}}),this.list=I("div",{class:"hibira-st-list"}),this.textarea=I("textarea",{rows:1,placeholder:U("placeholder"),"aria-label":U("placeholder"),maxlength:Y.maxLength,oninput:()=>{this.clearError(),this.resize()},onkeydown:o=>{o.key==="Enter"&&(o.metaKey||o.ctrlKey)&&(o.preventDefault(),this.send())}}),this.sendButton=I("button",{type:"button",class:"hibira-st-send","aria-label":U("send"),"data-tip":U("send_hint"),onclick:()=>this.send()},Ot("send",18)),this.error=I("div",{class:"hibira-st-error",role:"alert"}),this.compose=I("div",{class:"hibira-st-compose"},this.textarea,this.sendButton),this.card.replaceChildren(this.head(U("comments"),this.resolvedToggle),this.list,this.compose,this.error),this.resize()}renderComment(o){let p=String(o.author.id)===String(Y.user.id),P=p||Y.user.super,E=I("span",{class:"hibira-st-comment-actions"},o.resolved_at?At("undo",U("reopen"),()=>this.resolve(o,!1),"hibira-st-sm"):At("check",U("resolve"),()=>this.resolve(o,!0),"hibira-st-sm"),P?At("trash",U("delete"),()=>{this.confirming=o.id,this.renderComments()},"hibira-st-sm"):null),L=this.confirming===o.id?I("div",{class:"hibira-st-confirm"},I("span",{},U("delete_confirm")),I("button",{type:"button",class:"hibira-st-text-button hibira-st-danger",onclick:()=>this.remove(o)},U("delete")),I("button",{type:"button",class:"hibira-st-text-button",onclick:()=>{this.confirming=null,this.renderComments()}},U("dismiss"))):null;return I("div",{class:"hibira-st-comment"+(o.resolved_at?" hibira-st-resolved":"")},je(o.author),I("div",{class:"hibira-st-comment-main"},I("div",{class:"hibira-st-comment-meta"},I("span",{class:"hibira-st-comment-name"},p?U("you"):o.author.name),I("time",{class:"hibira-st-comment-time",datetime:o.created_at,title:new Date(o.created_at).toLocaleString(Y.locale)},Qn(o.created_at)),E),I("div",{class:"hibira-st-comment-body"},o.body),o.resolved_by?I("div",{class:"hibira-st-comment-note"},U("resolved_by",{name:o.resolved_by.name})):null,L))}resize(){this.textarea&&(this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight+2,160)+"px",this.sendButton.disabled=this.textarea.value.trim()==="")}async send(){let o=this.textarea.value.trim();if(!(!o||this.sending)){if(o.length>Y.maxLength){this.error.textContent=U("too_long",{max:Y.maxLength});return}this.sending=!0,this.sendButton.disabled=!0;try{let{comment:p}=await Ct(Mt("comments",this.entryId),{method:"POST",body:{body:o}});this.textarea.value="",this.clearError(),this.onComment({action:"added",comment:p}),this.list&&(this.list.scrollTop=this.list.scrollHeight)}catch{this.error.textContent=U("failed")}finally{this.sending=!1,this.resize()}}}async resolve(o,p){try{let P=await Ct(Mt("resolve",this.entryId,o.id),{method:"POST",body:{resolved:p}});this.clearError(),this.onComment({action:"updated",comment:P.comment})}catch{this.error.textContent=U("failed")}}async remove(o){this.confirming=null;try{await Ct(Mt("comment",this.entryId,o.id),{method:"DELETE"}),this.clearError(),this.onComment({action:"deleted",comment:{id:o.id}})}catch{this.renderComments(),this.error.textContent=U("failed")}}async renderPreview(){let o=I("div",{class:"hibira-st-preview"},I("div",{class:"hibira-st-hint"},"\u2026"));this.card.replaceChildren(this.head(U("preview")),o);let p=null;try{({url:p}=await Ct(Mt("previewLink",this.entryId)))}catch{p=null}if(this.open!=="preview")return;if(!p){o.replaceChildren(I("div",{class:"hibira-st-hint"},U("preview_none")));return}let P=(0,ze.default)(0,"M");P.addData(p),P.make();let E=I("div",{class:"hibira-st-qr",role:"img","aria-label":p});E.innerHTML=P.createSvgTag({cellSize:4,margin:0,scalable:!0});let L=I("button",{type:"button",class:"hibira-st-button",onclick:async()=>{try{await navigator.clipboard.writeText(p),L.lastChild.textContent=U("copied"),setTimeout(()=>L.lastChild.textContent=U("copy"),1500)}catch{window.getSelection().selectAllChildren(q)}}},Ot("copy",16),I("span",{},U("copy"))),q=I("div",{class:"hibira-st-link",title:p},p);o.replaceChildren(E,I("div",{class:"hibira-st-hint"},U("preview_scan")),q,I("div",{class:"hibira-st-row"},L,I("a",{class:"hibira-st-button",href:p,target:"_blank",rel:"noopener"},Ot("open",16),I("span",{},U("open")))))}destroy(){ft&&ft.unsubscribe(this.channelName),this.themeObserver.disconnect(),document.removeEventListener("keydown",this.onKey),this.root.remove()}};function Ue(){let A=location.pathname.match(Wn);return A&&!Kn.includes(A[1])?A[1]:null}async function zt(){let A=Ue();if(pt&&pt.entryId===A||(pt&&(pt.destroy(),pt=null),!A))return;await Yn();let{features:o}=Y;!Y.enabled||!(o.presence||o.comments||o.livePreview)||Ue()!==A||pt||(pt=new se(A))}function Fe(){if(!$e||window.HibiraStatamic)return;window.HibiraStatamic={get page(){return pt}};let A=document.createElement("style");A.textContent=Ne,document.head.append(A);for(let o of["pushState","replaceState"]){let p=history[o];history[o]=function(...P){let E=p.apply(this,P);return setTimeout(zt,0),E}}window.addEventListener("popstate",()=>setTimeout(zt,0)),setInterval(zt,1500),zt()}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Fe):Fe();})(); +/*! Bundled license information: + +pusher-js/dist/web/pusher.js: + (*! + * Pusher JavaScript Library v8.6.0 + * https://pusher.com/ + * + * Copyright 2020, Pusher + * Released under the MIT licence. + *) +*/ diff --git a/package.json b/package.json index 29f04f2..0c7606d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "private": true, "scripts": { - "build": "esbuild resources/js/cp.js --bundle --minify --format=iife --target=es2019 --loader:.css=text --outfile=dist/cp.js --legal-comments=none && esbuild resources/js/preview.js --minify --target=es2017 --outfile=dist/preview.js --legal-comments=none" + "build": "esbuild resources/js/cp.js --bundle --minify --format=iife --target=es2019 --loader:.css=text --outfile=dist/cp.js --legal-comments=eof \"--banner:js=/*! Hibira Realtime for Statamic. MIT License. Includes pusher-js (MIT, Copyright (c) 2020 Pusher, Ltd), @stablelib/base64 and @stablelib/utf8 (MIT, Copyright (C) 2016 Dmitry Chestnykh) and qrcode-generator (MIT, Copyright (c) 2009 Kazuhiko Arase). Full license texts: THIRD-PARTY-NOTICES. */\" && esbuild resources/js/preview.js --minify --target=es2017 --outfile=dist/preview.js --legal-comments=none" }, "devDependencies": { "esbuild": "^0.25.0", diff --git a/resources/js/cp.css b/resources/js/cp.css index 8926606..14ac1a0 100644 --- a/resources/js/cp.css +++ b/resources/js/cp.css @@ -158,6 +158,7 @@ .hibira-st-text-button:hover { background: var(--h-soft); color: var(--h-fg); } .hibira-st-list { max-height: min(55vh, 460px); overflow-y: auto; padding: 4px 0; } .hibira-st-empty { padding: 20px 16px; color: var(--h-muted); text-align: center; } +.hibira-st-empty .hibira-st-text-button { margin-top: 8px; } .hibira-st-comment { display: flex; gap: 10px; padding: 10px 14px; } .hibira-st-comment + .hibira-st-comment { border-top: 1px solid var(--h-soft); } .hibira-st-comment.hibira-st-resolved { opacity: .65; } diff --git a/resources/js/cp.js b/resources/js/cp.js index c8bf306..587d9c3 100644 --- a/resources/js/cp.js +++ b/resources/js/cp.js @@ -174,6 +174,9 @@ class EntryPage { this.channelName = 'presence-hibira-statamic.entry.' + entryId; this.comments = []; this.loaded = false; + this.loadFailed = false; + this.loading = null; + this.reloadAfter = false; this.showResolved = false; this.open = null; this.unread = false; @@ -273,7 +276,7 @@ class EntryPage { this.channel.bind('pusher:member_added', () => this.renderPeople()); this.channel.bind('pusher:member_removed', () => this.renderPeople()); this.channel.bind('saved', (data) => this.onSaved(data)); - this.channel.bind('comment', (data) => this.onComment(data)); + this.channel.bind('comment', (data) => this.onRemoteComment(data)); } others() { @@ -326,22 +329,54 @@ class EntryPage { // -- Comments -------------------------------------------------------------- - async loadComments() { - try { - const data = await api(route('comments', this.entryId)); - this.comments = data.comments || []; - this.loaded = true; + // Fetches the comments. Calls made while a fetch runs are folded into + // one more fetch after it, so a burst of events costs two requests. + loadComments() { + if (this.loading) { + this.reloadAfter = true; + return this.loading; + } + + this.loading = (async () => { + try { + const data = await api(route('comments', this.entryId)); + const known = new Set(this.comments.map((c) => c.id)); + this.comments = data.comments || []; + if (this.loaded && this.open !== 'comments' && this.comments.some((c) => !known.has(c.id) && String(c.author.id) !== String(config.user.id))) { + this.unread = true; + } + this.loaded = true; + this.loadFailed = false; + } catch (e) { + // Shown in the card with a retry button; a reconnect also tries again. + this.loadFailed = true; + } finally { + this.loading = null; + } this.renderCount(); if (this.open === 'comments') this.renderComments(); - } catch (e) { - // Shown as an empty list; the next reconnect tries again. + if (this.reloadAfter) { + this.reloadAfter = false; + this.loadComments(); + } + })(); + + return this.loading; + } + + // Events from the others carry only the comment ID, so a long comment + // never meets the message size limit: fetch the comments again. + onRemoteComment({ action, id }) { + if (action === 'deleted') { + this.onComment({ action, comment: { id } }); + } else { + this.loadComments(); } } onComment({ action, comment }) { if (action === 'added') { if (!this.comments.some((c) => c.id === comment.id)) this.comments.push(comment); - if (this.open !== 'comments' && String(comment.author.id) !== String(config.user.id)) this.unread = true; } else if (action === 'updated') { this.comments = this.comments.map((c) => (c.id === comment.id ? comment : c)); } else if (action === 'deleted') { @@ -378,13 +413,30 @@ class EntryPage { const atEnd = list.scrollTop + list.clientHeight >= list.scrollHeight - 8; const scrollTop = list.scrollTop; - list.replaceChildren(...(visible.length - ? visible.map((comment) => this.renderComment(comment)) - : [h('div', { class: 'hibira-st-empty' }, this.loaded ? t('empty') : '…')])); + let placeholder; + if (this.loadFailed && !this.loaded) { + placeholder = h('div', { class: 'hibira-st-empty' }, + h('div', {}, t('load_failed')), + h('button', { type: 'button', class: 'hibira-st-text-button', onclick: () => this.retryLoad() }, t('retry'))); + } else { + placeholder = h('div', { class: 'hibira-st-empty', 'aria-busy': this.loaded ? 'false' : 'true' }, this.loaded ? t('empty') : '…'); + } + + list.replaceChildren(...(visible.length ? visible.map((comment) => this.renderComment(comment)) : [placeholder])); list.scrollTop = atEnd ? list.scrollHeight : scrollTop; } + retryLoad() { + this.loadFailed = false; + this.renderComments(); + this.loadComments(); + } + + clearError() { + if (this.error) this.error.textContent = ''; + } + buildCommentsCard() { this.resolvedToggle = h('button', { type: 'button', @@ -400,7 +452,10 @@ class EntryPage { placeholder: t('placeholder'), 'aria-label': t('placeholder'), maxlength: config.maxLength, - oninput: () => this.resize(), + oninput: () => { + this.clearError(); + this.resize(); + }, onkeydown: (event) => { if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) { event.preventDefault(); @@ -481,6 +536,7 @@ class EntryPage { try { const { comment } = await api(route('comments', this.entryId), { method: 'POST', body: { body } }); this.textarea.value = ''; + this.clearError(); this.onComment({ action: 'added', comment }); if (this.list) this.list.scrollTop = this.list.scrollHeight; } catch (e) { @@ -494,6 +550,7 @@ class EntryPage { async resolve(comment, resolved) { try { const data = await api(route('resolve', this.entryId, comment.id), { method: 'POST', body: { resolved } }); + this.clearError(); this.onComment({ action: 'updated', comment: data.comment }); } catch (e) { this.error.textContent = t('failed'); @@ -504,6 +561,7 @@ class EntryPage { this.confirming = null; try { await api(route('comment', this.entryId, comment.id), { method: 'DELETE' }); + this.clearError(); this.onComment({ action: 'deleted', comment: { id: comment.id } }); } catch (e) { this.renderComments(); diff --git a/resources/lang/en/messages.php b/resources/lang/en/messages.php index a355ee3..c5d9f58 100644 --- a/resources/lang/en/messages.php +++ b/resources/lang/en/messages.php @@ -22,6 +22,8 @@ 'resolved_by' => 'Resolved by :name', 'close' => 'Close', 'failed' => 'Couldn’t save. Try again.', + 'load_failed' => 'Couldn’t load the comments.', + 'retry' => 'Try again', 'too_long' => 'Comments can be up to :max characters.', 'new_comment' => ':name commented', 'you' => 'You', diff --git a/resources/lang/ja/messages.php b/resources/lang/ja/messages.php index 2c77915..d3aaf1d 100644 --- a/resources/lang/ja/messages.php +++ b/resources/lang/ja/messages.php @@ -22,6 +22,8 @@ 'resolved_by' => ':name さんが解決済みにしました', 'close' => '閉じる', 'failed' => '保存できませんでした。もう一度お試しください。', + 'load_failed' => 'コメントを読み込めませんでした。', + 'retry' => '再試行', 'too_long' => 'コメントは :max 文字までです。', 'new_comment' => ':name さんがコメントしました', 'you' => 'あなた', diff --git a/resources/lang/ko/messages.php b/resources/lang/ko/messages.php index 480c109..16a450a 100644 --- a/resources/lang/ko/messages.php +++ b/resources/lang/ko/messages.php @@ -22,6 +22,8 @@ 'resolved_by' => ':name 님이 해결함', 'close' => '닫기', 'failed' => '저장하지 못했습니다. 다시 시도하세요.', + 'load_failed' => '댓글을 불러오지 못했습니다.', + 'retry' => '다시 시도', 'too_long' => '댓글은 최대 :max자까지 쓸 수 있습니다.', 'new_comment' => ':name 님이 댓글을 남겼습니다', 'you' => '나', diff --git a/resources/lang/th/messages.php b/resources/lang/th/messages.php index 9ea86ab..9277138 100644 --- a/resources/lang/th/messages.php +++ b/resources/lang/th/messages.php @@ -22,6 +22,8 @@ 'resolved_by' => ':name ทำเครื่องหมายว่าแก้ไขแล้ว', 'close' => 'ปิด', 'failed' => 'บันทึกไม่สำเร็จ โปรดลองอีกครั้ง', + 'load_failed' => 'โหลดความคิดเห็นไม่สำเร็จ', + 'retry' => 'ลองอีกครั้ง', 'too_long' => 'ความคิดเห็นยาวได้ไม่เกิน :max ตัวอักษร', 'new_comment' => ':name แสดงความคิดเห็น', 'you' => 'คุณ', diff --git a/resources/lang/vi/messages.php b/resources/lang/vi/messages.php index 0bfec01..8934fb6 100644 --- a/resources/lang/vi/messages.php +++ b/resources/lang/vi/messages.php @@ -22,6 +22,8 @@ 'resolved_by' => ':name đã đánh dấu xử lý', 'close' => 'Đóng', 'failed' => 'Không lưu được. Hãy thử lại.', + 'load_failed' => 'Không tải được bình luận.', + 'retry' => 'Thử lại', 'too_long' => 'Bình luận tối đa :max ký tự.', 'new_comment' => ':name đã bình luận', 'you' => 'Bạn', diff --git a/resources/lang/zh_CN/messages.php b/resources/lang/zh_CN/messages.php index 13a09e9..eb80dd5 100644 --- a/resources/lang/zh_CN/messages.php +++ b/resources/lang/zh_CN/messages.php @@ -22,6 +22,8 @@ 'resolved_by' => ':name 已标记为解决', 'close' => '关闭', 'failed' => '保存失败,请重试。', + 'load_failed' => '无法加载评论。', + 'retry' => '重试', 'too_long' => '评论最多 :max 个字。', 'new_comment' => ':name 发表了评论', 'you' => '你', diff --git a/resources/lang/zh_TW/messages.php b/resources/lang/zh_TW/messages.php index 80cec25..91d6a30 100644 --- a/resources/lang/zh_TW/messages.php +++ b/resources/lang/zh_TW/messages.php @@ -22,6 +22,8 @@ 'resolved_by' => ':name 已標記為解決', 'close' => '關閉', 'failed' => '儲存失敗,請再試一次。', + 'load_failed' => '無法載入留言。', + 'retry' => '重試', 'too_long' => '留言最多 :max 個字。', 'new_comment' => ':name 留言了', 'you' => '你', diff --git a/src/Comments/CommentStore.php b/src/Comments/CommentStore.php index e3460c9..a6c1d85 100644 --- a/src/Comments/CommentStore.php +++ b/src/Comments/CommentStore.php @@ -133,9 +133,12 @@ protected function change(string $entryId, callable $callback): void flock($handle, LOCK_EX); $comments = $callback($this->decode((string) stream_get_contents($handle))); + // Encode before truncating, so a failure leaves the file as it was. + $json = json_encode($comments, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)."\n"; + ftruncate($handle, 0); rewind($handle); - fwrite($handle, json_encode($comments, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."\n"); + fwrite($handle, $json); fflush($handle); } finally { flock($handle, LOCK_UN); diff --git a/src/Http/Controllers/CommentController.php b/src/Http/Controllers/CommentController.php index 2ca0cb8..4de28ba 100644 --- a/src/Http/Controllers/CommentController.php +++ b/src/Http/Controllers/CommentController.php @@ -31,11 +31,13 @@ public function store(Request $request, string $entry): JsonResponse 'body' => ['required', 'string', 'max:'.(int) config('hibira-statamic.comments.max_length', 2000)], ]); + abort_unless(mb_check_encoding($data['body'], 'UTF-8'), 422); + $body = trim(str_replace("\r\n", "\n", $data['body'])); abort_if($body === '', 422); $comment = $this->comments->add($entry, Members::info($this->user()), $body); - $this->broadcast($request, $entry, 'added', $comment); + $this->broadcast($request, $entry, 'added', $comment['id']); return response()->json(['comment' => $comment], 201); } @@ -54,7 +56,7 @@ public function resolve(Request $request, string $entry, string $comment): JsonR ); abort_if($changed === null, 404); - $this->broadcast($request, $entry, 'updated', $changed); + $this->broadcast($request, $entry, 'updated', $changed['id']); return response()->json(['comment' => $changed]); } @@ -70,18 +72,22 @@ public function destroy(Request $request, string $entry, string $comment): JsonR abort_unless($user->isSuper() || (string) ($found['author']['id'] ?? '') === (string) $user->id(), 403); $this->comments->delete($entry, $comment); - $this->broadcast($request, $entry, 'deleted', ['id' => $comment]); + $this->broadcast($request, $entry, 'deleted', $comment); return response()->json(['deleted' => true]); } - /** @param array $comment */ - protected function broadcast(Request $request, string $entry, string $action, array $comment): void + /** + * Tell the others on the entry which comment changed. Only the ID is + * sent: they fetch the comment from the control panel, so its text, + * however long, never meets the plan's message size limit. + */ + protected function broadcast(Request $request, string $entry, string $action, string $commentId): void { $this->realtime->trigger( (string) Channels::entry($entry), 'comment', - ['action' => $action, 'comment' => $comment], + ['action' => $action, 'id' => $commentId], Realtime::socketId($request->header('X-Socket-ID')), ); } diff --git a/src/Realtime.php b/src/Realtime.php index 746c703..780fffc 100644 --- a/src/Realtime.php +++ b/src/Realtime.php @@ -9,11 +9,18 @@ * Talks to Hibira for the addon: sends events and signs channel * subscriptions. * - * A failed send is reported but never fails the request. Comments are - * stored first, and open pages fetch them again when they reconnect. + * Events are sent after the response, so a slow or unreachable Hibira never + * holds up a save. A failed send is reported but never fails the request. + * Comments are stored first, and open pages fetch them again when they + * reconnect. */ class Realtime { + /** @var list, 3: ?string}> */ + protected array $pending = []; + + protected bool $flushRegistered = false; + public function __construct(protected Hibira $hibira) {} /** Whether the app ID, key and secret are set. */ @@ -22,13 +29,47 @@ public function configured(): bool return $this->hibira->missingRealtimeCredentials() === []; } - /** @param array $data */ + /** + * Send an event once the response has gone out. Outside of an HTTP + * request (queue workers, commands) it is sent at once. + * + * @param array $data + */ public function trigger(string $channel, string $event, array $data, ?string $exceptSocket = null): void { if (! $this->configured()) { return; } + if (app()->runningInConsole() && ! app()->runningUnitTests()) { + $this->send($channel, $event, $data, $exceptSocket); + + return; + } + + $this->pending[] = [$channel, $event, $data, $exceptSocket]; + + if (! $this->flushRegistered) { + $this->flushRegistered = true; + app()->terminating(fn () => $this->flush()); + } + } + + /** Send the events waiting for the end of the request. */ + public function flush(): void + { + $pending = $this->pending; + $this->pending = []; + $this->flushRegistered = false; + + foreach ($pending as [$channel, $event, $data, $exceptSocket]) { + $this->send($channel, $event, $data, $exceptSocket); + } + } + + /** @param array $data */ + protected function send(string $channel, string $event, array $data, ?string $exceptSocket): void + { try { $this->hibira->realtime()->trigger( $channel, diff --git a/tests/CommentsTest.php b/tests/CommentsTest.php index 7f71b5a..2150b3d 100644 --- a/tests/CommentsTest.php +++ b/tests/CommentsTest.php @@ -27,6 +27,7 @@ public function test_comments_are_added_listed_and_sent_to_the_others(): void $this->assertSame('presence-hibira-statamic.entry.post-1', $sent[0]['channel']); $this->assertSame('added', $sent[0]['data']['action']); $this->assertSame('11.22', $sent[0]['except']); + $this->assertSame(['action' => 'added', 'id' => $response->json('comment.id')], $sent[0]['data']); $this->actingAs($user)->getJson('/cp/hibira/entries/post-1/comments') ->assertOk() @@ -47,6 +48,49 @@ public function test_empty_and_too_long_comments_are_refused(): void $this->actingAs($user)->postJson('/cp/hibira/entries/missing/comments', ['body' => 'Hi'])->assertNotFound(); } + public function test_long_comments_are_announced_by_id_only(): void + { + $this->entry('post-1'); + $body = str_repeat('留言', 900); + + $id = $this->actingAs($this->superUser()) + ->postJson('/cp/hibira/entries/post-1/comments', ['body' => $body]) + ->assertCreated() + ->json('comment.id'); + + $sent = $this->realtime->sent('comment')[0]; + $this->assertSame(['action' => 'added', 'id' => $id], $sent['data']); + $this->assertLessThan(200, strlen(json_encode($sent['data']))); + } + + public function test_invalid_utf8_is_refused_and_keeps_the_existing_comments(): void + { + $this->entry('post-1'); + $store = app(CommentStore::class); + $store->add('post-1', ['id' => 'ada', 'name' => 'Ada'], 'Keep me'); + + $this->actingAs($this->superUser()) + ->post('/cp/hibira/entries/post-1/comments', ['body' => "bad \xB1\x31"], ['Accept' => 'application/json']) + ->assertStatus(422); + + $this->assertSame(['Keep me'], array_column($store->all('post-1'), 'body')); + } + + public function test_a_comment_that_cannot_be_encoded_leaves_the_file_untouched(): void + { + $this->entry('post-1'); + $store = app(CommentStore::class); + $store->add('post-1', ['id' => 'ada', 'name' => 'Ada'], 'Keep me'); + + try { + $store->add('post-1', ['id' => 'ada', 'name' => 'Ada'], "bad \xB1\x31"); + $this->fail('Expected the encoding to fail.'); + } catch (\JsonException) { + } + + $this->assertSame(['Keep me'], array_column($store->all('post-1'), 'body')); + } + public function test_comments_can_be_resolved_and_reopened(): void { $this->entry('post-1'); diff --git a/tests/ControlPanelTest.php b/tests/ControlPanelTest.php index 30d9884..1d5b283 100644 --- a/tests/ControlPanelTest.php +++ b/tests/ControlPanelTest.php @@ -129,11 +129,16 @@ public function test_people_who_cant_view_the_entry_cant_join(): void public function test_saving_an_entry_tells_the_people_who_have_it_open(): void { $entry = $this->entry('post-1'); + $this->realtime->flush(); $this->realtime->sent = []; $this->actingAs($this->superUser()); $entry->set('title', 'Changed')->save(); + // Sent after the response, so an unreachable Hibira can't slow the save. + $this->assertSame([], $this->realtime->sent('saved')); + $this->app->terminate(); + $sent = $this->realtime->sent('saved'); $this->assertCount(1, $sent); $this->assertSame('presence-hibira-statamic.entry.post-1', $sent[0]['channel']); diff --git a/tests/FakeRealtime.php b/tests/FakeRealtime.php index 9adcbfd..2c649b9 100644 --- a/tests/FakeRealtime.php +++ b/tests/FakeRealtime.php @@ -5,7 +5,7 @@ use Hibira\Laravel\Hibira; use Hibira\Statamic\Realtime; -/** Records events instead of sending them. */ +/** Records events instead of sending them, after the response like the real one. */ class FakeRealtime extends Realtime { /** @var list, except: ?string}> */ @@ -21,11 +21,9 @@ public function configured(): bool return $this->isConfigured; } - public function trigger(string $channel, string $event, array $data, ?string $exceptSocket = null): void + protected function send(string $channel, string $event, array $data, ?string $exceptSocket): void { - if ($this->isConfigured) { - $this->sent[] = ['channel' => $channel, 'event' => $event, 'data' => $data, 'except' => $exceptSocket]; - } + $this->sent[] = ['channel' => $channel, 'event' => $event, 'data' => $data, 'except' => $exceptSocket]; } /** @return list, except: ?string}> */