@pocketping/widget 2.5.0 → 2.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +4 -4
- package/dist/index.js +4 -4
- package/dist/pocketping.min.global.js +2 -2
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -2991,7 +2991,7 @@ function AttachmentDisplay({ attachment }) {
|
|
|
2991
2991
|
}
|
|
2992
2992
|
|
|
2993
2993
|
// src/version.ts
|
|
2994
|
-
var VERSION = "
|
|
2994
|
+
var VERSION = "2.6.0";
|
|
2995
2995
|
|
|
2996
2996
|
// src/client.ts
|
|
2997
2997
|
function detectBotSignals() {
|
|
@@ -4631,16 +4631,16 @@ var PocketPingClient = class {
|
|
|
4631
4631
|
}
|
|
4632
4632
|
return new Promise((resolve, reject) => {
|
|
4633
4633
|
const script = document.createElement("script");
|
|
4634
|
-
script.src = "https://
|
|
4634
|
+
script.src = "https://cdn.jsdelivr.net/npm/html2canvas-pro@1.6.6/dist/html2canvas-pro.min.js";
|
|
4635
4635
|
script.onload = () => {
|
|
4636
4636
|
const w = window;
|
|
4637
4637
|
if (typeof w.html2canvas !== "undefined") {
|
|
4638
4638
|
resolve(w.html2canvas);
|
|
4639
4639
|
} else {
|
|
4640
|
-
reject(new Error("html2canvas failed to load"));
|
|
4640
|
+
reject(new Error("html2canvas-pro failed to load"));
|
|
4641
4641
|
}
|
|
4642
4642
|
};
|
|
4643
|
-
script.onerror = () => reject(new Error("Failed to load html2canvas from CDN"));
|
|
4643
|
+
script.onerror = () => reject(new Error("Failed to load html2canvas-pro from CDN"));
|
|
4644
4644
|
document.head.appendChild(script);
|
|
4645
4645
|
});
|
|
4646
4646
|
}
|
package/dist/index.js
CHANGED
|
@@ -2950,7 +2950,7 @@ function AttachmentDisplay({ attachment }) {
|
|
|
2950
2950
|
}
|
|
2951
2951
|
|
|
2952
2952
|
// src/version.ts
|
|
2953
|
-
var VERSION = "
|
|
2953
|
+
var VERSION = "2.6.0";
|
|
2954
2954
|
|
|
2955
2955
|
// src/client.ts
|
|
2956
2956
|
function detectBotSignals() {
|
|
@@ -4590,16 +4590,16 @@ var PocketPingClient = class {
|
|
|
4590
4590
|
}
|
|
4591
4591
|
return new Promise((resolve, reject) => {
|
|
4592
4592
|
const script = document.createElement("script");
|
|
4593
|
-
script.src = "https://
|
|
4593
|
+
script.src = "https://cdn.jsdelivr.net/npm/html2canvas-pro@1.6.6/dist/html2canvas-pro.min.js";
|
|
4594
4594
|
script.onload = () => {
|
|
4595
4595
|
const w = window;
|
|
4596
4596
|
if (typeof w.html2canvas !== "undefined") {
|
|
4597
4597
|
resolve(w.html2canvas);
|
|
4598
4598
|
} else {
|
|
4599
|
-
reject(new Error("html2canvas failed to load"));
|
|
4599
|
+
reject(new Error("html2canvas-pro failed to load"));
|
|
4600
4600
|
}
|
|
4601
4601
|
};
|
|
4602
|
-
script.onerror = () => reject(new Error("Failed to load html2canvas from CDN"));
|
|
4602
|
+
script.onerror = () => reject(new Error("Failed to load html2canvas-pro from CDN"));
|
|
4603
4603
|
document.head.appendChild(script);
|
|
4604
4604
|
});
|
|
4605
4605
|
}
|
|
@@ -1528,7 +1528,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1528
1528
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function fi(t,e){if(t){if(typeof t=="string")return ar(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ar(t,e):void 0}}function ar(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function Vt(t,e){var n=e.countries,r=e.metadata;r=new O(r);for(var o=ui(n),i;!(i=o()).done;){var d=i.value;if(r.selectNumberingPlan(d),r.leadingDigits()){if(t&&t.search(r.leadingDigits())===0)return d}else if(ue({phone:t,country:d},void 0,r.metadata))return d}}var $i=!1;function Oe(t,e){var n=e.nationalNumber,r=e.metadata;if($i&&r.isNonGeographicCallingCode(t))return"001";var o=r.getCountryCodesForCallingCode(t);if(o)return o.length===1?o[0]:Vt(n,{countries:o,metadata:r.metadata})}function ye(t,e,n){var r=jt(t,n),o=r.carrierCode,i=r.nationalNumber;if(i!==t){if(!hi(t,i,n))return{nationalNumber:t};if(n.numberingPlan.possibleLengths()&&(e||(e=Oe(n.numberingPlan.callingCode(),{nationalNumber:i,metadata:n})),!gi(i,e,n)))return{nationalNumber:t}}return{nationalNumber:i,carrierCode:o}}function hi(t,e,n){return!(K(t,n.nationalNumberPattern())&&!K(e,n.nationalNumberPattern()))}function gi(t,e,n){switch(pe(t,e,n)){case"TOO_SHORT":case"INVALID_LENGTH":return!1;default:return!0}}function Gt(t,e,n,r,o){var i=e||n?ce(e||n,o):r;if(t.indexOf(i)===0){o=new O(o),o.selectNumberingPlan(e||n,i);var d=t.slice(i.length),s=ye(d,e,o),u=s.nationalNumber,c=ye(t,e,o),f=c.nationalNumber;if(!K(f,o.nationalNumberPattern())&&K(u,o.nationalNumberPattern())||pe(f,e,o)==="TOO_LONG")return{countryCallingCode:i,number:d}}return{number:t}}function Ae(t,e,n,r,o){if(!t)return{};var i;if(t[0]!=="+"){var d=Bt(t,e||n,r,o);if(d&&d!==t)i=!0,t="+"+d;else{if(e||n||r){var s=Gt(t,e,n,r,o),u=s.countryCallingCode,c=s.number;if(u)return{countryCallingCodeSource:"FROM_NUMBER_WITHOUT_PLUS_SIGN",countryCallingCode:u,number:c}}return{number:t}}}if(t[1]==="0")return{};o=new O(o);for(var f=2;f-1<=sr&&f<=t.length;){var l=t.slice(1,f);if(o.hasCallingCode(l))return o.selectNumberingPlan(l),{countryCallingCodeSource:i?"FROM_NUMBER_WITH_IDD":"FROM_NUMBER_WITH_PLUS_SIGN",countryCallingCode:l,number:t.slice(f)};f++}return{}}function Wt(t){return t.replace(new RegExp("[".concat(be,"]+"),"g")," ").trim()}var mi=/(\$\d)/;function zt(t,e,n){var r=n.useInternationalFormat,o=n.withNationalPrefix,i=n.carrierCode,d=n.metadata,s=t.replace(new RegExp(e.pattern()),r?e.internationalFormat():o&&e.nationalPrefixFormattingRule()?e.format().replace(mi,e.nationalPrefixFormattingRule()):e.format());return r?Wt(s):s}var bi=/^[\d]+(?:[~\u2053\u223C\uFF5E][\d]+)?$/;function Kt(t,e,n){var r=new O(n);if(r.selectNumberingPlan(t,e),r.defaultIDDPrefix())return r.defaultIDDPrefix();if(bi.test(r.IDDPrefix()))return r.IDDPrefix()}var yi=";ext=",ve=function(e){return"([".concat(q,"]{1,").concat(e,"})")};function Me(t){var e="20",n="15",r="9",o="6",i="[ \xA0\\t,]*",d="[:\\.\uFF0E]?[ \xA0\\t,-]*",s="#?",u="(?:e?xt(?:ensi(?:o\u0301?|\xF3))?n?|\uFF45?\uFF58\uFF54\uFF4E?|\u0434\u043E\u0431|anexo)",c="(?:[x\uFF58#\uFF03~\uFF5E]|int|\uFF49\uFF4E\uFF54)",f="[- ]+",l="[ \xA0\\t]*",$="(?:,{2}|;)",h=yi+ve(e),C=i+u+d+ve(e)+s,k=i+c+d+ve(r)+s,E=f+ve(o)+"#",m=l+$+d+ve(n)+s,_=l+"(?:,)+"+d+ve(r)+s;return h+"|"+C+"|"+k+"|"+E+"|"+m+"|"+_}var vi="["+q+"]{"+Ne+"}",xi="["+Te+"]{0,1}(?:["+be+"]*["+q+"]){3,}["+be+q+"]*",_i=new RegExp("^["+Te+"]{0,1}(?:["+be+"]*["+q+"]){1,2}$","i"),wi=xi+"(?:"+Me()+")?",Ci=new RegExp("^"+vi+"$|^"+wi+"$","i");function qt(t){return t.length>=Ne&&Ci.test(t)}function lr(t){return _i.test(t)}function cr(t){var e=t.number,n=t.ext;if(!e)return"";if(e[0]!=="+")throw new Error('"formatRFC3966()" expects "number" to be in E.164 format.');return"tel:".concat(e).concat(n?";ext="+n:"")}var pr={formatExtension:function(e,n,r){return"".concat(e).concat(r.ext()).concat(n)}};function Yt(t,e,n,r){if(n?n=ki({},pr,n):n=pr,r=new O(r),t.country&&t.country!=="001"){if(!r.hasCountry(t.country))throw new Error("Unknown country: ".concat(t.country));r.selectNumberingPlan(t.country)}else if(t.countryCallingCode)r.selectNumberingPlan(t.countryCallingCode);else return t.phone||"";var o=r.countryCallingCode(),i=n.v2?t.nationalNumber:t.phone,d;switch(e){case"NATIONAL":return i?(d=st(i,t.carrierCode,"NATIONAL",r,n),Xt(d,t.ext,r,n.formatExtension)):"";case"INTERNATIONAL":return i?(d=st(i,null,"INTERNATIONAL",r,n),d="+".concat(o," ").concat(d),Xt(d,t.ext,r,n.formatExtension)):"+".concat(o);case"E.164":return"+".concat(o).concat(i);case"RFC3966":return cr({number:"+".concat(o).concat(i),ext:t.ext});case"IDD":if(!n.fromCountry)return;var s=Ei(i,t.carrierCode,o,n.fromCountry,r);return s?Xt(s,t.ext,r,n.formatExtension):void 0;default:throw new Error('Unknown "format" argument passed to "formatNumber()": "'.concat(e,'"'))}}function st(t,e,n,r,o){var i=Pi(r.formats(),t);return i?zt(t,i,{useInternationalFormat:n==="INTERNATIONAL",withNationalPrefix:!(i.nationalPrefixIsOptionalWhenFormattingInNationalFormat()&&o&&o.nationalPrefix===!1),carrierCode:e,metadata:r}):t}function Pi(t,e){return Si(t,function(n){if(n.leadingDigitsPatterns().length>0){var r=n.leadingDigitsPatterns()[n.leadingDigitsPatterns().length-1];if(e.search(r)!==0)return!1}return K(e,n.pattern())})}function Xt(t,e,n,r){return e?r(t,e,n):t}function Ei(t,e,n,r,o){var i=ce(r,o.metadata);if(i===n){var d=st(t,e,"NATIONAL",o);return n==="1"?n+" "+d:d}var s=Kt(r,void 0,o.metadata);if(s)return"".concat(s," ").concat(n," ").concat(st(t,null,"INTERNATIONAL",o))}function ki(){for(var t=1,e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];for(;t<n.length;){if(n[t])for(var o in n[t])n[0][o]=n[t][o];t++}return n[0]}function Si(t,e){for(var n=0;n<t.length;){if(e(t[n]))return t[n];n++}}function Fe(t){"@babel/helpers - typeof";return Fe=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Fe(t)}function ur(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function fr(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?ur(Object(n),!0).forEach(function(r){Ii(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):ur(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Ii(t,e,n){return(e=hr(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Ni(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function $r(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,hr(r.key),r)}}function Ti(t,e,n){return e&&$r(t.prototype,e),n&&$r(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function hr(t){var e=Oi(t,"string");return Fe(e)=="symbol"?e:e+""}function Oi(t,e){if(Fe(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(Fe(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var Ai=!1,gr=(function(){function t(e,n,r){if(Ni(this,t),!e)throw new TypeError("First argument is required");if(typeof e!="string")throw new TypeError("First argument must be a string");if(e[0]==="+"&&!n)throw new TypeError("`metadata` argument not passed");if(re(n)&&re(n.countries)){r=n;var o=e;if(!Ri.test(o))throw new Error('Invalid `number` argument passed: must consist of a "+" followed by digits');var i=Ae(o,void 0,void 0,void 0,r),d=i.countryCallingCode,s=i.number;if(n=s,e=d,!n)throw new Error("Invalid `number` argument passed: too short")}if(!n)throw new TypeError("`nationalNumber` argument is required");if(typeof n!="string")throw new TypeError("`nationalNumber` argument must be a string");Mt(r);var u=Fi(e,r),c=u.country,f=u.countryCallingCode;this.country=c,this.countryCallingCode=f,this.nationalNumber=n,this.number="+"+this.countryCallingCode+this.nationalNumber,this.getMetadata=function(){return r}}return Ti(t,[{key:"setExt",value:function(n){this.ext=n}},{key:"getPossibleCountries",value:function(){return this.country?[this.country]:Ut(this.countryCallingCode,this.nationalNumber,this.getMetadata())}},{key:"isPossible",value:function(){return Rt(this,{v2:!0},this.getMetadata())}},{key:"isValid",value:function(){return Ht(this,{v2:!0},this.getMetadata())}},{key:"isNonGeographic",value:function(){var n=new O(this.getMetadata());return n.isNonGeographicCallingCode(this.countryCallingCode)}},{key:"isEqual",value:function(n){return this.number===n.number&&this.ext===n.ext}},{key:"getType",value:function(){return ue(this,{v2:!0},this.getMetadata())}},{key:"format",value:function(n,r){return Yt(this,n,r?fr(fr({},r),{},{v2:!0}):{v2:!0},this.getMetadata())}},{key:"formatNational",value:function(n){return this.format("NATIONAL",n)}},{key:"formatInternational",value:function(n){return this.format("INTERNATIONAL",n)}},{key:"getURI",value:function(n){return this.format("RFC3966",n)}}])})();var Mi=function(e){return/^[A-Z]{2}$/.test(e)};function Fi(t,e){var n,r,o=new O(e);return Mi(t)?(n=t,o.selectNumberingPlan(n),r=o.countryCallingCode()):(r=t,Ai&&o.isNonGeographicCallingCode(r)&&(n="001")),{country:n,countryCallingCode:r}}var Ri=/^\+\d+$/;function xe(t){"@babel/helpers - typeof";return xe=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},xe(t)}function mr(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,Di(r.key),r)}}function Li(t,e,n){return e&&mr(t.prototype,e),n&&mr(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function Di(t){var e=Hi(t,"string");return xe(e)=="symbol"?e:e+""}function Hi(t,e){if(xe(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(xe(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ui(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Bi(t,e,n){return e=Le(e),ji(t,Zt()?Reflect.construct(e,n||[],Le(t).constructor):e.apply(t,n))}function ji(t,e){if(e&&(xe(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Vi(t)}function Vi(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function Gi(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&Re(t,e)}function Jt(t){var e=typeof Map=="function"?new Map:void 0;return Jt=function(r){if(r===null||!zi(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(r))return e.get(r);e.set(r,o)}function o(){return Wi(r,arguments,Le(this).constructor)}return o.prototype=Object.create(r.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),Re(o,r)},Jt(t)}function Wi(t,e,n){if(Zt())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,e);var o=new(t.bind.apply(t,r));return n&&Re(o,n.prototype),o}function Zt(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Zt=function(){return!!t})()}function zi(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function Re(t,e){return Re=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},Re(t,e)}function Le(t){return Le=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Le(t)}var Z=(function(t){function e(n){var r;return Ui(this,e),r=Bi(this,e,[n]),Object.setPrototypeOf(r,e.prototype),r.name=r.constructor.name,r}return Gi(e,t),Li(e)})(Jt(Error));var br=new RegExp("(?:"+Me()+")$","i");function Qt(t){var e=t.search(br);if(e<0)return{};for(var n=t.slice(0,e),r=t.match(br),o=1;o<r.length;){if(r[o])return{number:n,ext:r[o]};o++}}var Ki={0:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9","\uFF10":"0","\uFF11":"1","\uFF12":"2","\uFF13":"3","\uFF14":"4","\uFF15":"5","\uFF16":"6","\uFF17":"7","\uFF18":"8","\uFF19":"9","\u0660":"0","\u0661":"1","\u0662":"2","\u0663":"3","\u0664":"4","\u0665":"5","\u0666":"6","\u0667":"7","\u0668":"8","\u0669":"9","\u06F0":"0","\u06F1":"1","\u06F2":"2","\u06F3":"3","\u06F4":"4","\u06F5":"5","\u06F6":"6","\u06F7":"7","\u06F8":"8","\u06F9":"9"};function yr(t){return Ki[t]}function qi(t,e){var n=typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=Xi(t))||e&&t&&typeof t.length=="number"){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
1529
1529
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Xi(t,e){if(t){if(typeof t=="string")return vr(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?vr(t,e):void 0}}function vr(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function at(t){for(var e="",n=qi(t.split("")),r;!(r=n()).done;){var o=r.value;e+=Yi(o,e)||""}return e}function Yi(t,e,n){if(t==="+"){if(e){typeof n=="function"&&n("end");return}return"+"}return yr(t)}var tn="+",Ji="[\\-\\.\\(\\)]?",xr="(["+q+"]|"+Ji+")",Zi="^\\"+tn+xr+"*["+q+"]"+xr+"*$",Qi=new RegExp(Zi,"g"),en=q,ed="["+en+"]+((\\-)*["+en+"])*",td="a-zA-Z",nd="["+td+"]+((\\-)*["+en+"])*",rd="^("+ed+"\\.)*"+nd+"\\.?$",od=new RegExp(rd,"g"),nn="tel:",lt=";phone-context=",_r=";isub=";function rn(t){var e=t.indexOf(lt);if(e<0)return null;var n=e+lt.length;if(n>=t.length)return"";var r=t.indexOf(";",n);return r>=0?t.substring(n,r):t.substring(n)}function wr(t){return t===null?!0:t.length===0?!1:Qi.test(t)||od.test(t)}function on(t,e){var n=e.extractFormattedPhoneNumber,r=rn(t);if(!wr(r))throw new Z("NOT_A_NUMBER");var o;if(r===null)o=n(t)||"";else{o="",r.charAt(0)===tn&&(o+=r);var i=t.indexOf(nn),d;i>=0?d=i+nn.length:d=0;var s=t.indexOf(lt);o+=t.substring(d,s)}var u=o.indexOf(_r);if(u>0&&(o=o.substring(0,u)),o!=="")return o}var id=250,dd=new RegExp("["+Te+q+"]"),sd=new RegExp("[^"+q+"#]+$"),ad=!1;function dn(t,e,n){if(e=e||{},n=new O(n),e.defaultCountry&&!n.hasCountry(e.defaultCountry))throw e.v2?new Z("INVALID_COUNTRY"):new Error("Unknown country: ".concat(e.defaultCountry));var r=cd(t,e.v2,e.extract),o=r.number,i=r.ext,d=r.error;if(!o){if(e.v2)throw d==="TOO_SHORT"?new Z("TOO_SHORT"):new Z("NOT_A_NUMBER");return{}}var s=ud(o,e.defaultCountry,e.defaultCallingCode,n),u=s.country,c=s.nationalNumber,f=s.countryCallingCode,l=s.countryCallingCodeSource,$=s.carrierCode;if(!n.hasSelectedNumberingPlan()){if(e.v2)throw new Z("INVALID_COUNTRY");return{}}if(!c||c.length<Ne){if(e.v2)throw new Z("TOO_SHORT");return{}}if(c.length>dr){if(e.v2)throw new Z("TOO_LONG");return{}}if(e.v2){var h=new gr(f,c,n.metadata);return u&&(h.country=u),$&&(h.carrierCode=$),i&&(h.ext=i),h.__countryCallingCodeSource=l,h}var C=(e.extended?n.hasSelectedNumberingPlan():u)?K(c,n.nationalNumberPattern()):!1;return e.extended?{country:u,countryCallingCode:f,carrierCode:$,valid:C,possible:C?!0:!!(e.extended===!0&&n.possibleLengths()&&Lt(c,u,n)),phone:c,ext:i}:C?pd(u,c,i):{}}function ld(t,e,n){if(t){if(t.length>id){if(n)throw new Z("TOO_LONG");return}if(e===!1)return t;var r=t.search(dd);if(!(r<0))return t.slice(r).replace(sd,"")}}function cd(t,e,n){var r=on(t,{extractFormattedPhoneNumber:function(d){return ld(d,n,e)}});if(!r)return{};if(!qt(r))return lr(r)?{error:"TOO_SHORT"}:{};var o=Qt(r);return o.ext?o:{number:r}}function pd(t,e,n){var r={country:t,phone:e};return n&&(r.ext=n),r}function ud(t,e,n,r){var o=Ae(at(t),void 0,e,n,r.metadata),i=o.countryCallingCodeSource,d=o.countryCallingCode,s=o.number,u;if(d)r.selectNumberingPlan(d);else if(s&&(e||n))r.selectNumberingPlan(e,n),e?u=e:ad&&r.isNonGeographicCallingCode(n)&&(u="001"),d=n||ce(e,r.metadata);else return{};if(!s)return{countryCallingCodeSource:i,countryCallingCode:d};var c=ye(at(s),u,r),f=c.nationalNumber,l=c.carrierCode,$=Oe(d,{nationalNumber:f,metadata:r});return $&&(u=$,$==="001"||r.selectNumberingPlan(u)),{country:u,countryCallingCode:d,countryCallingCodeSource:i,nationalNumber:f,carrierCode:l}}function De(t){"@babel/helpers - typeof";return De=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},De(t)}function Cr(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function Pr(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Cr(Object(n),!0).forEach(function(r){fd(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Cr(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function fd(t,e,n){return(e=$d(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function $d(t){var e=hd(t,"string");return De(e)=="symbol"?e:e+""}function hd(t,e){if(De(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(De(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function He(t,e,n){return dn(t,Pr(Pr({},e),{},{v2:!0}),n)}function Ue(t){"@babel/helpers - typeof";return Ue=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ue(t)}function Er(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function gd(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Er(Object(n),!0).forEach(function(r){md(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Er(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function md(t,e,n){return(e=bd(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function bd(t){var e=yd(t,"string");return Ue(e)=="symbol"?e:e+""}function yd(t,e){if(Ue(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(Ue(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function vd(t,e){return Cd(t)||wd(t,e)||_d(t,e)||xd()}function xd(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
1530
1530
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _d(t,e){if(t){if(typeof t=="string")return kr(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?kr(t,e):void 0}}function kr(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function wd(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,o,i,d,s=[],u=!0,c=!1;try{if(i=(n=n.call(t)).next,e===0){if(Object(n)!==n)return;u=!1}else for(;!(u=(r=i.call(n)).done)&&(s.push(r.value),s.length!==e);u=!0);}catch(f){c=!0,o=f}finally{try{if(!u&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(c)throw o}}return s}}function Cd(t){if(Array.isArray(t))return t}function Be(t){var e=Array.prototype.slice.call(t),n=vd(e,4),r=n[0],o=n[1],i=n[2],d=n[3],s,u,c;if(typeof r=="string")s=r;else throw new TypeError("A text for parsing must be a string.");if(!o||typeof o=="string")d?(u=i,c=d):(u=void 0,c=i),o&&(u=gd({defaultCountry:o},u));else if(re(o))i?(u=o,c=i):c=o;else throw new Error("Invalid second argument: ".concat(o));return{text:s,options:u,metadata:c}}function je(){var t=Be(arguments),e=t.text,n=t.options,r=t.metadata;return He(e,n,r)}function Ve(t){"@babel/helpers - typeof";return Ve=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ve(t)}function Sr(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function Ir(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Sr(Object(n),!0).forEach(function(r){Pd(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Sr(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Pd(t,e,n){return(e=Ed(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Ed(t){var e=kd(t,"string");return Ve(e)=="symbol"?e:e+""}function kd(t,e){if(Ve(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(Ve(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function sn(t,e,n){e&&e.defaultCountry&&!tr(e.defaultCountry,n)&&(e=Ir(Ir({},e),{},{defaultCountry:void 0}));try{return He(t,e,n)}catch(r){if(!(r instanceof Z))throw r}}function Ge(t){"@babel/helpers - typeof";return Ge=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ge(t)}function Nr(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function Tr(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Nr(Object(n),!0).forEach(function(r){Sd(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Nr(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Sd(t,e,n){return(e=Id(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Id(t){var e=Nd(t,"string");return Ge(e)=="symbol"?e:e+""}function Nd(t,e){if(Ge(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(Ge(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ct(){var t=Be(arguments),e=t.text,n=t.options,r=t.metadata;n=Tr(Tr({},n),{},{extract:!1});var o=sn(e,n,r);return o&&o.isValid()||!1}function pt(){return Ie(je,arguments)}function ut(){return Ie(ct,arguments)}var an=[{code:"FR",name:"France",dialCode:"+33",flag:"\u{1F1EB}\u{1F1F7}"},{code:"DE",name:"Germany",dialCode:"+49",flag:"\u{1F1E9}\u{1F1EA}"},{code:"GB",name:"United Kingdom",dialCode:"+44",flag:"\u{1F1EC}\u{1F1E7}"},{code:"ES",name:"Spain",dialCode:"+34",flag:"\u{1F1EA}\u{1F1F8}"},{code:"IT",name:"Italy",dialCode:"+39",flag:"\u{1F1EE}\u{1F1F9}"},{code:"PT",name:"Portugal",dialCode:"+351",flag:"\u{1F1F5}\u{1F1F9}"},{code:"NL",name:"Netherlands",dialCode:"+31",flag:"\u{1F1F3}\u{1F1F1}"},{code:"BE",name:"Belgium",dialCode:"+32",flag:"\u{1F1E7}\u{1F1EA}"},{code:"CH",name:"Switzerland",dialCode:"+41",flag:"\u{1F1E8}\u{1F1ED}"},{code:"AT",name:"Austria",dialCode:"+43",flag:"\u{1F1E6}\u{1F1F9}"},{code:"SE",name:"Sweden",dialCode:"+46",flag:"\u{1F1F8}\u{1F1EA}"},{code:"NO",name:"Norway",dialCode:"+47",flag:"\u{1F1F3}\u{1F1F4}"},{code:"DK",name:"Denmark",dialCode:"+45",flag:"\u{1F1E9}\u{1F1F0}"},{code:"FI",name:"Finland",dialCode:"+358",flag:"\u{1F1EB}\u{1F1EE}"},{code:"PL",name:"Poland",dialCode:"+48",flag:"\u{1F1F5}\u{1F1F1}"},{code:"CZ",name:"Czech Republic",dialCode:"+420",flag:"\u{1F1E8}\u{1F1FF}"},{code:"GR",name:"Greece",dialCode:"+30",flag:"\u{1F1EC}\u{1F1F7}"},{code:"IE",name:"Ireland",dialCode:"+353",flag:"\u{1F1EE}\u{1F1EA}"},{code:"RO",name:"Romania",dialCode:"+40",flag:"\u{1F1F7}\u{1F1F4}"},{code:"HU",name:"Hungary",dialCode:"+36",flag:"\u{1F1ED}\u{1F1FA}"},{code:"US",name:"United States",dialCode:"+1",flag:"\u{1F1FA}\u{1F1F8}"},{code:"CA",name:"Canada",dialCode:"+1",flag:"\u{1F1E8}\u{1F1E6}"},{code:"MX",name:"Mexico",dialCode:"+52",flag:"\u{1F1F2}\u{1F1FD}"},{code:"BR",name:"Brazil",dialCode:"+55",flag:"\u{1F1E7}\u{1F1F7}"},{code:"AR",name:"Argentina",dialCode:"+54",flag:"\u{1F1E6}\u{1F1F7}"},{code:"CL",name:"Chile",dialCode:"+56",flag:"\u{1F1E8}\u{1F1F1}"},{code:"CO",name:"Colombia",dialCode:"+57",flag:"\u{1F1E8}\u{1F1F4}"},{code:"PE",name:"Peru",dialCode:"+51",flag:"\u{1F1F5}\u{1F1EA}"},{code:"CN",name:"China",dialCode:"+86",flag:"\u{1F1E8}\u{1F1F3}"},{code:"JP",name:"Japan",dialCode:"+81",flag:"\u{1F1EF}\u{1F1F5}"},{code:"KR",name:"South Korea",dialCode:"+82",flag:"\u{1F1F0}\u{1F1F7}"},{code:"IN",name:"India",dialCode:"+91",flag:"\u{1F1EE}\u{1F1F3}"},{code:"ID",name:"Indonesia",dialCode:"+62",flag:"\u{1F1EE}\u{1F1E9}"},{code:"TH",name:"Thailand",dialCode:"+66",flag:"\u{1F1F9}\u{1F1ED}"},{code:"VN",name:"Vietnam",dialCode:"+84",flag:"\u{1F1FB}\u{1F1F3}"},{code:"MY",name:"Malaysia",dialCode:"+60",flag:"\u{1F1F2}\u{1F1FE}"},{code:"SG",name:"Singapore",dialCode:"+65",flag:"\u{1F1F8}\u{1F1EC}"},{code:"PH",name:"Philippines",dialCode:"+63",flag:"\u{1F1F5}\u{1F1ED}"},{code:"PK",name:"Pakistan",dialCode:"+92",flag:"\u{1F1F5}\u{1F1F0}"},{code:"BD",name:"Bangladesh",dialCode:"+880",flag:"\u{1F1E7}\u{1F1E9}"},{code:"AE",name:"United Arab Emirates",dialCode:"+971",flag:"\u{1F1E6}\u{1F1EA}"},{code:"SA",name:"Saudi Arabia",dialCode:"+966",flag:"\u{1F1F8}\u{1F1E6}"},{code:"IL",name:"Israel",dialCode:"+972",flag:"\u{1F1EE}\u{1F1F1}"},{code:"TR",name:"Turkey",dialCode:"+90",flag:"\u{1F1F9}\u{1F1F7}"},{code:"EG",name:"Egypt",dialCode:"+20",flag:"\u{1F1EA}\u{1F1EC}"},{code:"ZA",name:"South Africa",dialCode:"+27",flag:"\u{1F1FF}\u{1F1E6}"},{code:"NG",name:"Nigeria",dialCode:"+234",flag:"\u{1F1F3}\u{1F1EC}"},{code:"KE",name:"Kenya",dialCode:"+254",flag:"\u{1F1F0}\u{1F1EA}"},{code:"MA",name:"Morocco",dialCode:"+212",flag:"\u{1F1F2}\u{1F1E6}"},{code:"TN",name:"Tunisia",dialCode:"+216",flag:"\u{1F1F9}\u{1F1F3}"},{code:"DZ",name:"Algeria",dialCode:"+213",flag:"\u{1F1E9}\u{1F1FF}"},{code:"AU",name:"Australia",dialCode:"+61",flag:"\u{1F1E6}\u{1F1FA}"},{code:"NZ",name:"New Zealand",dialCode:"+64",flag:"\u{1F1F3}\u{1F1FF}"},{code:"RU",name:"Russia",dialCode:"+7",flag:"\u{1F1F7}\u{1F1FA}"},{code:"UA",name:"Ukraine",dialCode:"+380",flag:"\u{1F1FA}\u{1F1E6}"}].sort((t,e)=>t.name.localeCompare(e.name));function Td(t){return an.find(e=>e.code===t.toUpperCase())}var Or=Td("FR");var Od=0;function a(t,e,n,r,o,i){e||(e={});var d,s,u=e;if("ref"in u)for(s in u={},e)s=="ref"?d=e[s]:u[s]=e[s];var c={type:t,props:u,key:n,ref:d,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Od,__i:-1,__u:0,__source:o,__self:i};if(typeof t=="function"&&(d=t.defaultProps))for(s in d)u[s]===void 0&&(u[s]=d[s]);return T.vnode&&T.vnode(c),c}var Ad=()=>a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),a("path",{d:"M22 7l-10 7L2 7"})]}),Md=()=>a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",{d:"M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72 12.84 12.84 0 00.7 2.81 2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7A2 2 0 0122 16.92z"})}),Fd=()=>a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",{d:"M6 9l6 6 6-6"})});function Ar(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function Mr({client:t,config:e,onComplete:n,onSkip:r}){let o=e.fields==="email-only",i=e.fields==="phone-only",d=e.fields==="email-and-phone",s=e.fields==="email-or-phone",u=()=>i?"phone":"email",[c,f]=I(u()),[l,$]=I(""),[h,C]=I(""),[k,E]=I(Or),[m,_]=I(!1),[M,F]=I(""),[x,U]=I(""),[J,L]=I(""),[G,j]=I(!1),R=ne(null),X=ne(null);Y(()=>{let v=W=>{R.current&&!R.current.contains(W.target)&&_(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),Y(()=>{m&&X.current&&X.current.focus()},[m]);let _e=an.filter(v=>v.name.toLowerCase().includes(M.toLowerCase())||v.dialCode.includes(M)||v.code.toLowerCase().includes(M.toLowerCase())),de=v=>{E(v),_(!1),F("")},se=v=>v.replace(/\D/g,""),fe=v=>{let W=v.target,we=se(W.value);C(we),L("")},ee=()=>h?`${k.dialCode}${h}`:"",te=()=>{let v=!0;if((o||d)&&(l.trim()?Ar(l)||(U("Please enter a valid email"),v=!1):(U("Email is required"),v=!1)),i||d){let W=ee();h.trim()?ut(W,k.code)||(L("Please enter a valid phone number"),v=!1):(L("Phone number is required"),v=!1)}if(s)if(c==="email")l.trim()?Ar(l)||(U("Please enter a valid email"),v=!1):(U("Email is required"),v=!1);else{let W=ee();h.trim()?ut(W,k.code)||(L("Please enter a valid phone number"),v=!1):(L("Phone number is required"),v=!1)}return v},z=async v=>{if(v.preventDefault(),!!te()){j(!0);try{let W={};if((o||d||s&&c==="email")&&(W.email=l.trim()),i||d||s&&c==="phone"){let we=ee(),$e=pt(we,k.code);$e&&(W.phone=$e.format("E.164"),W.phoneCountry=k.code)}await t.submitPreChat(W),n()}catch(W){console.error("[PreChatForm] Submit error:",W),c==="email"||o||d?U("Something went wrong. Please try again."):L("Something went wrong. Please try again.")}finally{j(!1)}}},ae=()=>a("div",{class:"pp-prechat-field",children:[a("label",{class:"pp-prechat-label",children:"Email address"}),a("input",{type:"email",class:`pp-prechat-input ${x?"error":""}`,placeholder:"you@example.com",value:l,onInput:v=>{$(v.target.value),U("")}}),x&&a("div",{class:"pp-prechat-error",children:x})]}),Q=()=>a("div",{class:"pp-prechat-field",children:[a("label",{class:"pp-prechat-label",children:"Phone number"}),a("div",{class:"pp-phone-input-wrapper",children:[a("div",{class:"pp-country-select",ref:R,children:[a("button",{type:"button",class:"pp-country-btn",onClick:()=>_(!m),children:[a("span",{class:"pp-country-flag",children:k.flag}),a("span",{class:"pp-country-code",children:k.dialCode}),a(Fd,{})]}),m&&a("div",{class:"pp-country-dropdown",children:[a("div",{class:"pp-country-search",children:a("input",{ref:X,type:"text",class:"pp-country-search-input",placeholder:"Search country...",value:M,onInput:v=>F(v.target.value)})}),a("div",{class:"pp-country-list",children:_e.map(v=>a("div",{class:`pp-country-option ${v.code===k.code?"selected":""}`,onClick:()=>de(v),children:[a("span",{class:"pp-country-flag",children:v.flag}),a("span",{class:"pp-country-name",children:v.name}),a("span",{class:"pp-country-dial",children:v.dialCode})]},v.code))})]})]}),a("input",{type:"tel",class:`pp-prechat-input pp-phone-number-input ${J?"error":""}`,placeholder:"612 345 678",value:h,onInput:fe})]}),J&&a("div",{class:"pp-prechat-error",children:J})]});return a("div",{class:"pp-prechat",children:[a("h2",{class:"pp-prechat-title",children:"How can we reach you?"}),a("p",{class:"pp-prechat-subtitle",children:d?"Please provide your contact information so we can follow up if needed.":s?"Choose how you would like us to contact you.":o?"Enter your email so we can follow up with you.":"Enter your phone number so we can call you back."}),a("form",{onSubmit:z,children:[s&&a("div",{class:"pp-prechat-tabs",children:[a("button",{type:"button",class:`pp-prechat-tab ${c==="email"?"active":""}`,onClick:()=>{f("email"),L("")},children:[a(Ad,{}),"Email"]}),a("button",{type:"button",class:`pp-prechat-tab ${c==="phone"?"active":""}`,onClick:()=>{f("phone"),U("")},children:[a(Md,{}),"Phone"]})]}),o&&ae(),i&&Q(),d&&a(D,{children:[ae(),Q()]}),s&&a(D,{children:[c==="email"&&ae(),c==="phone"&&Q()]}),a("button",{type:"submit",class:"pp-prechat-submit",disabled:G,children:G?"Submitting...":"Start chatting"}),!e.required&&a("button",{type:"button",class:"pp-prechat-skip",onClick:r,children:"Skip for now"})]})]})}function Rr(t){if(!t)return"";let e=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),n=e.split(`
|
|
1531
|
-
`),r=!1,o=[];for(let i of n){let d=i.match(/^[\s]*[*-]\s+(.+)$/);d?(r||(o.push('<ul class="pp-md-list">'),r=!0),o.push(`<li>${Fr(d[1])}</li>`)):(r&&(o.push("</ul>"),r=!1),o.push(Fr(i)))}return r&&o.push("</ul>"),e=o.join("<br />"),e=e.replace(/<br \/><ul/g,"<ul").replace(/<\/ul><br \/>/g,"</ul>").replace(/<br \/><li>/g,"<li>").replace(/<\/li><br \/>/g,"</li>"),e}function Fr(t){return t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/__(.+?)__/g,"<strong>$1</strong>").replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,"<em>$1</em>").replace(/(?<!_)_([^_]+)_(?!_)/g,"<em>$1</em>").replace(/`([^`]+)`/g,"<code>$1</code>")}function Rd(t){let e=new Date,n=new Date(t),r=new Date(e.getFullYear(),e.getMonth(),e.getDate()),o=new Date(n.getFullYear(),n.getMonth(),n.getDate()),i=Math.floor((r.getTime()-o.getTime())/(1e3*60*60*24));return i===0?"Today":i===1?"Yesterday":n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:n.getFullYear()!==e.getFullYear()?"numeric":void 0})}function Lr(t){let e=new Date(t);return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function Gr({client:t,config:e}){let[n,r]=I(!1),[o,i]=I([]),[d,s]=I(""),[u,c]=I(!1),[f,l]=I(!1),[$,h]=I(!1),[C,k]=I(0),[E,m]=I([]),[_,M]=I(!1),[F,x]=I(null),[U,J]=I(null),[L,G]=I(""),[j,R]=I(null),[X,_e]=I(!1),[de,se]=I(null),[fe,ee]=I(0),te=ne(null),[z,ae]=I(e),[Q,v]=I(void 0),[W,we]=I(!1),$e=ne(null),Ce=ne(null),cn=ne(null),lo=ne(null);Y(()=>{let p=t.on("openChange",r),g=t.on("message",()=>{i([...t.getMessages()])}),b=t.on("typing",y=>{c(y.isTyping)}),S=t.on("presence",y=>{l(y.online)}),N=t.on("connect",()=>{h(!0),i(t.getMessages()),l(t.getSession()?.operatorOnline??!1),ae(t.getConfig()),v(t.getSession()?.preChatForm)}),A=t.on("preChatCompleted",()=>{v(y=>y&&{...y,completed:!0})}),w=t.on("configUpdate",()=>{ae(t.getConfig())});return t.isConnected()&&(h(!0),i(t.getMessages()),l(t.getSession()?.operatorOnline??!1),ae(t.getConfig()),v(t.getSession()?.preChatForm)),()=>{p(),g(),b(),S(),N(),A(),w()}},[t]),Y(()=>{n&&$e.current?.scrollIntoView({behavior:"smooth"})},[o,n]),Y(()=>{n&&(setTimeout(()=>{$e.current?.scrollIntoView({behavior:"auto"})},50),Ce.current?.focus(),k(0))},[n]),Y(()=>{let p=window.innerWidth<=480;if(n&&p){let g=window.scrollY,b={overflow:document.body.style.overflow,position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,right:document.body.style.right,width:document.body.style.width};return document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`-${g}px`,document.body.style.left="0",document.body.style.right="0",document.body.style.width="100%",()=>{document.body.style.overflow=b.overflow,document.body.style.position=b.position,document.body.style.top=b.top,document.body.style.left=b.left,document.body.style.right=b.right,document.body.style.width=b.width,window.scrollTo(0,g)}}},[n]);let[We,pn]=I(null);Y(()=>{let p=window.innerWidth<=480;if(!n||!p){pn(null);return}let g=window.visualViewport;if(!g)return;let b=()=>{pn({height:g.height,top:g.offsetTop})};return b(),g.addEventListener("resize",b),g.addEventListener("scroll",b),()=>{g.removeEventListener("resize",b),g.removeEventListener("scroll",b)}},[n]),Y(()=>{if(!n&&o.length>0){let p=o.filter(g=>g.sender!=="visitor"&&g.status!=="read").length;k(p)}},[o,n]);let ze=Wn(()=>{if(!n||!$)return;let p=o.filter(g=>g.sender!=="visitor"&&g.status!=="read");if(p.length>0){let g=p.map(b=>b.id);t.sendReadStatus(g,"read")}},[n,$,o,t]);if(Y(()=>{if(!n||!$)return;let p=setTimeout(()=>{ze()},1e3);return()=>clearTimeout(p)},[n,$,o,ze]),Y(()=>{let p=()=>{document.visibilityState==="visible"&&n&&ze()};return document.addEventListener("visibilitychange",p),()=>document.removeEventListener("visibilitychange",p)},[n,ze]),Y(()=>{let p=t.on("read",()=>{i([...t.getMessages()])});return()=>p()},[t]),!Ld(z))return null;let co=async p=>{p.preventDefault();let g=d.trim().length>0,b=E.filter(w=>w.status==="ready"&&w.attachment);if(!g&&b.length===0)return;let S=d,N=b.map(w=>w.attachment.id),A=F?.id;s(""),m([]),x(null),Ce.current&&(Ce.current.style.height="auto");try{await t.sendMessage(S,N,A)}catch(w){console.error("[PocketPing] Failed to send message:",w)}},po=p=>{let g=p.target;s(g.value),g.style.height="auto",g.style.height=Math.min(g.scrollHeight,120)+"px",t.sendTyping(!0)},uo=p=>{if(p.key==="Enter"&&!p.shiftKey){p.preventDefault();let g=p.target.closest("form");g&&g.requestSubmit()}},fo=async p=>{let g=p.target,b=g.files;if(!b||b.length===0)return;let S=[];for(let N=0;N<b.length;N++){let A=b[N],w=`pending-${Date.now()}-${N}`,y;A.type.startsWith("image/")&&(y=URL.createObjectURL(A)),S.push({id:w,file:A,preview:y,progress:0,status:"pending"})}m(N=>[...N,...S]),g.value="",M(!0);for(let N of S)try{m(w=>w.map(y=>y.id===N.id?{...y,status:"uploading"}:y));let A=await t.uploadFile(N.file,w=>{m(y=>y.map(qe=>qe.id===N.id?{...qe,progress:w}:qe))});m(w=>w.map(y=>y.id===N.id?{...y,status:"ready",progress:100,attachment:A}:y))}catch(A){console.error("[PocketPing] Failed to upload file:",A),m(w=>w.map(y=>y.id===N.id?{...y,status:"error",error:"Upload failed"}:y))}M(!1)},$o=p=>{m(g=>{let b=g.find(S=>S.id===p);return b?.preview&&URL.revokeObjectURL(b.preview),g.filter(S=>S.id!==p)})},un=p=>{x(p),R(null),Ce.current?.focus()},ho=()=>{x(null)},fn=p=>{p.sender==="visitor"&&(J(p),G(p.content),R(null))},$n=()=>{J(null),G("")},go=async()=>{if(!(!U||!L.trim()))try{await t.editMessage(U.id,L.trim()),J(null),G("")}catch(p){console.error("[PocketPing] Failed to edit message:",p)}},hn=async p=>{if(p.sender==="visitor"&&(R(null),confirm("Delete this message?")))try{await t.deleteMessage(p.id)}catch(g){console.error("[PocketPing] Failed to delete message:",g)}},mo=(p,g)=>{p.preventDefault();let b=p;R({message:g,x:b.clientX,y:b.clientY})},bo=(p,g)=>{let b=p.touches[0];te.current={x:b.clientX,y:b.clientY,time:Date.now()},de&&de!==g.id&&(se(null),ee(0))},yo=(p,g)=>{if(!te.current)return;let b=p.touches[0],S=b.clientX-te.current.x,N=b.clientY-te.current.y;if(Math.abs(N)>10||Math.abs(S)<15){de===g.id&&fe!==0&&(ee(0),se(null));return}if(p.preventDefault(),S<0){let A=Math.max(S,-80);ee(A),se(g.id)}},gn=p=>{if(!te.current)return;let g=Date.now()-te.current.time;fe<-50||fe<-20&&g<200?(ee(-80),navigator.vibrate&&navigator.vibrate(30)):(ee(0),se(null)),te.current=null},Ke=()=>{se(null),ee(0)};Y(()=>{if(!j)return;let p=()=>R(null);return document.addEventListener("click",p),()=>document.removeEventListener("click",p)},[j]);let mn=p=>{let g=document.getElementById(`pp-msg-${p}`);g&&(g.scrollIntoView({behavior:"smooth",block:"center"}),g.classList.add("pp-message-highlight"),setTimeout(()=>{g.classList.remove("pp-message-highlight")},1500))},Pe=ne(0),vo=p=>{p.preventDefault(),p.stopPropagation(),Pe.current++,Pe.current===1&&_e(!0)},xo=p=>{p.preventDefault(),p.stopPropagation()},_o=p=>{p.preventDefault(),p.stopPropagation(),Pe.current--,Pe.current===0&&_e(!1)},wo=async p=>{p.preventDefault(),p.stopPropagation(),Pe.current=0,_e(!1);let g=p.dataTransfer?.files;if(!g||g.length===0)return;let b=[];for(let S=0;S<g.length;S++){let N=g[S],A=`pending-${Date.now()}-${S}`,w;N.type.startsWith("image/")&&(w=URL.createObjectURL(N)),b.push({id:A,file:N,preview:w,progress:0,status:"pending"})}m(S=>[...S,...b]),M(!0);for(let S of b)try{m(A=>A.map(w=>w.id===S.id?{...w,status:"uploading"}:w));let N=await t.uploadFile(S.file,A=>{m(w=>w.map(y=>y.id===S.id?{...y,progress:A}:y))});m(A=>A.map(w=>w.id===S.id?{...w,status:"ready",progress:100,attachment:N}:w))}catch(N){console.error("[PocketPing] Failed to upload dropped file:",N),m(A=>A.map(w=>w.id===S.id?{...w,status:"error",error:"Upload failed"}:w))}M(!1)},bn=z.position??"bottom-right",gt=Dd(z.theme??"auto"),Co=z.primaryColor??"#6366f1",yn=gt==="dark"?"#9ca3af":"#6b7280",Po={primaryColor:Co,theme:gt,headerColor:z.headerColor,footerColor:z.footerColor,chatBackground:z.chatBackground,toggleColor:z.toggleColor},mt=Q&&Q.enabled&&!Q.completed&&!W&&(Q.timing==="before-first-message"&&o.length===0||Q.timing==="after-first-message"&&o.some(p=>p.sender==="visitor"));return a(D,{children:[a("style",{children:Xn(Po)}),!n&&a("button",{class:`pp-toggle pp-${bn}`,onClick:()=>t.toggleOpen(),"aria-label":"Open chat",children:[a(Hd,{}),C>0&&a("span",{class:"pp-unread-badge",children:C>9?"9+":C}),C===0&&f&&a("span",{class:"pp-online-dot"})]}),n&&a("div",{class:`pp-window pp-${bn} pp-theme-${gt} ${X?"pp-dragging":""}`,style:We?{height:`${We.height}px`,maxHeight:`${We.height}px`,top:`${We.top}px`,bottom:"auto"}:void 0,onDragEnter:vo,onDragOver:xo,onDragLeave:_o,onDrop:wo,children:[X&&a("div",{class:"pp-drop-overlay",children:[a("div",{class:"pp-drop-icon",children:a(Ur,{})}),a("div",{class:"pp-drop-text",children:"Drop files to upload"})]}),a("div",{class:"pp-header",children:[a("div",{class:"pp-header-info",children:[z.operatorAvatar&&a("img",{src:z.operatorAvatar,alt:"",class:"pp-avatar"}),a("div",{children:[a("div",{class:"pp-header-title",children:z.operatorName??"Support"}),a("div",{class:"pp-header-status",children:f?a(D,{children:[a("span",{class:"pp-status-dot pp-online"})," Online"]}):a(D,{children:[a("span",{class:"pp-status-dot"})," Away"]})})]})]}),a("button",{class:"pp-close-btn",onClick:()=>t.setOpen(!1),"aria-label":"Close chat",children:a(ft,{})})]}),mt&&Q&&a(Mr,{client:t,config:Q,onComplete:()=>{v(p=>p&&{...p,completed:!0})},onSkip:()=>{we(!0)}}),!mt&&a("div",{class:"pp-messages",ref:lo,onClick:()=>de&&Ke(),children:[z.welcomeMessage&&o.length===0&&a("div",{class:"pp-welcome",children:z.welcomeMessage}),o.map((p,g)=>{let b=!!p.deletedAt,S=!!p.editedAt,N=new Date(p.timestamp),A=g>0?o[g-1]:null,w=!A||Lr(new Date(A.timestamp))!==Lr(N),y=null;if(p.replyTo)if(typeof p.replyTo=="object")y=p.replyTo;else{let V=o.find(Xe=>Xe.id===p.replyTo);if(V){let Xe=!!(V.attachments&&V.attachments.length>0);y={id:V.id,sender:V.sender,content:V.content,deleted:!!V.deletedAt,hasAttachment:Xe,attachmentType:Xe?V.attachments[0].mimeType:void 0}}}let Eo=de===p.id?fe:0;return a(D,{children:[w&&a("div",{class:"pp-date-separator",children:a("span",{children:Rd(N)})}),a("div",{class:`pp-message-swipe-container ${p.sender==="visitor"?"pp-swipe-left":"pp-swipe-right"}`,children:[a("div",{class:"pp-swipe-actions",children:[a("button",{class:"pp-swipe-action pp-swipe-reply",onClick:()=>{un(p),Ke()},children:a(Br,{color:"#fff"})}),p.sender==="visitor"&&!b&&a(D,{children:[a("button",{class:"pp-swipe-action pp-swipe-edit",onClick:()=>{fn(p),Ke()},children:a(jr,{color:"#fff"})}),a("button",{class:"pp-swipe-action pp-swipe-delete",onClick:()=>{hn(p),Ke()},children:a(Vr,{color:"#fff"})})]})]}),a("div",{id:`pp-msg-${p.id}`,class:`pp-message pp-message-${p.sender} ${b?"pp-message-deleted":""}`,style:{transform:`translateX(${Eo}px)`,transition:te.current?"none":"transform 0.2s ease-out"},onContextMenu:V=>mo(V,p),onTouchStart:V=>bo(V,p),onTouchMove:V=>yo(V,p),onTouchEnd:()=>gn(p),onTouchCancel:()=>gn(p),children:[y&&(y.content||y.hasAttachment)&&a("div",{class:"pp-reply-quote pp-reply-quote-clickable",onClick:()=>mn(y.id),role:"button",tabIndex:0,onKeyDown:V=>V.key==="Enter"&&mn(y.id),children:[a("span",{class:"pp-reply-sender",children:y.sender==="visitor"?"You":"Support"}),a("span",{class:"pp-reply-content",children:y.deleted?"Message deleted":a(D,{children:[y.hasAttachment&&a("span",{class:"pp-reply-attachment-icon",children:y.attachmentType?.startsWith("image/")?"\u{1F4F7} ":"\u{1F4CE} "}),y.content?a(D,{children:[(y.content||"").slice(0,50),(y.content||"").length>50?"...":""]}):y.attachmentType?.startsWith("image/")?"Photo":"File"]})})]}),b?a("div",{class:"pp-message-content pp-deleted-content",children:[a("span",{class:"pp-deleted-icon",children:"\u{1F5D1}\uFE0F"})," Message deleted"]}):a(D,{children:[p.content&&a("div",{class:"pp-message-content",children:[a("span",{dangerouslySetInnerHTML:{__html:Rr(p.content)}}),a("span",{class:"pp-message-time",children:[Dr(p.timestamp),S&&a("span",{class:"pp-edited-badge",children:"edited"}),p.sender==="ai"&&a("span",{class:"pp-ai-badge",children:"AI"}),p.sender==="visitor"&&a("span",{class:`pp-status pp-status-${p.status??"sent"}`,children:a(Hr,{status:p.status})})]})]}),p.attachments&&p.attachments.length>0&&a("div",{class:"pp-message-attachments",children:[p.attachments.map(V=>a(Bd,{attachment:V},V.id)),!p.content&&a("span",{class:"pp-message-time pp-attachment-time",children:[Dr(p.timestamp),S&&a("span",{class:"pp-edited-badge",children:"edited"}),p.sender==="ai"&&a("span",{class:"pp-ai-badge",children:"AI"}),p.sender==="visitor"&&a("span",{class:`pp-status pp-status-${p.status??"sent"}`,children:a(Hr,{status:p.status})})]})]})]})]})]})]},p.id)}),u&&a("div",{class:"pp-message pp-message-operator pp-typing",children:[a("span",{}),a("span",{}),a("span",{})]}),a("div",{ref:$e})]}),j&&a("div",{class:"pp-message-menu",style:{top:`${j.y}px`,left:`${j.x}px`},children:[a("button",{onClick:()=>un(j.message),children:[a(Br,{color:yn})," Reply"]}),j.message.sender==="visitor"&&!j.message.deletedAt&&a(D,{children:[a("button",{onClick:()=>fn(j.message),children:[a(jr,{color:yn})," Edit"]}),a("button",{class:"pp-menu-delete",onClick:()=>hn(j.message),children:[a(Vr,{color:"#ef4444"})," Delete"]})]})]}),U&&a("div",{class:"pp-edit-modal",children:[a("div",{class:"pp-edit-header",children:[a("span",{children:"Edit message"}),a("button",{onClick:$n,children:a(ft,{})})]}),a("textarea",{class:"pp-edit-input",value:L,onInput:p=>G(p.target.value),autoFocus:!0}),a("div",{class:"pp-edit-actions",children:[a("button",{class:"pp-edit-cancel",onClick:$n,children:"Cancel"}),a("button",{class:"pp-edit-save",onClick:go,disabled:!L.trim(),children:"Save"})]})]}),F&&a("div",{class:"pp-reply-preview",children:[a("div",{class:"pp-reply-preview-content",children:[a("span",{class:"pp-reply-label",children:"Replying to"}),a("span",{class:"pp-reply-text",children:[F.attachments&&F.attachments.length>0&&a("span",{class:"pp-reply-attachment-icon",children:F.attachments[0].mimeType.startsWith("image/")?"\u{1F4F7} ":"\u{1F4CE} "}),F.content?a(D,{children:[F.content.slice(0,50),F.content.length>50?"...":""]}):F.attachments?.[0]?.mimeType.startsWith("image/")?"Photo":"File"]})]}),a("button",{class:"pp-reply-cancel",onClick:ho,children:a(ft,{})})]}),E.length>0&&a("div",{class:"pp-attachments-preview",children:E.map(p=>a("div",{class:`pp-attachment-preview pp-attachment-${p.status}`,children:[p.preview?a("img",{src:p.preview,alt:p.file.name,class:"pp-preview-img"}):a("div",{class:"pp-preview-file",children:a(Wr,{mimeType:p.file.type})}),a("button",{class:"pp-remove-attachment",onClick:()=>$o(p.id),"aria-label":"Remove attachment",type:"button",children:a(ft,{})}),p.status==="uploading"&&a("div",{class:"pp-upload-progress",style:{width:`${p.progress}%`}}),p.status==="error"&&a("div",{class:"pp-upload-error",title:p.error,children:"!"})]},p.id))}),!mt&&a("form",{class:"pp-input-form",onSubmit:co,children:[a("input",{ref:p=>{cn.current=p,p&&(p.onchange=fo)},type:"file",class:"pp-file-input",accept:"image/*,audio/*,video/*,.pdf,.doc,.docx,.xls,.xlsx,.txt",multiple:!0}),a("button",{type:"button",class:"pp-attach-btn",onClick:()=>cn.current?.click(),disabled:!$||_,"aria-label":"Attach file",children:a(Ur,{})}),a("textarea",{ref:Ce,class:"pp-input",placeholder:z.placeholder??"Type a message...",value:d,onInput:po,onKeyDown:uo,disabled:!$,rows:1}),a("button",{type:"submit",class:"pp-send-btn",disabled:!d.trim()&&E.filter(p=>p.status==="ready").length===0||!$||_,"aria-label":"Send message",children:a(Ud,{})})]}),a("div",{class:"pp-footer",children:["Powered by ",a("a",{href:"https://pocketping.io",target:"_blank",rel:"noopener",children:"PocketPing"})]})]})]})}function Ld(t){let e=window.location.pathname;return t.hideOnPages?.some(n=>new RegExp(n).test(e))?!1:t.showOnPages?.length?t.showOnPages.some(n=>new RegExp(n).test(e)):!0}function Dd(t){return t==="auto"?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":t}function Dr(t){return new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function Hd(){return a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:a("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function ft(){return a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[a("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Ud(){return a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[a("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),a("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function Hr({status:t}){return!t||t==="sending"||t==="sent"?a("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"2",class:"pp-check",children:a("polyline",{points:"3 8 7 12 13 4"})}):t==="delivered"?a("svg",{viewBox:"0 0 20 16",fill:"none",stroke:"currentColor","stroke-width":"2",class:"pp-check-double",children:[a("polyline",{points:"1 8 5 12 11 4"}),a("polyline",{points:"7 8 11 12 17 4"})]}):t==="read"?a("svg",{viewBox:"0 0 20 16",fill:"none",stroke:"currentColor","stroke-width":"2",class:"pp-check-double pp-check-read",children:[a("polyline",{points:"1 8 5 12 11 4"}),a("polyline",{points:"7 8 11 12 17 4"})]}):null}function Ur(){return a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:a("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})})}function Br({color:t,size:e=16}){return a("svg",{viewBox:"0 0 24 24",fill:"none","stroke-width":"2",style:{stroke:t||"currentColor",width:`${e}px`,minWidth:`${e}px`,height:`${e}px`,display:"block",flexShrink:0},children:[a("polyline",{points:"9 17 4 12 9 7"}),a("path",{d:"M20 18v-2a4 4 0 0 0-4-4H4"})]})}function jr({color:t,size:e=16}){return a("svg",{viewBox:"0 0 24 24",fill:"none","stroke-width":"2",style:{stroke:t||"currentColor",width:`${e}px`,minWidth:`${e}px`,height:`${e}px`,display:"block",flexShrink:0},children:a("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}function Vr({color:t,size:e=16}){return a("svg",{viewBox:"0 0 24 24",fill:"none","stroke-width":"2",style:{stroke:t||"currentColor",width:`${e}px`,minWidth:`${e}px`,height:`${e}px`,display:"block",flexShrink:0},children:[a("polyline",{points:"3 6 5 6 21 6"}),a("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function Wr({mimeType:t}){return t==="application/pdf"?a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[a("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),a("polyline",{points:"14 2 14 8 20 8"}),a("path",{d:"M9 15h6"}),a("path",{d:"M9 11h6"})]}):t.startsWith("audio/")?a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[a("path",{d:"M9 18V5l12-2v13"}),a("circle",{cx:"6",cy:"18",r:"3"}),a("circle",{cx:"18",cy:"16",r:"3"})]}):t.startsWith("video/")?a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[a("rect",{x:"2",y:"2",width:"20",height:"20",rx:"2.18",ry:"2.18"}),a("line",{x1:"7",y1:"2",x2:"7",y2:"22"}),a("line",{x1:"17",y1:"2",x2:"17",y2:"22"}),a("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),a("line",{x1:"2",y1:"7",x2:"7",y2:"7"}),a("line",{x1:"2",y1:"17",x2:"7",y2:"17"}),a("line",{x1:"17",y1:"17",x2:"22",y2:"17"}),a("line",{x1:"17",y1:"7",x2:"22",y2:"7"})]}):a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[a("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),a("polyline",{points:"14 2 14 8 20 8"})]})}function Bd({attachment:t}){let e=t.mimeType.startsWith("image/"),n=t.mimeType.startsWith("audio/"),r=t.mimeType.startsWith("video/"),o=i=>i<1024?`${i} B`:i<1024*1024?`${(i/1024).toFixed(1)} KB`:`${(i/(1024*1024)).toFixed(1)} MB`;return e?a("a",{href:t.url,target:"_blank",rel:"noopener",class:"pp-attachment pp-attachment-image",children:a("img",{src:t.thumbnailUrl||t.url,alt:t.filename})}):n?a("div",{class:"pp-attachment pp-attachment-audio",children:[a("audio",{controls:!0,preload:"metadata",children:a("source",{src:t.url,type:t.mimeType})}),a("span",{class:"pp-attachment-name",children:t.filename})]}):r?a("div",{class:"pp-attachment pp-attachment-video",children:a("video",{controls:!0,preload:"metadata",children:a("source",{src:t.url,type:t.mimeType})})}):a("a",{href:t.url,target:"_blank",rel:"noopener",class:"pp-attachment pp-attachment-file",children:[a(Wr,{mimeType:t.mimeType}),a("div",{class:"pp-attachment-info",children:[a("span",{class:"pp-attachment-name",children:t.filename}),a("span",{class:"pp-attachment-size",children:o(t.size)})]})]})}var $t="0.3.8";function jd(){return{webdriver:!!navigator.webdriver,plugins:navigator.plugins.length===0,languages:navigator.languages.length===0,chrome:/Chrome/.test(navigator.userAgent)&&typeof window.chrome>"u",permissions:typeof Notification<"u"&&Notification.permission==="denied"}}var ht=class{constructor(e){this.session=null;this.ws=null;this.sse=null;this.isOpen=!1;this.listeners=new Map;this.customEventHandlers=new Map;this.reconnectAttempts=0;this.maxReconnectAttempts=5;this.reconnectTimeout=null;this.pollingTimeout=null;this.pollingFailures=0;this.maxPollingFailures=10;this.wsConnectedAt=0;this.quickFailureThreshold=2e3;this.connectionMode="none";this.trackedElementCleanups=[];this.currentTrackedElements=[];this.inspectorMode=!1;this.inspectorCleanup=null;this.connectedAt=0;this.disconnectNotified=!1;this.boundHandleUnload=null;this.boundHandleVisibilityChange=null;this.config=e}async connect(){let e=this.getOrCreateVisitorId(),n=this.getStoredSessionId(),r=this.getStoredIdentity(),i=new URLSearchParams(window.location.search).get("pp_inspector"),d=await this.fetch("/connect",{method:"POST",body:JSON.stringify({visitorId:e,sessionId:n,inspectorToken:i||void 0,metadata:{url:window.location.href,referrer:document.referrer||void 0,pageTitle:document.title||void 0,userAgent:navigator.userAgent,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,language:navigator.language,screenResolution:`${window.screen.width}x${window.screen.height}`,botSignals:jd()},identity:r||void 0})});return this.session={sessionId:d.sessionId,visitorId:d.visitorId,operatorOnline:d.operatorOnline??!1,messages:d.messages??[],identity:d.identity||r||void 0,preChatForm:d.preChatForm},d.operatorName&&(this.config.operatorName=d.operatorName),d.operatorAvatar&&(this.config.operatorAvatar=d.operatorAvatar),d.primaryColor&&(this.config.primaryColor=d.primaryColor),d.headerColor&&(this.config.headerColor=d.headerColor),d.footerColor&&(this.config.footerColor=d.footerColor),d.chatBackground&&(this.config.chatBackground=d.chatBackground),d.toggleColor&&(this.config.toggleColor=d.toggleColor),d.welcomeMessage&&(this.config.welcomeMessage=d.welcomeMessage),this.emit("configUpdate",{operatorName:this.config.operatorName,operatorAvatar:this.config.operatorAvatar,primaryColor:this.config.primaryColor,headerColor:this.config.headerColor,footerColor:this.config.footerColor,chatBackground:this.config.chatBackground,toggleColor:this.config.toggleColor,welcomeMessage:this.config.welcomeMessage}),this.storeSessionId(d.sessionId),this.connectedAt=Date.now(),this.disconnectNotified=!1,this.setupUnloadListeners(),this.connectRealtime(),d.inspectorMode?this.enableInspectorMode():d.trackedElements?.length&&this.setupTrackedElements(d.trackedElements),this.emit("connect",this.session),this.config.onConnect?.(d.sessionId),this.session}disconnect(){this.notifyDisconnect(),this.cleanupUnloadListeners(),this.ws&&(this.ws.onclose=null,this.ws.onmessage=null,this.ws.onerror=null,this.ws.onopen=null,this.ws.close(),this.ws=null),this.sse&&(this.sse.close(),this.sse=null),this.session=null,this.connectionMode="none",this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.stopPolling(),this.cleanupTrackedElements(),this.disableInspectorMode()}async sendMessage(e,n,r){if(!this.session)throw new Error("Not connected");let o=`temp-${this.generateId()}`,i={id:o,sessionId:this.session.sessionId,content:e,sender:"visitor",timestamp:new Date().toISOString(),status:"sending",replyTo:r};this.session.messages.push(i),this.emit("message",i);try{let d=await this.fetch("/message",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,content:e,sender:"visitor",attachmentIds:n||[],replyTo:r})}),s=this.session.messages.findIndex(c=>c.id===o);s>=0&&(this.session.messages[s].id=d.messageId,this.session.messages[s].timestamp=d.timestamp,this.session.messages[s].status="sent",d.attachments&&d.attachments.length>0&&(this.session.messages[s].attachments=d.attachments),this.emit("message",this.session.messages[s]));let u=this.session.messages[s]||{id:d.messageId,sessionId:this.session.sessionId,content:e,sender:"visitor",timestamp:d.timestamp,status:"sent",attachments:d.attachments};return this.config.onMessage?.(u),u}catch(d){let s=this.session.messages.findIndex(u=>u.id===o);throw s>=0&&(this.session.messages.splice(s,1),this.emit("message",i)),d}}async uploadFile(e,n){if(!this.session)throw new Error("Not connected");this.emit("uploadStart",{filename:e.name,size:e.size});try{let r=await this.fetch("/upload",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,filename:e.name,mimeType:e.type||"application/octet-stream",size:e.size})});n?.(10),this.emit("uploadProgress",{filename:e.name,progress:10}),await this.uploadToPresignedUrl(r.uploadUrl,e,i=>{let d=10+i*.8;n?.(d),this.emit("uploadProgress",{filename:e.name,progress:d})});let o=await this.fetch("/upload/complete",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,attachmentId:r.attachmentId})});return n?.(100),this.emit("uploadComplete",o),{id:o.id,filename:o.filename,mimeType:o.mimeType,size:o.size,url:o.url,thumbnailUrl:o.thumbnailUrl,status:o.status}}catch(r){throw this.emit("uploadError",{filename:e.name,error:r}),r}}async uploadFiles(e,n){let r=[],o=e.length;for(let i=0;i<o;i++){let d=e[i],s=i/o*100,u=100/o,c=await this.uploadFile(d,f=>{let l=s+f/100*u;n?.(l)});r.push(c)}return r}uploadToPresignedUrl(e,n,r){return new Promise((o,i)=>{let d=new XMLHttpRequest;d.upload.addEventListener("progress",s=>{if(s.lengthComputable){let u=s.loaded/s.total*100;r?.(u)}}),d.addEventListener("load",()=>{d.status>=200&&d.status<300?o():i(new Error(`Upload failed with status ${d.status}`))}),d.addEventListener("error",()=>{i(new Error("Upload failed"))}),d.open("PUT",e),d.setRequestHeader("Content-Type",n.type||"application/octet-stream"),d.send(n)})}async fetchMessages(e){if(!this.session)throw new Error("Not connected");let n=new URLSearchParams({sessionId:this.session.sessionId});return e&&n.set("after",e),(await this.fetch(`/messages?${n}`,{method:"GET"})).messages}async sendTyping(e=!0){this.session&&await this.fetch("/typing",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,sender:"visitor",isTyping:e})})}async sendReadStatus(e,n){if(!(!this.session||e.length===0))try{await this.fetch("/read",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,messageIds:e,status:n})});for(let r of this.session.messages)e.includes(r.id)&&(r.status=n,n==="delivered"?r.deliveredAt=new Date().toISOString():n==="read"&&(r.readAt=new Date().toISOString()));this.emit("readStatusSent",{messageIds:e,status:n})}catch(r){console.error("[PocketPing] Failed to send read status:",r)}}async editMessage(e,n){if(!this.session)throw new Error("Not connected");let r=await this.fetch(`/message/${e}`,{method:"PATCH",body:JSON.stringify({sessionId:this.session.sessionId,content:n})}),o=this.session.messages.findIndex(i=>i.id===e);return o>=0&&(this.session.messages[o].content=r.message.content,this.session.messages[o].editedAt=r.message.editedAt,this.emit("messageEdited",this.session.messages[o])),this.session.messages[o]}async deleteMessage(e){if(!this.session)throw new Error("Not connected");let n=await this.fetch(`/message/${e}?sessionId=${encodeURIComponent(this.session.sessionId)}`,{method:"DELETE"});if(n.deleted){let r=this.session.messages.findIndex(o=>o.id===e);r>=0&&(this.session.messages[r].deletedAt=new Date().toISOString(),this.session.messages[r].content="",this.emit("messageDeleted",this.session.messages[r]))}return n.deleted}async getPresence(){return this.fetch("/presence",{method:"GET"})}async identify(e){if(!e?.id)throw new Error("[PocketPing] identity.id is required");if(this.storeIdentity(e),this.session)try{await this.fetch("/identify",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,identity:e})}),this.session.identity=e,this.emit("identify",e)}catch(n){throw console.error("[PocketPing] Failed to identify:",n),n}}async submitPreChat(e){if(!this.session)throw new Error("[PocketPing] Not connected");if(!e.email&&!e.phone)throw new Error("[PocketPing] Either email or phone is required");try{await this.fetch("/prechat",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,email:e.email,phone:e.phone,phoneCountry:e.phoneCountry})}),this.session.preChatForm&&(this.session.preChatForm.completed=!0),this.emit("preChatCompleted",e)}catch(n){throw console.error("[PocketPing] Failed to submit pre-chat form:",n),n}}async reset(e){this.clearIdentity(),this.session&&(this.session.identity=void 0),e?.newSession&&(localStorage.removeItem("pocketping_session_id"),localStorage.removeItem("pocketping_visitor_id"),this.disconnect(),await this.connect()),this.emit("reset",null)}getIdentity(){return this.session?.identity||this.getStoredIdentity()}getSession(){return this.session}getMessages(){return this.session?.messages??[]}isConnected(){return this.session!==null}isWidgetOpen(){return this.isOpen}getConfig(){return this.config}setOpen(e){this.isOpen=e,this.emit("openChange",e),e?this.config.onOpen?.():this.config.onClose?.()}toggleOpen(){this.setOpen(!this.isOpen)}on(e,n){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(n),()=>{this.listeners.get(e)?.delete(n)}}emit(e,n){this.listeners.get(e)?.forEach(r=>r(n))}trigger(e,n,r){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){console.warn("[PocketPing] Cannot trigger event: WebSocket not connected");return}let o={name:e,data:n,timestamp:new Date().toISOString()};this.ws.send(JSON.stringify({type:"event",data:o})),this.emit(`event:${e}`,o),r?.widgetMessage&&(this.setOpen(!0),this.emit("triggerMessage",{message:r.widgetMessage,eventName:e}))}onEvent(e,n){return this.customEventHandlers.has(e)||this.customEventHandlers.set(e,new Set),this.customEventHandlers.get(e).add(n),()=>{this.customEventHandlers.get(e)?.delete(n)}}offEvent(e,n){this.customEventHandlers.get(e)?.delete(n)}emitCustomEvent(e){let n=this.customEventHandlers.get(e.name);n&&n.forEach(r=>r(e.data,e)),this.config.onEvent?.(e),this.emit("event",e),this.emit(`event:${e.name}`,e)}setupTrackedElements(e){this.cleanupTrackedElements(),this.currentTrackedElements=e;for(let n of e){let r=n.event||"click",o=d=>{let s={...n.data,selector:n.selector,elementText:d.target?.textContent?.trim().slice(0,100),url:window.location.href};this.trigger(n.name,s,{widgetMessage:n.widgetMessage})},i=d=>{d.target?.closest(n.selector)&&o(d)};document.addEventListener(r,i,!0),this.trackedElementCleanups.push(()=>{document.removeEventListener(r,i,!0)})}e.length>0&&console.info(`[PocketPing] Tracking ${e.length} element(s)`)}cleanupTrackedElements(){for(let e of this.trackedElementCleanups)e();this.trackedElementCleanups=[],this.currentTrackedElements=[]}getTrackedElements(){return[...this.currentTrackedElements]}enableInspectorMode(){if(this.inspectorMode)return;this.inspectorMode=!0,console.info("[PocketPing] \u{1F50D} Inspector mode active - click on any element to select it");let e=document.createElement("div");e.id="pp-inspector-overlay",e.innerHTML=`
|
|
1531
|
+
`),r=!1,o=[];for(let i of n){let d=i.match(/^[\s]*[*-]\s+(.+)$/);d?(r||(o.push('<ul class="pp-md-list">'),r=!0),o.push(`<li>${Fr(d[1])}</li>`)):(r&&(o.push("</ul>"),r=!1),o.push(Fr(i)))}return r&&o.push("</ul>"),e=o.join("<br />"),e=e.replace(/<br \/><ul/g,"<ul").replace(/<\/ul><br \/>/g,"</ul>").replace(/<br \/><li>/g,"<li>").replace(/<\/li><br \/>/g,"</li>"),e}function Fr(t){return t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/__(.+?)__/g,"<strong>$1</strong>").replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,"<em>$1</em>").replace(/(?<!_)_([^_]+)_(?!_)/g,"<em>$1</em>").replace(/`([^`]+)`/g,"<code>$1</code>")}function Rd(t){let e=new Date,n=new Date(t),r=new Date(e.getFullYear(),e.getMonth(),e.getDate()),o=new Date(n.getFullYear(),n.getMonth(),n.getDate()),i=Math.floor((r.getTime()-o.getTime())/(1e3*60*60*24));return i===0?"Today":i===1?"Yesterday":n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:n.getFullYear()!==e.getFullYear()?"numeric":void 0})}function Lr(t){let e=new Date(t);return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function Gr({client:t,config:e}){let[n,r]=I(!1),[o,i]=I([]),[d,s]=I(""),[u,c]=I(!1),[f,l]=I(!1),[$,h]=I(!1),[C,k]=I(0),[E,m]=I([]),[_,M]=I(!1),[F,x]=I(null),[U,J]=I(null),[L,G]=I(""),[j,R]=I(null),[X,_e]=I(!1),[de,se]=I(null),[fe,ee]=I(0),te=ne(null),[z,ae]=I(e),[Q,v]=I(void 0),[W,we]=I(!1),$e=ne(null),Ce=ne(null),cn=ne(null),lo=ne(null);Y(()=>{let p=t.on("openChange",r),g=t.on("message",()=>{i([...t.getMessages()])}),b=t.on("typing",y=>{c(y.isTyping)}),S=t.on("presence",y=>{l(y.online)}),N=t.on("connect",()=>{h(!0),i(t.getMessages()),l(t.getSession()?.operatorOnline??!1),ae(t.getConfig()),v(t.getSession()?.preChatForm)}),A=t.on("preChatCompleted",()=>{v(y=>y&&{...y,completed:!0})}),w=t.on("configUpdate",()=>{ae(t.getConfig())});return t.isConnected()&&(h(!0),i(t.getMessages()),l(t.getSession()?.operatorOnline??!1),ae(t.getConfig()),v(t.getSession()?.preChatForm)),()=>{p(),g(),b(),S(),N(),A(),w()}},[t]),Y(()=>{n&&$e.current?.scrollIntoView({behavior:"smooth"})},[o,n]),Y(()=>{n&&(setTimeout(()=>{$e.current?.scrollIntoView({behavior:"auto"})},50),Ce.current?.focus(),k(0))},[n]),Y(()=>{let p=window.innerWidth<=480;if(n&&p){let g=window.scrollY,b={overflow:document.body.style.overflow,position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,right:document.body.style.right,width:document.body.style.width};return document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`-${g}px`,document.body.style.left="0",document.body.style.right="0",document.body.style.width="100%",()=>{document.body.style.overflow=b.overflow,document.body.style.position=b.position,document.body.style.top=b.top,document.body.style.left=b.left,document.body.style.right=b.right,document.body.style.width=b.width,window.scrollTo(0,g)}}},[n]);let[We,pn]=I(null);Y(()=>{let p=window.innerWidth<=480;if(!n||!p){pn(null);return}let g=window.visualViewport;if(!g)return;let b=()=>{pn({height:g.height,top:g.offsetTop})};return b(),g.addEventListener("resize",b),g.addEventListener("scroll",b),()=>{g.removeEventListener("resize",b),g.removeEventListener("scroll",b)}},[n]),Y(()=>{if(!n&&o.length>0){let p=o.filter(g=>g.sender!=="visitor"&&g.status!=="read").length;k(p)}},[o,n]);let ze=Wn(()=>{if(!n||!$)return;let p=o.filter(g=>g.sender!=="visitor"&&g.status!=="read");if(p.length>0){let g=p.map(b=>b.id);t.sendReadStatus(g,"read")}},[n,$,o,t]);if(Y(()=>{if(!n||!$)return;let p=setTimeout(()=>{ze()},1e3);return()=>clearTimeout(p)},[n,$,o,ze]),Y(()=>{let p=()=>{document.visibilityState==="visible"&&n&&ze()};return document.addEventListener("visibilitychange",p),()=>document.removeEventListener("visibilitychange",p)},[n,ze]),Y(()=>{let p=t.on("read",()=>{i([...t.getMessages()])});return()=>p()},[t]),!Ld(z))return null;let co=async p=>{p.preventDefault();let g=d.trim().length>0,b=E.filter(w=>w.status==="ready"&&w.attachment);if(!g&&b.length===0)return;let S=d,N=b.map(w=>w.attachment.id),A=F?.id;s(""),m([]),x(null),Ce.current&&(Ce.current.style.height="auto");try{await t.sendMessage(S,N,A)}catch(w){console.error("[PocketPing] Failed to send message:",w)}},po=p=>{let g=p.target;s(g.value),g.style.height="auto",g.style.height=Math.min(g.scrollHeight,120)+"px",t.sendTyping(!0)},uo=p=>{if(p.key==="Enter"&&!p.shiftKey){p.preventDefault();let g=p.target.closest("form");g&&g.requestSubmit()}},fo=async p=>{let g=p.target,b=g.files;if(!b||b.length===0)return;let S=[];for(let N=0;N<b.length;N++){let A=b[N],w=`pending-${Date.now()}-${N}`,y;A.type.startsWith("image/")&&(y=URL.createObjectURL(A)),S.push({id:w,file:A,preview:y,progress:0,status:"pending"})}m(N=>[...N,...S]),g.value="",M(!0);for(let N of S)try{m(w=>w.map(y=>y.id===N.id?{...y,status:"uploading"}:y));let A=await t.uploadFile(N.file,w=>{m(y=>y.map(qe=>qe.id===N.id?{...qe,progress:w}:qe))});m(w=>w.map(y=>y.id===N.id?{...y,status:"ready",progress:100,attachment:A}:y))}catch(A){console.error("[PocketPing] Failed to upload file:",A),m(w=>w.map(y=>y.id===N.id?{...y,status:"error",error:"Upload failed"}:y))}M(!1)},$o=p=>{m(g=>{let b=g.find(S=>S.id===p);return b?.preview&&URL.revokeObjectURL(b.preview),g.filter(S=>S.id!==p)})},un=p=>{x(p),R(null),Ce.current?.focus()},ho=()=>{x(null)},fn=p=>{p.sender==="visitor"&&(J(p),G(p.content),R(null))},$n=()=>{J(null),G("")},go=async()=>{if(!(!U||!L.trim()))try{await t.editMessage(U.id,L.trim()),J(null),G("")}catch(p){console.error("[PocketPing] Failed to edit message:",p)}},hn=async p=>{if(p.sender==="visitor"&&(R(null),confirm("Delete this message?")))try{await t.deleteMessage(p.id)}catch(g){console.error("[PocketPing] Failed to delete message:",g)}},mo=(p,g)=>{p.preventDefault();let b=p;R({message:g,x:b.clientX,y:b.clientY})},bo=(p,g)=>{let b=p.touches[0];te.current={x:b.clientX,y:b.clientY,time:Date.now()},de&&de!==g.id&&(se(null),ee(0))},yo=(p,g)=>{if(!te.current)return;let b=p.touches[0],S=b.clientX-te.current.x,N=b.clientY-te.current.y;if(Math.abs(N)>10||Math.abs(S)<15){de===g.id&&fe!==0&&(ee(0),se(null));return}if(p.preventDefault(),S<0){let A=Math.max(S,-80);ee(A),se(g.id)}},gn=p=>{if(!te.current)return;let g=Date.now()-te.current.time;fe<-50||fe<-20&&g<200?(ee(-80),navigator.vibrate&&navigator.vibrate(30)):(ee(0),se(null)),te.current=null},Ke=()=>{se(null),ee(0)};Y(()=>{if(!j)return;let p=()=>R(null);return document.addEventListener("click",p),()=>document.removeEventListener("click",p)},[j]);let mn=p=>{let g=document.getElementById(`pp-msg-${p}`);g&&(g.scrollIntoView({behavior:"smooth",block:"center"}),g.classList.add("pp-message-highlight"),setTimeout(()=>{g.classList.remove("pp-message-highlight")},1500))},Pe=ne(0),vo=p=>{p.preventDefault(),p.stopPropagation(),Pe.current++,Pe.current===1&&_e(!0)},xo=p=>{p.preventDefault(),p.stopPropagation()},_o=p=>{p.preventDefault(),p.stopPropagation(),Pe.current--,Pe.current===0&&_e(!1)},wo=async p=>{p.preventDefault(),p.stopPropagation(),Pe.current=0,_e(!1);let g=p.dataTransfer?.files;if(!g||g.length===0)return;let b=[];for(let S=0;S<g.length;S++){let N=g[S],A=`pending-${Date.now()}-${S}`,w;N.type.startsWith("image/")&&(w=URL.createObjectURL(N)),b.push({id:A,file:N,preview:w,progress:0,status:"pending"})}m(S=>[...S,...b]),M(!0);for(let S of b)try{m(A=>A.map(w=>w.id===S.id?{...w,status:"uploading"}:w));let N=await t.uploadFile(S.file,A=>{m(w=>w.map(y=>y.id===S.id?{...y,progress:A}:y))});m(A=>A.map(w=>w.id===S.id?{...w,status:"ready",progress:100,attachment:N}:w))}catch(N){console.error("[PocketPing] Failed to upload dropped file:",N),m(A=>A.map(w=>w.id===S.id?{...w,status:"error",error:"Upload failed"}:w))}M(!1)},bn=z.position??"bottom-right",gt=Dd(z.theme??"auto"),Co=z.primaryColor??"#6366f1",yn=gt==="dark"?"#9ca3af":"#6b7280",Po={primaryColor:Co,theme:gt,headerColor:z.headerColor,footerColor:z.footerColor,chatBackground:z.chatBackground,toggleColor:z.toggleColor},mt=Q&&Q.enabled&&!Q.completed&&!W&&(Q.timing==="before-first-message"&&o.length===0||Q.timing==="after-first-message"&&o.some(p=>p.sender==="visitor"));return a(D,{children:[a("style",{children:Xn(Po)}),!n&&a("button",{class:`pp-toggle pp-${bn}`,onClick:()=>t.toggleOpen(),"aria-label":"Open chat",children:[a(Hd,{}),C>0&&a("span",{class:"pp-unread-badge",children:C>9?"9+":C}),C===0&&f&&a("span",{class:"pp-online-dot"})]}),n&&a("div",{class:`pp-window pp-${bn} pp-theme-${gt} ${X?"pp-dragging":""}`,style:We?{height:`${We.height}px`,maxHeight:`${We.height}px`,top:`${We.top}px`,bottom:"auto"}:void 0,onDragEnter:vo,onDragOver:xo,onDragLeave:_o,onDrop:wo,children:[X&&a("div",{class:"pp-drop-overlay",children:[a("div",{class:"pp-drop-icon",children:a(Ur,{})}),a("div",{class:"pp-drop-text",children:"Drop files to upload"})]}),a("div",{class:"pp-header",children:[a("div",{class:"pp-header-info",children:[z.operatorAvatar&&a("img",{src:z.operatorAvatar,alt:"",class:"pp-avatar"}),a("div",{children:[a("div",{class:"pp-header-title",children:z.operatorName??"Support"}),a("div",{class:"pp-header-status",children:f?a(D,{children:[a("span",{class:"pp-status-dot pp-online"})," Online"]}):a(D,{children:[a("span",{class:"pp-status-dot"})," Away"]})})]})]}),a("button",{class:"pp-close-btn",onClick:()=>t.setOpen(!1),"aria-label":"Close chat",children:a(ft,{})})]}),mt&&Q&&a(Mr,{client:t,config:Q,onComplete:()=>{v(p=>p&&{...p,completed:!0})},onSkip:()=>{we(!0)}}),!mt&&a("div",{class:"pp-messages",ref:lo,onClick:()=>de&&Ke(),children:[z.welcomeMessage&&o.length===0&&a("div",{class:"pp-welcome",children:z.welcomeMessage}),o.map((p,g)=>{let b=!!p.deletedAt,S=!!p.editedAt,N=new Date(p.timestamp),A=g>0?o[g-1]:null,w=!A||Lr(new Date(A.timestamp))!==Lr(N),y=null;if(p.replyTo)if(typeof p.replyTo=="object")y=p.replyTo;else{let V=o.find(Xe=>Xe.id===p.replyTo);if(V){let Xe=!!(V.attachments&&V.attachments.length>0);y={id:V.id,sender:V.sender,content:V.content,deleted:!!V.deletedAt,hasAttachment:Xe,attachmentType:Xe?V.attachments[0].mimeType:void 0}}}let Eo=de===p.id?fe:0;return a(D,{children:[w&&a("div",{class:"pp-date-separator",children:a("span",{children:Rd(N)})}),a("div",{class:`pp-message-swipe-container ${p.sender==="visitor"?"pp-swipe-left":"pp-swipe-right"}`,children:[a("div",{class:"pp-swipe-actions",children:[a("button",{class:"pp-swipe-action pp-swipe-reply",onClick:()=>{un(p),Ke()},children:a(Br,{color:"#fff"})}),p.sender==="visitor"&&!b&&a(D,{children:[a("button",{class:"pp-swipe-action pp-swipe-edit",onClick:()=>{fn(p),Ke()},children:a(jr,{color:"#fff"})}),a("button",{class:"pp-swipe-action pp-swipe-delete",onClick:()=>{hn(p),Ke()},children:a(Vr,{color:"#fff"})})]})]}),a("div",{id:`pp-msg-${p.id}`,class:`pp-message pp-message-${p.sender} ${b?"pp-message-deleted":""}`,style:{transform:`translateX(${Eo}px)`,transition:te.current?"none":"transform 0.2s ease-out"},onContextMenu:V=>mo(V,p),onTouchStart:V=>bo(V,p),onTouchMove:V=>yo(V,p),onTouchEnd:()=>gn(p),onTouchCancel:()=>gn(p),children:[y&&(y.content||y.hasAttachment)&&a("div",{class:"pp-reply-quote pp-reply-quote-clickable",onClick:()=>mn(y.id),role:"button",tabIndex:0,onKeyDown:V=>V.key==="Enter"&&mn(y.id),children:[a("span",{class:"pp-reply-sender",children:y.sender==="visitor"?"You":"Support"}),a("span",{class:"pp-reply-content",children:y.deleted?"Message deleted":a(D,{children:[y.hasAttachment&&a("span",{class:"pp-reply-attachment-icon",children:y.attachmentType?.startsWith("image/")?"\u{1F4F7} ":"\u{1F4CE} "}),y.content?a(D,{children:[(y.content||"").slice(0,50),(y.content||"").length>50?"...":""]}):y.attachmentType?.startsWith("image/")?"Photo":"File"]})})]}),b?a("div",{class:"pp-message-content pp-deleted-content",children:[a("span",{class:"pp-deleted-icon",children:"\u{1F5D1}\uFE0F"})," Message deleted"]}):a(D,{children:[p.content&&a("div",{class:"pp-message-content",children:[a("span",{dangerouslySetInnerHTML:{__html:Rr(p.content)}}),a("span",{class:"pp-message-time",children:[Dr(p.timestamp),S&&a("span",{class:"pp-edited-badge",children:"edited"}),p.sender==="ai"&&a("span",{class:"pp-ai-badge",children:"AI"}),p.sender==="visitor"&&a("span",{class:`pp-status pp-status-${p.status??"sent"}`,children:a(Hr,{status:p.status})})]})]}),p.attachments&&p.attachments.length>0&&a("div",{class:"pp-message-attachments",children:[p.attachments.map(V=>a(Bd,{attachment:V},V.id)),!p.content&&a("span",{class:"pp-message-time pp-attachment-time",children:[Dr(p.timestamp),S&&a("span",{class:"pp-edited-badge",children:"edited"}),p.sender==="ai"&&a("span",{class:"pp-ai-badge",children:"AI"}),p.sender==="visitor"&&a("span",{class:`pp-status pp-status-${p.status??"sent"}`,children:a(Hr,{status:p.status})})]})]})]})]})]})]},p.id)}),u&&a("div",{class:"pp-message pp-message-operator pp-typing",children:[a("span",{}),a("span",{}),a("span",{})]}),a("div",{ref:$e})]}),j&&a("div",{class:"pp-message-menu",style:{top:`${j.y}px`,left:`${j.x}px`},children:[a("button",{onClick:()=>un(j.message),children:[a(Br,{color:yn})," Reply"]}),j.message.sender==="visitor"&&!j.message.deletedAt&&a(D,{children:[a("button",{onClick:()=>fn(j.message),children:[a(jr,{color:yn})," Edit"]}),a("button",{class:"pp-menu-delete",onClick:()=>hn(j.message),children:[a(Vr,{color:"#ef4444"})," Delete"]})]})]}),U&&a("div",{class:"pp-edit-modal",children:[a("div",{class:"pp-edit-header",children:[a("span",{children:"Edit message"}),a("button",{onClick:$n,children:a(ft,{})})]}),a("textarea",{class:"pp-edit-input",value:L,onInput:p=>G(p.target.value),autoFocus:!0}),a("div",{class:"pp-edit-actions",children:[a("button",{class:"pp-edit-cancel",onClick:$n,children:"Cancel"}),a("button",{class:"pp-edit-save",onClick:go,disabled:!L.trim(),children:"Save"})]})]}),F&&a("div",{class:"pp-reply-preview",children:[a("div",{class:"pp-reply-preview-content",children:[a("span",{class:"pp-reply-label",children:"Replying to"}),a("span",{class:"pp-reply-text",children:[F.attachments&&F.attachments.length>0&&a("span",{class:"pp-reply-attachment-icon",children:F.attachments[0].mimeType.startsWith("image/")?"\u{1F4F7} ":"\u{1F4CE} "}),F.content?a(D,{children:[F.content.slice(0,50),F.content.length>50?"...":""]}):F.attachments?.[0]?.mimeType.startsWith("image/")?"Photo":"File"]})]}),a("button",{class:"pp-reply-cancel",onClick:ho,children:a(ft,{})})]}),E.length>0&&a("div",{class:"pp-attachments-preview",children:E.map(p=>a("div",{class:`pp-attachment-preview pp-attachment-${p.status}`,children:[p.preview?a("img",{src:p.preview,alt:p.file.name,class:"pp-preview-img"}):a("div",{class:"pp-preview-file",children:a(Wr,{mimeType:p.file.type})}),a("button",{class:"pp-remove-attachment",onClick:()=>$o(p.id),"aria-label":"Remove attachment",type:"button",children:a(ft,{})}),p.status==="uploading"&&a("div",{class:"pp-upload-progress",style:{width:`${p.progress}%`}}),p.status==="error"&&a("div",{class:"pp-upload-error",title:p.error,children:"!"})]},p.id))}),!mt&&a("form",{class:"pp-input-form",onSubmit:co,children:[a("input",{ref:p=>{cn.current=p,p&&(p.onchange=fo)},type:"file",class:"pp-file-input",accept:"image/*,audio/*,video/*,.pdf,.doc,.docx,.xls,.xlsx,.txt",multiple:!0}),a("button",{type:"button",class:"pp-attach-btn",onClick:()=>cn.current?.click(),disabled:!$||_,"aria-label":"Attach file",children:a(Ur,{})}),a("textarea",{ref:Ce,class:"pp-input",placeholder:z.placeholder??"Type a message...",value:d,onInput:po,onKeyDown:uo,disabled:!$,rows:1}),a("button",{type:"submit",class:"pp-send-btn",disabled:!d.trim()&&E.filter(p=>p.status==="ready").length===0||!$||_,"aria-label":"Send message",children:a(Ud,{})})]}),a("div",{class:"pp-footer",children:["Powered by ",a("a",{href:"https://pocketping.io",target:"_blank",rel:"noopener",children:"PocketPing"})]})]})]})}function Ld(t){let e=window.location.pathname;return t.hideOnPages?.some(n=>new RegExp(n).test(e))?!1:t.showOnPages?.length?t.showOnPages.some(n=>new RegExp(n).test(e)):!0}function Dd(t){return t==="auto"?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":t}function Dr(t){return new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function Hd(){return a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:a("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function ft(){return a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[a("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Ud(){return a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[a("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),a("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function Hr({status:t}){return!t||t==="sending"||t==="sent"?a("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"2",class:"pp-check",children:a("polyline",{points:"3 8 7 12 13 4"})}):t==="delivered"?a("svg",{viewBox:"0 0 20 16",fill:"none",stroke:"currentColor","stroke-width":"2",class:"pp-check-double",children:[a("polyline",{points:"1 8 5 12 11 4"}),a("polyline",{points:"7 8 11 12 17 4"})]}):t==="read"?a("svg",{viewBox:"0 0 20 16",fill:"none",stroke:"currentColor","stroke-width":"2",class:"pp-check-double pp-check-read",children:[a("polyline",{points:"1 8 5 12 11 4"}),a("polyline",{points:"7 8 11 12 17 4"})]}):null}function Ur(){return a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:a("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})})}function Br({color:t,size:e=16}){return a("svg",{viewBox:"0 0 24 24",fill:"none","stroke-width":"2",style:{stroke:t||"currentColor",width:`${e}px`,minWidth:`${e}px`,height:`${e}px`,display:"block",flexShrink:0},children:[a("polyline",{points:"9 17 4 12 9 7"}),a("path",{d:"M20 18v-2a4 4 0 0 0-4-4H4"})]})}function jr({color:t,size:e=16}){return a("svg",{viewBox:"0 0 24 24",fill:"none","stroke-width":"2",style:{stroke:t||"currentColor",width:`${e}px`,minWidth:`${e}px`,height:`${e}px`,display:"block",flexShrink:0},children:a("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}function Vr({color:t,size:e=16}){return a("svg",{viewBox:"0 0 24 24",fill:"none","stroke-width":"2",style:{stroke:t||"currentColor",width:`${e}px`,minWidth:`${e}px`,height:`${e}px`,display:"block",flexShrink:0},children:[a("polyline",{points:"3 6 5 6 21 6"}),a("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function Wr({mimeType:t}){return t==="application/pdf"?a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[a("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),a("polyline",{points:"14 2 14 8 20 8"}),a("path",{d:"M9 15h6"}),a("path",{d:"M9 11h6"})]}):t.startsWith("audio/")?a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[a("path",{d:"M9 18V5l12-2v13"}),a("circle",{cx:"6",cy:"18",r:"3"}),a("circle",{cx:"18",cy:"16",r:"3"})]}):t.startsWith("video/")?a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[a("rect",{x:"2",y:"2",width:"20",height:"20",rx:"2.18",ry:"2.18"}),a("line",{x1:"7",y1:"2",x2:"7",y2:"22"}),a("line",{x1:"17",y1:"2",x2:"17",y2:"22"}),a("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),a("line",{x1:"2",y1:"7",x2:"7",y2:"7"}),a("line",{x1:"2",y1:"17",x2:"7",y2:"17"}),a("line",{x1:"17",y1:"17",x2:"22",y2:"17"}),a("line",{x1:"17",y1:"7",x2:"22",y2:"7"})]}):a("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[a("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),a("polyline",{points:"14 2 14 8 20 8"})]})}function Bd({attachment:t}){let e=t.mimeType.startsWith("image/"),n=t.mimeType.startsWith("audio/"),r=t.mimeType.startsWith("video/"),o=i=>i<1024?`${i} B`:i<1024*1024?`${(i/1024).toFixed(1)} KB`:`${(i/(1024*1024)).toFixed(1)} MB`;return e?a("a",{href:t.url,target:"_blank",rel:"noopener",class:"pp-attachment pp-attachment-image",children:a("img",{src:t.thumbnailUrl||t.url,alt:t.filename})}):n?a("div",{class:"pp-attachment pp-attachment-audio",children:[a("audio",{controls:!0,preload:"metadata",children:a("source",{src:t.url,type:t.mimeType})}),a("span",{class:"pp-attachment-name",children:t.filename})]}):r?a("div",{class:"pp-attachment pp-attachment-video",children:a("video",{controls:!0,preload:"metadata",children:a("source",{src:t.url,type:t.mimeType})})}):a("a",{href:t.url,target:"_blank",rel:"noopener",class:"pp-attachment pp-attachment-file",children:[a(Wr,{mimeType:t.mimeType}),a("div",{class:"pp-attachment-info",children:[a("span",{class:"pp-attachment-name",children:t.filename}),a("span",{class:"pp-attachment-size",children:o(t.size)})]})]})}var $t="2.6.0";function jd(){return{webdriver:!!navigator.webdriver,plugins:navigator.plugins.length===0,languages:navigator.languages.length===0,chrome:/Chrome/.test(navigator.userAgent)&&typeof window.chrome>"u",permissions:typeof Notification<"u"&&Notification.permission==="denied"}}var ht=class{constructor(e){this.session=null;this.ws=null;this.sse=null;this.isOpen=!1;this.listeners=new Map;this.customEventHandlers=new Map;this.reconnectAttempts=0;this.maxReconnectAttempts=5;this.reconnectTimeout=null;this.pollingTimeout=null;this.pollingFailures=0;this.maxPollingFailures=10;this.wsConnectedAt=0;this.quickFailureThreshold=2e3;this.connectionMode="none";this.trackedElementCleanups=[];this.currentTrackedElements=[];this.inspectorMode=!1;this.inspectorCleanup=null;this.connectedAt=0;this.disconnectNotified=!1;this.boundHandleUnload=null;this.boundHandleVisibilityChange=null;this.config=e}async connect(){let e=this.getOrCreateVisitorId(),n=this.getStoredSessionId(),r=this.getStoredIdentity(),i=new URLSearchParams(window.location.search).get("pp_inspector"),d=await this.fetch("/connect",{method:"POST",body:JSON.stringify({visitorId:e,sessionId:n,inspectorToken:i||void 0,metadata:{url:window.location.href,referrer:document.referrer||void 0,pageTitle:document.title||void 0,userAgent:navigator.userAgent,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,language:navigator.language,screenResolution:`${window.screen.width}x${window.screen.height}`,botSignals:jd()},identity:r||void 0})});return this.session={sessionId:d.sessionId,visitorId:d.visitorId,operatorOnline:d.operatorOnline??!1,messages:d.messages??[],identity:d.identity||r||void 0,preChatForm:d.preChatForm},d.operatorName&&(this.config.operatorName=d.operatorName),d.operatorAvatar&&(this.config.operatorAvatar=d.operatorAvatar),d.primaryColor&&(this.config.primaryColor=d.primaryColor),d.headerColor&&(this.config.headerColor=d.headerColor),d.footerColor&&(this.config.footerColor=d.footerColor),d.chatBackground&&(this.config.chatBackground=d.chatBackground),d.toggleColor&&(this.config.toggleColor=d.toggleColor),d.welcomeMessage&&(this.config.welcomeMessage=d.welcomeMessage),this.emit("configUpdate",{operatorName:this.config.operatorName,operatorAvatar:this.config.operatorAvatar,primaryColor:this.config.primaryColor,headerColor:this.config.headerColor,footerColor:this.config.footerColor,chatBackground:this.config.chatBackground,toggleColor:this.config.toggleColor,welcomeMessage:this.config.welcomeMessage}),this.storeSessionId(d.sessionId),this.connectedAt=Date.now(),this.disconnectNotified=!1,this.setupUnloadListeners(),this.connectRealtime(),d.inspectorMode?this.enableInspectorMode():d.trackedElements?.length&&this.setupTrackedElements(d.trackedElements),this.emit("connect",this.session),this.config.onConnect?.(d.sessionId),this.session}disconnect(){this.notifyDisconnect(),this.cleanupUnloadListeners(),this.ws&&(this.ws.onclose=null,this.ws.onmessage=null,this.ws.onerror=null,this.ws.onopen=null,this.ws.close(),this.ws=null),this.sse&&(this.sse.close(),this.sse=null),this.session=null,this.connectionMode="none",this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.stopPolling(),this.cleanupTrackedElements(),this.disableInspectorMode()}async sendMessage(e,n,r){if(!this.session)throw new Error("Not connected");let o=`temp-${this.generateId()}`,i={id:o,sessionId:this.session.sessionId,content:e,sender:"visitor",timestamp:new Date().toISOString(),status:"sending",replyTo:r};this.session.messages.push(i),this.emit("message",i);try{let d=await this.fetch("/message",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,content:e,sender:"visitor",attachmentIds:n||[],replyTo:r})}),s=this.session.messages.findIndex(c=>c.id===o);s>=0&&(this.session.messages[s].id=d.messageId,this.session.messages[s].timestamp=d.timestamp,this.session.messages[s].status="sent",d.attachments&&d.attachments.length>0&&(this.session.messages[s].attachments=d.attachments),this.emit("message",this.session.messages[s]));let u=this.session.messages[s]||{id:d.messageId,sessionId:this.session.sessionId,content:e,sender:"visitor",timestamp:d.timestamp,status:"sent",attachments:d.attachments};return this.config.onMessage?.(u),u}catch(d){let s=this.session.messages.findIndex(u=>u.id===o);throw s>=0&&(this.session.messages.splice(s,1),this.emit("message",i)),d}}async uploadFile(e,n){if(!this.session)throw new Error("Not connected");this.emit("uploadStart",{filename:e.name,size:e.size});try{let r=await this.fetch("/upload",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,filename:e.name,mimeType:e.type||"application/octet-stream",size:e.size})});n?.(10),this.emit("uploadProgress",{filename:e.name,progress:10}),await this.uploadToPresignedUrl(r.uploadUrl,e,i=>{let d=10+i*.8;n?.(d),this.emit("uploadProgress",{filename:e.name,progress:d})});let o=await this.fetch("/upload/complete",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,attachmentId:r.attachmentId})});return n?.(100),this.emit("uploadComplete",o),{id:o.id,filename:o.filename,mimeType:o.mimeType,size:o.size,url:o.url,thumbnailUrl:o.thumbnailUrl,status:o.status}}catch(r){throw this.emit("uploadError",{filename:e.name,error:r}),r}}async uploadFiles(e,n){let r=[],o=e.length;for(let i=0;i<o;i++){let d=e[i],s=i/o*100,u=100/o,c=await this.uploadFile(d,f=>{let l=s+f/100*u;n?.(l)});r.push(c)}return r}uploadToPresignedUrl(e,n,r){return new Promise((o,i)=>{let d=new XMLHttpRequest;d.upload.addEventListener("progress",s=>{if(s.lengthComputable){let u=s.loaded/s.total*100;r?.(u)}}),d.addEventListener("load",()=>{d.status>=200&&d.status<300?o():i(new Error(`Upload failed with status ${d.status}`))}),d.addEventListener("error",()=>{i(new Error("Upload failed"))}),d.open("PUT",e),d.setRequestHeader("Content-Type",n.type||"application/octet-stream"),d.send(n)})}async fetchMessages(e){if(!this.session)throw new Error("Not connected");let n=new URLSearchParams({sessionId:this.session.sessionId});return e&&n.set("after",e),(await this.fetch(`/messages?${n}`,{method:"GET"})).messages}async sendTyping(e=!0){this.session&&await this.fetch("/typing",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,sender:"visitor",isTyping:e})})}async sendReadStatus(e,n){if(!(!this.session||e.length===0))try{await this.fetch("/read",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,messageIds:e,status:n})});for(let r of this.session.messages)e.includes(r.id)&&(r.status=n,n==="delivered"?r.deliveredAt=new Date().toISOString():n==="read"&&(r.readAt=new Date().toISOString()));this.emit("readStatusSent",{messageIds:e,status:n})}catch(r){console.error("[PocketPing] Failed to send read status:",r)}}async editMessage(e,n){if(!this.session)throw new Error("Not connected");let r=await this.fetch(`/message/${e}`,{method:"PATCH",body:JSON.stringify({sessionId:this.session.sessionId,content:n})}),o=this.session.messages.findIndex(i=>i.id===e);return o>=0&&(this.session.messages[o].content=r.message.content,this.session.messages[o].editedAt=r.message.editedAt,this.emit("messageEdited",this.session.messages[o])),this.session.messages[o]}async deleteMessage(e){if(!this.session)throw new Error("Not connected");let n=await this.fetch(`/message/${e}?sessionId=${encodeURIComponent(this.session.sessionId)}`,{method:"DELETE"});if(n.deleted){let r=this.session.messages.findIndex(o=>o.id===e);r>=0&&(this.session.messages[r].deletedAt=new Date().toISOString(),this.session.messages[r].content="",this.emit("messageDeleted",this.session.messages[r]))}return n.deleted}async getPresence(){return this.fetch("/presence",{method:"GET"})}async identify(e){if(!e?.id)throw new Error("[PocketPing] identity.id is required");if(this.storeIdentity(e),this.session)try{await this.fetch("/identify",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,identity:e})}),this.session.identity=e,this.emit("identify",e)}catch(n){throw console.error("[PocketPing] Failed to identify:",n),n}}async submitPreChat(e){if(!this.session)throw new Error("[PocketPing] Not connected");if(!e.email&&!e.phone)throw new Error("[PocketPing] Either email or phone is required");try{await this.fetch("/prechat",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,email:e.email,phone:e.phone,phoneCountry:e.phoneCountry})}),this.session.preChatForm&&(this.session.preChatForm.completed=!0),this.emit("preChatCompleted",e)}catch(n){throw console.error("[PocketPing] Failed to submit pre-chat form:",n),n}}async reset(e){this.clearIdentity(),this.session&&(this.session.identity=void 0),e?.newSession&&(localStorage.removeItem("pocketping_session_id"),localStorage.removeItem("pocketping_visitor_id"),this.disconnect(),await this.connect()),this.emit("reset",null)}getIdentity(){return this.session?.identity||this.getStoredIdentity()}getSession(){return this.session}getMessages(){return this.session?.messages??[]}isConnected(){return this.session!==null}isWidgetOpen(){return this.isOpen}getConfig(){return this.config}setOpen(e){this.isOpen=e,this.emit("openChange",e),e?this.config.onOpen?.():this.config.onClose?.()}toggleOpen(){this.setOpen(!this.isOpen)}on(e,n){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(n),()=>{this.listeners.get(e)?.delete(n)}}emit(e,n){this.listeners.get(e)?.forEach(r=>r(n))}trigger(e,n,r){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){console.warn("[PocketPing] Cannot trigger event: WebSocket not connected");return}let o={name:e,data:n,timestamp:new Date().toISOString()};this.ws.send(JSON.stringify({type:"event",data:o})),this.emit(`event:${e}`,o),r?.widgetMessage&&(this.setOpen(!0),this.emit("triggerMessage",{message:r.widgetMessage,eventName:e}))}onEvent(e,n){return this.customEventHandlers.has(e)||this.customEventHandlers.set(e,new Set),this.customEventHandlers.get(e).add(n),()=>{this.customEventHandlers.get(e)?.delete(n)}}offEvent(e,n){this.customEventHandlers.get(e)?.delete(n)}emitCustomEvent(e){let n=this.customEventHandlers.get(e.name);n&&n.forEach(r=>r(e.data,e)),this.config.onEvent?.(e),this.emit("event",e),this.emit(`event:${e.name}`,e)}setupTrackedElements(e){this.cleanupTrackedElements(),this.currentTrackedElements=e;for(let n of e){let r=n.event||"click",o=d=>{let s={...n.data,selector:n.selector,elementText:d.target?.textContent?.trim().slice(0,100),url:window.location.href};this.trigger(n.name,s,{widgetMessage:n.widgetMessage})},i=d=>{d.target?.closest(n.selector)&&o(d)};document.addEventListener(r,i,!0),this.trackedElementCleanups.push(()=>{document.removeEventListener(r,i,!0)})}e.length>0&&console.info(`[PocketPing] Tracking ${e.length} element(s)`)}cleanupTrackedElements(){for(let e of this.trackedElementCleanups)e();this.trackedElementCleanups=[],this.currentTrackedElements=[]}getTrackedElements(){return[...this.currentTrackedElements]}enableInspectorMode(){if(this.inspectorMode)return;this.inspectorMode=!0,console.info("[PocketPing] \u{1F50D} Inspector mode active - click on any element to select it");let e=document.createElement("div");e.id="pp-inspector-overlay",e.innerHTML=`
|
|
1532
1532
|
<style>
|
|
1533
1533
|
#pp-inspector-overlay {
|
|
1534
1534
|
position: fixed;
|
|
@@ -1616,4 +1616,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1616
1616
|
<polyline points="20 6 9 17 4 12"/>
|
|
1617
1617
|
</svg>
|
|
1618
1618
|
<span>Selector captured: <code style="background:rgba(255,255,255,0.2);padding:2px 6px;border-radius:4px;font-family:monospace;">${f}</code></span>
|
|
1619
|
-
`,setTimeout(()=>{l&&this.inspectorMode&&(l.innerHTML=$,document.getElementById("pp-inspector-exit")?.addEventListener("click",()=>{this.disableInspectorMode()}))},2e3)}console.info(`[PocketPing] \u{1F4CC} Selector captured: ${f}`)};document.addEventListener("mouseover",i,!0),document.addEventListener("mouseout",d,!0),document.addEventListener("click",s,!0),this.inspectorCleanup=()=>{document.removeEventListener("mouseover",i,!0),document.removeEventListener("mouseout",d,!0),document.removeEventListener("click",s,!0),e.remove(),r&&r.classList.remove("pp-inspector-highlight")},document.getElementById("pp-inspector-exit")?.addEventListener("click",()=>{this.disableInspectorMode()})}disableInspectorMode(){this.inspectorMode&&(this.inspectorMode=!1,this.inspectorCleanup&&(this.inspectorCleanup(),this.inspectorCleanup=null),console.info("[PocketPing] Inspector mode disabled"),this.emit("inspectorDisabled",null))}isInspectorModeActive(){return this.inspectorMode}connectRealtime(){if(this.session){if(this.connectionMode==="polling"){this.startPolling();return}if(this.connectionMode==="sse"){this.connectSSE();return}this.connectWebSocket()}}connectWebSocket(){if(!this.session)return;let e=this.config.endpoint.replace(/^http/,"ws").replace(/\/$/,"")+`/stream?sessionId=${this.session.sessionId}`;try{this.ws=new WebSocket(e),this.wsConnectedAt=Date.now();let n=setTimeout(()=>{console.warn("[PocketPing] \u23F1\uFE0F WebSocket timeout - trying SSE"),this.ws&&this.ws.readyState!==WebSocket.OPEN&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onopen=null,this.ws.close(),this.ws=null,this.connectSSE())},5e3);this.ws.onopen=()=>{clearTimeout(n),this.connectionMode="ws",this.reconnectAttempts=0,this.wsConnectedAt=Date.now(),this.emit("wsConnected",null)},this.ws.onmessage=r=>{try{let o=JSON.parse(r.data);this.handleRealtimeEvent(o)}catch(o){console.error("[PocketPing] Failed to parse WS message:",o)}},this.ws.onclose=()=>{clearTimeout(n),this.emit("wsDisconnected",null),this.handleWsFailure()},this.ws.onerror=()=>{clearTimeout(n)}}catch{console.warn("[PocketPing] WebSocket unavailable - trying SSE"),this.connectSSE()}}connectSSE(){if(!this.session)return;let e=new URLSearchParams({sessionId:this.session.sessionId}),n=this.getLastEventTimestamp();n&&e.set("after",n);let r=this.config.endpoint.replace(/\/$/,"")+`/stream?${e.toString()}`;try{this.sse=new EventSource(r);let o=setTimeout(()=>{console.warn("[PocketPing] \u23F1\uFE0F SSE timeout - falling back to polling"),this.sse&&this.sse.readyState!==EventSource.OPEN&&(this.sse.close(),this.sse=null,this.connectionMode="polling",this.startPolling())},5e3);this.sse.onopen=()=>{clearTimeout(o),this.connectionMode="sse",this.emit("sseConnected",null)},this.sse.addEventListener("message",i=>{try{let d=JSON.parse(i.data);this.handleRealtimeEvent(d)}catch(d){console.error("[PocketPing] Failed to parse SSE message:",d)}}),this.sse.addEventListener("screenshot_request",i=>{try{let d=JSON.parse(i.data);this.handleRealtimeEvent(d)}catch(d){console.error("[PocketPing] Failed to parse SSE screenshot_request:",d)}}),this.sse.addEventListener("connected",()=>{}),this.sse.onerror=()=>{clearTimeout(o),console.warn("[PocketPing] \u274C SSE error - falling back to polling"),this.sse&&(this.sse.close(),this.sse=null),this.connectionMode="polling",this.startPolling()}}catch{console.warn("[PocketPing] SSE unavailable - falling back to polling"),this.connectionMode="polling",this.startPolling()}}handleWsFailure(){if(Date.now()-this.wsConnectedAt<this.quickFailureThreshold){console.info("[PocketPing] WebSocket failed quickly - trying SSE"),this.connectSSE();return}this.scheduleReconnect()}handleRealtimeEvent(e){this.handleWebSocketEvent(e)}getLastEventTimestamp(){if(!this.session)return null;let e=null;for(let n of this.session.messages){let r=[n.timestamp,n.editedAt,n.deletedAt,n.deliveredAt,n.readAt].filter(Boolean).map(o=>new Date(o)).filter(o=>!isNaN(o.getTime()));for(let o of r)(!e||o>e)&&(e=o)}return e?e.toISOString():null}handleWebSocketEvent(e){switch(e.type){case"message":let n=e.data;if(this.session){let c=this.session.messages.findIndex(f=>f.id===n.id);if(c<0&&n.sender==="visitor"&&(c=this.session.messages.findIndex(f=>f.id.startsWith("temp-")&&f.content===n.content&&f.sender==="visitor"),c>=0&&(this.session.messages[c].id=n.id)),c<0&&n.sender!=="visitor"){let f=new Date(n.timestamp).getTime();c=this.session.messages.findIndex(l=>l.sender===n.sender&&l.content===n.content&&Math.abs(new Date(l.timestamp).getTime()-f)<2e3)}if(c>=0){let f=this.session.messages[c],l=!1;n.status&&n.status!==f.status&&(f.status=n.status,l=!0,n.deliveredAt&&(f.deliveredAt=n.deliveredAt),n.readAt&&(f.readAt=n.readAt),this.emit("read",{messageIds:[n.id],status:n.status})),n.content!==void 0&&n.content!==f.content&&(f.content=n.content,l=!0),n.editedAt!==void 0&&n.editedAt!==f.editedAt&&(f.editedAt=n.editedAt,l=!0),n.deletedAt!==void 0&&n.deletedAt!==f.deletedAt&&(f.deletedAt=n.deletedAt,l=!0),n.replyTo!==void 0&&(f.replyTo=n.replyTo,l=!0),n.attachments!==void 0&&(f.attachments=n.attachments,l=!0),l&&this.emit("message",f)}else this.session.messages.push(n),this.emit("message",n),this.config.onMessage?.(n),n.sender!=="visitor"&&!this.isOpen&&(this.config.autoOpenOnMessage??!0)&&this.setOpen(!0)}n.sender!=="visitor"&&this.emit("typing",{isTyping:!1});break;case"typing":let r=e.data;r.sender!=="visitor"&&this.emit("typing",{isTyping:r.isTyping});break;case"presence":this.session&&(this.session.operatorOnline=e.data.online),this.emit("presence",e.data);break;case"ai_takeover":this.emit("aiTakeover",e.data);break;case"read":let o=e.data;if(this.session)for(let c of this.session.messages)o.messageIds.includes(c.id)&&(c.status=o.status,o.deliveredAt&&(c.deliveredAt=o.deliveredAt),o.readAt&&(c.readAt=o.readAt));this.emit("read",o);break;case"message_edited":if(this.session){let c=e.data,f=this.session.messages.findIndex(l=>l.id===c.messageId);if(f>=0){let l=this.session.messages[f];l.content=c.content,l.editedAt=c.editedAt??new Date().toISOString(),this.emit("message",l)}}break;case"message_deleted":if(this.session){let c=e.data,f=this.session.messages.findIndex(l=>l.id===c.messageId);if(f>=0){let l=this.session.messages[f];l.deletedAt=c.deletedAt??new Date().toISOString(),this.emit("message",l)}}break;case"event":let i=e.data;this.emitCustomEvent(i);break;case"version_warning":let d=e.data;this.handleVersionWarning(d);break;case"config_update":let s=e.data;s.trackedElements&&(this.setupTrackedElements(s.trackedElements),this.emit("configUpdate",s));break;case"screenshot_request":let u=e.data;this.handleScreenshotRequest(u);break}}handleVersionWarning(e){let n="[PocketPing]",r=e.upgradeUrl?` Upgrade: ${e.upgradeUrl}`:" Update your widget to the latest version.";switch(e.severity){case"error":console.error(`${n} \u{1F6A8} VERSION ERROR: ${e.message}${r}`),console.error(`${n} Current: ${e.currentVersion}, Required: ${e.minVersion||"unknown"}`);break;case"warning":console.warn(`${n} \u26A0\uFE0F VERSION WARNING: ${e.message}${r}`),console.warn(`${n} Current: ${e.currentVersion}, Latest: ${e.latestVersion||"unknown"}`);break;case"info":console.info(`${n} \u2139\uFE0F ${e.message}`);break}this.emit("versionWarning",e),this.config.onVersionWarning?.(e),e.canContinue||(console.error(`${n} Widget is incompatible with backend. Please update immediately.`),this.disconnect())}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.warn("[PocketPing] Max reconnect attempts reached, trying SSE"),this.connectSSE();return}let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.connectWebSocket()},e)}startPolling(){let e=async()=>{if(this.session){try{let n=this.getLastEventTimestamp(),r=await this.fetchMessages(n??void 0);await this.pollScreenshotRequests(),this.pollingFailures=0;for(let o of r){let i=this.session.messages.findIndex(d=>d.id===o.id);if(i>=0){let d=this.session.messages[i],s=!1;o.status&&o.status!==d.status&&(d.status=o.status,s=!0,o.deliveredAt&&(d.deliveredAt=o.deliveredAt),o.readAt&&(d.readAt=o.readAt),this.emit("read",{messageIds:[o.id],status:o.status})),o.content!==void 0&&o.content!==d.content&&(d.content=o.content,s=!0),o.editedAt!==void 0&&o.editedAt!==d.editedAt&&(d.editedAt=o.editedAt,s=!0),o.deletedAt!==void 0&&o.deletedAt!==d.deletedAt&&(d.deletedAt=o.deletedAt,s=!0),o.replyTo!==void 0&&(d.replyTo=o.replyTo,s=!0),o.attachments!==void 0&&(d.attachments=o.attachments,s=!0),s&&this.emit("message",d)}else this.session.messages.push(o),this.emit("message",o),this.config.onMessage?.(o),o.sender!=="visitor"&&!this.isOpen&&(this.config.autoOpenOnMessage??!0)&&this.setOpen(!0)}}catch(n){if(this.pollingFailures++,console.error("[PocketPing] \u274C Polling error:",n),(this.pollingFailures<=3||this.pollingFailures%3===0)&&console.warn(`[PocketPing] Polling failed (${this.pollingFailures}/${this.maxPollingFailures})`),this.pollingFailures>=this.maxPollingFailures){console.error("[PocketPing] Polling disabled after too many failures. Real-time updates unavailable."),this.emit("pollingDisabled",{failures:this.pollingFailures});return}}if(this.session){let n=this.pollingFailures>0?Math.min(2e3*Math.pow(2,this.pollingFailures-1),3e4):2e3;this.pollingTimeout=setTimeout(e,n)}}};this.pollingTimeout=setTimeout(e,500)}stopPolling(){this.pollingTimeout&&(clearTimeout(this.pollingTimeout),this.pollingTimeout=null),this.pollingFailures=0}setupUnloadListeners(){console.log("[PocketPing] Setting up unload listeners"),this.boundHandleUnload=()=>{console.log("[PocketPing] beforeunload/pagehide fired"),this.notifyDisconnect()},window.addEventListener("beforeunload",this.boundHandleUnload),window.addEventListener("pagehide",this.boundHandleUnload),this.boundHandleVisibilityChange=()=>{document.visibilityState==="hidden"?this.sendVisibilityPing("hidden"):document.visibilityState==="visible"&&this.sendVisibilityPing("visible")},document.addEventListener("visibilitychange",this.boundHandleVisibilityChange)}cleanupUnloadListeners(){this.boundHandleUnload&&(window.removeEventListener("beforeunload",this.boundHandleUnload),window.removeEventListener("pagehide",this.boundHandleUnload),this.boundHandleUnload=null),this.boundHandleVisibilityChange&&(document.removeEventListener("visibilitychange",this.boundHandleVisibilityChange),this.boundHandleVisibilityChange=null)}notifyDisconnect(){if(console.log("[PocketPing] notifyDisconnect called",{disconnectNotified:this.disconnectNotified,hasSession:!!this.session,sessionId:this.session?.sessionId}),this.disconnectNotified||!this.session){console.log("[PocketPing] Skipping disconnect notification (already notified or no session)");return}this.disconnectNotified=!0;let e=this.connectedAt?Math.round((Date.now()-this.connectedAt)/1e3):0,n=this.config.endpoint.replace(/\/$/,"")+"/disconnect",r=JSON.stringify({sessionId:this.session.sessionId,duration:e,reason:"page_unload"});if(console.log("[PocketPing] Sending disconnect beacon to:",n,"data:",r),navigator.sendBeacon){let o=new Blob([r],{type:"application/json"}),i=navigator.sendBeacon(n,o);console.log("[PocketPing] sendBeacon result:",i)}else try{let o=new XMLHttpRequest;o.open("POST",n,!1),o.setRequestHeader("Content-Type","application/json"),o.send(r)}catch{}}sendVisibilityPing(e){if(!this.session)return;let n=this.config.endpoint.replace(/\/$/,"")+"/visibility",r=JSON.stringify({sessionId:this.session.sessionId,state:e,timestamp:Date.now()});if(e==="hidden"&&navigator.sendBeacon){let o=new Blob([r],{type:"application/json"});navigator.sendBeacon(n,o)}else fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!0}).catch(()=>{})}async fetch(e,n){let r=this.config.endpoint.replace(/\/$/,"")+e,o=await fetch(r,{...n,headers:{"Content-Type":"application/json","X-PocketPing-Version":$t,...n.headers}});if(this.checkVersionHeaders(o),!o.ok){let i=await o.text();throw new Error(`PocketPing API error: ${o.status} ${i}`)}return o.json()}checkVersionHeaders(e){let n=e.headers.get("X-PocketPing-Version-Status"),r=e.headers.get("X-PocketPing-Min-Version"),o=e.headers.get("X-PocketPing-Latest-Version"),i=e.headers.get("X-PocketPing-Version-Message");if(!n||n==="ok")return;let d="info",s=!0;n==="deprecated"?d="warning":n==="unsupported"?(d="error",s=!1):n==="outdated"&&(d="info");let u={severity:d,message:i||`Widget version ${$t} is ${n}`,currentVersion:$t,minVersion:r||void 0,latestVersion:o||void 0,canContinue:s,upgradeUrl:"https://docs.pocketping.io/widget/installation"};this.handleVersionWarning(u)}getOrCreateVisitorId(){let e="pocketping_visitor_id",n=localStorage.getItem(e);return n||(n=this.generateId(),localStorage.setItem(e,n)),n}getStoredSessionId(){return localStorage.getItem("pocketping_session_id")}storeSessionId(e){localStorage.setItem("pocketping_session_id",e)}getStoredIdentity(){try{let e=localStorage.getItem("pocketping_user_identity");return e?JSON.parse(e):null}catch{return null}}storeIdentity(e){localStorage.setItem("pocketping_user_identity",JSON.stringify(e))}clearIdentity(){localStorage.removeItem("pocketping_user_identity")}generateId(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}async pollScreenshotRequests(){if(this.session)try{let e=await this.fetch(`/screenshot/requests?sessionId=${this.session.sessionId}`,{method:"GET"});for(let n of e.requests||[])this.handleScreenshotRequest(n)}catch{}}async handleScreenshotRequest(e){console.log("[PocketPing] Screenshot requested by",e.requestedBy,"via",e.requestedFrom,e.silent?"(silent)":"");try{let n=await this.captureScreenshot(),r=await this.fetch("/screenshot/upload",{method:"POST",body:JSON.stringify({sessionId:this.session?.sessionId,requestId:e.requestId})}),o=await fetch(r.uploadUrl,{method:"PUT",body:n,headers:{"Content-Type":"image/png"}});if(!o.ok)throw new Error(`Upload failed: ${o.status}`);await this.fetch("/screenshot/upload/complete",{method:"POST",body:JSON.stringify({sessionId:this.session?.sessionId,requestId:e.requestId,attachmentId:r.attachmentId,size:n.size})}),console.log("[PocketPing] Screenshot captured and uploaded successfully")}catch(n){console.error("[PocketPing] Screenshot capture failed:",n)}}async captureScreenshot(){let e=await this.loadHtml2Canvas(),n=document.getElementById("pocketping-widget"),r=document.getElementById("pocketping-toggle"),o=!1,i=!1;n&&(o=n.style.display!=="none",n.style.display="none"),r&&(i=r.style.display!=="none",r.style.display="none");try{let d=await e(document.documentElement,{width:window.innerWidth,height:window.innerHeight,x:window.scrollX,y:window.scrollY,windowWidth:window.innerWidth,windowHeight:window.innerHeight,logging:!1,useCORS:!0,allowTaint:!0});return new Promise((s,u)=>{d.toBlob(c=>{c?s(c):u(new Error("Failed to create blob from canvas"))},"image/png",.9)})}finally{n&&o&&(n.style.display=""),r&&i&&(r.style.display="")}}async loadHtml2Canvas(){let e=window;return typeof e.html2canvas<"u"?e.html2canvas:new Promise((n,r)=>{let o=document.createElement("script");o.src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js",o.onload=()=>{let i=window;typeof i.html2canvas<"u"?n(i.html2canvas):r(new Error("html2canvas failed to load"))},o.onerror=()=>r(new Error("Failed to load html2canvas from CDN")),document.head.appendChild(o)})}};var P=null,ie=null,Vd="https://app.pocketping.io/api/widget";function ln(t){if(P)return console.warn("[PocketPing] Already initialized"),P;let e=t.endpoint;if(!e&&t.projectId&&(e=`${Vd}/${t.projectId}`),!e)throw new Error("[PocketPing] endpoint or projectId is required");let n={...t,endpoint:e};return P=new ht(n),ie=document.createElement("div"),ie.id="pocketping-container",document.body.appendChild(ie),kt(Ct(Gr,{client:P,config:t}),ie),P.connect().catch(r=>{console.error("[PocketPing] Failed to connect:",r)}),P}function zr(){ie&&(kt(null,ie),ie.remove(),ie=null),P&&(P.disconnect(),P=null)}function Kr(){P?.setOpen(!0)}function qr(){P?.setOpen(!1)}function Xr(){P?.toggleOpen()}function Yr(t,e){if(!P)throw new Error("[PocketPing] Not initialized");return P.sendMessage(t,e)}async function Jr(t,e){if(!P)throw new Error("[PocketPing] Not initialized");return P.uploadFile(t,e)}async function Zr(t,e){if(!P)throw new Error("[PocketPing] Not initialized");return P.uploadFiles(t,e)}function Qr(t,e,n){if(!P){console.warn("[PocketPing] Not initialized, cannot trigger event");return}P.trigger(t,e,n)}function eo(t){if(!P){console.warn("[PocketPing] Not initialized, cannot setup tracked elements");return}P.setupTrackedElements(t)}function to(){return P?.getTrackedElements()||[]}function no(t,e){return P?P.onEvent(t,e):(console.warn("[PocketPing] Not initialized, cannot subscribe to event"),()=>{})}function ro(t,e){P?.offEvent(t,e)}async function oo(t){if(!P)throw new Error("[PocketPing] Not initialized");return P.identify(t)}async function io(t){if(!P){console.warn("[PocketPing] Not initialized");return}return P.reset(t)}function so(){return P?.getIdentity()||null}function ao(t,e){return P?P.on(t,e):(console.warn("[PocketPing] Not initialized, cannot subscribe to event"),()=>{})}if(typeof document<"u"){let t=document.currentScript;if(t){let e=t.dataset.projectId,n=t.dataset.endpoint;(e||n)&&ln({projectId:e,endpoint:n,theme:t.dataset.theme||"auto",position:t.dataset.position||"bottom-right"})}}var Gd={init:ln,destroy:zr,open:Kr,close:qr,toggle:Xr,sendMessage:Yr,uploadFile:Jr,uploadFiles:Zr,trigger:Qr,onEvent:no,offEvent:ro,on:ao,identify:oo,reset:io,getIdentity:so,setupTrackedElements:eo,getTrackedElements:to};return Oo(Wd);})();
|
|
1619
|
+
`,setTimeout(()=>{l&&this.inspectorMode&&(l.innerHTML=$,document.getElementById("pp-inspector-exit")?.addEventListener("click",()=>{this.disableInspectorMode()}))},2e3)}console.info(`[PocketPing] \u{1F4CC} Selector captured: ${f}`)};document.addEventListener("mouseover",i,!0),document.addEventListener("mouseout",d,!0),document.addEventListener("click",s,!0),this.inspectorCleanup=()=>{document.removeEventListener("mouseover",i,!0),document.removeEventListener("mouseout",d,!0),document.removeEventListener("click",s,!0),e.remove(),r&&r.classList.remove("pp-inspector-highlight")},document.getElementById("pp-inspector-exit")?.addEventListener("click",()=>{this.disableInspectorMode()})}disableInspectorMode(){this.inspectorMode&&(this.inspectorMode=!1,this.inspectorCleanup&&(this.inspectorCleanup(),this.inspectorCleanup=null),console.info("[PocketPing] Inspector mode disabled"),this.emit("inspectorDisabled",null))}isInspectorModeActive(){return this.inspectorMode}connectRealtime(){if(this.session){if(this.connectionMode==="polling"){this.startPolling();return}if(this.connectionMode==="sse"){this.connectSSE();return}this.connectWebSocket()}}connectWebSocket(){if(!this.session)return;let e=this.config.endpoint.replace(/^http/,"ws").replace(/\/$/,"")+`/stream?sessionId=${this.session.sessionId}`;try{this.ws=new WebSocket(e),this.wsConnectedAt=Date.now();let n=setTimeout(()=>{console.warn("[PocketPing] \u23F1\uFE0F WebSocket timeout - trying SSE"),this.ws&&this.ws.readyState!==WebSocket.OPEN&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onopen=null,this.ws.close(),this.ws=null,this.connectSSE())},5e3);this.ws.onopen=()=>{clearTimeout(n),this.connectionMode="ws",this.reconnectAttempts=0,this.wsConnectedAt=Date.now(),this.emit("wsConnected",null)},this.ws.onmessage=r=>{try{let o=JSON.parse(r.data);this.handleRealtimeEvent(o)}catch(o){console.error("[PocketPing] Failed to parse WS message:",o)}},this.ws.onclose=()=>{clearTimeout(n),this.emit("wsDisconnected",null),this.handleWsFailure()},this.ws.onerror=()=>{clearTimeout(n)}}catch{console.warn("[PocketPing] WebSocket unavailable - trying SSE"),this.connectSSE()}}connectSSE(){if(!this.session)return;let e=new URLSearchParams({sessionId:this.session.sessionId}),n=this.getLastEventTimestamp();n&&e.set("after",n);let r=this.config.endpoint.replace(/\/$/,"")+`/stream?${e.toString()}`;try{this.sse=new EventSource(r);let o=setTimeout(()=>{console.warn("[PocketPing] \u23F1\uFE0F SSE timeout - falling back to polling"),this.sse&&this.sse.readyState!==EventSource.OPEN&&(this.sse.close(),this.sse=null,this.connectionMode="polling",this.startPolling())},5e3);this.sse.onopen=()=>{clearTimeout(o),this.connectionMode="sse",this.emit("sseConnected",null)},this.sse.addEventListener("message",i=>{try{let d=JSON.parse(i.data);this.handleRealtimeEvent(d)}catch(d){console.error("[PocketPing] Failed to parse SSE message:",d)}}),this.sse.addEventListener("screenshot_request",i=>{try{let d=JSON.parse(i.data);this.handleRealtimeEvent(d)}catch(d){console.error("[PocketPing] Failed to parse SSE screenshot_request:",d)}}),this.sse.addEventListener("connected",()=>{}),this.sse.onerror=()=>{clearTimeout(o),console.warn("[PocketPing] \u274C SSE error - falling back to polling"),this.sse&&(this.sse.close(),this.sse=null),this.connectionMode="polling",this.startPolling()}}catch{console.warn("[PocketPing] SSE unavailable - falling back to polling"),this.connectionMode="polling",this.startPolling()}}handleWsFailure(){if(Date.now()-this.wsConnectedAt<this.quickFailureThreshold){console.info("[PocketPing] WebSocket failed quickly - trying SSE"),this.connectSSE();return}this.scheduleReconnect()}handleRealtimeEvent(e){this.handleWebSocketEvent(e)}getLastEventTimestamp(){if(!this.session)return null;let e=null;for(let n of this.session.messages){let r=[n.timestamp,n.editedAt,n.deletedAt,n.deliveredAt,n.readAt].filter(Boolean).map(o=>new Date(o)).filter(o=>!isNaN(o.getTime()));for(let o of r)(!e||o>e)&&(e=o)}return e?e.toISOString():null}handleWebSocketEvent(e){switch(e.type){case"message":let n=e.data;if(this.session){let c=this.session.messages.findIndex(f=>f.id===n.id);if(c<0&&n.sender==="visitor"&&(c=this.session.messages.findIndex(f=>f.id.startsWith("temp-")&&f.content===n.content&&f.sender==="visitor"),c>=0&&(this.session.messages[c].id=n.id)),c<0&&n.sender!=="visitor"){let f=new Date(n.timestamp).getTime();c=this.session.messages.findIndex(l=>l.sender===n.sender&&l.content===n.content&&Math.abs(new Date(l.timestamp).getTime()-f)<2e3)}if(c>=0){let f=this.session.messages[c],l=!1;n.status&&n.status!==f.status&&(f.status=n.status,l=!0,n.deliveredAt&&(f.deliveredAt=n.deliveredAt),n.readAt&&(f.readAt=n.readAt),this.emit("read",{messageIds:[n.id],status:n.status})),n.content!==void 0&&n.content!==f.content&&(f.content=n.content,l=!0),n.editedAt!==void 0&&n.editedAt!==f.editedAt&&(f.editedAt=n.editedAt,l=!0),n.deletedAt!==void 0&&n.deletedAt!==f.deletedAt&&(f.deletedAt=n.deletedAt,l=!0),n.replyTo!==void 0&&(f.replyTo=n.replyTo,l=!0),n.attachments!==void 0&&(f.attachments=n.attachments,l=!0),l&&this.emit("message",f)}else this.session.messages.push(n),this.emit("message",n),this.config.onMessage?.(n),n.sender!=="visitor"&&!this.isOpen&&(this.config.autoOpenOnMessage??!0)&&this.setOpen(!0)}n.sender!=="visitor"&&this.emit("typing",{isTyping:!1});break;case"typing":let r=e.data;r.sender!=="visitor"&&this.emit("typing",{isTyping:r.isTyping});break;case"presence":this.session&&(this.session.operatorOnline=e.data.online),this.emit("presence",e.data);break;case"ai_takeover":this.emit("aiTakeover",e.data);break;case"read":let o=e.data;if(this.session)for(let c of this.session.messages)o.messageIds.includes(c.id)&&(c.status=o.status,o.deliveredAt&&(c.deliveredAt=o.deliveredAt),o.readAt&&(c.readAt=o.readAt));this.emit("read",o);break;case"message_edited":if(this.session){let c=e.data,f=this.session.messages.findIndex(l=>l.id===c.messageId);if(f>=0){let l=this.session.messages[f];l.content=c.content,l.editedAt=c.editedAt??new Date().toISOString(),this.emit("message",l)}}break;case"message_deleted":if(this.session){let c=e.data,f=this.session.messages.findIndex(l=>l.id===c.messageId);if(f>=0){let l=this.session.messages[f];l.deletedAt=c.deletedAt??new Date().toISOString(),this.emit("message",l)}}break;case"event":let i=e.data;this.emitCustomEvent(i);break;case"version_warning":let d=e.data;this.handleVersionWarning(d);break;case"config_update":let s=e.data;s.trackedElements&&(this.setupTrackedElements(s.trackedElements),this.emit("configUpdate",s));break;case"screenshot_request":let u=e.data;this.handleScreenshotRequest(u);break}}handleVersionWarning(e){let n="[PocketPing]",r=e.upgradeUrl?` Upgrade: ${e.upgradeUrl}`:" Update your widget to the latest version.";switch(e.severity){case"error":console.error(`${n} \u{1F6A8} VERSION ERROR: ${e.message}${r}`),console.error(`${n} Current: ${e.currentVersion}, Required: ${e.minVersion||"unknown"}`);break;case"warning":console.warn(`${n} \u26A0\uFE0F VERSION WARNING: ${e.message}${r}`),console.warn(`${n} Current: ${e.currentVersion}, Latest: ${e.latestVersion||"unknown"}`);break;case"info":console.info(`${n} \u2139\uFE0F ${e.message}`);break}this.emit("versionWarning",e),this.config.onVersionWarning?.(e),e.canContinue||(console.error(`${n} Widget is incompatible with backend. Please update immediately.`),this.disconnect())}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.warn("[PocketPing] Max reconnect attempts reached, trying SSE"),this.connectSSE();return}let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.connectWebSocket()},e)}startPolling(){let e=async()=>{if(this.session){try{let n=this.getLastEventTimestamp(),r=await this.fetchMessages(n??void 0);await this.pollScreenshotRequests(),this.pollingFailures=0;for(let o of r){let i=this.session.messages.findIndex(d=>d.id===o.id);if(i>=0){let d=this.session.messages[i],s=!1;o.status&&o.status!==d.status&&(d.status=o.status,s=!0,o.deliveredAt&&(d.deliveredAt=o.deliveredAt),o.readAt&&(d.readAt=o.readAt),this.emit("read",{messageIds:[o.id],status:o.status})),o.content!==void 0&&o.content!==d.content&&(d.content=o.content,s=!0),o.editedAt!==void 0&&o.editedAt!==d.editedAt&&(d.editedAt=o.editedAt,s=!0),o.deletedAt!==void 0&&o.deletedAt!==d.deletedAt&&(d.deletedAt=o.deletedAt,s=!0),o.replyTo!==void 0&&(d.replyTo=o.replyTo,s=!0),o.attachments!==void 0&&(d.attachments=o.attachments,s=!0),s&&this.emit("message",d)}else this.session.messages.push(o),this.emit("message",o),this.config.onMessage?.(o),o.sender!=="visitor"&&!this.isOpen&&(this.config.autoOpenOnMessage??!0)&&this.setOpen(!0)}}catch(n){if(this.pollingFailures++,console.error("[PocketPing] \u274C Polling error:",n),(this.pollingFailures<=3||this.pollingFailures%3===0)&&console.warn(`[PocketPing] Polling failed (${this.pollingFailures}/${this.maxPollingFailures})`),this.pollingFailures>=this.maxPollingFailures){console.error("[PocketPing] Polling disabled after too many failures. Real-time updates unavailable."),this.emit("pollingDisabled",{failures:this.pollingFailures});return}}if(this.session){let n=this.pollingFailures>0?Math.min(2e3*Math.pow(2,this.pollingFailures-1),3e4):2e3;this.pollingTimeout=setTimeout(e,n)}}};this.pollingTimeout=setTimeout(e,500)}stopPolling(){this.pollingTimeout&&(clearTimeout(this.pollingTimeout),this.pollingTimeout=null),this.pollingFailures=0}setupUnloadListeners(){console.log("[PocketPing] Setting up unload listeners"),this.boundHandleUnload=()=>{console.log("[PocketPing] beforeunload/pagehide fired"),this.notifyDisconnect()},window.addEventListener("beforeunload",this.boundHandleUnload),window.addEventListener("pagehide",this.boundHandleUnload),this.boundHandleVisibilityChange=()=>{document.visibilityState==="hidden"?this.sendVisibilityPing("hidden"):document.visibilityState==="visible"&&this.sendVisibilityPing("visible")},document.addEventListener("visibilitychange",this.boundHandleVisibilityChange)}cleanupUnloadListeners(){this.boundHandleUnload&&(window.removeEventListener("beforeunload",this.boundHandleUnload),window.removeEventListener("pagehide",this.boundHandleUnload),this.boundHandleUnload=null),this.boundHandleVisibilityChange&&(document.removeEventListener("visibilitychange",this.boundHandleVisibilityChange),this.boundHandleVisibilityChange=null)}notifyDisconnect(){if(console.log("[PocketPing] notifyDisconnect called",{disconnectNotified:this.disconnectNotified,hasSession:!!this.session,sessionId:this.session?.sessionId}),this.disconnectNotified||!this.session){console.log("[PocketPing] Skipping disconnect notification (already notified or no session)");return}this.disconnectNotified=!0;let e=this.connectedAt?Math.round((Date.now()-this.connectedAt)/1e3):0,n=this.config.endpoint.replace(/\/$/,"")+"/disconnect",r=JSON.stringify({sessionId:this.session.sessionId,duration:e,reason:"page_unload"});if(console.log("[PocketPing] Sending disconnect beacon to:",n,"data:",r),navigator.sendBeacon){let o=new Blob([r],{type:"application/json"}),i=navigator.sendBeacon(n,o);console.log("[PocketPing] sendBeacon result:",i)}else try{let o=new XMLHttpRequest;o.open("POST",n,!1),o.setRequestHeader("Content-Type","application/json"),o.send(r)}catch{}}sendVisibilityPing(e){if(!this.session)return;let n=this.config.endpoint.replace(/\/$/,"")+"/visibility",r=JSON.stringify({sessionId:this.session.sessionId,state:e,timestamp:Date.now()});if(e==="hidden"&&navigator.sendBeacon){let o=new Blob([r],{type:"application/json"});navigator.sendBeacon(n,o)}else fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!0}).catch(()=>{})}async fetch(e,n){let r=this.config.endpoint.replace(/\/$/,"")+e,o=await fetch(r,{...n,headers:{"Content-Type":"application/json","X-PocketPing-Version":$t,...n.headers}});if(this.checkVersionHeaders(o),!o.ok){let i=await o.text();throw new Error(`PocketPing API error: ${o.status} ${i}`)}return o.json()}checkVersionHeaders(e){let n=e.headers.get("X-PocketPing-Version-Status"),r=e.headers.get("X-PocketPing-Min-Version"),o=e.headers.get("X-PocketPing-Latest-Version"),i=e.headers.get("X-PocketPing-Version-Message");if(!n||n==="ok")return;let d="info",s=!0;n==="deprecated"?d="warning":n==="unsupported"?(d="error",s=!1):n==="outdated"&&(d="info");let u={severity:d,message:i||`Widget version ${$t} is ${n}`,currentVersion:$t,minVersion:r||void 0,latestVersion:o||void 0,canContinue:s,upgradeUrl:"https://docs.pocketping.io/widget/installation"};this.handleVersionWarning(u)}getOrCreateVisitorId(){let e="pocketping_visitor_id",n=localStorage.getItem(e);return n||(n=this.generateId(),localStorage.setItem(e,n)),n}getStoredSessionId(){return localStorage.getItem("pocketping_session_id")}storeSessionId(e){localStorage.setItem("pocketping_session_id",e)}getStoredIdentity(){try{let e=localStorage.getItem("pocketping_user_identity");return e?JSON.parse(e):null}catch{return null}}storeIdentity(e){localStorage.setItem("pocketping_user_identity",JSON.stringify(e))}clearIdentity(){localStorage.removeItem("pocketping_user_identity")}generateId(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}async pollScreenshotRequests(){if(this.session)try{let e=await this.fetch(`/screenshot/requests?sessionId=${this.session.sessionId}`,{method:"GET"});for(let n of e.requests||[])this.handleScreenshotRequest(n)}catch{}}async handleScreenshotRequest(e){console.log("[PocketPing] Screenshot requested by",e.requestedBy,"via",e.requestedFrom,e.silent?"(silent)":"");try{let n=await this.captureScreenshot(),r=await this.fetch("/screenshot/upload",{method:"POST",body:JSON.stringify({sessionId:this.session?.sessionId,requestId:e.requestId})}),o=await fetch(r.uploadUrl,{method:"PUT",body:n,headers:{"Content-Type":"image/png"}});if(!o.ok)throw new Error(`Upload failed: ${o.status}`);await this.fetch("/screenshot/upload/complete",{method:"POST",body:JSON.stringify({sessionId:this.session?.sessionId,requestId:e.requestId,attachmentId:r.attachmentId,size:n.size})}),console.log("[PocketPing] Screenshot captured and uploaded successfully")}catch(n){console.error("[PocketPing] Screenshot capture failed:",n)}}async captureScreenshot(){let e=await this.loadHtml2Canvas(),n=document.getElementById("pocketping-widget"),r=document.getElementById("pocketping-toggle"),o=!1,i=!1;n&&(o=n.style.display!=="none",n.style.display="none"),r&&(i=r.style.display!=="none",r.style.display="none");try{let d=await e(document.documentElement,{width:window.innerWidth,height:window.innerHeight,x:window.scrollX,y:window.scrollY,windowWidth:window.innerWidth,windowHeight:window.innerHeight,logging:!1,useCORS:!0,allowTaint:!0});return new Promise((s,u)=>{d.toBlob(c=>{c?s(c):u(new Error("Failed to create blob from canvas"))},"image/png",.9)})}finally{n&&o&&(n.style.display=""),r&&i&&(r.style.display="")}}async loadHtml2Canvas(){let e=window;return typeof e.html2canvas<"u"?e.html2canvas:new Promise((n,r)=>{let o=document.createElement("script");o.src="https://cdn.jsdelivr.net/npm/html2canvas-pro@1.6.6/dist/html2canvas-pro.min.js",o.onload=()=>{let i=window;typeof i.html2canvas<"u"?n(i.html2canvas):r(new Error("html2canvas-pro failed to load"))},o.onerror=()=>r(new Error("Failed to load html2canvas-pro from CDN")),document.head.appendChild(o)})}};var P=null,ie=null,Vd="https://app.pocketping.io/api/widget";function ln(t){if(P)return console.warn("[PocketPing] Already initialized"),P;let e=t.endpoint;if(!e&&t.projectId&&(e=`${Vd}/${t.projectId}`),!e)throw new Error("[PocketPing] endpoint or projectId is required");let n={...t,endpoint:e};return P=new ht(n),ie=document.createElement("div"),ie.id="pocketping-container",document.body.appendChild(ie),kt(Ct(Gr,{client:P,config:t}),ie),P.connect().catch(r=>{console.error("[PocketPing] Failed to connect:",r)}),P}function zr(){ie&&(kt(null,ie),ie.remove(),ie=null),P&&(P.disconnect(),P=null)}function Kr(){P?.setOpen(!0)}function qr(){P?.setOpen(!1)}function Xr(){P?.toggleOpen()}function Yr(t,e){if(!P)throw new Error("[PocketPing] Not initialized");return P.sendMessage(t,e)}async function Jr(t,e){if(!P)throw new Error("[PocketPing] Not initialized");return P.uploadFile(t,e)}async function Zr(t,e){if(!P)throw new Error("[PocketPing] Not initialized");return P.uploadFiles(t,e)}function Qr(t,e,n){if(!P){console.warn("[PocketPing] Not initialized, cannot trigger event");return}P.trigger(t,e,n)}function eo(t){if(!P){console.warn("[PocketPing] Not initialized, cannot setup tracked elements");return}P.setupTrackedElements(t)}function to(){return P?.getTrackedElements()||[]}function no(t,e){return P?P.onEvent(t,e):(console.warn("[PocketPing] Not initialized, cannot subscribe to event"),()=>{})}function ro(t,e){P?.offEvent(t,e)}async function oo(t){if(!P)throw new Error("[PocketPing] Not initialized");return P.identify(t)}async function io(t){if(!P){console.warn("[PocketPing] Not initialized");return}return P.reset(t)}function so(){return P?.getIdentity()||null}function ao(t,e){return P?P.on(t,e):(console.warn("[PocketPing] Not initialized, cannot subscribe to event"),()=>{})}if(typeof document<"u"){let t=document.currentScript;if(t){let e=t.dataset.projectId,n=t.dataset.endpoint;(e||n)&&ln({projectId:e,endpoint:n,theme:t.dataset.theme||"auto",position:t.dataset.position||"bottom-right"})}}var Gd={init:ln,destroy:zr,open:Kr,close:qr,toggle:Xr,sendMessage:Yr,uploadFile:Jr,uploadFiles:Zr,trigger:Qr,onEvent:no,offEvent:ro,on:ao,identify:oo,reset:io,getIdentity:so,setupTrackedElements:eo,getTrackedElements:to};return Oo(Wd);})();
|