@blockspark/chat-widget 1.0.16 → 1.0.18

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.
Files changed (42) hide show
  1. package/README.md +28 -28
  2. package/dist/{ChatWidget-CFvb5g7s.js → ChatWidget-Bs0XV_7i.js} +31 -36
  3. package/dist/ChatWidget-Bs0XV_7i.js.map +1 -0
  4. package/dist/ChatWidget-PcqRrOmi.cjs +2 -0
  5. package/dist/ChatWidget-PcqRrOmi.cjs.map +1 -0
  6. package/dist/adapters/vue/useChatMode.d.ts +1 -1
  7. package/dist/adapters/vue/useChatMode.d.ts.map +1 -1
  8. package/dist/components/ChatWidget.d.ts +1 -5
  9. package/dist/components/ChatWidget.d.ts.map +1 -1
  10. package/dist/core/stateManager.d.ts.map +1 -1
  11. package/dist/core/types.d.ts +0 -2
  12. package/dist/core/types.d.ts.map +1 -1
  13. package/dist/entry/vite.d.ts +1 -1
  14. package/dist/hooks/useChatMode.d.ts +1 -1
  15. package/dist/hooks/useChatMode.d.ts.map +1 -1
  16. package/dist/index.cjs.js +1 -1
  17. package/dist/index.cjs.js.map +1 -1
  18. package/dist/index.d.ts +5 -5
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.esm.js +39 -22
  21. package/dist/index.esm.js.map +1 -1
  22. package/dist/nuxt.cjs.js +1 -1
  23. package/dist/nuxt.esm.js +2 -2
  24. package/dist/sanitize-C8MB41vY.cjs +4 -0
  25. package/dist/sanitize-C8MB41vY.cjs.map +1 -0
  26. package/dist/{sanitize-NEykcppO.js → sanitize-Cm1kskSD.js} +274 -1267
  27. package/dist/sanitize-Cm1kskSD.js.map +1 -0
  28. package/dist/services/chatService.d.ts.map +1 -1
  29. package/dist/services/dialogflowBackendService.d.ts +36 -0
  30. package/dist/services/dialogflowBackendService.d.ts.map +1 -0
  31. package/dist/styles.css +1 -1
  32. package/dist/types.d.ts +1 -1
  33. package/dist/types.d.ts.map +1 -1
  34. package/dist/vue.cjs.js +1 -1
  35. package/dist/vue.esm.js +2 -2
  36. package/package.json +2 -2
  37. package/dist/ChatWidget-CFvb5g7s.js.map +0 -1
  38. package/dist/ChatWidget-CdA7TymM.cjs +0 -2
  39. package/dist/ChatWidget-CdA7TymM.cjs.map +0 -1
  40. package/dist/sanitize-DRKcO9o5.cjs +0 -4
  41. package/dist/sanitize-DRKcO9o5.cjs.map +0 -1
  42. package/dist/sanitize-NEykcppO.js.map +0 -1
@@ -1,4 +0,0 @@
1
- "use strict";const e=crypto,t=e=>e instanceof CryptoKey,n=new TextEncoder,r=new TextDecoder;const o=e=>(e=>{let t=e;"string"==typeof t&&(t=n.encode(t));const r=[];for(let n=0;n<t.length;n+=32768)r.push(String.fromCharCode.apply(null,t.subarray(n,n+32768)));return btoa(r.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),s=e=>{let t=e;t instanceof Uint8Array&&(t=r.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class a extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}a.code="ERR_JOSE_GENERIC";(class extends a{constructor(e,t,n="unspecified",r="unspecified"){super(e,{cause:{claim:n,reason:r,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=r,this.payload=t}}).code="ERR_JWT_CLAIM_VALIDATION_FAILED";(class extends a{constructor(e,t,n="unspecified",r="unspecified"){super(e,{cause:{claim:n,reason:r,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=r,this.payload=t}}).code="ERR_JWT_EXPIRED";(class extends a{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}).code="ERR_JOSE_ALG_NOT_ALLOWED";class i extends a{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}i.code="ERR_JOSE_NOT_SUPPORTED";(class extends a{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends a{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class c extends a{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}c.code="ERR_JWS_INVALID";class l extends a{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}l.code="ERR_JWT_INVALID";(class extends a{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}).code="ERR_JWK_INVALID";(class extends a{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}).code="ERR_JWKS_INVALID";(class extends a{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}).code="ERR_JWKS_NO_MATCHING_KEY";(class extends a{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}).code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";(class extends a{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}).code="ERR_JWKS_TIMEOUT";function u(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function d(e,t){return e.name===t}function h(e){return parseInt(e.name.slice(4),10)}function p(e,t,...n){switch(t){case"HS256":case"HS384":case"HS512":{if(!d(e.algorithm,"HMAC"))throw u("HMAC");const n=parseInt(t.slice(2),10);if(h(e.algorithm.hash)!==n)throw u(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!d(e.algorithm,"RSASSA-PKCS1-v1_5"))throw u("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(h(e.algorithm.hash)!==n)throw u(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!d(e.algorithm,"RSA-PSS"))throw u("RSA-PSS");const n=parseInt(t.slice(2),10);if(h(e.algorithm.hash)!==n)throw u(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw u("Ed25519 or Ed448");break;case"Ed25519":if(!d(e.algorithm,"Ed25519"))throw u("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!d(e.algorithm,"ECDSA"))throw u("ECDSA");const n=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==n)throw u(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const n=t.pop();e+=`one of ${t.join(", ")}, or ${n}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,n)}function f(e,t,...n){if((n=n.filter(Boolean)).length>2){const t=n.pop();e+=`one of type ${n.join(", ")}, or ${t}.`}else 2===n.length?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}(class extends a{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}).code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";const m=(e,...t)=>f("Key must be ",e,...t);function g(e,t,...n){return f(`Key for the ${e} algorithm must be `,t,...n)}const y=e=>!!t(e)||"KeyObject"===e?.[Symbol.toStringTag],E=["CryptoKey"];function S(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let n=e;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}function w(e){return S(e)&&"string"==typeof e.kty}const A=async t=>{if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:n,keyUsages:r}=function(e){let t,n;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},n=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},n=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new i('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},n=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},n=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},n=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new i('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},n=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},n=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new i('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new i('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:n}}(t),o=[n,t.ext??!1,t.key_ops??r],s={...t};return delete s.alg,delete s.use,e.subtle.importKey("jwk",s,...o)},_=e=>s(e);let T;const b=e=>"KeyObject"===e?.[Symbol.toStringTag],R=async(e,t,n,r,o=!1)=>{let s=e.get(t);if(s?.[r])return s[r];const a=await A({...n,alg:r});return o&&Object.freeze(t),s?s[r]=a:e.set(t,{[r]:a}),a},I=(e,t)=>{if(b(e)){let n=e.export({format:"jwk"});return n.k?_(n.k):(T||(T=new WeakMap),R(T,e,n,t))}if(w(e)){if(e.k)return s(e.k);T||(T=new WeakMap);return R(T,e,e,t,!0)}return e},v=(e,t,n=0)=>{0===n&&(t.unshift(t.length),t.unshift(6));const r=e.indexOf(t[0],n);if(-1===r)return!1;const o=e.subarray(r,r+t.length);return o.length===t.length&&(o.every((e,n)=>e===t[n])||v(e,t,r+1))},C=e=>{switch(!0){case v(e,[42,134,72,206,61,3,1,7]):return"P-256";case v(e,[43,129,4,0,34]):return"P-384";case v(e,[43,129,4,0,35]):return"P-521";case v(e,[43,101,110]):return"X25519";case v(e,[43,101,111]):return"X448";case v(e,[43,101,112]):return"Ed25519";case v(e,[43,101,113]):return"Ed448";default:throw new i("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},k=(t,n,r)=>(async(t,n,r,o)=>{let s,a;const c=new Uint8Array(atob(r.replace(t,"")).split("").map(e=>e.charCodeAt(0)));switch(o){case"PS256":case"PS384":case"PS512":s={name:"RSA-PSS",hash:`SHA-${o.slice(-3)}`},a=["sign"];break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${o.slice(-3)}`},a=["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s={name:"RSA-OAEP",hash:`SHA-${parseInt(o.slice(-3),10)||1}`},a=["decrypt","unwrapKey"];break;case"ES256":s={name:"ECDSA",namedCurve:"P-256"},a=["sign"];break;case"ES384":s={name:"ECDSA",namedCurve:"P-384"},a=["sign"];break;case"ES512":s={name:"ECDSA",namedCurve:"P-521"},a=["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=C(c);s=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},a=["deriveBits"];break}case"Ed25519":s={name:"Ed25519"},a=["sign"];break;case"EdDSA":s={name:C(c)},a=["sign"];break;default:throw new i('Invalid or unsupported "alg" (Algorithm) value')}return e.subtle.importKey(n,c,s,!1,a)})(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",t,n);const N=e=>e?.[Symbol.toStringTag],D=(e,t,n)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(n))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${n}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},O=(e,t,n,r)=>{if(!(t instanceof Uint8Array)){if(r&&w(t)){if(function(e){return w(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&D(e,t,n))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!y(t))throw new TypeError(g(e,t,...E,"Uint8Array",r?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${N(t)} instances for symmetric algorithms must be of type "secret"`)}};function P(e,t,n,r){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?O(t,n,r,e):((e,t,n,r)=>{if(r&&w(t))switch(n){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&D(e,t,n))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&D(e,t,n))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!y(t))throw new TypeError(g(e,t,...E,r?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${N(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===n&&"public"===t.type)throw new TypeError(`${N(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===n&&"public"===t.type)throw new TypeError(`${N(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===n&&"private"===t.type)throw new TypeError(`${N(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===n&&"private"===t.type)throw new TypeError(`${N(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,n,r,e)}P.bind(void 0,!1);const x=P.bind(void 0,!0);const H=e=>Math.floor(e.getTime()/1e3),L=86400,M=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,W=e=>{const t=M.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const n=parseFloat(t[2]);let r;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":r=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":r=Math.round(60*n);break;case"hour":case"hours":case"hr":case"hrs":case"h":r=Math.round(3600*n);break;case"day":case"days":case"d":r=Math.round(n*L);break;case"week":case"weeks":case"w":r=Math.round(604800*n);break;default:r=Math.round(31557600*n)}return"-"===t[1]||"ago"===t[4]?-r:r},U=async(n,r,o)=>{const s=await async function(n,r,o){if(r=await I(r,n),t(r))return p(r,n,o),r;if(r instanceof Uint8Array){if(!n.startsWith("HS"))throw new TypeError(m(r,...E));return e.subtle.importKey("raw",r,{hash:`SHA-${n.slice(-3)}`,name:"HMAC"},!1,[o])}throw new TypeError(m(r,...E,"Uint8Array","JSON Web Key"))}(n,r,"sign");((e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:n}=t.algorithm;if("number"!=typeof n||n<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}})(n,s);const a=await e.subtle.sign(function(e,t){const n=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:n,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:n,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:n,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:n,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new i(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(n,s.algorithm),s,o);return new Uint8Array(a)};class K{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new c("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let n;for(const r of t){const e=Object.keys(r);if(n&&0!==n.size)for(const t of e){if(n.has(t))return!1;n.add(t)}else n=new Set(e)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new c("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...this._protectedHeader,...this._unprotectedHeader},a=function(e,t,n,r,o){if(void 0!==o.crit&&void 0===r?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||void 0===r.crit)return new Set;if(!Array.isArray(r.crit)||0===r.crit.length||r.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;s=void 0!==n?new Map([...Object.entries(n),...t.entries()]):t;for(const a of r.crit){if(!s.has(a))throw new i(`Extension Header Parameter "${a}" is not recognized`);if(void 0===o[a])throw new e(`Extension Header Parameter "${a}" is missing`);if(s.get(a)&&void 0===r[a])throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(r.crit)}(c,new Map([["b64",!0]]),t?.crit,this._protectedHeader,s);let l=!0;if(a.has("b64")&&(l=this._protectedHeader.b64,"boolean"!=typeof l))throw new c('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:u}=s;if("string"!=typeof u||!u)throw new c('JWS "alg" (Algorithm) Header Parameter missing or invalid');x(u,e,"sign");let d,h=this._payload;l&&(h=n.encode(o(h))),d=this._protectedHeader?n.encode(o(JSON.stringify(this._protectedHeader))):n.encode("");const p=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t);let r=0;for(const o of e)n.set(o,r),r+=o.length;return n}(d,n.encode("."),h),f=await U(u,e,p),m={signature:o(f),payload:""};return l&&(m.payload=r.decode(h)),this._unprotectedHeader&&(m.header=this._unprotectedHeader),this._protectedHeader&&(m.protected=r.decode(d)),m}}class ${constructor(e){this._flattened=new K(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const n=await this._flattened.sign(e,t);if(void 0===n.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}function j(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class F{constructor(e={}){if(!S(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:j("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:j("setNotBefore",H(e))}:this._payload={...this._payload,nbf:H(new Date)+W(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:j("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:j("setExpirationTime",H(e))}:this._payload={...this._payload,exp:H(new Date)+W(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:H(new Date)}:e instanceof Date?this._payload={...this._payload,iat:j("setIssuedAt",H(e))}:this._payload="string"==typeof e?{...this._payload,iat:j("setIssuedAt",H(new Date)+W(e))}:{...this._payload,iat:j("setIssuedAt",e)},this}}class z extends F{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new $(n.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new l("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}async function J(e){const t=Math.floor(Date.now()/1e3);let n=e.private_key;if(!n)throw new Error("Private key is missing from service account key");if(n=n.trim(),n.includes("-----BEGIN")){if(n=n.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),n.includes("BEGIN RSA PRIVATE KEY"))throw new Error("Private key is in PKCS#1 format (RSA PRIVATE KEY). Please download a new service account key from Google Cloud Console. The key should be in PKCS#8 format (PRIVATE KEY).");const e=n.match(/-----BEGIN PRIVATE KEY-----\n?([\s\S]*?)\n?-----END PRIVATE KEY-----/);if(e){const t=e[1].replace(/\s/g,"");if(!t.includes("\n")||t.length>64){n=`-----BEGIN PRIVATE KEY-----\n${t.match(/.{1,64}/g)?.join("\n")||t}\n-----END PRIVATE KEY-----`}}}else{const e=n.replace(/\s/g,"");n=`-----BEGIN PRIVATE KEY-----\n${e.match(/.{1,64}/g)?.join("\n")||e}\n-----END PRIVATE KEY-----`}try{const r=await async function(e,t){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return k(e,t)}(n,"RS256"),o=await new z({scope:"https://www.googleapis.com/auth/cloud-platform"}).setProtectedHeader({alg:"RS256"}).setIssuedAt(t).setExpirationTime(t+3600).setIssuer(e.client_email).setSubject(e.client_email).setAudience("https://oauth2.googleapis.com/token").sign(r),s=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o})});if(!s.ok){const e=await s.json();throw new Error(e.error_description||"Failed to get access token")}return(await s.json()).access_token}catch(r){if(r.message&&r.message.includes("pkcs8"))throw new Error("Invalid private key format. The service account key must be in PKCS#8 format. Please ensure your service account key JSON file has a properly formatted private_key field. If you downloaded the key from Google Cloud Console, it should already be in the correct format.");throw r}}async function B(e){if(e.accessToken)return e.accessToken;if(!e.serviceAccountKey)throw new Error("Either serviceAccountKey or accessToken must be provided");return await J(e.serviceAccountKey)}function G(e,t,n,r){return`projects/${e}/locations/${t}/agents/${n}/sessions/${r}`}function V(e){let t=null;for(const n of e)if(n.payload){if(n.payload.richContent){t=n.payload.richContent;break}if(n.payload.fields&&n.payload.fields.richContent){const e=n.payload.fields.richContent;e.listValue&&e.listValue.values?t=e.listValue.values.map(e=>e.listValue&&e.listValue.values?e.listValue.values.map(e=>{if(e.structValue&&e.structValue.fields){const t=e.structValue.fields;if(t.type&&t.options)return{type:t.type.stringValue||t.type,options:t.options.listValue?t.options.listValue.values.map(e=>({text:e.structValue?.fields?.text?.stringValue||"",payload:e.structValue?.fields?.payload?.stringValue||""})):[]}}return e}):e):"object"!=typeof e||e.listValue||(t=e);break}}return t}const Y="chat_session_id";class q{constructor(){this.sessionId=null,this.sessionId=this.loadSessionId()}loadSessionId(){return"undefined"!=typeof localStorage?localStorage.getItem(Y):null}saveSessionId(e){this.sessionId=e,"undefined"!=typeof localStorage&&(e?localStorage.setItem(Y,e):localStorage.removeItem(Y))}updateSessionFromResponse(e){const t=e?.data?.session_id||e?.session_id;t&&"string"==typeof t&&this.saveSessionId(t)}getSessionId(){return this.sessionId||""}getSessionHeader(){return{"X-Session-ID":this.getSessionId()}}}let X=null;class Z extends Error{constructor(e="chat_resolved"){super(e),this.reason="chat_resolved",this.name="ChatResolvedError"}}const Q="undefined"!=typeof process&&process.env?.REACT_APP_BACKEND_BASE_URL,ee="undefined"!=typeof process&&process.env?.REACT_APP_BACKEND_WS_URL;class te{constructor(e={}){this.ws=null,this.wsReconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimeout=null,this.pingInterval=null,this.currentChatId=null,this.currentSessionId=null,this.messageHandlers=new Set,this.connectionHandlers=new Set,this.baseUrl=e.baseUrl||Q,this.wsUrl=e.wsUrl||ee,this.debug=e.debug||!1,this.sessionManager=(X||(X=new q),X)}async startSupportChat(e,t,n,r){try{const o={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};e&&(o["X-Session-ID"]=e);const s={};t&&(s.name=t),n&&(s.email=n),r&&(s.mobile=r);const a=await fetch(`${this.baseUrl}/api/support/chat/start`,{method:"POST",headers:o,body:JSON.stringify(s)});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${a.status}`)}const i=await a.json();if(this.sessionManager.updateSessionFromResponse(i),i.status&&i.data)return{chat_id:i.data.chat_id,session_id:i.data.session_id};if(i.chat_id&&i.session_id)return{chat_id:i.chat_id,session_id:i.session_id};throw new Error("Invalid response format from chat start endpoint")}catch(o){throw new Error(o.message||"Failed to start support chat session")}}async requestHandoff(e,t,n,r,o,s,a){if(!e||"undefined"===e||"null"===e)throw new Error("Invalid chat_id. Chat must be initialized first.");try{const i={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};t?i["X-Session-ID"]=t:r&&(i["X-Session-ID"]=r);const c={};n&&(c.reason=n),o&&(c.name=o),s&&(c.email=s),a&&(c.mobile=a);const l=await fetch(`${this.baseUrl}/api/support/chat/${e}/handoff`,{method:"POST",headers:i,body:JSON.stringify(c)});if(400===l.status||404===l.status){const e=await l.json().catch(()=>({}));throw new Error(e.message||"Invalid chat_id. Chat may have expired.")}if(!l.ok){const e=await l.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${l.status}`)}const u=await l.json();return this.sessionManager.updateSessionFromResponse(u),u.status?{success:!0,message:u.message||u.data?.message}:{success:!0,message:u.message}}catch(i){throw i}}async sendMessageToAgent(e,t,n){try{const r={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};t&&(r["X-Session-ID"]=t);const o=await fetch(`${this.baseUrl}/api/support/chat/${e}/message`,{method:"POST",headers:r,body:JSON.stringify({content:n})});if(401===o.status||404===o.status){const e=await o.json().catch(()=>({}));throw new Error(e.message||"Chat not found or unauthorized")}if(!o.ok){const e=await o.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${o.status}`)}const s=await o.json();if(this.sessionManager.updateSessionFromResponse(s),!0===s?.ignored&&"chat_resolved"===s?.reason)throw new Z;return{id:s.id,sender_type:"customer",content:n,timestamp:s.timestamp||(new Date).toISOString()}}catch(r){if(r instanceof Z||"ChatResolvedError"===r?.name)throw r;throw new Error(r.message||"Failed to send message to agent")}}async ensureChatInitialized(e,t,n,r,o,s){return e&&"undefined"!==e&&"null"!==e&&t?{chat_id:e,session_id:t}:await this.startSupportChat(n||null,r||null,o||null,s||null)}async loadMessageHistory(e,t){try{const n={...this.sessionManager.getSessionHeader()};t&&(n["X-Session-ID"]=t);const r=await fetch(`${this.baseUrl}/api/support/chat/${e}/messages`,{method:"GET",headers:n});if(401===r.status||404===r.status){const e=await r.json().catch(()=>({}));throw new Error(e.message||"Chat not found or unauthorized")}if(!r.ok){const e=await r.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${r.status}`)}const o=await r.json();return this.sessionManager.updateSessionFromResponse(o),o.messages||[]}catch(n){throw new Error(n.message||"Failed to load message history")}}connectWebSocket(e,t,n,r,o){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&this.ws.readyState===WebSocket.OPEN)return void this.debug;this.currentChatId=e,this.currentSessionId=t,n&&this.messageHandlers.add(n),r&&this.connectionHandlers.add(r);const s=t||this.sessionManager.getSessionId()||"",a=`${this.wsUrl}/ws/support/${e}?X-Session-ID=${encodeURIComponent(s)}`;try{this.ws=new WebSocket(a),this.ws.onopen=()=>{this.debug,this.wsReconnectAttempts=0,this.connectionHandlers.forEach(e=>e(!0)),this.startPingInterval()},this.ws.onmessage=e=>{try{const t=JSON.parse(e.data);if(this.debug,t.session_id&&this.sessionManager.updateSessionFromResponse({session_id:t.session_id}),"agent_accepted"===t.type||"chat_resolved"===t.type||t.type,"pong"===t.type)return;this.debug&&t.type,this.messageHandlers.forEach(e=>e(t))}catch(t){this.debug}},this.ws.onerror=e=>{this.connectionHandlers.forEach(e=>e(!1))},this.ws.onclose=e=>{if(this.debug,this.stopPingInterval(),this.connectionHandlers.forEach(e=>e(!1)),this.ws=null,o?.(e),4e3===e.code)return this.wsReconnectAttempts=this.maxReconnectAttempts,this.currentChatId=null,void(this.currentSessionId=null);if(this.wsReconnectAttempts<this.maxReconnectAttempts&&this.currentChatId&&this.currentSessionId){this.wsReconnectAttempts++;const e=Math.min(1e3*Math.pow(2,this.wsReconnectAttempts),3e4);this.debug,this.reconnectTimeout=setTimeout(()=>{this.currentChatId&&this.currentSessionId&&this.connectWebSocket(this.currentChatId,this.currentSessionId,n,r,o)},e)}else this.debug}}catch(i){this.connectionHandlers.forEach(e=>e(!1))}}sendMessageViaWebSocket(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return!1;try{return this.ws.send(JSON.stringify({type:"message",content:e})),!0}catch(t){return!1}}sendTypingIndicator(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return!1;try{return this.ws.send(JSON.stringify({type:e})),!0}catch(t){return!1}}startPingInterval(){this.stopPingInterval(),this.pingInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"ping"}))}catch(e){}},3e4)}stopPingInterval(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}disconnectWebSocket(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.stopPingInterval(),this.ws&&(this.ws.close(),this.ws=null),this.messageHandlers.clear(),this.connectionHandlers.clear(),this.wsReconnectAttempts=0,this.currentChatId=null,this.currentSessionId=null}isWebSocketConnected(){return null!==this.ws&&this.ws.readyState===WebSocket.OPEN}removeMessageHandler(e){this.messageHandlers.delete(e)}removeConnectionHandler(e){this.connectionHandlers.delete(e)}}
2
- /*! @license DOMPurify 3.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.1/LICENSE */
3
- const{entries:ne,setPrototypeOf:re,isFrozen:oe,getPrototypeOf:se,getOwnPropertyDescriptor:ae}=Object;let{freeze:ie,seal:ce,create:le}=Object,{apply:ue,construct:de}="undefined"!=typeof Reflect&&Reflect;ie||(ie=function(e){return e}),ce||(ce=function(e){return e}),ue||(ue=function(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),o=2;o<n;o++)r[o-2]=arguments[o];return e.apply(t,r)}),de||(de=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return new e(...n)});const he=ve(Array.prototype.forEach),pe=ve(Array.prototype.lastIndexOf),fe=ve(Array.prototype.pop),me=ve(Array.prototype.push),ge=ve(Array.prototype.splice),ye=ve(String.prototype.toLowerCase),Ee=ve(String.prototype.toString),Se=ve(String.prototype.match),we=ve(String.prototype.replace),Ae=ve(String.prototype.indexOf),_e=ve(String.prototype.trim),Te=ve(Object.prototype.hasOwnProperty),be=ve(RegExp.prototype.test),Re=(Ie=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return de(Ie,t)});var Ie;function ve(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return ue(e,t,r)}}function Ce(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ye;re&&re(e,null);let r=t.length;for(;r--;){let o=t[r];if("string"==typeof o){const e=n(o);e!==o&&(oe(t)||(t[r]=e),o=e)}e[o]=!0}return e}function ke(e){for(let t=0;t<e.length;t++){Te(e,t)||(e[t]=null)}return e}function Ne(e){const t=le(null);for(const[n,r]of ne(e)){Te(e,n)&&(Array.isArray(r)?t[n]=ke(r):r&&"object"==typeof r&&r.constructor===Object?t[n]=Ne(r):t[n]=r)}return t}function De(e,t){for(;null!==e;){const n=ae(e,t);if(n){if(n.get)return ve(n.get);if("function"==typeof n.value)return ve(n.value)}e=se(e)}return function(){return null}}const Oe=ie(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Pe=ie(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),xe=ie(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),He=ie(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Le=ie(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Me=ie(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),We=ie(["#text"]),Ue=ie(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Ke=ie(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),$e=ie(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),je=ie(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Fe=ce(/\{\{[\w\W]*|[\w\W]*\}\}/gm),ze=ce(/<%[\w\W]*|[\w\W]*%>/gm),Je=ce(/\$\{[\w\W]*/gm),Be=ce(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ge=ce(/^aria-[\-\w]+$/),Ve=ce(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ye=ce(/^(?:\w+script|data):/i),qe=ce(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Xe=ce(/^html$/i),Ze=ce(/^[a-z][.\w]*(-[.\w]+)+$/i);var Qe=Object.freeze({__proto__:null,ARIA_ATTR:Ge,ATTR_WHITESPACE:qe,CUSTOM_ELEMENT:Ze,DATA_ATTR:Be,DOCTYPE_NAME:Xe,ERB_EXPR:ze,IS_ALLOWED_URI:Ve,IS_SCRIPT_OR_DATA:Ye,MUSTACHE_EXPR:Fe,TMPLIT_EXPR:Je});const et=1,tt=3,nt=7,rt=8,ot=9;var st=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"undefined"==typeof window?null:window;const n=t=>e(t);if(n.version="3.3.1",n.removed=[],!t||!t.document||t.document.nodeType!==ot||!t.Element)return n.isSupported=!1,n;let{document:r}=t;const o=r,s=o.currentScript,{DocumentFragment:a,HTMLTemplateElement:i,Node:c,Element:l,NodeFilter:u,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:h,DOMParser:p,trustedTypes:f}=t,m=l.prototype,g=De(m,"cloneNode"),y=De(m,"remove"),E=De(m,"nextSibling"),S=De(m,"childNodes"),w=De(m,"parentNode");if("function"==typeof i){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let A,_="";const{implementation:T,createNodeIterator:b,createDocumentFragment:R,getElementsByTagName:I}=r,{importNode:v}=o;let C={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof ne&&"function"==typeof w&&T&&void 0!==T.createHTMLDocument;const{MUSTACHE_EXPR:k,ERB_EXPR:N,TMPLIT_EXPR:D,DATA_ATTR:O,ARIA_ATTR:P,IS_SCRIPT_OR_DATA:x,ATTR_WHITESPACE:H,CUSTOM_ELEMENT:L}=Qe;let{IS_ALLOWED_URI:M}=Qe,W=null;const U=Ce({},[...Oe,...Pe,...xe,...Le,...We]);let K=null;const $=Ce({},[...Ue,...Ke,...$e,...je]);let j=Object.seal(le(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),F=null,z=null;const J=Object.seal(le(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let B=!0,G=!0,V=!1,Y=!0,q=!1,X=!0,Z=!1,Q=!1,ee=!1,te=!1,re=!1,oe=!1,se=!0,ae=!1,ce=!0,ue=!1,de={},Ie=null;const ve=Ce({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let ke=null;const Fe=Ce({},["audio","video","img","source","image","track"]);let ze=null;const Je=Ce({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Be="http://www.w3.org/1998/Math/MathML",Ge="http://www.w3.org/2000/svg",Ye="http://www.w3.org/1999/xhtml";let qe=Ye,Ze=!1,st=null;const at=Ce({},[Be,Ge,Ye],Ee);let it=Ce({},["mi","mo","mn","ms","mtext"]),ct=Ce({},["annotation-xml"]);const lt=Ce({},["title","style","font","a","script"]);let ut=null;const dt=["application/xhtml+xml","text/html"];let ht=null,pt=null;const ft=r.createElement("form"),mt=function(e){return e instanceof RegExp||e instanceof Function},gt=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!pt||pt!==e){if(e&&"object"==typeof e||(e={}),e=Ne(e),ut=-1===dt.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,ht="application/xhtml+xml"===ut?Ee:ye,W=Te(e,"ALLOWED_TAGS")?Ce({},e.ALLOWED_TAGS,ht):U,K=Te(e,"ALLOWED_ATTR")?Ce({},e.ALLOWED_ATTR,ht):$,st=Te(e,"ALLOWED_NAMESPACES")?Ce({},e.ALLOWED_NAMESPACES,Ee):at,ze=Te(e,"ADD_URI_SAFE_ATTR")?Ce(Ne(Je),e.ADD_URI_SAFE_ATTR,ht):Je,ke=Te(e,"ADD_DATA_URI_TAGS")?Ce(Ne(Fe),e.ADD_DATA_URI_TAGS,ht):Fe,Ie=Te(e,"FORBID_CONTENTS")?Ce({},e.FORBID_CONTENTS,ht):ve,F=Te(e,"FORBID_TAGS")?Ce({},e.FORBID_TAGS,ht):Ne({}),z=Te(e,"FORBID_ATTR")?Ce({},e.FORBID_ATTR,ht):Ne({}),de=!!Te(e,"USE_PROFILES")&&e.USE_PROFILES,B=!1!==e.ALLOW_ARIA_ATTR,G=!1!==e.ALLOW_DATA_ATTR,V=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Y=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,q=e.SAFE_FOR_TEMPLATES||!1,X=!1!==e.SAFE_FOR_XML,Z=e.WHOLE_DOCUMENT||!1,te=e.RETURN_DOM||!1,re=e.RETURN_DOM_FRAGMENT||!1,oe=e.RETURN_TRUSTED_TYPE||!1,ee=e.FORCE_BODY||!1,se=!1!==e.SANITIZE_DOM,ae=e.SANITIZE_NAMED_PROPS||!1,ce=!1!==e.KEEP_CONTENT,ue=e.IN_PLACE||!1,M=e.ALLOWED_URI_REGEXP||Ve,qe=e.NAMESPACE||Ye,it=e.MATHML_TEXT_INTEGRATION_POINTS||it,ct=e.HTML_INTEGRATION_POINTS||ct,j=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&mt(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(j.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&mt(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(j.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(j.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),q&&(G=!1),re&&(te=!0),de&&(W=Ce({},We),K=[],!0===de.html&&(Ce(W,Oe),Ce(K,Ue)),!0===de.svg&&(Ce(W,Pe),Ce(K,Ke),Ce(K,je)),!0===de.svgFilters&&(Ce(W,xe),Ce(K,Ke),Ce(K,je)),!0===de.mathMl&&(Ce(W,Le),Ce(K,$e),Ce(K,je))),e.ADD_TAGS&&("function"==typeof e.ADD_TAGS?J.tagCheck=e.ADD_TAGS:(W===U&&(W=Ne(W)),Ce(W,e.ADD_TAGS,ht))),e.ADD_ATTR&&("function"==typeof e.ADD_ATTR?J.attributeCheck=e.ADD_ATTR:(K===$&&(K=Ne(K)),Ce(K,e.ADD_ATTR,ht))),e.ADD_URI_SAFE_ATTR&&Ce(ze,e.ADD_URI_SAFE_ATTR,ht),e.FORBID_CONTENTS&&(Ie===ve&&(Ie=Ne(Ie)),Ce(Ie,e.FORBID_CONTENTS,ht)),e.ADD_FORBID_CONTENTS&&(Ie===ve&&(Ie=Ne(Ie)),Ce(Ie,e.ADD_FORBID_CONTENTS,ht)),ce&&(W["#text"]=!0),Z&&Ce(W,["html","head","body"]),W.table&&(Ce(W,["tbody"]),delete F.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Re('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Re('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');A=e.TRUSTED_TYPES_POLICY,_=A.createHTML("")}else void 0===A&&(A=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const o="dompurify"+(n?"#"+n:"");try{return e.createPolicy(o,{createHTML:e=>e,createScriptURL:e=>e})}catch(s){return null}}(f,s)),null!==A&&"string"==typeof _&&(_=A.createHTML(""));ie&&ie(e),pt=e}},yt=Ce({},[...Pe,...xe,...He]),Et=Ce({},[...Le,...Me]),St=function(e){me(n.removed,{element:e});try{w(e).removeChild(e)}catch(t){y(e)}},wt=function(e,t){try{me(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(r){me(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(te||re)try{St(t)}catch(r){}else try{t.setAttribute(e,"")}catch(r){}},At=function(e){let t=null,n=null;if(ee)e="<remove></remove>"+e;else{const t=Se(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===ut&&qe===Ye&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const o=A?A.createHTML(e):e;if(qe===Ye)try{t=(new p).parseFromString(o,ut)}catch(a){}if(!t||!t.documentElement){t=T.createDocument(qe,"template",null);try{t.documentElement.innerHTML=Ze?_:o}catch(a){}}const s=t.body||t.documentElement;return e&&n&&s.insertBefore(r.createTextNode(n),s.childNodes[0]||null),qe===Ye?I.call(t,Z?"html":"body")[0]:Z?t.documentElement:s},_t=function(e){return b.call(e.ownerDocument||e,e,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},Tt=function(e){return e instanceof h&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof d)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},bt=function(e){return"function"==typeof c&&e instanceof c};function Rt(e,t,r){he(e,e=>{e.call(n,t,r,pt)})}const It=function(e){let t=null;if(Rt(C.beforeSanitizeElements,e,null),Tt(e))return St(e),!0;const r=ht(e.nodeName);if(Rt(C.uponSanitizeElement,e,{tagName:r,allowedTags:W}),X&&e.hasChildNodes()&&!bt(e.firstElementChild)&&be(/<[/\w!]/g,e.innerHTML)&&be(/<[/\w!]/g,e.textContent))return St(e),!0;if(e.nodeType===nt)return St(e),!0;if(X&&e.nodeType===rt&&be(/<[/\w]/g,e.data))return St(e),!0;if(!(J.tagCheck instanceof Function&&J.tagCheck(r))&&(!W[r]||F[r])){if(!F[r]&&Ct(r)){if(j.tagNameCheck instanceof RegExp&&be(j.tagNameCheck,r))return!1;if(j.tagNameCheck instanceof Function&&j.tagNameCheck(r))return!1}if(ce&&!Ie[r]){const t=w(e)||e.parentNode,n=S(e)||e.childNodes;if(n&&t){for(let r=n.length-1;r>=0;--r){const o=g(n[r],!0);o.__removalCount=(e.__removalCount||0)+1,t.insertBefore(o,E(e))}}}return St(e),!0}return e instanceof l&&!function(e){let t=w(e);t&&t.tagName||(t={namespaceURI:qe,tagName:"template"});const n=ye(e.tagName),r=ye(t.tagName);return!!st[e.namespaceURI]&&(e.namespaceURI===Ge?t.namespaceURI===Ye?"svg"===n:t.namespaceURI===Be?"svg"===n&&("annotation-xml"===r||it[r]):Boolean(yt[n]):e.namespaceURI===Be?t.namespaceURI===Ye?"math"===n:t.namespaceURI===Ge?"math"===n&&ct[r]:Boolean(Et[n]):e.namespaceURI===Ye?!(t.namespaceURI===Ge&&!ct[r])&&!(t.namespaceURI===Be&&!it[r])&&!Et[n]&&(lt[n]||!yt[n]):!("application/xhtml+xml"!==ut||!st[e.namespaceURI]))}(e)?(St(e),!0):"noscript"!==r&&"noembed"!==r&&"noframes"!==r||!be(/<\/no(script|embed|frames)/i,e.innerHTML)?(q&&e.nodeType===tt&&(t=e.textContent,he([k,N,D],e=>{t=we(t,e," ")}),e.textContent!==t&&(me(n.removed,{element:e.cloneNode()}),e.textContent=t)),Rt(C.afterSanitizeElements,e,null),!1):(St(e),!0)},vt=function(e,t,n){if(se&&("id"===t||"name"===t)&&(n in r||n in ft))return!1;if(G&&!z[t]&&be(O,t));else if(B&&be(P,t));else if(J.attributeCheck instanceof Function&&J.attributeCheck(t,e));else if(!K[t]||z[t]){if(!(Ct(e)&&(j.tagNameCheck instanceof RegExp&&be(j.tagNameCheck,e)||j.tagNameCheck instanceof Function&&j.tagNameCheck(e))&&(j.attributeNameCheck instanceof RegExp&&be(j.attributeNameCheck,t)||j.attributeNameCheck instanceof Function&&j.attributeNameCheck(t,e))||"is"===t&&j.allowCustomizedBuiltInElements&&(j.tagNameCheck instanceof RegExp&&be(j.tagNameCheck,n)||j.tagNameCheck instanceof Function&&j.tagNameCheck(n))))return!1}else if(ze[t]);else if(be(M,we(n,H,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Ae(n,"data:")||!ke[e]){if(V&&!be(x,we(n,H,"")));else if(n)return!1}else;return!0},Ct=function(e){return"annotation-xml"!==e&&Se(e,L)},kt=function(e){Rt(C.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||Tt(e))return;const r={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:K,forceKeepAttr:void 0};let o=t.length;for(;o--;){const a=t[o],{name:i,namespaceURI:c,value:l}=a,u=ht(i),d=l;let h="value"===i?d:_e(d);if(r.attrName=u,r.attrValue=h,r.keepAttr=!0,r.forceKeepAttr=void 0,Rt(C.uponSanitizeAttribute,e,r),h=r.attrValue,!ae||"id"!==u&&"name"!==u||(wt(i,e),h="user-content-"+h),X&&be(/((--!?|])>)|<\/(style|title|textarea)/i,h)){wt(i,e);continue}if("attributename"===u&&Se(h,"href")){wt(i,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){wt(i,e);continue}if(!Y&&be(/\/>/i,h)){wt(i,e);continue}q&&he([k,N,D],e=>{h=we(h,e," ")});const p=ht(e.nodeName);if(vt(p,u,h)){if(A&&"object"==typeof f&&"function"==typeof f.getAttributeType)if(c);else switch(f.getAttributeType(p,u)){case"TrustedHTML":h=A.createHTML(h);break;case"TrustedScriptURL":h=A.createScriptURL(h)}if(h!==d)try{c?e.setAttributeNS(c,i,h):e.setAttribute(i,h),Tt(e)?St(e):fe(n.removed)}catch(s){wt(i,e)}}else wt(i,e)}Rt(C.afterSanitizeAttributes,e,null)},Nt=function e(t){let n=null;const r=_t(t);for(Rt(C.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)Rt(C.uponSanitizeShadowNode,n,null),It(n),kt(n),n.content instanceof a&&e(n.content);Rt(C.afterSanitizeShadowDOM,t,null)};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,s=null,i=null,l=null;if(Ze=!e,Ze&&(e="\x3c!--\x3e"),"string"!=typeof e&&!bt(e)){if("function"!=typeof e.toString)throw Re("toString is not a function");if("string"!=typeof(e=e.toString()))throw Re("dirty is not a string, aborting")}if(!n.isSupported)return e;if(Q||gt(t),n.removed=[],"string"==typeof e&&(ue=!1),ue){if(e.nodeName){const t=ht(e.nodeName);if(!W[t]||F[t])throw Re("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof c)r=At("\x3c!----\x3e"),s=r.ownerDocument.importNode(e,!0),s.nodeType===et&&"BODY"===s.nodeName||"HTML"===s.nodeName?r=s:r.appendChild(s);else{if(!te&&!q&&!Z&&-1===e.indexOf("<"))return A&&oe?A.createHTML(e):e;if(r=At(e),!r)return te?null:oe?_:""}r&&ee&&St(r.firstChild);const u=_t(ue?e:r);for(;i=u.nextNode();)It(i),kt(i),i.content instanceof a&&Nt(i.content);if(ue)return e;if(te){if(re)for(l=R.call(r.ownerDocument);r.firstChild;)l.appendChild(r.firstChild);else l=r;return(K.shadowroot||K.shadowrootmode)&&(l=v.call(o,l,!0)),l}let d=Z?r.outerHTML:r.innerHTML;return Z&&W["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&be(Xe,r.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+r.ownerDocument.doctype.name+">\n"+d),q&&he([k,N,D],e=>{d=we(d,e," ")}),A&&oe?A.createHTML(d):d},n.setConfig=function(){gt(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Q=!0},n.clearConfig=function(){pt=null,Q=!1},n.isValidAttribute=function(e,t,n){pt||gt({});const r=ht(e),o=ht(t);return vt(r,o,n)},n.addHook=function(e,t){"function"==typeof t&&me(C[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=pe(C[e],t);return-1===n?void 0:ge(C[e],n,1)[0]}return fe(C[e])},n.removeHooks=function(e){C[e]=[]},n.removeAllHooks=function(){C={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();function at(e){return function(e,t){const n={ALLOWED_TAGS:["a","b","strong","i","em","u","br","p","span"],ALLOWED_ATTR:["href","target","rel"],ALLOW_DATA_ATTR:!1,...t?.allowedTags&&{ALLOWED_TAGS:t.allowedTags},...t?.allowedAttributes&&{ALLOWED_ATTR:Object.keys(t.allowedAttributes).flatMap(e=>t.allowedAttributes[e])}},r=st.sanitize(e,n);return"string"==typeof r?r:String(r)}(e.replace(/(https?:\/\/[^\s]+)/g,'<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>'),{allowedTags:["a"],allowedAttributes:{a:["href","target","rel"]}})}exports.ChatResolvedError=Z,exports.createChatService=function(e){return new te(e)},exports.createDialogflowSession=async function(e){try{const t=await B(e),n=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,r=e.dfLocation.split(" ")[0].trim(),o=`https://${r}-dialogflow.googleapis.com/v3/${G(e.dfProjectId,r,e.dfAgentId,n)}:detectIntent`,s={queryInput:{text:{text:"hello"},languageCode:e.languageCode||"en"}},a=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e.error?.message||`HTTP error! status: ${a.status}`)}const i=await a.json();let c="Hello! I'm BlockSpark AI Assistant. How can I help you today?",l=null;if(i.queryResult?.responseMessages){const e=i.queryResult.responseMessages.filter(e=>e.text).map(e=>e.text.text.join(" "));e.length>0&&(c=e.join(" ")),l=V(i.queryResult.responseMessages)}else i.queryResult?.fulfillmentText&&(c=i.queryResult.fulfillmentText);return{session_id:n,message:c,...l&&{richContent:l}}}catch(t){const e=t.message||"Failed to create session";if(e.includes("401")||e.includes("Unauthorized"))throw new Error("Authentication failed. Please check your service account key or access token.");if(e.includes("403")||e.includes("Forbidden"))throw new Error("Access forbidden. Please check your Dialogflow API permissions.");if(e.includes("404")||e.includes("Not Found"))throw new Error("Dialogflow agent not found. Please check your project ID, location, and agent ID.");throw new Error(e)}},exports.linkifyText=at,exports.safeLinkifyText=function(e){return at(e)},exports.sendDialogflowMessage=async function(e,t,n){try{const r=await B(n),o=n.dfLocation.split(" ")[0].trim(),s=`https://${o}-dialogflow.googleapis.com/v3/${G(n.dfProjectId,o,n.dfAgentId,t)}:detectIntent`,a={queryInput:{text:{text:e.trim()},languageCode:n.languageCode||"en"}},i=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(a)});if(!i.ok){const e=await i.text();let t={};try{t=JSON.parse(e)}catch{t={message:e||`HTTP ${i.status}`}}const n=t.error?.message||t.message||`HTTP error! status: ${i.status}`;throw new Error(n)}const c=await i.json();let l="I'm sorry, I didn't understand that. Could you please rephrase?",u=null,d=!1;if(!0===c.queryResult?.parameters?.fields?.handoff?.boolValue)d=!0;else if(c.queryResult?.responseMessages)for(const e of c.queryResult.responseMessages)if(e.payload&&"object"==typeof e.payload){if(!0===e.payload.handoff){d=!0;break}if(!0===e.payload.fields?.handoff?.boolValue){d=!0;break}}if(!0===c.handoff&&(d=!0),c.queryResult?.responseMessages){const e=c.queryResult.responseMessages.filter(e=>e.text).map(e=>e.text.text.join(" "));e.length>0&&(l=e.join(" ")),u=V(c.queryResult.responseMessages)}else c.queryResult?.fulfillmentText&&(l=c.queryResult.fulfillmentText);return{response:l,session_id:t,source:"dialogflow",timestamp:(new Date).toISOString(),...u&&{richContent:u},...d&&{handoff:!0}}}catch(r){const e=r.message||"Failed to send message";if(e.includes("401")||e.includes("Unauthorized"))throw new Error("Authentication failed. Please check your service account key or access token.");if(e.includes("403")||e.includes("Forbidden"))throw new Error("Access forbidden. Please check your Dialogflow API permissions.");if(e.includes("404")||e.includes("Not Found"))throw new Error("Dialogflow agent not found. Please check your project ID, location, and agent ID.");if(e.includes("CORS"))throw new Error("CORS error. Dialogflow API may not allow browser requests. Consider using a backend proxy.");throw new Error(e)}};
4
- //# sourceMappingURL=sanitize-DRKcO9o5.cjs.map