@gengage/assistant-fe 0.2.2 → 0.2.3

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/chat/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAA0C,MAAM,oBAAoB,CAAC;AAO7G,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAkCtD,OAAO,KAAK,EACV,gBAAgB,EAMjB,MAAM,YAAY,CAAC;AA+BpB;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,WAAY,SAAQ,UAAU,CAAC,gBAAgB,CAAC;IAC3D,OAAO,CAAC,OAAO,CAA2B;IAC1C,OAAO,CAAC,OAAO,CAA4B;IAC3C,OAAO,CAAC,SAAS,CAAiC;IAClD,OAAO,CAAC,OAAO,CAA2B;IAC1C,OAAO,CAAC,OAAO,CAAoC;IACnD,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,SAAS,CAAqB;IAGtC,OAAO,CAAC,iBAAiB,CAAK;IAC9B,OAAO,CAAC,iBAAiB,CAA8B;IACvD,+EAA+E;IAC/E,OAAO,CAAC,gBAAgB,CAAuB;IAC/C,wEAAwE;IACxE,OAAO,CAAC,aAAa,CAAuB;IAC5C,8DAA8D;IAC9D,OAAO,CAAC,cAAc,CAAM;IAC5B,2EAA2E;IAC3E,OAAO,CAAC,mBAAmB,CAA4D;IACvF,OAAO,CAAC,YAAY,CAAyC;IAC7D,OAAO,CAAC,QAAQ,CAAqB;IACrC,OAAO,CAAC,qBAAqB,CAAS;IACtC,OAAO,CAAC,uBAAuB,CAAgB;IAC/C,OAAO,CAAC,iBAAiB,CAAwB;IACjD,OAAO,CAAC,iBAAiB,CAA4B;IACrD,OAAO,CAAC,UAAU,CAA2B;IAC7C,OAAO,CAAC,iBAAiB,CAAO;IAChC,OAAO,CAAC,iBAAiB,CAAS;IAClC,OAAO,CAAC,YAAY,CAAS;IAC7B,qEAAqE;IACrE,OAAO,CAAC,mBAAmB,CAAS;IACpC,+DAA+D;IAC/D,OAAO,CAAC,mBAAmB,CAAkD;IAC7E,OAAO,CAAC,6BAA6B,CAAuB;IAC5D,OAAO,CAAC,KAAK,CAA0B;IACvC,OAAO,CAAC,oBAAoB,CAAoC;IAChE,oFAAoF;IACpF,OAAO,CAAC,iBAAiB,CAAiC;IAC1D,6EAA6E;IAC7E,OAAO,CAAC,gBAAgB,CAA4B;IACpD,6FAA6F;IAC7F,OAAO,CAAC,sBAAsB,CAAuB;IACrD,iEAAiE;IACjE,OAAO,CAAC,iBAAiB,CAA+C;IACxE,kEAAkE;IAClE,OAAO,CAAC,iBAAiB,CAAuB;IAChD,oEAAoE;IACpE,OAAO,CAAC,aAAa,CAAS;IAC9B,6EAA6E;IAC7E,OAAO,CAAC,eAAe,CAGf;IACR,oFAAoF;IACpF,OAAO,CAAC,cAAc,CAAwC;IAC9D,wDAAwD;IACxD,OAAO,CAAC,aAAa,CAAuB;IAC5C,OAAO,CAAC,oBAAoB,CAA0B;IACtD,2DAA2D;IAC3D,OAAO,CAAC,MAAM,CAA6B;IAC3C,6CAA6C;IAC7C,OAAO,CAAC,QAAQ,CAAmC;IACnD,gGAAgG;IAChG,OAAO,CAAC,eAAe,CAA2F;IAClH,mDAAmD;IACnD,OAAO,CAAC,eAAe,CAGP;cAEA,MAAM,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;IAwL/D,SAAS,CAAC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG,IAAI;IAOvD,SAAS,CAAC,MAAM,IAAI,IAAI;IAsBxB,SAAS,CAAC,MAAM,IAAI,IAAI;IAYxB,SAAS,CAAC,SAAS,IAAI,IAAI;IA8B3B,IAAI,CAAC,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;QAAC,cAAc,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI;IAa1E,cAAc,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,CAAC,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,GAAG,IAAI;IAmBhG,2EAA2E;IAC3E,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAI/B,8CAA8C;IAC9C,UAAU,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI;IAIvE,KAAK,IAAI,IAAI;IAIb,WAAW,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI;IAKjD,IAAI,MAAM,IAAI,OAAO,CAEpB;IAED;;;;;OAKG;IACH,WAAW,CACT,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,GACxE,MAAM,IAAI;IAiBb,oEAAoE;IACpE,OAAO,CAAC,gBAAgB;IAqCxB,OAAO,CAAC,oBAAoB;IAqF5B,OAAO,CAAC,kBAAkB;IAuB1B,OAAO,CAAC,WAAW;IAenB,OAAO,CAAC,WAAW;IAqBnB,OAAO,CAAC,kBAAkB;IAa1B,OAAO,CAAC,sBAAsB;IAS9B,OAAO,CAAC,iBAAiB;IAazB,OAAO,CAAC,YAAY;IAwBpB,OAAO,CAAC,wBAAwB;IAShC,OAAO,CAAC,WAAW;IAy3BnB,4DAA4D;IAC5D,OAAO,CAAC,mBAAmB;IAO3B,2DAA2D;IAC3D,OAAO,CAAC,sBAAsB;IAa9B,OAAO,CAAC,eAAe;IAMvB,mDAAmD;IACnD,OAAO,CAAC,iBAAiB;YA8DX,mBAAmB;IAkBjC,OAAO,CAAC,gBAAgB;IAUxB,OAAO,CAAC,8BAA8B;IAItC,OAAO,CAAC,+BAA+B;IAIvC,OAAO,CAAC,6BAA6B;IAKrC,OAAO,CAAC,+BAA+B;YAYzB,sBAAsB;YAKtB,YAAY;IAK1B;;;;OAIG;YACW,qBAAqB;IA8JnC;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IAmB5B;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IA6F5B;;;OAGG;IACH,OAAO,CAAC,mBAAmB;YAmGb,eAAe;IAO7B;;;OAGG;YACW,kBAAkB;IAmBhC;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAY9B;;;OAGG;IACH,OAAO,CAAC,oBAAoB;IA6C5B,OAAO,CAAC,cAAc;IAWtB,OAAO,CAAC,YAAY;IAKpB,OAAO,CAAC,sBAAsB;IAK9B,OAAO,CAAC,aAAa;CAgBtB;AAMD,wBAAgB,gBAAgB,IAAI,WAAW,CAE9C;AAED,YAAY,EACV,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,QAAQ,EACR,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,EAClB,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,YAAY,EACZ,+BAA+B,EAC/B,gCAAgC,GACjC,MAAM,8BAA8B,CAAC;AACtC,YAAY,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,YAAY,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/chat/index.ts"],"names":[],"mappings":"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"}
package/dist/chat.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("./schemas-DOxyUYVA.cjs");const e=require("./index-CB8DgwIv.cjs");exports.GengageChat=e.GengageChat;exports.chatCatalog=e.chatCatalog;exports.createChatWidget=e.createChatWidget;exports.createDefaultChatUISpecRegistry=e.createDefaultChatUISpecRegistry;exports.defaultChatUnknownUISpecRenderer=e.defaultChatUnknownUISpecRenderer;exports.renderUISpec=e.renderUISpec;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("./schemas-DOxyUYVA.cjs");const e=require("./index-CO5VnxEn.cjs");exports.GengageChat=e.GengageChat;exports.chatCatalog=e.chatCatalog;exports.createChatWidget=e.createChatWidget;exports.createDefaultChatUISpecRegistry=e.createDefaultChatUISpecRegistry;exports.defaultChatUnknownUISpecRenderer=e.defaultChatUnknownUISpecRenderer;exports.renderUISpec=e.renderUISpec;
2
2
  //# sourceMappingURL=chat.cjs.map
package/dist/chat.iife.js CHANGED
@@ -93,5 +93,5 @@
93
93
 
94
94
  `)}p.write("payload.value = newResult;"),p.write("return payload;");const T=p.compile();return(S,y)=>T(u,S,y)};let o;const r=Fe,s=!sn.jitless,l=s&&Nr.value,g=t.catchall;let d;e._zod.parse=(u,p)=>{d??(d=a.value);const f=u.value;return r(f)?s&&l&&p?.async===!1&&p.jitless!==!0?(o||(o=i(t.shape)),u=o(u,p),g?In([],f,u,p,d,e):u):n(u,p):(u.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),u)}});function An(e,t,n,a){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const i=e.filter(o=>!Ie(o));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(r=>_e(r,a,fe())))}),t)}const vc=m("$ZodUnion",(e,t)=>{H.init(e,t),B(e._zod,"optin",()=>t.options.some(i=>i._zod.optin==="optional")?"optional":void 0),B(e._zod,"optout",()=>t.options.some(i=>i._zod.optout==="optional")?"optional":void 0),B(e._zod,"values",()=>{if(t.options.every(i=>i._zod.values))return new Set(t.options.flatMap(i=>Array.from(i._zod.values)))}),B(e._zod,"pattern",()=>{if(t.options.every(i=>i._zod.pattern)){const i=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${i.map(o=>dt(o.source)).join("|")})$`)}});const n=t.options.length===1,a=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(n)return a(i,o);let r=!1;const s=[];for(const c of t.options){const l=c._zod.run({value:i.value,issues:[]},o);if(l instanceof Promise)s.push(l),r=!0;else{if(l.issues.length===0)return l;s.push(l)}}return r?Promise.all(s).then(c=>An(c,i,e,o)):An(s,i,e,o)}}),yc=m("$ZodIntersection",(e,t)=>{H.init(e,t),e._zod.parse=(n,a)=>{const i=n.value,o=t.left._zod.run({value:i,issues:[]},a),r=t.right._zod.run({value:i,issues:[]},a);return o instanceof Promise||r instanceof Promise?Promise.all([o,r]).then(([c,l])=>zn(n,c,l)):zn(n,o,r)}});function ft(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Te(e)&&Te(t)){const n=Object.keys(t),a=Object.keys(e).filter(o=>n.indexOf(o)!==-1),i={...e,...t};for(const o of a){const r=ft(e[o],t[o]);if(!r.valid)return{valid:!1,mergeErrorPath:[o,...r.mergeErrorPath]};i[o]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let a=0;a<e.length;a++){const i=e[a],o=t[a],r=ft(i,o);if(!r.valid)return{valid:!1,mergeErrorPath:[a,...r.mergeErrorPath]};n.push(r.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function zn(e,t,n){const a=new Map;let i;for(const s of t.issues)if(s.code==="unrecognized_keys"){i??(i=s);for(const c of s.keys)a.has(c)||a.set(c,{}),a.get(c).l=!0}else e.issues.push(s);for(const s of n.issues)if(s.code==="unrecognized_keys")for(const c of s.keys)a.has(c)||a.set(c,{}),a.get(c).r=!0;else e.issues.push(s);const o=[...a].filter(([,s])=>s.l&&s.r).map(([s])=>s);if(o.length&&i&&e.issues.push({...i,keys:o}),Ie(e))return e;const r=ft(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const wc=m("$ZodRecord",(e,t)=>{H.init(e,t),e._zod.parse=(n,a)=>{const i=n.value;if(!Te(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;const o=[],r=t.keyType._zod.values;if(r){n.value={};const s=new Set;for(const l of r)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){s.add(typeof l=="number"?l.toString():l);const g=t.valueType._zod.run({value:i[l],issues:[]},a);g instanceof Promise?o.push(g.then(d=>{d.issues.length&&n.issues.push(...Ae(l,d.issues)),n.value[l]=d.value})):(g.issues.length&&n.issues.push(...Ae(l,g.issues)),n.value[l]=g.value)}let c;for(const l in i)s.has(l)||(c=c??[],c.push(l));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c})}else{n.value={};for(const s of Reflect.ownKeys(i)){if(s==="__proto__")continue;let c=t.keyType._zod.run({value:s,issues:[]},a);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof s=="string"&&yn.test(s)&&c.issues.length){const d=t.keyType._zod.run({value:Number(s),issues:[]},a);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){t.mode==="loose"?n.value[s]=i[s]:n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>_e(d,a,fe())),input:s,path:[s],inst:e});continue}const g=t.valueType._zod.run({value:i[s],issues:[]},a);g instanceof Promise?o.push(g.then(d=>{d.issues.length&&n.issues.push(...Ae(s,d.issues)),n.value[c.value]=d.value})):(g.issues.length&&n.issues.push(...Ae(s,g.issues)),n.value[c.value]=g.value)}}return o.length?Promise.all(o).then(()=>n):n}}),xc=m("$ZodEnum",(e,t)=>{H.init(e,t);const n=cn(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(i=>Mr.has(typeof i)).map(i=>typeof i=="string"?Ze(i):i.toString()).join("|")})$`),e._zod.parse=(i,o)=>{const r=i.value;return a.has(r)||i.issues.push({code:"invalid_value",values:n,input:r,inst:e}),i}}),kc=m("$ZodTransform",(e,t)=>{H.init(e,t),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new rn(e.constructor.name);const i=t.transform(n.value,n);if(a.async)return(i instanceof Promise?i:Promise.resolve(i)).then(r=>(n.value=r,n));if(i instanceof Promise)throw new Se;return n.value=i,n}});function Pn(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const Ln=m("$ZodOptional",(e,t)=>{H.init(e,t),e._zod.optin="optional",e._zod.optout="optional",B(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),B(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${dt(n.source)})?$`):void 0}),e._zod.parse=(n,a)=>{if(t.innerType._zod.optin==="optional"){const i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(o=>Pn(o,n.value)):Pn(i,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),Cc=m("$ZodExactOptional",(e,t)=>{Ln.init(e,t),B(e._zod,"values",()=>t.innerType._zod.values),B(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,a)=>t.innerType._zod.run(n,a)}),Ec=m("$ZodNullable",(e,t)=>{H.init(e,t),B(e._zod,"optin",()=>t.innerType._zod.optin),B(e._zod,"optout",()=>t.innerType._zod.optout),B(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${dt(n.source)}|null)$`):void 0}),B(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,a)=>n.value===null?n:t.innerType._zod.run(n,a)}),Sc=m("$ZodDefault",(e,t)=>{H.init(e,t),e._zod.optin="optional",B(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(o=>Nn(o,t)):Nn(i,t)}});function Nn(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Tc=m("$ZodPrefault",(e,t)=>{H.init(e,t),e._zod.optin="optional",B(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>(a.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,a))}),Ic=m("$ZodNonOptional",(e,t)=>{H.init(e,t),B(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(a=>a!==void 0)):void 0}),e._zod.parse=(n,a)=>{const i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(o=>Mn(o,e)):Mn(i,e)}});function Mn(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Ac=m("$ZodCatch",(e,t)=>{H.init(e,t),B(e._zod,"optin",()=>t.innerType._zod.optin),B(e._zod,"optout",()=>t.innerType._zod.optout),B(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(o=>(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(r=>_e(r,a,fe()))},input:n.value}),n.issues=[]),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(o=>_e(o,a,fe()))},input:n.value}),n.issues=[]),n)}}),zc=m("$ZodPipe",(e,t)=>{H.init(e,t),B(e._zod,"values",()=>t.in._zod.values),B(e._zod,"optin",()=>t.in._zod.optin),B(e._zod,"optout",()=>t.out._zod.optout),B(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,a)=>{if(a.direction==="backward"){const o=t.out._zod.run(n,a);return o instanceof Promise?o.then(r=>Ge(r,t.in,a)):Ge(o,t.in,a)}const i=t.in._zod.run(n,a);return i instanceof Promise?i.then(o=>Ge(o,t.out,a)):Ge(i,t.out,a)}});function Ge(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Pc=m("$ZodReadonly",(e,t)=>{H.init(e,t),B(e._zod,"propValues",()=>t.innerType._zod.propValues),B(e._zod,"values",()=>t.innerType._zod.values),B(e._zod,"optin",()=>t.innerType?._zod?.optin),B(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then($n):$n(i)}});function $n(e){return e.value=Object.freeze(e.value),e}const Lc=m("$ZodCustom",(e,t)=>{Q.init(e,t),H.init(e,t),e._zod.parse=(n,a)=>n,e._zod.check=n=>{const a=n.value,i=t.fn(a);if(i instanceof Promise)return i.then(o=>On(o,n,a,e));On(i,n,a,e)}});function On(e,t,n,a){if(!e){const i={code:"custom",input:n,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(i.params=a._zod.def.params),t.issues.push($e(i))}}var Rn;class Nc{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const a=n[0];return this._map.set(t,a),a&&typeof a=="object"&&"id"in a&&this._idmap.set(a.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const a={...this.get(n)??{}};delete a.id;const i={...a,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function Mc(){return new Nc}(Rn=globalThis).__zod_globalRegistry??(Rn.__zod_globalRegistry=Mc());const Oe=globalThis.__zod_globalRegistry;function $c(e,t){return new e({type:"string",...A(t)})}function Oc(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...A(t)})}function Bn(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...A(t)})}function Rc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...A(t)})}function Bc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(t)})}function Dc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(t)})}function Uc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(t)})}function Fc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...A(t)})}function Zc(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...A(t)})}function jc(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(t)})}function qc(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...A(t)})}function Hc(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...A(t)})}function Vc(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...A(t)})}function Wc(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...A(t)})}function Gc(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...A(t)})}function Kc(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...A(t)})}function Yc(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...A(t)})}function Jc(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A(t)})}function Xc(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(t)})}function Qc(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...A(t)})}function el(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...A(t)})}function tl(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...A(t)})}function nl(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...A(t)})}function al(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(t)})}function il(e,t){return new e({type:"string",format:"date",check:"string_format",...A(t)})}function ol(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...A(t)})}function rl(e,t){return new e({type:"string",format:"duration",check:"string_format",...A(t)})}function sl(e,t){return new e({type:"number",checks:[],...A(t)})}function cl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...A(t)})}function ll(e,t){return new e({type:"boolean",...A(t)})}function dl(e){return new e({type:"unknown"})}function gl(e,t){return new e({type:"never",...A(t)})}function Dn(e,t){return new xn({check:"less_than",...A(t),value:e,inclusive:!1})}function mt(e,t){return new xn({check:"less_than",...A(t),value:e,inclusive:!0})}function Un(e,t){return new kn({check:"greater_than",...A(t),value:e,inclusive:!1})}function bt(e,t){return new kn({check:"greater_than",...A(t),value:e,inclusive:!0})}function Fn(e,t){return new Ts({check:"multiple_of",...A(t),value:e})}function Zn(e,t){return new As({check:"max_length",...A(t),maximum:e})}function Ke(e,t){return new zs({check:"min_length",...A(t),minimum:e})}function jn(e,t){return new Ps({check:"length_equals",...A(t),length:e})}function pl(e,t){return new Ls({check:"string_format",format:"regex",...A(t),pattern:e})}function ul(e){return new Ns({check:"string_format",format:"lowercase",...A(e)})}function hl(e){return new Ms({check:"string_format",format:"uppercase",...A(e)})}function fl(e,t){return new $s({check:"string_format",format:"includes",...A(t),includes:e})}function ml(e,t){return new Os({check:"string_format",format:"starts_with",...A(t),prefix:e})}function bl(e,t){return new Rs({check:"string_format",format:"ends_with",...A(t),suffix:e})}function ze(e){return new Bs({check:"overwrite",tx:e})}function _l(e){return ze(t=>t.normalize(e))}function vl(){return ze(e=>e.trim())}function yl(){return ze(e=>e.toLowerCase())}function wl(){return ze(e=>e.toUpperCase())}function xl(){return ze(e=>Lr(e))}function kl(e,t,n){return new e({type:"array",element:t,...A(n)})}function Cl(e,t,n){return new e({type:"custom",check:"custom",fn:t,...A(n)})}function El(e){const t=Sl(n=>(n.addIssue=a=>{if(typeof a=="string")n.issues.push($e(a,n.value,t._zod.def));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),n.issues.push($e(i))}},e(n.value,n)));return t}function Sl(e,t){const n=new Q({check:"custom",...A(t)});return n._zod.check=e,n}function qn(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Oe,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function W(e,t,n={path:[],schemaPath:[]}){var a;const i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const r={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,r);const s=e._zod.toJSONSchema?.();if(s)r.schema=s;else{const g={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,r.schema,g);else{const u=r.schema,p=t.processors[i.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);p(e,t,u,g)}const d=e._zod.parent;d&&(r.ref||(r.ref=d),W(d,t,g),t.seen.get(d).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(r.schema,c),t.io==="input"&&X(e)&&(delete r.schema.examples,delete r.schema.default),t.io==="input"&&r.schema._prefault&&((a=r.schema).default??(a.default=r.schema._prefault)),delete r.schema._prefault,t.seen.get(e).schema}function Hn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=new Map;for(const r of e.seen.entries()){const s=e.metadataRegistry.get(r[0])?.id;if(s){const c=a.get(s);if(c&&c!==r[0])throw new Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);a.set(s,r[0])}}const i=r=>{const s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const d=e.external.registry.get(r[0])?.id,u=e.external.uri??(f=>f);if(d)return{ref:u(d)};const p=r[1].defId??r[1].schema.id??`schema${e.counter++}`;return r[1].defId=p,{defId:p,ref:`${u("__shared")}#/${s}/${p}`}}if(r[1]===n)return{ref:"#"};const l=`#/${s}/`,g=r[1].schema.id??`__schema${e.counter++}`;return{defId:g,ref:l+g}},o=r=>{if(r[1].schema.$ref)return;const s=r[1],{ref:c,defId:l}=i(r);s.def={...s.schema},l&&(s.defId=l);const g=s.schema;for(const d in g)delete g[d];g.$ref=c};if(e.cycles==="throw")for(const r of e.seen.entries()){const s=r[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.cycle?.join("/")}/<root>
95
95
 
96
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const r of e.seen.entries()){const s=r[1];if(t===r[0]){o(r);continue}if(e.external){const l=e.external.registry.get(r[0])?.id;if(t!==r[0]&&l){o(r);continue}}if(e.metadataRegistry.get(r[0])?.id){o(r);continue}if(s.cycle){o(r);continue}if(s.count>1&&e.reused==="ref"){o(r);continue}}}function Vn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=r=>{const s=e.seen.get(r);if(s.ref===null)return;const c=s.def??s.schema,l={...c},g=s.ref;if(s.ref=null,g){a(g);const u=e.seen.get(g),p=u.schema;if(p.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(p)):Object.assign(c,p),Object.assign(c,l),r._zod.parent===g)for(const _ in c)_==="$ref"||_==="allOf"||_ in l||delete c[_];if(p.$ref&&u.def)for(const _ in c)_==="$ref"||_==="allOf"||_ in u.def&&JSON.stringify(c[_])===JSON.stringify(u.def[_])&&delete c[_]}const d=r._zod.parent;if(d&&d!==g){a(d);const u=e.seen.get(d);if(u?.schema.$ref&&(c.$ref=u.schema.$ref,u.def))for(const p in c)p==="$ref"||p==="allOf"||p in u.def&&JSON.stringify(c[p])===JSON.stringify(u.def[p])&&delete c[p]}e.override({zodSchema:r,jsonSchema:c,path:s.path??[]})};for(const r of[...e.seen.entries()].reverse())a(r[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const r=e.external.registry.get(t)?.id;if(!r)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(r)}Object.assign(i,n.def??n.schema);const o=e.external?.defs??{};for(const r of e.seen.entries()){const s=r[1];s.def&&s.defId&&(o[s.defId]=s.def)}e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?i.$defs=o:i.definitions=o);try{const r=JSON.parse(JSON.stringify(i));return Object.defineProperty(r,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ye(t,"input",e.processors),output:Ye(t,"output",e.processors)}},enumerable:!1,writable:!1}),r}catch{throw new Error("Error converting schema to JSON.")}}function X(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const a=e._zod.def;if(a.type==="transform")return!0;if(a.type==="array")return X(a.element,n);if(a.type==="set")return X(a.valueType,n);if(a.type==="lazy")return X(a.getter(),n);if(a.type==="promise"||a.type==="optional"||a.type==="nonoptional"||a.type==="nullable"||a.type==="readonly"||a.type==="default"||a.type==="prefault")return X(a.innerType,n);if(a.type==="intersection")return X(a.left,n)||X(a.right,n);if(a.type==="record"||a.type==="map")return X(a.keyType,n)||X(a.valueType,n);if(a.type==="pipe")return X(a.in,n)||X(a.out,n);if(a.type==="object"){for(const i in a.shape)if(X(a.shape[i],n))return!0;return!1}if(a.type==="union"){for(const i of a.options)if(X(i,n))return!0;return!1}if(a.type==="tuple"){for(const i of a.items)if(X(i,n))return!0;return!!(a.rest&&X(a.rest,n))}return!1}const Tl=(e,t={})=>n=>{const a=qn({...n,processors:t});return W(e,a),Hn(a,e),Vn(a,e)},Ye=(e,t,n={})=>a=>{const{libraryOptions:i,target:o}=a??{},r=qn({...i??{},target:o,io:t,processors:n});return W(e,r),Hn(r,e),Vn(r,e)},Il={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Al=(e,t,n,a)=>{const i=n;i.type="string";const{minimum:o,maximum:r,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof o=="number"&&(i.minLength=o),typeof r=="number"&&(i.maxLength=r),s&&(i.format=Il[s]??s,i.format===""&&delete i.format,s==="time"&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){const g=[...c];g.length===1?i.pattern=g[0].source:g.length>1&&(i.allOf=[...g.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},zl=(e,t,n,a)=>{const i=n,{minimum:o,maximum:r,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:g}=e._zod.bag;typeof s=="string"&&s.includes("int")?i.type="integer":i.type="number",typeof g=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.minimum=g,i.exclusiveMinimum=!0):i.exclusiveMinimum=g),typeof o=="number"&&(i.minimum=o,typeof g=="number"&&t.target!=="draft-04"&&(g>=o?delete i.minimum:delete i.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l),typeof r=="number"&&(i.maximum=r,typeof l=="number"&&t.target!=="draft-04"&&(l<=r?delete i.maximum:delete i.exclusiveMaximum)),typeof c=="number"&&(i.multipleOf=c)},Pl=(e,t,n,a)=>{n.type="boolean"},Ll=(e,t,n,a)=>{n.not={}},Nl=(e,t,n,a)=>{},Ml=(e,t,n,a)=>{const i=e._zod.def,o=cn(i.entries);o.every(r=>typeof r=="number")&&(n.type="number"),o.every(r=>typeof r=="string")&&(n.type="string"),n.enum=o},$l=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Ol=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Rl=(e,t,n,a)=>{const i=n,o=e._zod.def,{minimum:r,maximum:s}=e._zod.bag;typeof r=="number"&&(i.minItems=r),typeof s=="number"&&(i.maxItems=s),i.type="array",i.items=W(o.element,t,{...a,path:[...a.path,"items"]})},Bl=(e,t,n,a)=>{const i=n,o=e._zod.def;i.type="object",i.properties={};const r=o.shape;for(const l in r)i.properties[l]=W(r[l],t,{...a,path:[...a.path,"properties",l]});const s=new Set(Object.keys(r)),c=new Set([...s].filter(l=>{const g=o.shape[l]._zod;return t.io==="input"?g.optin===void 0:g.optout===void 0}));c.size>0&&(i.required=Array.from(c)),o.catchall?._zod.def.type==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=W(o.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},Dl=(e,t,n,a)=>{const i=e._zod.def,o=i.inclusive===!1,r=i.options.map((s,c)=>W(s,t,{...a,path:[...a.path,o?"oneOf":"anyOf",c]}));o?n.oneOf=r:n.anyOf=r},Ul=(e,t,n,a)=>{const i=e._zod.def,o=W(i.left,t,{...a,path:[...a.path,"allOf",0]}),r=W(i.right,t,{...a,path:[...a.path,"allOf",1]}),s=l=>"allOf"in l&&Object.keys(l).length===1,c=[...s(o)?o.allOf:[o],...s(r)?r.allOf:[r]];n.allOf=c},Fl=(e,t,n,a)=>{const i=n,o=e._zod.def;i.type="object";const r=o.keyType,c=r._zod.bag?.patterns;if(o.mode==="loose"&&c&&c.size>0){const g=W(o.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});i.patternProperties={};for(const d of c)i.patternProperties[d.source]=g}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(i.propertyNames=W(o.keyType,t,{...a,path:[...a.path,"propertyNames"]})),i.additionalProperties=W(o.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const l=r._zod.values;if(l){const g=[...l].filter(d=>typeof d=="string"||typeof d=="number");g.length>0&&(i.required=g)}},Zl=(e,t,n,a)=>{const i=e._zod.def,o=W(i.innerType,t,a),r=t.seen.get(e);t.target==="openapi-3.0"?(r.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},jl=(e,t,n,a)=>{const i=e._zod.def;W(i.innerType,t,a);const o=t.seen.get(e);o.ref=i.innerType},ql=(e,t,n,a)=>{const i=e._zod.def;W(i.innerType,t,a);const o=t.seen.get(e);o.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Hl=(e,t,n,a)=>{const i=e._zod.def;W(i.innerType,t,a);const o=t.seen.get(e);o.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Vl=(e,t,n,a)=>{const i=e._zod.def;W(i.innerType,t,a);const o=t.seen.get(e);o.ref=i.innerType;let r;try{r=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=r},Wl=(e,t,n,a)=>{const i=e._zod.def,o=t.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;W(o,t,a);const r=t.seen.get(e);r.ref=o},Gl=(e,t,n,a)=>{const i=e._zod.def;W(i.innerType,t,a);const o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0},Wn=(e,t,n,a)=>{const i=e._zod.def;W(i.innerType,t,a);const o=t.seen.get(e);o.ref=i.innerType},Kl=m("ZodISODateTime",(e,t)=>{Xs.init(e,t),j.init(e,t)});function Yl(e){return al(Kl,e)}const Jl=m("ZodISODate",(e,t)=>{Qs.init(e,t),j.init(e,t)});function Xl(e){return il(Jl,e)}const Ql=m("ZodISOTime",(e,t)=>{ec.init(e,t),j.init(e,t)});function ed(e){return ol(Ql,e)}const td=m("ZodISODuration",(e,t)=>{tc.init(e,t),j.init(e,t)});function nd(e){return rl(td,e)}const te=m("ZodError",(e,t)=>{hn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Hr(e,n)},flatten:{value:n=>qr(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,st,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,st,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),ad=pt(te),id=ut(te),od=qe(te),rd=He(te),sd=Gr(te),cd=Kr(te),ld=Yr(te),dd=Jr(te),gd=Xr(te),pd=Qr(te),ud=es(te),hd=ts(te),V=m("ZodType",(e,t)=>(H.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ye(e,"input"),output:Ye(e,"output")}}),e.toJSONSchema=Tl(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(me(t,{checks:[...t.checks??[],...n.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),{parent:!0}),e.with=e.check,e.clone=(n,a)=>be(e,n,a),e.brand=()=>e,e.register=((n,a)=>(n.add(e,a),e)),e.parse=(n,a)=>ad(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>od(e,n,a),e.parseAsync=async(n,a)=>id(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>rd(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>sd(e,n,a),e.decode=(n,a)=>cd(e,n,a),e.encodeAsync=async(n,a)=>ld(e,n,a),e.decodeAsync=async(n,a)=>dd(e,n,a),e.safeEncode=(n,a)=>gd(e,n,a),e.safeDecode=(n,a)=>pd(e,n,a),e.safeEncodeAsync=async(n,a)=>ud(e,n,a),e.safeDecodeAsync=async(n,a)=>hd(e,n,a),e.refine=(n,a)=>e.check(rg(n,a)),e.superRefine=n=>e.check(sg(n)),e.overwrite=n=>e.check(ze(n)),e.optional=()=>Qn(e),e.exactOptional=()=>Wd(e),e.nullable=()=>ea(e),e.nullish=()=>Qn(ea(e)),e.nonoptional=n=>Qd(e,n),e.array=()=>Z(e),e.or=n=>Xe([e,n]),e.and=n=>Zd(e,n),e.transform=n=>na(e,Hd(n)),e.default=n=>Yd(e,n),e.prefault=n=>Xd(e,n),e.catch=n=>tg(e,n),e.pipe=n=>na(e,n),e.readonly=()=>ig(e),e.describe=n=>{const a=e.clone();return Oe.add(a,{description:n}),a},Object.defineProperty(e,"description",{get(){return Oe.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Oe.get(e);const a=e.clone();return Oe.add(a,n[0]),a},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),Gn=m("_ZodString",(e,t)=>{ht.init(e,t),V.init(e,t),e._zod.processJSONSchema=(a,i,o)=>Al(e,a,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...a)=>e.check(pl(...a)),e.includes=(...a)=>e.check(fl(...a)),e.startsWith=(...a)=>e.check(ml(...a)),e.endsWith=(...a)=>e.check(bl(...a)),e.min=(...a)=>e.check(Ke(...a)),e.max=(...a)=>e.check(Zn(...a)),e.length=(...a)=>e.check(jn(...a)),e.nonempty=(...a)=>e.check(Ke(1,...a)),e.lowercase=a=>e.check(ul(a)),e.uppercase=a=>e.check(hl(a)),e.trim=()=>e.check(vl()),e.normalize=(...a)=>e.check(_l(...a)),e.toLowerCase=()=>e.check(yl()),e.toUpperCase=()=>e.check(wl()),e.slugify=()=>e.check(xl())}),fd=m("ZodString",(e,t)=>{ht.init(e,t),Gn.init(e,t),e.email=n=>e.check(Oc(md,n)),e.url=n=>e.check(Fc(bd,n)),e.jwt=n=>e.check(nl(Ld,n)),e.emoji=n=>e.check(Zc(_d,n)),e.guid=n=>e.check(Bn(Kn,n)),e.uuid=n=>e.check(Rc(Je,n)),e.uuidv4=n=>e.check(Bc(Je,n)),e.uuidv6=n=>e.check(Dc(Je,n)),e.uuidv7=n=>e.check(Uc(Je,n)),e.nanoid=n=>e.check(jc(vd,n)),e.guid=n=>e.check(Bn(Kn,n)),e.cuid=n=>e.check(qc(yd,n)),e.cuid2=n=>e.check(Hc(wd,n)),e.ulid=n=>e.check(Vc(xd,n)),e.base64=n=>e.check(Qc(Ad,n)),e.base64url=n=>e.check(el(zd,n)),e.xid=n=>e.check(Wc(kd,n)),e.ksuid=n=>e.check(Gc(Cd,n)),e.ipv4=n=>e.check(Kc(Ed,n)),e.ipv6=n=>e.check(Yc(Sd,n)),e.cidrv4=n=>e.check(Jc(Td,n)),e.cidrv6=n=>e.check(Xc(Id,n)),e.e164=n=>e.check(tl(Pd,n)),e.datetime=n=>e.check(Yl(n)),e.date=n=>e.check(Xl(n)),e.time=n=>e.check(ed(n)),e.duration=n=>e.check(nd(n))});function k(e){return $c(fd,e)}const j=m("ZodStringFormat",(e,t)=>{F.init(e,t),Gn.init(e,t)}),md=m("ZodEmail",(e,t)=>{js.init(e,t),j.init(e,t)}),Kn=m("ZodGUID",(e,t)=>{Fs.init(e,t),j.init(e,t)}),Je=m("ZodUUID",(e,t)=>{Zs.init(e,t),j.init(e,t)}),bd=m("ZodURL",(e,t)=>{qs.init(e,t),j.init(e,t)}),_d=m("ZodEmoji",(e,t)=>{Hs.init(e,t),j.init(e,t)}),vd=m("ZodNanoID",(e,t)=>{Vs.init(e,t),j.init(e,t)}),yd=m("ZodCUID",(e,t)=>{Ws.init(e,t),j.init(e,t)}),wd=m("ZodCUID2",(e,t)=>{Gs.init(e,t),j.init(e,t)}),xd=m("ZodULID",(e,t)=>{Ks.init(e,t),j.init(e,t)}),kd=m("ZodXID",(e,t)=>{Ys.init(e,t),j.init(e,t)}),Cd=m("ZodKSUID",(e,t)=>{Js.init(e,t),j.init(e,t)}),Ed=m("ZodIPv4",(e,t)=>{nc.init(e,t),j.init(e,t)}),Sd=m("ZodIPv6",(e,t)=>{ac.init(e,t),j.init(e,t)}),Td=m("ZodCIDRv4",(e,t)=>{ic.init(e,t),j.init(e,t)}),Id=m("ZodCIDRv6",(e,t)=>{oc.init(e,t),j.init(e,t)}),Ad=m("ZodBase64",(e,t)=>{rc.init(e,t),j.init(e,t)}),zd=m("ZodBase64URL",(e,t)=>{cc.init(e,t),j.init(e,t)}),Pd=m("ZodE164",(e,t)=>{lc.init(e,t),j.init(e,t)}),Ld=m("ZodJWT",(e,t)=>{gc.init(e,t),j.init(e,t)}),Yn=m("ZodNumber",(e,t)=>{En.init(e,t),V.init(e,t),e._zod.processJSONSchema=(a,i,o)=>zl(e,a,i),e.gt=(a,i)=>e.check(Un(a,i)),e.gte=(a,i)=>e.check(bt(a,i)),e.min=(a,i)=>e.check(bt(a,i)),e.lt=(a,i)=>e.check(Dn(a,i)),e.lte=(a,i)=>e.check(mt(a,i)),e.max=(a,i)=>e.check(mt(a,i)),e.int=a=>e.check(Jn(a)),e.safe=a=>e.check(Jn(a)),e.positive=a=>e.check(Un(0,a)),e.nonnegative=a=>e.check(bt(0,a)),e.negative=a=>e.check(Dn(0,a)),e.nonpositive=a=>e.check(mt(0,a)),e.multipleOf=(a,i)=>e.check(Fn(a,i)),e.step=(a,i)=>e.check(Fn(a,i)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function ve(e){return sl(Yn,e)}const Nd=m("ZodNumberFormat",(e,t)=>{pc.init(e,t),Yn.init(e,t)});function Jn(e){return cl(Nd,e)}const Md=m("ZodBoolean",(e,t)=>{uc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Pl(e,n,a)});function _t(e){return ll(Md,e)}const $d=m("ZodUnknown",(e,t)=>{hc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Nl()});function ie(){return dl($d)}const Od=m("ZodNever",(e,t)=>{fc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Ll(e,n,a)});function Rd(e){return gl(Od,e)}const Bd=m("ZodArray",(e,t)=>{mc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Rl(e,n,a,i),e.element=t.element,e.min=(n,a)=>e.check(Ke(n,a)),e.nonempty=n=>e.check(Ke(1,n)),e.max=(n,a)=>e.check(Zn(n,a)),e.length=(n,a)=>e.check(jn(n,a)),e.unwrap=()=>e.element});function Z(e,t){return kl(Bd,e,t)}const Dd=m("ZodObject",(e,t)=>{_c.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Bl(e,n,a,i),B(e,"shape",()=>t.shape),e.keyof=()=>yt(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ie()}),e.loose=()=>e.clone({...e._zod.def,catchall:ie()}),e.strict=()=>e.clone({...e._zod.def,catchall:Rd()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Dr(e,n),e.safeExtend=n=>Ur(e,n),e.merge=n=>Fr(e,n),e.pick=n=>Rr(e,n),e.omit=n=>Br(e,n),e.partial=(...n)=>Zr(Xn,e,n[0]),e.required=(...n)=>jr(ta,e,n[0])});function O(e,t){const n={type:"object",shape:e??{},...A(t)};return new Dd(n)}const Ud=m("ZodUnion",(e,t)=>{vc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Dl(e,n,a,i),e.options=t.options});function Xe(e,t){return new Ud({type:"union",options:e,...A(t)})}const Fd=m("ZodIntersection",(e,t)=>{yc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Ul(e,n,a,i)});function Zd(e,t){return new Fd({type:"intersection",left:e,right:t})}const jd=m("ZodRecord",(e,t)=>{wc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Fl(e,n,a,i),e.keyType=t.keyType,e.valueType=t.valueType});function Re(e,t,n){return new jd({type:"record",keyType:e,valueType:t,...A(n)})}const vt=m("ZodEnum",(e,t)=>{xc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(a,i,o)=>Ml(e,a,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(a,i)=>{const o={};for(const r of a)if(n.has(r))o[r]=t.entries[r];else throw new Error(`Key ${r} not found in enum`);return new vt({...t,checks:[],...A(i),entries:o})},e.exclude=(a,i)=>{const o={...t.entries};for(const r of a)if(n.has(r))delete o[r];else throw new Error(`Key ${r} not found in enum`);return new vt({...t,checks:[],...A(i),entries:o})}});function yt(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new vt({type:"enum",entries:n,...A(t)})}const qd=m("ZodTransform",(e,t)=>{kc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Ol(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new rn(e.constructor.name);n.addIssue=o=>{if(typeof o=="string")n.issues.push($e(o,n.value,t));else{const r=o;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=e),n.issues.push($e(r))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(o=>(n.value=o,n)):(n.value=i,n)}});function Hd(e){return new qd({type:"transform",transform:e})}const Xn=m("ZodOptional",(e,t)=>{Ln.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Wn(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function Qn(e){return new Xn({type:"optional",innerType:e})}const Vd=m("ZodExactOptional",(e,t)=>{Cc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Wn(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function Wd(e){return new Vd({type:"optional",innerType:e})}const Gd=m("ZodNullable",(e,t)=>{Ec.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Zl(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function ea(e){return new Gd({type:"nullable",innerType:e})}const Kd=m("ZodDefault",(e,t)=>{Sc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>ql(e,n,a,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Yd(e,t){return new Kd({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():pn(t)}})}const Jd=m("ZodPrefault",(e,t)=>{Tc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Hl(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function Xd(e,t){return new Jd({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():pn(t)}})}const ta=m("ZodNonOptional",(e,t)=>{Ic.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>jl(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function Qd(e,t){return new ta({type:"nonoptional",innerType:e,...A(t)})}const eg=m("ZodCatch",(e,t)=>{Ac.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Vl(e,n,a,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function tg(e,t){return new eg({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const ng=m("ZodPipe",(e,t)=>{zc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Wl(e,n,a,i),e.in=t.in,e.out=t.out});function na(e,t){return new ng({type:"pipe",in:e,out:t})}const ag=m("ZodReadonly",(e,t)=>{Pc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Gl(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function ig(e){return new ag({type:"readonly",innerType:e})}const og=m("ZodCustom",(e,t)=>{Lc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>$l(e,n)});function rg(e,t={}){return Cl(og,e,t)}function sg(e){return El(e)}const cg=O({role:yt(["user","assistant"]),content:k(),timestamp:ve().optional()}),lg=O({sku:k(),name:k(),imageUrl:k().url().optional(),price:k().optional(),originalPrice:k().optional(),url:k().url(),ctaLabel:k().optional()}),dg=O({buttons:Z(O({label:k(),action:O({title:k(),type:k(),payload:ie().optional()})}))}),gg=O({}),pg=O({label:k().optional()}),aa=O({sku:k(),name:k(),price:k(),imageUrl:k().optional(),rating:ve().optional(),reviewCount:ve().optional()}),ug=O({recommended:aa,products:Z(aa),attributes:Z(O({label:k(),values:Z(k())})),highlights:Z(k()),specialCases:Z(k()).optional(),recommendedText:k().optional(),winnerHits:Re(k(),O({positive:Z(k()).optional(),negative:Z(k()).optional()})).optional(),productActions:Re(k(),O({title:k(),type:k(),payload:ie().optional()})).optional()}),hg=O({label:k(),sentiment:yt(["positive","negative","neutral"]).optional()}),fg=O({product:Re(k(),ie()),role:k().optional(),reason:k().optional(),labels:Z(hg).optional(),expertQualityScore:ve().optional(),reviewHighlight:k().optional(),action:O({title:k(),type:k(),payload:ie().optional()}).optional()}),mg=O({suggestions:Z(fg)}),bg=O({title:k().optional(),text:k().optional(),reviewCount:k().optional(),action:O({title:k(),type:k(),payload:ie().optional()})}),_g=O({entries:Z(O({name:k(),image:k().optional(),description:k().optional(),action:O({title:k(),type:k(),payload:ie().optional()})}))}),vg=O({entries:Z(O({shortName:k(),detailedMessage:k().optional(),whyDifferent:k().optional(),image:k().optional(),action:O({title:k(),type:k(),payload:ie().optional()})}))}),ia=O({title:k(),type:k(),payload:ie().optional()}),yg=O({name:k().optional(),variant_name:k().optional(),sku:k().optional(),price:Xe([ve(),k()]).optional()}),wg=O({product:O({sku:k().optional(),name:k().optional(),images:Z(k()).optional(),imageUrl:k().optional(),rating:ve().optional(),reviewCount:ve().optional(),price:k().optional(),originalPrice:k().optional(),price_async:_t().optional(),inStock:_t().optional(),promotions:Z(k()).optional(),variants:Z(yg).optional(),url:k().optional(),cartCode:k().optional(),description:k().optional(),specifications:Xe([Re(k(),k()),Z(O({key:k(),value:k()}))]).optional()}).optional(),action:ia.optional()}),xg=O({endOfList:_t().optional()}),kg=O({review_class:k().optional(),review_text:k().optional(),review_rating:Xe([k(),ve()]).optional(),review_tag:k().optional()}),Cg=O({reviews:Z(kg).optional()}),Eg=O({productName:k().optional(),pros:Z(k()).optional(),cons:Z(k()).optional()}),Sg=O({groups:Z(O({groupName:k(),products:Z(Re(k(),ie())).optional()})).optional(),filterTags:Z(O({title:k(),action:ia.optional()})).optional()}),Tg=O({summary:k().optional(),products_discussed:Z(k()).optional(),user_sentiment:k().optional()}),Ig={components:{MessageBubble:{schema:cg,description:"A single chat message bubble for user or assistant turns."},ProductCard:{schema:lg,description:"A product card rendered inline in the chat stream."},ActionButtons:{schema:dg,description:"A horizontal row of quick-reply action buttons."},TypingIndicator:{schema:gg,description:"An animated indicator shown while the assistant is typing."},Divider:{schema:pg,description:"A horizontal rule with an optional label."},ComparisonTable:{schema:ug,description:"A product comparison table with recommended pick, attribute rows, and highlights."},AITopPicks:{schema:mg,description:"Rich AI-curated product suggestion cards with roles, sentiment labels, scores, and review quotes."},GroundingReviewCard:{schema:bg,description:"A card showing review grounding data with review count and CTA."},AIGroupingCards:{schema:_g,description:"Category grouping cards with images and labels for product discovery."},AISuggestedSearchCards:{schema:vg,description:"Suggested search cards with images, descriptions, and differentiation."},ProductDetailsPanel:{schema:wg,description:"Full product detail view with images, specs, variants, and purchase actions."},ProductGrid:{schema:xg,description:'A scrollable grid of ProductCard children with optional "more" pagination.'},ReviewHighlights:{schema:Cg,description:"A list of highlighted customer reviews with sentiment and ratings."},ProsAndCons:{schema:Eg,description:"A pros and cons list for a product."},CategoriesContainer:{schema:Sg,description:"Tabbed product groups with optional filter tag buttons."},HandoffNotice:{schema:Tg,description:"A notice shown when the conversation is escalated to a human agent."}}};function Ag(e){return e.length>120?!1:/^[a-zA-Z0-9#(),.\s%/\-]+$/.test(e)}function wt(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}class oa extends Za{constructor(){super(...arguments),this._shadow=null,this._rootEl=null,this._launcher=null,this._drawer=null,this._bridge=null,this._drawerVisible=!1,this._messages=[],this._currentMessageId=0,this._abortControllers=new Set,this._currentThreadId=null,this._lastThreadId=null,this._chatCreatedAt="",this._lastBackendContext=null,this._productSort={type:"related"},this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._thumbnailEntries=[],this._choicePrompterEl=null,this._openState="full",this._mobileBreakpoint=768,this._isMobileViewport=!1,this._pdpLaunched=!1,this._pdpPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._i18n=nt,this._extendedModeManager=null,this._activeTypewriter=null,this._activeTtsHandle=null,this._activeRequestThreadId=null,this._skuToProductItem={},this._conversationMode=null,this._initComplete=!1,this._pendingActions=[],this._bridgeContext=null,this._cartQuantity=null,this._threadsWithFirstBot=new Set,this._panel=null,this._session=null,this._eventCallbacks=new Map,this._lastSentAction=null}async onInit(t){this._i18n=this._resolveI18n(t),this._chatCreatedAt=new Date().toISOString(),this._shadow=this.root.attachShadow({mode:"open"});const n=document.createElement("style");n.textContent=hr,this._shadow.appendChild(n);const a=document.createElement("div");a.className="gengage-chat-root",this._rootEl=a,this._shadow.appendChild(a);const i=t.variant??"floating";if(i==="floating"){const d={onClick:()=>this.open(),ariaLabel:this._i18n.openButton};t.launcherImageUrl!==void 0?d.imageUrl=t.launcherImageUrl:t.launcherSvg!==void 0&&(d.svgMarkup=t.launcherSvg),t.hideMobileLauncher!==void 0&&(d.hideMobile=t.hideMobileLauncher),t.mobileBreakpoint!==void 0&&(d.mobileBreakpoint=t.mobileBreakpoint),t.launcherTooltip!==void 0&&(d.tooltip=t.launcherTooltip),this._launcher=co(d),a.appendChild(this._launcher.container)}i==="overlay"&&a.classList.add("gengage-chat--overlay");const o=document.createElement("div");a.appendChild(o),this._drawer=new ro(o,{i18n:this._i18n,onSend:(d,u)=>this._sendMessage(d,u),onClose:()=>this.close(),onAttachment:d=>this._handleAttachment(d),onPanelToggle:()=>{this._drawer?.persistPanelState(t.accountId)},onRollback:d=>this._handleRollback(d),onPanelBack:()=>this._panel?.navigateBack(),onPanelForward:()=>this._panel?.navigateForward(),headerTitle:t.headerTitle,headerAvatarUrl:t.headerAvatarUrl,headerBadge:t.headerBadge,headerCartUrl:t.headerCartUrl,headerFavoritesToggle:t.headerFavoritesToggle,onFavoritesClick:()=>{Cr(),t.onFavoritesClick?.()},onThumbnailClick:d=>this._rollbackToThread(d),onLinkClick:d=>{this._saveSessionAndOpenURL(d)},voiceEnabled:t.voiceEnabled,voiceLang:t.locale?`${t.locale.split("-")[0]??"tr"}-${(t.locale.split("-")[1]??t.locale.split("-")[0]??"TR").toUpperCase()}`:void 0}),this._extendedModeManager=new ir({onChange:d=>this._panel?.notifyExtension(d),productDetailsInPanel:t.isDemoWebsite??!1}),this._panel=new or({drawer:()=>this._drawer,shadow:()=>this._shadow,currentThreadId:()=>this._currentThreadId,bridge:()=>this._bridge,extendedModeManager:()=>this._extendedModeManager,i18n:()=>this._i18n,rollbackToThread:d=>this._rollbackToThread(d)}),i!=="inline"&&this._drawer.getElement().classList.add("gengage-chat-drawer--hidden"),this._drawer.restorePanelState(t.accountId);const r=t.panelMode??"auto";r==="collapsed"?this._drawer.setPanelCollapsed(!0):r==="expanded"&&this._drawer.setForceExpanded();const s=sessionStorage.getItem("gengage_restore_session_id"),c=sessionStorage.getItem("gengage_restore_sku"),l=!!(s&&c);l&&(sessionStorage.removeItem("gengage_restore_session_id"),sessionStorage.removeItem("gengage_restore_sku"));try{const d=new nr;await d.open(),this._session=new en(d),await this._restoreFromIndexedDB(l)}catch{this._session=new en(null)}this._registerPublicAPI(),t.mobileInitialState!==void 0&&(this._openState=t.mobileInitialState),this._mobileBreakpoint=t.mobileBreakpoint??768,this._syncViewportState();const g=()=>this._syncViewportState();if(window.addEventListener("resize",g,{passive:!0}),this.addCleanup(()=>window.removeEventListener("resize",g)),window.visualViewport){const d=()=>{if(!this._drawerVisible||!this._isMobileViewport)return;const u=this._drawer?.getElement();if(!u)return;const p=window.innerHeight-(window.visualViewport?.height??window.innerHeight);u.style.setProperty("--gengage-keyboard-offset",`${Math.max(0,p)}px`)};window.visualViewport.addEventListener("resize",d),this.addCleanup(()=>window.visualViewport?.removeEventListener("resize",d))}i==="inline"&&(this._drawerVisible=!0,this.isVisible=!0,this._applyOpenStateClasses()),this._bridge=new Ha({namespace:"chat",onMessage:d=>this._handleBridgeMessage(d)}),this._lastSku=this.config.pageContext?.sku,this._initComplete=!0;for(const d of this._pendingActions)this._sendAction(d.action,d.options);this._pendingActions=[],re("gengage:chat:ready",{}),mr("chat"),t.onReady?.()}onUpdate(t){t.sku!==void 0&&t.sku!==this._lastSku&&(this._lastSku=t.sku,this._resetForNewPage())}onShow(){this._showDrawer(),this.emit("open"),re("gengage:chat:open",{state:this._openState}),br("chat"),this.config.onOpen?.(),!this._pdpLaunched&&this.config.pageContext?.sku&&(this._pdpLaunched=!0,this._pdpPrimingInFlight=!0,this._sendAction({title:"",type:"launchSingleProduct",payload:{sku:this.config.pageContext.sku}},{silent:!0,isPdpPrime:!0}))}onHide(){(this.config.variant??"floating")==="floating"&&(this.root.style.display=""),this._hideDrawer(),this.emit("close"),re("gengage:chat:close",{}),this.config.onClose?.()}onDestroy(){this._abortControllers.forEach(t=>t.abort()),this._abortControllers.clear(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._drawer?.destroy(),this._drawer=null,this._bridge?.destroy(),this._bridge=null,this._extendedModeManager=null,this._panel?.destroy(),this._panel=null,this._session?.close(),this._session=null,window.gengage&&delete window.gengage.chat,this._shadow&&(this._shadow.innerHTML="",this._shadow=null),this._rootEl=null}open(t){t?.state!==void 0&&(this._openState=t.state,this._drawerVisible&&this._applyOpenStateClasses()),this.show(),t?.initialMessage!==void 0&&this._sendMessage(t.initialMessage)}openWithAction(t,n){n?.sku!==void 0&&this.update({sku:n.sku}),this._pdpLaunched=!0,n?.state!==void 0?this._openState=n.state:this._isMobileViewport&&(this._openState="half"),this.show(),this._drawerVisible&&this._applyOpenStateClasses(),this._sendAction(t)}sendMessage(t){this._sendMessage(t)}sendAction(t,n){this._sendAction(t,n)}close(){this.hide()}saveSession(t,n){sessionStorage.setItem("gengage_restore_session_id",t),sessionStorage.setItem("gengage_restore_sku",n)}get isOpen(){return this._drawerVisible}addCallback(t,n){let a=this._eventCallbacks.get(t);return a||(a=new Set,this._eventCallbacks.set(t,a)),a.add(n),()=>{a.delete(n),a.size===0&&this._eventCallbacks.delete(t)}}_resetForNewPage(){this._activeRequestThreadId=null,this._abortControllers.forEach(t=>t.abort()),this._abortControllers.clear(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._messages.length=0,this._drawer?.clearMessages(),this._drawer?.clearPanel(),this._panel.snapshots.clear(),this._panel.threads=[],this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._currentThreadId=null,this._lastThreadId=null,this._lastBackendContext=null,this._chatCreatedAt=new Date().toISOString(),this._pdpLaunched=!1,this._pdpPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null}_handleBridgeMessage(t){switch(t.type){case"openChat":this.open();break;case"closeChat":this.close();break;case"startNewChatWithLauncherAction":{const n=t.payload,a=n?.action,i=wt(a)?a:wt(n)?n:null;i&&this._sendAction(i,{silent:!0}),this.open();break}case"startNewChatWithDetailContext":{const n=t.payload;if(n&&typeof n=="object"){this._bridgeContext=n;const a=n.sku;if(a&&this.update({sku:a}),wt(n.action)){this._pdpLaunched=!0,this.open(),this._sendAction(n.action);break}}this.open();break}case"launcherAction":{const a=t.payload?.action;a&&typeof a=="object"&&"type"in a&&this._sendAction(a);break}case"scrollToBottom":this._drawer?.scrollToBottomIfNeeded();break;case"addToCardHandler":{this._bridge?.send("addToCardResult",t.payload);break}case"cartQuantityHandler":{const n=t.payload;n&&"quantity"in n&&typeof n.quantity=="number"&&(this._cartQuantity=n.quantity);break}case"minimizeRequestedByUser":this._extendedModeManager?.setHiddenByUser(!0);break;case"bgColorChange":{const a=t.payload?.color;typeof a=="string"&&Ag(a)&&this._shadow&&this._shadow.host.style.setProperty("--gengage-chat-bg",a);break}}}_registerPublicAPI(){window.gengage||(window.gengage={}),window.gengage.chat={open:t=>this.open(t),openWithAction:(t,n)=>this.openWithAction(t,n),sendMessage:t=>this.sendMessage(t),sendAction:(t,n)=>this.sendAction(t,n),close:()=>this.close(),saveSession:(t,n)=>this.saveSession(t,n),get isOpen(){return!1},on:(t,n)=>this.on(t,n),trackCheckout:(t,n)=>this.trackCheckout(t,n),flushMeteringSummary:t=>this.flushMeteringSummary(t),addCallback:(t,n)=>this.addCallback(t,n)},Object.defineProperty(window.gengage.chat,"isOpen",{get:()=>this._drawerVisible})}_showDrawer(){if(this._drawerVisible)return;this._drawerVisible=!0;const t=this._drawer?.getElement();t&&t.classList.remove("gengage-chat-drawer--hidden"),this._applyOpenStateClasses(),this._drawer?.trapFocus(),this._isMobileViewport&&this._openState==="half"||this._drawer?.focusInput(),this._extendedModeManager?.setChatShown(!0)}_hideDrawer(){if(!this._drawerVisible)return;this._drawer?.releaseFocus(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._drawerVisible=!1,this._openState="full";const t=this._drawer?.getElement();t&&t.classList.add("gengage-chat-drawer--hidden"),this._applyOpenStateClasses(),this._extendedModeManager?.setChatShown(!1)}_syncViewportState(){if(this._rootEl){if(this._isMobileViewport=window.innerWidth<=this._mobileBreakpoint,this._rootEl.classList.toggle("gengage-chat-root--mobile",this._isMobileViewport),this._launcher){const t=this._isMobileViewport&&this.config.hideMobileLauncher===!0;this._launcher.container.classList.toggle("gengage-chat-launcher--hidden-mobile",t)}this._applyOpenStateClasses()}}_applyOpenStateClasses(){if(!this._rootEl)return;const t=this._drawerVisible&&this._isMobileViewport&&this._openState==="half",n=this._drawerVisible&&this._isMobileViewport&&this._openState==="full";this._rootEl.classList.toggle("gengage-chat-root--open",this._drawerVisible),this._rootEl.classList.toggle("gengage-chat-root--mobile-half",t),this._rootEl.classList.toggle("gengage-chat-root--mobile-full",n)}_handleAttachment(t){const n=Qa(t);if(!n.ok){const a=n.reason==="invalid_type"?this._i18n.invalidFileType:this._i18n.fileTooLarge;re("gengage:global:error",{message:a,source:"chat"});return}this._drawer?.stageAttachment(t)}_sendMessage(t,n){if(this._pdpPrimingInFlight){this._queuedUserMessages.push(n!==void 0?{text:t,attachment:n}:{text:t});return}Ir(),this._messages.some(o=>o.role==="user")||Ar();const i={title:t,type:"user_message",payload:t};n!==void 0?this._sendAction(i,{attachment:n}):this._sendAction(i)}_flushQueuedUserMessages(){if(this._pdpPrimingInFlight||this._queuedUserMessages.length===0)return;const t=[...this._queuedUserMessages];this._queuedUserMessages=[];for(const n of t)this._sendMessage(n.text,n.attachment)}_sendAction(t,n){if(this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._lastSentAction={action:t,options:n},!this._initComplete){this._pendingActions.length<10&&this._pendingActions.push({action:t,options:n});return}if(this._choicePrompterEl?.remove(),this._choicePrompterEl=null,!n?.preservePanel&&this._comparisonSelectMode&&(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[]),this._currentThreadId&&this._lastThreadId&&this._lastThreadId>this._currentThreadId){const h=this._currentThreadId,x=this._messages.filter(E=>E.threadId!==void 0&&E.threadId>h);this._messages=this._messages.filter(E=>!E.threadId||E.threadId<=h);for(const E of x)this._shadow?.querySelector(`[data-message-id="${CSS.escape(E.id)}"]`)?.remove(),this._panel.snapshots.delete(E.id),this._panel.snapshotTypes.delete(E.id);this._shadow?.querySelectorAll("[data-thread-id]")?.forEach(E=>{E instanceof HTMLElement&&E.dataset.threadId&&E.dataset.threadId>h&&E.remove()})}this._drawer?.setPills([]),this._drawer?.clearInputAreaChips(),this._bridge?.send("isResponding",!0);const a=qa();this._currentThreadId=a,this._lastThreadId=a,this._panel&&t.type!=="launchSingleProduct"&&(this._panel.lastActionType=t.type);const i=n?.preservePanel===!0,o=t.type==="launchSingleProduct"&&n?.silent===!0&&n?.isPdpPrime===!0;if(i||(this._activeRequestThreadId=a),!n?.silent){const h=this._createMessage("user",typeof t.payload=="string"?t.payload:t.title);h.threadId=a,n?.attachment!==void 0&&(h.attachment=n.attachment),this._drawer?.addMessage(h),this._messages.push(h)}if(!n?.silent&&this._hasUnavailableProductContext()&&(t.type==="user_message"||t.type==="inputText")){const h=this._i18n.productNotFoundMessage,x=this._createMessage("assistant",h);x.threadId=a,x.status="done",this._messages.push(x),this._ensureAssistantMessageRendered(x),this._drawer?.updateBotMessage(x.id,h),this._bridge?.send("isResponding",!1),this.emit("message",x),this._persistToIndexedDB().catch(()=>{});return}let s=null;const c=()=>{if(s||n?.preservePanel)return;const h=this._drawer?.getPanelContentElement();h&&(s=h.cloneNode(!0))},l=()=>{this._drawer?.isPanelLoading()&&(s?this._drawer.setPanelContent(s):this._drawer.clearPanel(),s=null)};this._drawer?.showTypingIndicator();let g="";const d=this._createMessage("assistant","");d.threadId=a,d.status="streaming",n?.silent&&(d.silent=!0),this._messages.push(d),n?.preservePanel||(this._abortControllers.forEach(h=>h.abort()),this._abortControllers.clear());const u={middlewareUrl:this.config.middlewareUrl,...this.config.accountId?{accountId:this.config.accountId}:{}};n?.attachment!==void 0&&(u.attachment=n.attachment);const f=this._getVisibleMessages().filter(h=>h.content).slice(-50).map(h=>({role:h.role==="user"?"user":"model",content:h.content??""})),_={outputLanguage:ur(this.config.locale),parentUrl:window.location.href,windowWidth:String(window.innerWidth),windowHeight:String(window.innerHeight),selfUrl:"",id:this.config.session?.sessionId??"",userId:this.config.session?.userId??"",appId:this.config.accountId,threads:[],createdAt:this._chatCreatedAt,kvkkApproved:nn(this.config.accountId),voiceEnabled:this.config.voiceEnabled??!1,threadId:a,isControlGroup:this.config.session?.abTestVariant==="control",isMobile:this._isMobileViewport};this.config.session?.viewId!==void 0&&(_.viewId=this.config.session.viewId);const v=Vi(t,{pageContext:this.config.pageContext,backendContext:this._lastBackendContext,isMobile:this._isMobileViewport}),C={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",type:v.type,locale:this.config.locale??"tr",meta:_,context:{...this._lastBackendContext??{},messages:f,session_id:this.config.session?.sessionId??""}};this.config.session?.userId!==void 0&&(C.user_id=this.config.session.userId),this.config.session?.viewId!==void 0&&(C.view_id=this.config.session.viewId),v.payload!==void 0&&(C.payload=v.payload),this.config.pageContext?.sku!==void 0&&(C.sku=this.config.pageContext.sku),this.config.pageContext?.pageType!==void 0&&(C.page_type=this.config.pageContext.pageType);const T=crypto.randomUUID(),S=Date.now();let y=0,I=!1,D=!1;this.track(ga(this.analyticsContext(),{endpoint:"process_action",request_id:T,widget:"chat"}));let G=null;if(G=Ki(C,{onTextChunk:(h,x,w)=>{if(!i&&a!==this._activeRequestThreadId||(g+=h,this._drawer?.removeTypingIndicator(),w?.skuToProductItem&&(this._skuToProductItem={...this._skuToProductItem,...w.skuToProductItem}),w?.conversationMode&&(this._conversationMode=w.conversationMode),this.track(pa(this.analyticsContext(),{request_id:T,chunk_index:y++,widget:"chat"})),!this._drawer))return;let E=g;if(x&&rt(E)){const P=this.config.accountId;if(!nn(P)){const R=gr(E);R&&this._drawer?.showKvkkBanner(R,()=>{this._drawer?.hideKvkkBanner()}),lr(P)}E=dr(E)}const z=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(z?z.innerHTML=oe(E):(d.content=E,d.role==="assistant"&&d.threadId&&!this._threadsWithFirstBot.has(d.threadId)&&(this._threadsWithFirstBot.add(d.threadId),this._drawer.markFirstBotMessage(d.id)),this._drawer.addMessage(d)),x){d.content=E,d.status="done",on();const P=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(P){this._activeTypewriter?.cancel();const R=w?.productMentions;this._activeTypewriter=Wo({container:P,html:oe(E),onTick:()=>this._drawer?.scrollToBottomIfNeeded(),onComplete:()=>{this._activeTypewriter=null,R&&R.length>0&&P&&Go({container:P,mentions:R,onProductClick:q=>{this._sendAction({title:R.find(M=>M.sku===q)?.short_name??q,type:"launchSingleProduct",payload:{sku:q}})}})}})}}},onUISpec:(h,x,w)=>{if(!i&&a!==this._activeRequestThreadId||x!=="chat")return;const E=h.elements[h.root],z=E?.type??"unknown";this.track(ua(this.analyticsContext(),{request_id:T,chunk_index:y,component_type:z,widget:"chat"}));const P=this._buildRenderContext();if(z==="ComparisonTable"){const M=E?.props?.products;xr(Array.isArray(M)?M.length:0)}if(z==="ProductGrid"){const M=E?.children?.length??0;Er(void 0,M)}const R=w==="panel"&&this._panel?this._panel.toPanelSpec(h):h,q=!d.silent&&(w!=="panel"||z==="ProductCard")&&z!=="ActionButtons";if(w==="panel"&&this._panel){const M=!D;D=!0;const L=rr({componentType:z,similarsAppend:E?.props?.similarsAppend===!0,currentPanelType:this._panel.currentType,hasPanelContent:this._drawer?.hasPanelContent()??!1,isPanelLoading:this._drawer?.isPanelLoading()??!1,isFirstPanelContentInStream:M});L==="appendSimilars"?this._appendSimilarsToPanel(R,P):L==="append"?this._drawer?.appendPanelContent(this._renderUISpec(R,P)):(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._drawer?.setPanelContent(this._renderUISpec(R,P)),this._panel.currentType=z),z==="ProductDetailsPanel"&&t.type==="launchSingleProduct"&&this._clearUnavailableProductContext(),d.threadId&&!this._panel.threads.includes(d.threadId)&&this._panel.threads.push(d.threadId);const $=this._panel.currentType??z,b=E?.props?.panelTitle;this._panel.updateTopBar($,b),this._panel.updateExtendedMode(z)}if(z==="ProductDetailsPanel"&&!d.silent&&w==="panel"){const M=E?.props?.product;if(M){const L={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:M}}}},$=this._shadow?.querySelector(".gengage-chat-messages");if($){const b=this._renderUISpec(L,P);d.threadId&&(b.dataset.threadId=d.threadId),$.appendChild(b),b.scrollIntoView({behavior:"auto",block:"end"})}}}if(q){const M=this._shadow?.querySelector(".gengage-chat-messages");if(M){const L=this._renderUISpec(h,P);d.threadId&&(L.dataset.threadId=d.threadId),M.appendChild(L),L.scrollIntoView({behavior:"auto",block:"end"})}}if((z==="ProductGrid"||z==="ProductCard")&&d.threadId){const M=E?.children??[],L=z==="ProductGrid"?M.map($=>h.elements[$]?.props?.product).filter(Boolean):[E?.props?.product].filter(Boolean);for(const $ of L){const b=$.sku,N=$.imageUrl;b&&N&&this._thumbnailEntries.push({sku:b,imageUrl:N,threadId:d.threadId})}this._drawer?.setThumbnails(this._thumbnailEntries)}if(z==="ProductGrid"||z==="ProductDetailsPanel"){const L=(z==="ProductGrid"?(E?.children??[]).map($=>h.elements[$]?.props?.product).filter(Boolean):[E?.props?.product??E?.props].filter(Boolean)).map($=>$.imageUrl).filter($=>typeof $=="string").slice(0,5);L.length>0&&this._bridge?.send("previewImages",{images:L})}if(z==="ProductGrid"&&w==="panel"&&!this._comparisonSelectMode&&!Qo()){this._choicePrompterEl?.remove(),this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(b=>b.remove()),this._choicePrompterEl=Xo({heading:this._i18n.choicePrompterHeading,suggestion:this._i18n.choicePrompterSuggestion,ctaLabel:this._i18n.choicePrompterCta,dismissAriaLabel:this._i18n.dismissAriaLabel,onCtaClick:()=>{this._comparisonSelectMode=!0,this._choicePrompterEl=null,this._refreshComparisonUI()},onDismiss:()=>{this._choicePrompterEl=null}});const L=this._isMobileViewport||this._drawer?.isPanelCollapsed()?".gengage-chat-conversation":".gengage-chat-panel",$=this._shadow?.querySelector(L);$?$.appendChild(this._choicePrompterEl):this._choicePrompterEl=null}if(z==="ActionButtons"){const M=E?.props?.buttons;if(M&&M.length>0){const L=[],$=[];for(const b of M)if(Jo(b)){const N={label:b.label,action:b.action};b.icon&&(N.icon=b.icon),L.push(N)}else $.push(b);L.length>0&&this._drawer?.setInputAreaChips(L.map(b=>({label:b.label,onAction:()=>this._sendAction(b.action),...b.icon?{icon:b.icon}:{}}))),$.length>0&&this._drawer?.setPills($.map(b=>{const N={label:b.label,onAction:()=>this._sendAction(b.action)};return b.icon&&(N.icon=b.icon),b.image&&(N.image=b.image),b.description&&(N.description=b.description),N}))}}d.uiSpec=h},onAction:h=>{if(!(!i&&a!==this._activeRequestThreadId)&&h.type==="action"){const x={};this.config.actionHandling?.unknownActionPolicy!==void 0&&(x.unknownActionPolicy=this.config.actionHandling.unknownActionPolicy),this.config.actionHandling?.allowScriptCall!==void 0&&(x.allowScriptCall=this.config.actionHandling.allowScriptCall),Ga(h,{openChat:()=>this.open(),navigate:w=>{ee(w.url)&&(this._bridge?.send("navigate",w),w.newTab?window.open(w.url,"_blank","noopener,noreferrer"):window.location.href=w.url)},saveSession:w=>this.saveSession(w.sessionId,w.sku),addToCart:w=>{re("gengage:similar:add-to-cart",w)},scriptCall:w=>{re("gengage:chat:script-call",w),this.config.onScriptCall?.(w)}},x)}},onMetadata:h=>{if(!(!i&&a!==this._activeRequestThreadId)&&h.type==="metadata"&&h.meta){if((h.meta.panel!==void 0||h.meta.messages!==void 0||h.meta.message_id!==void 0)&&(this._lastBackendContext=h.meta),h.meta.panelLoading){I=!0,D=!1,c();const w=typeof h.meta.panelPendingType=="string"?h.meta.panelPendingType:void 0;this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(w),w&&this._panel?.updateTopBarForLoading(w)}if(h.meta.voice){const w=new CustomEvent("gengage:chat:voice",{detail:{payload:h.meta.voice},bubbles:!1,cancelable:!0}),E=window.dispatchEvent(w);if(zr(),E){const z=h.meta.voice;z.audio_base64&&(this._activeTtsHandle?.stop(),this._activeTtsHandle=go(z.audio_base64,z.content_type??"audio/ogg"))}}(h.meta.redirectTarget||h.meta.redirect)&&re("gengage:chat:redirect",{target:h.meta.redirectTarget??null,payload:h.meta.redirect??null}),h.meta.analyzeAnimation&&(I=!0,D=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(),this._panel?.updateTopBarForLoading("productDetails")),h.meta.loading&&typeof h.meta.loadingText=="string"&&(this._drawer?.addThinkingStep(h.meta.loadingText),this._bridge?.send("loadingMessage",{text:h.meta.loadingText})),h.meta.visitorDataResponse&&this._bridge?.send("engagingMessage",h.meta.visitorDataResponse),h.meta.formType&&this._bridge?.send("glovOtokoc",{type:h.meta.formType,data:h.meta.formPayload}),h.meta.launcherContent&&this._bridge?.send("launcherContent",h.meta.launcherContent),re("gengage:chat:metadata",{payload:h.meta});const x=h.meta;typeof x.prompt_tokens=="number"&&typeof x.completion_tokens=="number"&&this.track(ma(this.analyticsContext(),{model:h.model??"unknown",prompt_tokens:x.prompt_tokens,completion_tokens:x.completion_tokens,total_tokens:x.total_tokens??x.prompt_tokens+x.completion_tokens}))}},onError:h=>{if(G&&this._abortControllers.delete(G),!i&&a!==this._activeRequestThreadId)return;this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator();const x=D;if(I&&!D&&l(),I=!1,D=!1,!(d.silent||d.content!=null&&d.content.length>0||g.length>0||x))if(o||this._hasUnavailableProductContext()){const E=this._i18n.productNotFoundMessage;d.content=E,d.status="done",this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,E),this._markUnavailableProductContext()}else this.emit("error",h),this._drawer?.showError(this._i18n.errorMessage,()=>{this._lastSentAction&&this._sendAction(this._lastSentAction.action,this._lastSentAction.options)});o&&(this._pdpPrimingInFlight=!1,this._flushQueuedUserMessages()),d.status==="streaming"&&(d.status="error"),this.track(fa(this.analyticsContext(),{request_id:T,error_code:"STREAM_ERROR",error_message:h.message,widget:"chat"}))},onDone:()=>{if(G&&this._abortControllers.delete(G),!(!i&&a!==this._activeRequestThreadId)){if(this._activeRequestThreadId=null,this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),I&&!D&&l(),I=!1,D=!1,o&&!g&&!D){const h=this._i18n.productNotFoundMessage;d.content=h,this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,h),this._markUnavailableProductContext()}o&&(this._pdpPrimingInFlight=!1,this._flushQueuedUserMessages()),d.status==="streaming"&&(d.status="done",on()),this.emit("message",d),this._panel?.snapshotForMessage(d.id),this._panel?.attachClickHandler(d.id),this.track(ha(this.analyticsContext(),{request_id:T,latency_ms:Date.now()-S,chunk_count:y,widget:"chat"})),this.track(ba(this.analyticsContext(),{meter_key:"chat_request",quantity:1,unit:"request"})),this.track(va(this.analyticsContext(),{message_count:this._messages.length,history_ref:this.config.session?.sessionId??"",redaction_level:"none"})),this._persistToIndexedDB().catch(()=>{})}}},u),this._abortControllers.add(G),!n?.silent&&!i){const h=G;this._drawer?.showStopButton(()=>{h.abort(),this._abortControllers.delete(h),this._drawer?.removeTypingIndicator(),this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),d.status==="streaming"&&(d.status="done")})}}_getVisibleMessages(){const t=this._messages.filter(a=>!a.silent);if(!this._currentThreadId)return t;const n=this._currentThreadId;return t.filter(a=>!a.threadId||a.threadId<=n)}_appendSimilarsToPanel(t,n){if(!this._drawer)return;const a=this._drawer.getPanelContentElement();if(!a)return;const i=document.createElement("h3");i.className="gengage-chat-product-details-similars-heading",i.textContent=this._i18n.similarProductsLabel??"Similar Products",a.appendChild(i);const o=this._renderUISpec(t,n);o.classList.add("gengage-chat-product-details-similars"),a.appendChild(o)}_handleRollback(t){const n=this._messages.find(a=>a.id===t);n?.threadId&&this._rollbackToThread(n.threadId)}_rollbackToThread(t){this._currentThreadId=t,this._extendedModeManager?.setHiddenByUser(!1);for(const o of this._messages){const r=this._shadow?.querySelector(`[data-message-id="${CSS.escape(o.id)}"]`);r&&(o.threadId&&o.threadId>t?r.classList.add("gengage-chat-bubble--hidden"):r.classList.remove("gengage-chat-bubble--hidden"))}this._shadow?.querySelectorAll("[data-thread-id]").forEach(o=>{o instanceof HTMLElement&&o.dataset.threadId&&o.dataset.threadId>t?o.classList.add("gengage-chat-bubble--hidden"):o instanceof HTMLElement&&o.classList.remove("gengage-chat-bubble--hidden")});const n=this._messages.find(o=>o.role==="assistant"&&o.threadId===t);n&&this._panel?.restoreForMessage(n.id)||this._drawer?.clearPanel();const i=this._panel.currentType??"";this._panel?.updateTopBar(i),this._drawer?.setPills([]),this._session?.db&&this.config.session?.sessionId&&this._session?.db.loadContext(this.config.session.sessionId,t).then(o=>{o&&(this._lastBackendContext=o.context)}).catch(()=>{}),this._session?.db&&this.config.session?.sessionId&&this._session?.db.deleteContextsAfterThread(this.config.session.sessionId,t).catch(()=>{})}async _persistToIndexedDB(){!this._session||!this.config.session?.sessionId||await this._session.persist({userId:this.config.session.userId??"",appId:this.config.accountId,sessionId:this.config.session.sessionId,messages:this._messages,currentThreadId:this._currentThreadId,lastThreadId:this._lastThreadId,chatCreatedAt:this._chatCreatedAt,panelSnapshots:this._panel?.snapshots??new Map,panelThreads:this._panel?.threads??[],thumbnailEntries:this._thumbnailEntries,lastBackendContext:this._lastBackendContext,sku:this.config.pageContext?.sku})}_isSameOriginUrl(t){try{return t.trim()?new URL(t,window.location.href).origin===window.location.origin:!1}catch{return!1}}_markUnavailableProductContext(){this._productContextUnavailableSku=this.config.pageContext?.sku??null}_clearUnavailableProductContext(){this._productContextUnavailableSku=null}_hasUnavailableProductContext(){const t=this.config.pageContext?.sku;return t!==void 0&&t.length>0&&this._productContextUnavailableSku===t}_ensureAssistantMessageRendered(t){if(!(this._shadow?.querySelector(`[data-message-id="${CSS.escape(t.id)}"]`)||!this._drawer)){if(t.role==="assistant"&&t.threadId&&!this._threadsWithFirstBot.has(t.threadId)){this._threadsWithFirstBot.add(t.threadId),this._drawer.addMessage(t),this._drawer.markFirstBotMessage(t.id);return}this._drawer.addMessage(t)}}async _saveSessionAndOpenURL(t){this._session&&await this._session.saveAndOpenURL(t,()=>this._persistToIndexedDB(),this._bridge)}async _loadPayload(t,n){return this._session?this._session.loadPayload(t,n):null}async _restoreFromIndexedDB(t){if(!this._session?.db)return;const n=this.config.session?.sessionId;if(!n)return;const a=this.config.session?.userId??"",i=this.config.accountId;if(await this._session.loadFavorites(a,i),!t)return;const o=await this._session.db?.loadSession(a,i,n);if(!o||o.messages.length===0)return;const r=this.config.pageContext?.sku;if(r&&o.sku&&o.sku!==r)return;if(this._pdpLaunched=!0,this._drawer?.lockScrollForRestore(),this._currentThreadId=o.currentThreadId,this._lastThreadId=o.lastThreadId,this._chatCreatedAt=o.createdAt,o.panelThreads&&(this._panel.threads=o.panelThreads),o.thumbnailEntries&&(this._thumbnailEntries=o.thumbnailEntries,this._drawer?.setThumbnails(this._thumbnailEntries)),o.panelSnapshotHtml)for(const[c,l]of Object.entries(o.panelSnapshotHtml)){const g=document.createElement("div");g.innerHTML=oe(l),this._panel.snapshots.set(c,g)}let s=0;for(const c of o.messages){const l={id:c.id,role:c.role,timestamp:c.timestamp,status:c.status};if(c.threadId!==void 0&&(l.threadId=c.threadId),c.content!==void 0&&(l.content=c.content),c.silent&&(l.silent=!0),this._messages.push(l),l.silent)continue;l.role==="assistant"&&l.threadId&&!this._threadsWithFirstBot.has(l.threadId)&&(this._threadsWithFirstBot.add(l.threadId),this._drawer?.markFirstBotMessage(l.id)),this._drawer?.addMessage(l);const g=parseInt(c.id.replace("msg-",""),10);if(!isNaN(g)&&g>s&&(s=g),l.role==="assistant"&&l.threadId){const d=await this._loadPayload(l.threadId,l.id);d&&(l.uiSpec=d,this._restoreInlineUISpec(l),this._panel?.attachClickHandler(l.id),delete l.uiSpec)}}if(s>this._currentMessageId&&(this._currentMessageId=s),this._currentThreadId){let c=await this._session.db?.loadContext(n,this._currentThreadId);c||(c=await this._session.db?.loadLatestContext(n)),c&&(this._lastBackendContext=c.context)}if(this._currentThreadId){const c=[...this._messages].reverse().find(l=>l.role==="assistant"&&l.threadId===this._currentThreadId&&!l.silent);c&&this._panel.snapshots.has(c.id)&&this._panel?.restoreForMessage(c.id)}if(this._currentThreadId){const c=this._currentThreadId;for(const l of this._messages)l.threadId&&l.threadId>c&&this._shadow?.querySelector(`[data-message-id="${CSS.escape(l.id)}"]`)?.classList.add("gengage-chat-bubble--hidden");this._shadow?.querySelectorAll("[data-thread-id]").forEach(l=>{l instanceof HTMLElement&&l.dataset.threadId&&l.dataset.threadId>c&&l.classList.add("gengage-chat-bubble--hidden")})}if(this._panel.threads.length>0&&this._currentThreadId){const c=this._panel.threads[this._panel.threads.length-1];if(c){const l=[...this._messages].reverse().find(g=>g.role==="assistant"&&g.threadId===c);if(l?.threadId){const g=await this._loadPayload(l.threadId,l.id);if(g){const d=g.elements[g.root];d&&this._panel?.updateTopBar(d.type)}}}}setTimeout(()=>{this._drawer?.scrollToLastThread()},550)}_toggleComparisonSku(t){t===""?(this._comparisonSelectMode=!this._comparisonSelectMode,this._comparisonSelectMode||(this._comparisonSelectedSkus=[],wr())):this._comparisonSelectedSkus.indexOf(t)>=0?this._comparisonSelectedSkus=this._comparisonSelectedSkus.filter(a=>a!==t):(this._comparisonSelectedSkus=[...this._comparisonSelectedSkus,t],yr(t)),this._refreshComparisonUI()}_refreshComparisonUI(){const t=this._shadow?.querySelector(".gengage-chat-panel");if(!t)return;const n=t.querySelector(".gengage-chat-product-grid-wrapper");if(!n)return;const a=n.querySelector(".gengage-chat-product-grid");if(!a)return;const i=n.querySelector(".gengage-chat-comparison-toggle-btn");if(i&&i.classList.toggle("gengage-chat-comparison-toggle-btn--active",this._comparisonSelectMode),this._comparisonSelectMode){const r=a.querySelectorAll(".gengage-chat-product-card[data-sku]");for(const s of r){if(s.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){const d=s.parentElement.querySelector(".gengage-chat-comparison-checkbox");d&&(d.checked=this._comparisonSelectedSkus.includes(s.dataset.sku));continue}const c=s.dataset.sku,l=document.createElement("div");l.className="gengage-chat-comparison-select-wrapper";const g=document.createElement("input");g.type="checkbox",g.className="gengage-chat-comparison-checkbox",g.checked=this._comparisonSelectedSkus.includes(c),g.addEventListener("change",()=>{this._toggleComparisonSku(c)}),s.parentNode.insertBefore(l,s),l.appendChild(g),l.appendChild(s),l.style.cursor="pointer",l.addEventListener("click",d=>{d.target!==g&&(g.checked=!g.checked,this._toggleComparisonSku(c))})}}else{const r=a.querySelectorAll(".gengage-chat-comparison-select-wrapper");for(const s of r){const c=s.querySelector(".gengage-chat-product-card");c&&s.parentNode&&(s.parentNode.insertBefore(c,s),s.remove())}}const o=n.querySelector(".gengage-chat-comparison-floating-btn");if(this._comparisonSelectMode){const r=this._comparisonSelectedSkus.length,s=r>=2,c=this._i18n.compareSelected??"Compare",l=s?`${c} (${r})`:this._i18n.compareMinHint??"Select at least 2 products";if(o)o.textContent=l,o.disabled=!s,o.classList.toggle("gengage-chat-comparison-floating-btn--disabled",!s);else{const g=document.createElement("button");g.className="gengage-chat-comparison-floating-btn",g.type="button",g.textContent=l,g.disabled=!s,s||g.classList.add("gengage-chat-comparison-floating-btn--disabled"),g.addEventListener("click",()=>{this._comparisonSelectedSkus.length<2||(an(this._comparisonSelectedSkus),this._sendAction({title:c,type:"getComparisonTable",payload:{sku_list:[...this._comparisonSelectedSkus]}}))}),n.appendChild(g)}}else o?.remove()}_buildRenderContext(){const t={onAction:n=>{if(_r(n.title,n.type),n.type==="findSimilar"){const i=typeof n.payload=="object"&&n.payload!==null&&"sku"in n.payload?String(n.payload.sku):"";vr(i)}n.type==="getComparisonTable"&&an(this._comparisonSelectedSkus);const a=n.type==="addToCart"||n.type==="like";this._sendAction(n,a?{preservePanel:!0}:void 0)},onProductClick:n=>{Sr(n.sku),this.config.isDemoWebsite!==!0&&this._isSameOriginUrl(n.url)?(re("gengage:similar:product-click",{sku:n.sku,url:n.url,sessionId:this.config.session?.sessionId??null}),this._saveSessionAndOpenURL(n.url)):this._sendAction({title:n.sku,type:"launchSingleProduct",payload:{sku:n.sku}})},onAddToCart:n=>{Tr(n.sku,n.quantity);const a={...n,sessionId:this.config.session?.sessionId??null};re("gengage:chat:add-to-cart",a),this._bridge?.send("addToCart",n),this._runEventCallbacks("gengage-cart-add",a),this._sendAction({title:this._i18n.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:n.sku,cart_code:n.cartCode,quantity:n.quantity}},{preservePanel:!0})},onProductSelect:n=>{const a={root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:n}}}};this._drawer?.setPanelContent(this._renderUISpec(a,t))},i18n:this._i18n,pricing:this.config.pricing,productSort:this._productSort,onSortChange:n=>{this._productSort=n},comparisonSelectMode:this._comparisonSelectMode,comparisonSelectedSkus:this._comparisonSelectedSkus,onToggleComparisonSku:n=>{this._toggleComparisonSku(n)},favoritedSkus:this._session?.favoritedSkus??new Set,onFavoriteToggle:(n,a)=>{kr(n),this._toggleFavorite(n,a);const i=a.name??n;this._sendAction({title:i,type:"like",payload:{sku:n}},{preservePanel:!0})}};return t}async _toggleFavorite(t,n){if(!this._session)return;const a=this.config.session?.userId??"",i=this.config.accountId;await this._session.toggleFavorite(a,i,t,n)}async _runEventCallbacks(t,n){const a=this._eventCallbacks.get(t);if(!(!a||a.size===0))for(const i of a)try{const o=i(n);if((o instanceof Promise?await o:o)===!1){this._handleCallbackFailure(t,n);return}}catch{this._handleCallbackFailure(t,n);return}}_handleCallbackFailure(t,n){if(t==="gengage-cart-add"){const a=this._i18n.cartAddErrorMessage,i=this._createMessage("assistant",a);this._currentThreadId&&(i.threadId=this._currentThreadId),this._messages.push(i),this._drawer?.addMessage(i)}}_restoreInlineUISpec(t){if(!t.uiSpec||!this._drawer)return;const n=t.uiSpec,a=n.elements[n.root];if(!a)return;const i=a.type;if(i==="ActionButtons"||i==="ComparisonTable"||i==="ProductGrid"&&a.props?.similarsAppend===!0)return;const o=this._buildRenderContext(),r=this._shadow?.querySelector(".gengage-chat-messages");if(!r)return;if(i==="ProductDetailsPanel"){const c=a.props?.product;if(!c)return;const l={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:c}}}},g=this._renderUISpec(l,o);t.threadId&&(g.dataset.threadId=t.threadId),r.appendChild(g);return}const s=this._renderUISpec(n,o);t.threadId&&(s.dataset.threadId=t.threadId),r.appendChild(s)}_createMessage(t,n){return this._currentMessageId++,{id:`msg-${this._currentMessageId}`,role:t,content:n,timestamp:Date.now(),status:"done"}}_resolveI18n(t){return{...Xi(t.locale),...t.i18n}}_resolveUISpecRegistry(){const t=Wt();return da(t,this.config.renderer?.registry)}_renderUISpec(t,n){const a=this._resolveUISpecRegistry(),i=this.config.renderer?.unknownRenderer??ot,o=(c,l)=>Gt(c,l,a,i),r=this.config.renderer?.renderUISpec;return r?r(t,n,{registry:a,unknownRenderer:i,defaultRender:o}):o(t,n)}}function zg(){return new oa}ye.GengageChat=oa,ye.chatCatalog=Ig,ye.createChatWidget=zg,ye.createDefaultChatUISpecRegistry=Wt,ye.defaultChatUnknownUISpecRenderer=ot,ye.renderUISpec=Gt,Object.defineProperty(ye,Symbol.toStringTag,{value:"Module"})})(this.Gengage=this.Gengage||{});
96
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const r of e.seen.entries()){const s=r[1];if(t===r[0]){o(r);continue}if(e.external){const l=e.external.registry.get(r[0])?.id;if(t!==r[0]&&l){o(r);continue}}if(e.metadataRegistry.get(r[0])?.id){o(r);continue}if(s.cycle){o(r);continue}if(s.count>1&&e.reused==="ref"){o(r);continue}}}function Vn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=r=>{const s=e.seen.get(r);if(s.ref===null)return;const c=s.def??s.schema,l={...c},g=s.ref;if(s.ref=null,g){a(g);const u=e.seen.get(g),p=u.schema;if(p.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(p)):Object.assign(c,p),Object.assign(c,l),r._zod.parent===g)for(const _ in c)_==="$ref"||_==="allOf"||_ in l||delete c[_];if(p.$ref&&u.def)for(const _ in c)_==="$ref"||_==="allOf"||_ in u.def&&JSON.stringify(c[_])===JSON.stringify(u.def[_])&&delete c[_]}const d=r._zod.parent;if(d&&d!==g){a(d);const u=e.seen.get(d);if(u?.schema.$ref&&(c.$ref=u.schema.$ref,u.def))for(const p in c)p==="$ref"||p==="allOf"||p in u.def&&JSON.stringify(c[p])===JSON.stringify(u.def[p])&&delete c[p]}e.override({zodSchema:r,jsonSchema:c,path:s.path??[]})};for(const r of[...e.seen.entries()].reverse())a(r[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const r=e.external.registry.get(t)?.id;if(!r)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(r)}Object.assign(i,n.def??n.schema);const o=e.external?.defs??{};for(const r of e.seen.entries()){const s=r[1];s.def&&s.defId&&(o[s.defId]=s.def)}e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?i.$defs=o:i.definitions=o);try{const r=JSON.parse(JSON.stringify(i));return Object.defineProperty(r,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ye(t,"input",e.processors),output:Ye(t,"output",e.processors)}},enumerable:!1,writable:!1}),r}catch{throw new Error("Error converting schema to JSON.")}}function X(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const a=e._zod.def;if(a.type==="transform")return!0;if(a.type==="array")return X(a.element,n);if(a.type==="set")return X(a.valueType,n);if(a.type==="lazy")return X(a.getter(),n);if(a.type==="promise"||a.type==="optional"||a.type==="nonoptional"||a.type==="nullable"||a.type==="readonly"||a.type==="default"||a.type==="prefault")return X(a.innerType,n);if(a.type==="intersection")return X(a.left,n)||X(a.right,n);if(a.type==="record"||a.type==="map")return X(a.keyType,n)||X(a.valueType,n);if(a.type==="pipe")return X(a.in,n)||X(a.out,n);if(a.type==="object"){for(const i in a.shape)if(X(a.shape[i],n))return!0;return!1}if(a.type==="union"){for(const i of a.options)if(X(i,n))return!0;return!1}if(a.type==="tuple"){for(const i of a.items)if(X(i,n))return!0;return!!(a.rest&&X(a.rest,n))}return!1}const Tl=(e,t={})=>n=>{const a=qn({...n,processors:t});return W(e,a),Hn(a,e),Vn(a,e)},Ye=(e,t,n={})=>a=>{const{libraryOptions:i,target:o}=a??{},r=qn({...i??{},target:o,io:t,processors:n});return W(e,r),Hn(r,e),Vn(r,e)},Il={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Al=(e,t,n,a)=>{const i=n;i.type="string";const{minimum:o,maximum:r,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof o=="number"&&(i.minLength=o),typeof r=="number"&&(i.maxLength=r),s&&(i.format=Il[s]??s,i.format===""&&delete i.format,s==="time"&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){const g=[...c];g.length===1?i.pattern=g[0].source:g.length>1&&(i.allOf=[...g.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},zl=(e,t,n,a)=>{const i=n,{minimum:o,maximum:r,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:g}=e._zod.bag;typeof s=="string"&&s.includes("int")?i.type="integer":i.type="number",typeof g=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.minimum=g,i.exclusiveMinimum=!0):i.exclusiveMinimum=g),typeof o=="number"&&(i.minimum=o,typeof g=="number"&&t.target!=="draft-04"&&(g>=o?delete i.minimum:delete i.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l),typeof r=="number"&&(i.maximum=r,typeof l=="number"&&t.target!=="draft-04"&&(l<=r?delete i.maximum:delete i.exclusiveMaximum)),typeof c=="number"&&(i.multipleOf=c)},Pl=(e,t,n,a)=>{n.type="boolean"},Ll=(e,t,n,a)=>{n.not={}},Nl=(e,t,n,a)=>{},Ml=(e,t,n,a)=>{const i=e._zod.def,o=cn(i.entries);o.every(r=>typeof r=="number")&&(n.type="number"),o.every(r=>typeof r=="string")&&(n.type="string"),n.enum=o},$l=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Ol=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Rl=(e,t,n,a)=>{const i=n,o=e._zod.def,{minimum:r,maximum:s}=e._zod.bag;typeof r=="number"&&(i.minItems=r),typeof s=="number"&&(i.maxItems=s),i.type="array",i.items=W(o.element,t,{...a,path:[...a.path,"items"]})},Bl=(e,t,n,a)=>{const i=n,o=e._zod.def;i.type="object",i.properties={};const r=o.shape;for(const l in r)i.properties[l]=W(r[l],t,{...a,path:[...a.path,"properties",l]});const s=new Set(Object.keys(r)),c=new Set([...s].filter(l=>{const g=o.shape[l]._zod;return t.io==="input"?g.optin===void 0:g.optout===void 0}));c.size>0&&(i.required=Array.from(c)),o.catchall?._zod.def.type==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=W(o.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},Dl=(e,t,n,a)=>{const i=e._zod.def,o=i.inclusive===!1,r=i.options.map((s,c)=>W(s,t,{...a,path:[...a.path,o?"oneOf":"anyOf",c]}));o?n.oneOf=r:n.anyOf=r},Ul=(e,t,n,a)=>{const i=e._zod.def,o=W(i.left,t,{...a,path:[...a.path,"allOf",0]}),r=W(i.right,t,{...a,path:[...a.path,"allOf",1]}),s=l=>"allOf"in l&&Object.keys(l).length===1,c=[...s(o)?o.allOf:[o],...s(r)?r.allOf:[r]];n.allOf=c},Fl=(e,t,n,a)=>{const i=n,o=e._zod.def;i.type="object";const r=o.keyType,c=r._zod.bag?.patterns;if(o.mode==="loose"&&c&&c.size>0){const g=W(o.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});i.patternProperties={};for(const d of c)i.patternProperties[d.source]=g}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(i.propertyNames=W(o.keyType,t,{...a,path:[...a.path,"propertyNames"]})),i.additionalProperties=W(o.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const l=r._zod.values;if(l){const g=[...l].filter(d=>typeof d=="string"||typeof d=="number");g.length>0&&(i.required=g)}},Zl=(e,t,n,a)=>{const i=e._zod.def,o=W(i.innerType,t,a),r=t.seen.get(e);t.target==="openapi-3.0"?(r.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},jl=(e,t,n,a)=>{const i=e._zod.def;W(i.innerType,t,a);const o=t.seen.get(e);o.ref=i.innerType},ql=(e,t,n,a)=>{const i=e._zod.def;W(i.innerType,t,a);const o=t.seen.get(e);o.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Hl=(e,t,n,a)=>{const i=e._zod.def;W(i.innerType,t,a);const o=t.seen.get(e);o.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Vl=(e,t,n,a)=>{const i=e._zod.def;W(i.innerType,t,a);const o=t.seen.get(e);o.ref=i.innerType;let r;try{r=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=r},Wl=(e,t,n,a)=>{const i=e._zod.def,o=t.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;W(o,t,a);const r=t.seen.get(e);r.ref=o},Gl=(e,t,n,a)=>{const i=e._zod.def;W(i.innerType,t,a);const o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0},Wn=(e,t,n,a)=>{const i=e._zod.def;W(i.innerType,t,a);const o=t.seen.get(e);o.ref=i.innerType},Kl=m("ZodISODateTime",(e,t)=>{Xs.init(e,t),j.init(e,t)});function Yl(e){return al(Kl,e)}const Jl=m("ZodISODate",(e,t)=>{Qs.init(e,t),j.init(e,t)});function Xl(e){return il(Jl,e)}const Ql=m("ZodISOTime",(e,t)=>{ec.init(e,t),j.init(e,t)});function ed(e){return ol(Ql,e)}const td=m("ZodISODuration",(e,t)=>{tc.init(e,t),j.init(e,t)});function nd(e){return rl(td,e)}const te=m("ZodError",(e,t)=>{hn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Hr(e,n)},flatten:{value:n=>qr(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,st,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,st,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),ad=pt(te),id=ut(te),od=qe(te),rd=He(te),sd=Gr(te),cd=Kr(te),ld=Yr(te),dd=Jr(te),gd=Xr(te),pd=Qr(te),ud=es(te),hd=ts(te),V=m("ZodType",(e,t)=>(H.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ye(e,"input"),output:Ye(e,"output")}}),e.toJSONSchema=Tl(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(me(t,{checks:[...t.checks??[],...n.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),{parent:!0}),e.with=e.check,e.clone=(n,a)=>be(e,n,a),e.brand=()=>e,e.register=((n,a)=>(n.add(e,a),e)),e.parse=(n,a)=>ad(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>od(e,n,a),e.parseAsync=async(n,a)=>id(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>rd(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>sd(e,n,a),e.decode=(n,a)=>cd(e,n,a),e.encodeAsync=async(n,a)=>ld(e,n,a),e.decodeAsync=async(n,a)=>dd(e,n,a),e.safeEncode=(n,a)=>gd(e,n,a),e.safeDecode=(n,a)=>pd(e,n,a),e.safeEncodeAsync=async(n,a)=>ud(e,n,a),e.safeDecodeAsync=async(n,a)=>hd(e,n,a),e.refine=(n,a)=>e.check(rg(n,a)),e.superRefine=n=>e.check(sg(n)),e.overwrite=n=>e.check(ze(n)),e.optional=()=>Qn(e),e.exactOptional=()=>Wd(e),e.nullable=()=>ea(e),e.nullish=()=>Qn(ea(e)),e.nonoptional=n=>Qd(e,n),e.array=()=>Z(e),e.or=n=>Xe([e,n]),e.and=n=>Zd(e,n),e.transform=n=>na(e,Hd(n)),e.default=n=>Yd(e,n),e.prefault=n=>Xd(e,n),e.catch=n=>tg(e,n),e.pipe=n=>na(e,n),e.readonly=()=>ig(e),e.describe=n=>{const a=e.clone();return Oe.add(a,{description:n}),a},Object.defineProperty(e,"description",{get(){return Oe.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Oe.get(e);const a=e.clone();return Oe.add(a,n[0]),a},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),Gn=m("_ZodString",(e,t)=>{ht.init(e,t),V.init(e,t),e._zod.processJSONSchema=(a,i,o)=>Al(e,a,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...a)=>e.check(pl(...a)),e.includes=(...a)=>e.check(fl(...a)),e.startsWith=(...a)=>e.check(ml(...a)),e.endsWith=(...a)=>e.check(bl(...a)),e.min=(...a)=>e.check(Ke(...a)),e.max=(...a)=>e.check(Zn(...a)),e.length=(...a)=>e.check(jn(...a)),e.nonempty=(...a)=>e.check(Ke(1,...a)),e.lowercase=a=>e.check(ul(a)),e.uppercase=a=>e.check(hl(a)),e.trim=()=>e.check(vl()),e.normalize=(...a)=>e.check(_l(...a)),e.toLowerCase=()=>e.check(yl()),e.toUpperCase=()=>e.check(wl()),e.slugify=()=>e.check(xl())}),fd=m("ZodString",(e,t)=>{ht.init(e,t),Gn.init(e,t),e.email=n=>e.check(Oc(md,n)),e.url=n=>e.check(Fc(bd,n)),e.jwt=n=>e.check(nl(Ld,n)),e.emoji=n=>e.check(Zc(_d,n)),e.guid=n=>e.check(Bn(Kn,n)),e.uuid=n=>e.check(Rc(Je,n)),e.uuidv4=n=>e.check(Bc(Je,n)),e.uuidv6=n=>e.check(Dc(Je,n)),e.uuidv7=n=>e.check(Uc(Je,n)),e.nanoid=n=>e.check(jc(vd,n)),e.guid=n=>e.check(Bn(Kn,n)),e.cuid=n=>e.check(qc(yd,n)),e.cuid2=n=>e.check(Hc(wd,n)),e.ulid=n=>e.check(Vc(xd,n)),e.base64=n=>e.check(Qc(Ad,n)),e.base64url=n=>e.check(el(zd,n)),e.xid=n=>e.check(Wc(kd,n)),e.ksuid=n=>e.check(Gc(Cd,n)),e.ipv4=n=>e.check(Kc(Ed,n)),e.ipv6=n=>e.check(Yc(Sd,n)),e.cidrv4=n=>e.check(Jc(Td,n)),e.cidrv6=n=>e.check(Xc(Id,n)),e.e164=n=>e.check(tl(Pd,n)),e.datetime=n=>e.check(Yl(n)),e.date=n=>e.check(Xl(n)),e.time=n=>e.check(ed(n)),e.duration=n=>e.check(nd(n))});function k(e){return $c(fd,e)}const j=m("ZodStringFormat",(e,t)=>{F.init(e,t),Gn.init(e,t)}),md=m("ZodEmail",(e,t)=>{js.init(e,t),j.init(e,t)}),Kn=m("ZodGUID",(e,t)=>{Fs.init(e,t),j.init(e,t)}),Je=m("ZodUUID",(e,t)=>{Zs.init(e,t),j.init(e,t)}),bd=m("ZodURL",(e,t)=>{qs.init(e,t),j.init(e,t)}),_d=m("ZodEmoji",(e,t)=>{Hs.init(e,t),j.init(e,t)}),vd=m("ZodNanoID",(e,t)=>{Vs.init(e,t),j.init(e,t)}),yd=m("ZodCUID",(e,t)=>{Ws.init(e,t),j.init(e,t)}),wd=m("ZodCUID2",(e,t)=>{Gs.init(e,t),j.init(e,t)}),xd=m("ZodULID",(e,t)=>{Ks.init(e,t),j.init(e,t)}),kd=m("ZodXID",(e,t)=>{Ys.init(e,t),j.init(e,t)}),Cd=m("ZodKSUID",(e,t)=>{Js.init(e,t),j.init(e,t)}),Ed=m("ZodIPv4",(e,t)=>{nc.init(e,t),j.init(e,t)}),Sd=m("ZodIPv6",(e,t)=>{ac.init(e,t),j.init(e,t)}),Td=m("ZodCIDRv4",(e,t)=>{ic.init(e,t),j.init(e,t)}),Id=m("ZodCIDRv6",(e,t)=>{oc.init(e,t),j.init(e,t)}),Ad=m("ZodBase64",(e,t)=>{rc.init(e,t),j.init(e,t)}),zd=m("ZodBase64URL",(e,t)=>{cc.init(e,t),j.init(e,t)}),Pd=m("ZodE164",(e,t)=>{lc.init(e,t),j.init(e,t)}),Ld=m("ZodJWT",(e,t)=>{gc.init(e,t),j.init(e,t)}),Yn=m("ZodNumber",(e,t)=>{En.init(e,t),V.init(e,t),e._zod.processJSONSchema=(a,i,o)=>zl(e,a,i),e.gt=(a,i)=>e.check(Un(a,i)),e.gte=(a,i)=>e.check(bt(a,i)),e.min=(a,i)=>e.check(bt(a,i)),e.lt=(a,i)=>e.check(Dn(a,i)),e.lte=(a,i)=>e.check(mt(a,i)),e.max=(a,i)=>e.check(mt(a,i)),e.int=a=>e.check(Jn(a)),e.safe=a=>e.check(Jn(a)),e.positive=a=>e.check(Un(0,a)),e.nonnegative=a=>e.check(bt(0,a)),e.negative=a=>e.check(Dn(0,a)),e.nonpositive=a=>e.check(mt(0,a)),e.multipleOf=(a,i)=>e.check(Fn(a,i)),e.step=(a,i)=>e.check(Fn(a,i)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function ve(e){return sl(Yn,e)}const Nd=m("ZodNumberFormat",(e,t)=>{pc.init(e,t),Yn.init(e,t)});function Jn(e){return cl(Nd,e)}const Md=m("ZodBoolean",(e,t)=>{uc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Pl(e,n,a)});function _t(e){return ll(Md,e)}const $d=m("ZodUnknown",(e,t)=>{hc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Nl()});function ie(){return dl($d)}const Od=m("ZodNever",(e,t)=>{fc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Ll(e,n,a)});function Rd(e){return gl(Od,e)}const Bd=m("ZodArray",(e,t)=>{mc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Rl(e,n,a,i),e.element=t.element,e.min=(n,a)=>e.check(Ke(n,a)),e.nonempty=n=>e.check(Ke(1,n)),e.max=(n,a)=>e.check(Zn(n,a)),e.length=(n,a)=>e.check(jn(n,a)),e.unwrap=()=>e.element});function Z(e,t){return kl(Bd,e,t)}const Dd=m("ZodObject",(e,t)=>{_c.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Bl(e,n,a,i),B(e,"shape",()=>t.shape),e.keyof=()=>yt(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ie()}),e.loose=()=>e.clone({...e._zod.def,catchall:ie()}),e.strict=()=>e.clone({...e._zod.def,catchall:Rd()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Dr(e,n),e.safeExtend=n=>Ur(e,n),e.merge=n=>Fr(e,n),e.pick=n=>Rr(e,n),e.omit=n=>Br(e,n),e.partial=(...n)=>Zr(Xn,e,n[0]),e.required=(...n)=>jr(ta,e,n[0])});function O(e,t){const n={type:"object",shape:e??{},...A(t)};return new Dd(n)}const Ud=m("ZodUnion",(e,t)=>{vc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Dl(e,n,a,i),e.options=t.options});function Xe(e,t){return new Ud({type:"union",options:e,...A(t)})}const Fd=m("ZodIntersection",(e,t)=>{yc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Ul(e,n,a,i)});function Zd(e,t){return new Fd({type:"intersection",left:e,right:t})}const jd=m("ZodRecord",(e,t)=>{wc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Fl(e,n,a,i),e.keyType=t.keyType,e.valueType=t.valueType});function Re(e,t,n){return new jd({type:"record",keyType:e,valueType:t,...A(n)})}const vt=m("ZodEnum",(e,t)=>{xc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(a,i,o)=>Ml(e,a,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(a,i)=>{const o={};for(const r of a)if(n.has(r))o[r]=t.entries[r];else throw new Error(`Key ${r} not found in enum`);return new vt({...t,checks:[],...A(i),entries:o})},e.exclude=(a,i)=>{const o={...t.entries};for(const r of a)if(n.has(r))delete o[r];else throw new Error(`Key ${r} not found in enum`);return new vt({...t,checks:[],...A(i),entries:o})}});function yt(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new vt({type:"enum",entries:n,...A(t)})}const qd=m("ZodTransform",(e,t)=>{kc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Ol(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new rn(e.constructor.name);n.addIssue=o=>{if(typeof o=="string")n.issues.push($e(o,n.value,t));else{const r=o;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=e),n.issues.push($e(r))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(o=>(n.value=o,n)):(n.value=i,n)}});function Hd(e){return new qd({type:"transform",transform:e})}const Xn=m("ZodOptional",(e,t)=>{Ln.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Wn(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function Qn(e){return new Xn({type:"optional",innerType:e})}const Vd=m("ZodExactOptional",(e,t)=>{Cc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Wn(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function Wd(e){return new Vd({type:"optional",innerType:e})}const Gd=m("ZodNullable",(e,t)=>{Ec.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Zl(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function ea(e){return new Gd({type:"nullable",innerType:e})}const Kd=m("ZodDefault",(e,t)=>{Sc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>ql(e,n,a,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Yd(e,t){return new Kd({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():pn(t)}})}const Jd=m("ZodPrefault",(e,t)=>{Tc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Hl(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function Xd(e,t){return new Jd({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():pn(t)}})}const ta=m("ZodNonOptional",(e,t)=>{Ic.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>jl(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function Qd(e,t){return new ta({type:"nonoptional",innerType:e,...A(t)})}const eg=m("ZodCatch",(e,t)=>{Ac.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Vl(e,n,a,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function tg(e,t){return new eg({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const ng=m("ZodPipe",(e,t)=>{zc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Wl(e,n,a,i),e.in=t.in,e.out=t.out});function na(e,t){return new ng({type:"pipe",in:e,out:t})}const ag=m("ZodReadonly",(e,t)=>{Pc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Gl(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function ig(e){return new ag({type:"readonly",innerType:e})}const og=m("ZodCustom",(e,t)=>{Lc.init(e,t),V.init(e,t),e._zod.processJSONSchema=(n,a,i)=>$l(e,n)});function rg(e,t={}){return Cl(og,e,t)}function sg(e){return El(e)}const cg=O({role:yt(["user","assistant"]),content:k(),timestamp:ve().optional()}),lg=O({sku:k(),name:k(),imageUrl:k().url().optional(),price:k().optional(),originalPrice:k().optional(),url:k().url(),ctaLabel:k().optional()}),dg=O({buttons:Z(O({label:k(),action:O({title:k(),type:k(),payload:ie().optional()})}))}),gg=O({}),pg=O({label:k().optional()}),aa=O({sku:k(),name:k(),price:k(),imageUrl:k().optional(),rating:ve().optional(),reviewCount:ve().optional()}),ug=O({recommended:aa,products:Z(aa),attributes:Z(O({label:k(),values:Z(k())})),highlights:Z(k()),specialCases:Z(k()).optional(),recommendedText:k().optional(),winnerHits:Re(k(),O({positive:Z(k()).optional(),negative:Z(k()).optional()})).optional(),productActions:Re(k(),O({title:k(),type:k(),payload:ie().optional()})).optional()}),hg=O({label:k(),sentiment:yt(["positive","negative","neutral"]).optional()}),fg=O({product:Re(k(),ie()),role:k().optional(),reason:k().optional(),labels:Z(hg).optional(),expertQualityScore:ve().optional(),reviewHighlight:k().optional(),action:O({title:k(),type:k(),payload:ie().optional()}).optional()}),mg=O({suggestions:Z(fg)}),bg=O({title:k().optional(),text:k().optional(),reviewCount:k().optional(),action:O({title:k(),type:k(),payload:ie().optional()})}),_g=O({entries:Z(O({name:k(),image:k().optional(),description:k().optional(),action:O({title:k(),type:k(),payload:ie().optional()})}))}),vg=O({entries:Z(O({shortName:k(),detailedMessage:k().optional(),whyDifferent:k().optional(),image:k().optional(),action:O({title:k(),type:k(),payload:ie().optional()})}))}),ia=O({title:k(),type:k(),payload:ie().optional()}),yg=O({name:k().optional(),variant_name:k().optional(),sku:k().optional(),price:Xe([ve(),k()]).optional()}),wg=O({product:O({sku:k().optional(),name:k().optional(),images:Z(k()).optional(),imageUrl:k().optional(),rating:ve().optional(),reviewCount:ve().optional(),price:k().optional(),originalPrice:k().optional(),price_async:_t().optional(),inStock:_t().optional(),promotions:Z(k()).optional(),variants:Z(yg).optional(),url:k().optional(),cartCode:k().optional(),description:k().optional(),specifications:Xe([Re(k(),k()),Z(O({key:k(),value:k()}))]).optional()}).optional(),action:ia.optional()}),xg=O({endOfList:_t().optional()}),kg=O({review_class:k().optional(),review_text:k().optional(),review_rating:Xe([k(),ve()]).optional(),review_tag:k().optional()}),Cg=O({reviews:Z(kg).optional()}),Eg=O({productName:k().optional(),pros:Z(k()).optional(),cons:Z(k()).optional()}),Sg=O({groups:Z(O({groupName:k(),products:Z(Re(k(),ie())).optional()})).optional(),filterTags:Z(O({title:k(),action:ia.optional()})).optional()}),Tg=O({summary:k().optional(),products_discussed:Z(k()).optional(),user_sentiment:k().optional()}),Ig={components:{MessageBubble:{schema:cg,description:"A single chat message bubble for user or assistant turns."},ProductCard:{schema:lg,description:"A product card rendered inline in the chat stream."},ActionButtons:{schema:dg,description:"A horizontal row of quick-reply action buttons."},TypingIndicator:{schema:gg,description:"An animated indicator shown while the assistant is typing."},Divider:{schema:pg,description:"A horizontal rule with an optional label."},ComparisonTable:{schema:ug,description:"A product comparison table with recommended pick, attribute rows, and highlights."},AITopPicks:{schema:mg,description:"Rich AI-curated product suggestion cards with roles, sentiment labels, scores, and review quotes."},GroundingReviewCard:{schema:bg,description:"A card showing review grounding data with review count and CTA."},AIGroupingCards:{schema:_g,description:"Category grouping cards with images and labels for product discovery."},AISuggestedSearchCards:{schema:vg,description:"Suggested search cards with images, descriptions, and differentiation."},ProductDetailsPanel:{schema:wg,description:"Full product detail view with images, specs, variants, and purchase actions."},ProductGrid:{schema:xg,description:'A scrollable grid of ProductCard children with optional "more" pagination.'},ReviewHighlights:{schema:Cg,description:"A list of highlighted customer reviews with sentiment and ratings."},ProsAndCons:{schema:Eg,description:"A pros and cons list for a product."},CategoriesContainer:{schema:Sg,description:"Tabbed product groups with optional filter tag buttons."},HandoffNotice:{schema:Tg,description:"A notice shown when the conversation is escalated to a human agent."}}};function Ag(e){return e.length>120?!1:/^[a-zA-Z0-9#(),.\s%/\-]+$/.test(e)}function wt(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}class oa extends Za{constructor(){super(...arguments),this._shadow=null,this._rootEl=null,this._launcher=null,this._drawer=null,this._bridge=null,this._drawerVisible=!1,this._messages=[],this._currentMessageId=0,this._abortControllers=new Set,this._currentThreadId=null,this._lastThreadId=null,this._chatCreatedAt="",this._lastBackendContext=null,this._productSort={type:"related"},this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._thumbnailEntries=[],this._choicePrompterEl=null,this._openState="full",this._mobileBreakpoint=768,this._isMobileViewport=!1,this._pdpLaunched=!1,this._pdpPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._i18n=nt,this._extendedModeManager=null,this._activeTypewriter=null,this._activeTtsHandle=null,this._activeRequestThreadId=null,this._skuToProductItem={},this._conversationMode=null,this._initComplete=!1,this._pendingActions=[],this._bridgeContext=null,this._cartQuantity=null,this._threadsWithFirstBot=new Set,this._panel=null,this._session=null,this._eventCallbacks=new Map,this._lastSentAction=null}async onInit(t){this._i18n=this._resolveI18n(t),this._chatCreatedAt=new Date().toISOString(),this._shadow=this.root.attachShadow({mode:"open"});const n=document.createElement("style");n.textContent=hr,this._shadow.appendChild(n);const a=document.createElement("div");a.className="gengage-chat-root",this._rootEl=a,this._shadow.appendChild(a);const i=t.variant??"floating";if(i==="floating"){const d={onClick:()=>this.open(),ariaLabel:this._i18n.openButton};t.launcherImageUrl!==void 0?d.imageUrl=t.launcherImageUrl:t.launcherSvg!==void 0&&(d.svgMarkup=t.launcherSvg),t.hideMobileLauncher!==void 0&&(d.hideMobile=t.hideMobileLauncher),t.mobileBreakpoint!==void 0&&(d.mobileBreakpoint=t.mobileBreakpoint),t.launcherTooltip!==void 0&&(d.tooltip=t.launcherTooltip),this._launcher=co(d),a.appendChild(this._launcher.container)}i==="overlay"&&a.classList.add("gengage-chat--overlay");const o=document.createElement("div");a.appendChild(o),this._drawer=new ro(o,{i18n:this._i18n,onSend:(d,u)=>this._sendMessage(d,u),onClose:()=>this.close(),onAttachment:d=>this._handleAttachment(d),onPanelToggle:()=>{this._drawer?.persistPanelState(t.accountId)},onRollback:d=>this._handleRollback(d),onPanelBack:()=>this._panel?.navigateBack(),onPanelForward:()=>this._panel?.navigateForward(),headerTitle:t.headerTitle,headerAvatarUrl:t.headerAvatarUrl,headerBadge:t.headerBadge,headerCartUrl:t.headerCartUrl,headerFavoritesToggle:t.headerFavoritesToggle,onFavoritesClick:()=>{Cr(),t.onFavoritesClick?.()},onThumbnailClick:d=>this._rollbackToThread(d),onLinkClick:d=>{this._saveSessionAndOpenURL(d)},voiceEnabled:t.voiceEnabled,voiceLang:t.locale?`${t.locale.split("-")[0]??"tr"}-${(t.locale.split("-")[1]??t.locale.split("-")[0]??"TR").toUpperCase()}`:void 0}),this._extendedModeManager=new ir({onChange:d=>this._panel?.notifyExtension(d),productDetailsInPanel:t.isDemoWebsite??!1}),this._panel=new or({drawer:()=>this._drawer,shadow:()=>this._shadow,currentThreadId:()=>this._currentThreadId,bridge:()=>this._bridge,extendedModeManager:()=>this._extendedModeManager,i18n:()=>this._i18n,rollbackToThread:d=>this._rollbackToThread(d)}),i!=="inline"&&this._drawer.getElement().classList.add("gengage-chat-drawer--hidden"),this._drawer.restorePanelState(t.accountId);const r=t.panelMode??"auto";r==="collapsed"?this._drawer.setPanelCollapsed(!0):r==="expanded"&&this._drawer.setForceExpanded();const s=sessionStorage.getItem("gengage_restore_session_id"),c=sessionStorage.getItem("gengage_restore_sku"),l=!!(s&&c);l&&(sessionStorage.removeItem("gengage_restore_session_id"),sessionStorage.removeItem("gengage_restore_sku"));try{const d=new nr;await d.open(),this._session=new en(d),await this._restoreFromIndexedDB(l)}catch{this._session=new en(null)}this._registerPublicAPI(),t.mobileInitialState!==void 0&&(this._openState=t.mobileInitialState),this._mobileBreakpoint=t.mobileBreakpoint??768,this._syncViewportState();const g=()=>this._syncViewportState();if(window.addEventListener("resize",g,{passive:!0}),this.addCleanup(()=>window.removeEventListener("resize",g)),window.visualViewport){const d=()=>{if(!this._drawerVisible||!this._isMobileViewport)return;const u=this._drawer?.getElement();if(!u)return;const p=window.innerHeight-(window.visualViewport?.height??window.innerHeight);u.style.setProperty("--gengage-keyboard-offset",`${Math.max(0,p)}px`)};window.visualViewport.addEventListener("resize",d),this.addCleanup(()=>window.visualViewport?.removeEventListener("resize",d))}i==="inline"&&(this._drawerVisible=!0,this.isVisible=!0,this._applyOpenStateClasses()),this._bridge=new Ha({namespace:"chat",onMessage:d=>this._handleBridgeMessage(d)}),this._lastSku=this.config.pageContext?.sku,this._initComplete=!0;for(const d of this._pendingActions)this._sendAction(d.action,d.options);this._pendingActions=[],re("gengage:chat:ready",{}),mr("chat"),t.onReady?.()}onUpdate(t){t.sku!==void 0&&t.sku!==this._lastSku&&(this._lastSku=t.sku,this._resetForNewPage())}onShow(){this._showDrawer(),this.emit("open"),re("gengage:chat:open",{state:this._openState}),br("chat"),this.config.onOpen?.(),!this._pdpLaunched&&this.config.pageContext?.sku&&(this._pdpLaunched=!0,this._pdpPrimingInFlight=!0,this._sendAction({title:"",type:"launchSingleProduct",payload:{sku:this.config.pageContext.sku}},{silent:!0,isPdpPrime:!0}))}onHide(){(this.config.variant??"floating")==="floating"&&(this.root.style.display=""),this._hideDrawer(),this.emit("close"),re("gengage:chat:close",{}),this.config.onClose?.()}onDestroy(){this._abortControllers.forEach(t=>t.abort()),this._abortControllers.clear(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._drawer?.destroy(),this._drawer=null,this._bridge?.destroy(),this._bridge=null,this._extendedModeManager=null,this._panel?.destroy(),this._panel=null,this._session?.close(),this._session=null,window.gengage&&delete window.gengage.chat,this._shadow&&(this._shadow.innerHTML="",this._shadow=null),this._rootEl=null}open(t){t?.state!==void 0&&(this._openState=t.state,this._drawerVisible&&this._applyOpenStateClasses()),this.show(),t?.initialMessage!==void 0&&this._sendMessage(t.initialMessage)}openWithAction(t,n){n?.sku!==void 0&&this.update({sku:n.sku}),this._pdpLaunched=!0,n?.state!==void 0?this._openState=n.state:this._isMobileViewport&&(this._openState="half"),this.show(),this._drawerVisible&&this._applyOpenStateClasses(),this._sendAction(t)}sendMessage(t){this._sendMessage(t)}sendAction(t,n){this._sendAction(t,n)}close(){this.hide()}saveSession(t,n){sessionStorage.setItem("gengage_restore_session_id",t),sessionStorage.setItem("gengage_restore_sku",n)}get isOpen(){return this._drawerVisible}addCallback(t,n){let a=this._eventCallbacks.get(t);return a||(a=new Set,this._eventCallbacks.set(t,a)),a.add(n),()=>{a.delete(n),a.size===0&&this._eventCallbacks.delete(t)}}_resetForNewPage(){this._activeRequestThreadId=null,this._abortControllers.forEach(t=>t.abort()),this._abortControllers.clear(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._messages.length=0,this._drawer?.clearMessages(),this._drawer?.clearPanel(),this._panel.snapshots.clear(),this._panel.threads=[],this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._currentThreadId=null,this._lastThreadId=null,this._lastBackendContext=null,this._chatCreatedAt=new Date().toISOString(),this._pdpLaunched=!1,this._pdpPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null}_handleBridgeMessage(t){switch(t.type){case"openChat":this.open();break;case"closeChat":this.close();break;case"startNewChatWithLauncherAction":{const n=t.payload,a=n?.action,i=wt(a)?a:wt(n)?n:null;i&&this._sendAction(i,{silent:!0}),this.open();break}case"startNewChatWithDetailContext":{const n=t.payload;if(n&&typeof n=="object"){this._bridgeContext=n;const a=n.sku;if(a&&this.update({sku:a}),wt(n.action)){this._pdpLaunched=!0,this.open(),this._sendAction(n.action);break}}this.open();break}case"launcherAction":{const a=t.payload?.action;a&&typeof a=="object"&&"type"in a&&this._sendAction(a);break}case"scrollToBottom":this._drawer?.scrollToBottomIfNeeded();break;case"addToCardHandler":{this._bridge?.send("addToCardResult",t.payload);break}case"cartQuantityHandler":{const n=t.payload;n&&"quantity"in n&&typeof n.quantity=="number"&&(this._cartQuantity=n.quantity);break}case"minimizeRequestedByUser":this._extendedModeManager?.setHiddenByUser(!0);break;case"bgColorChange":{const a=t.payload?.color;typeof a=="string"&&Ag(a)&&this._shadow&&this._shadow.host.style.setProperty("--gengage-chat-bg",a);break}}}_registerPublicAPI(){window.gengage||(window.gengage={}),window.gengage.chat={open:t=>this.open(t),openWithAction:(t,n)=>this.openWithAction(t,n),sendMessage:t=>this.sendMessage(t),sendAction:(t,n)=>this.sendAction(t,n),close:()=>this.close(),saveSession:(t,n)=>this.saveSession(t,n),get isOpen(){return!1},on:(t,n)=>this.on(t,n),trackCheckout:(t,n)=>this.trackCheckout(t,n),flushMeteringSummary:t=>this.flushMeteringSummary(t),addCallback:(t,n)=>this.addCallback(t,n)},Object.defineProperty(window.gengage.chat,"isOpen",{get:()=>this._drawerVisible})}_showDrawer(){if(this._drawerVisible)return;this._drawerVisible=!0;const t=this._drawer?.getElement();t&&t.classList.remove("gengage-chat-drawer--hidden"),this._applyOpenStateClasses(),this._drawer?.trapFocus(),this._isMobileViewport&&this._openState==="half"||this._drawer?.focusInput(),this._extendedModeManager?.setChatShown(!0)}_hideDrawer(){if(!this._drawerVisible)return;this._drawer?.releaseFocus(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._drawerVisible=!1,this._openState="full";const t=this._drawer?.getElement();t&&t.classList.add("gengage-chat-drawer--hidden"),this._applyOpenStateClasses(),this._extendedModeManager?.setChatShown(!1)}_syncViewportState(){if(this._rootEl){if(this._isMobileViewport=window.innerWidth<=this._mobileBreakpoint,this._rootEl.classList.toggle("gengage-chat-root--mobile",this._isMobileViewport),this._launcher){const t=this._isMobileViewport&&this.config.hideMobileLauncher===!0;this._launcher.container.classList.toggle("gengage-chat-launcher--hidden-mobile",t)}this._applyOpenStateClasses()}}_applyOpenStateClasses(){if(!this._rootEl)return;const t=this._drawerVisible&&this._isMobileViewport&&this._openState==="half",n=this._drawerVisible&&this._isMobileViewport&&this._openState==="full";this._rootEl.classList.toggle("gengage-chat-root--open",this._drawerVisible),this._rootEl.classList.toggle("gengage-chat-root--mobile-half",t),this._rootEl.classList.toggle("gengage-chat-root--mobile-full",n)}_handleAttachment(t){const n=Qa(t);if(!n.ok){const a=n.reason==="invalid_type"?this._i18n.invalidFileType:this._i18n.fileTooLarge;re("gengage:global:error",{message:a,source:"chat"});return}this._drawer?.stageAttachment(t)}_sendMessage(t,n){if(this._pdpPrimingInFlight){this._queuedUserMessages.push(n!==void 0?{text:t,attachment:n}:{text:t});return}Ir(),this._messages.some(o=>o.role==="user")||Ar();const i={title:t,type:"user_message",payload:t};n!==void 0?this._sendAction(i,{attachment:n}):this._sendAction(i)}_flushQueuedUserMessages(){if(this._pdpPrimingInFlight||this._queuedUserMessages.length===0)return;const t=[...this._queuedUserMessages];this._queuedUserMessages=[];for(const n of t)this._sendMessage(n.text,n.attachment)}_sendAction(t,n){if(this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._lastSentAction={action:t,options:n},!this._initComplete){this._pendingActions.length<10&&this._pendingActions.push({action:t,options:n});return}if(this._choicePrompterEl?.remove(),this._choicePrompterEl=null,!n?.preservePanel&&this._comparisonSelectMode&&(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[]),this._currentThreadId&&this._lastThreadId&&this._lastThreadId>this._currentThreadId){const h=this._currentThreadId,x=this._messages.filter(E=>E.threadId!==void 0&&E.threadId>h);this._messages=this._messages.filter(E=>!E.threadId||E.threadId<=h);for(const E of x)this._shadow?.querySelector(`[data-message-id="${CSS.escape(E.id)}"]`)?.remove(),this._panel.snapshots.delete(E.id),this._panel.snapshotTypes.delete(E.id);this._shadow?.querySelectorAll("[data-thread-id]")?.forEach(E=>{E instanceof HTMLElement&&E.dataset.threadId&&E.dataset.threadId>h&&E.remove()})}this._drawer?.setPills([]),this._drawer?.clearInputAreaChips(),this._bridge?.send("isResponding",!0);const a=qa();this._currentThreadId=a,this._lastThreadId=a,this._panel&&t.type!=="launchSingleProduct"&&(this._panel.lastActionType=t.type);const i=n?.preservePanel===!0,o=t.type==="launchSingleProduct"&&n?.silent===!0&&n?.isPdpPrime===!0;if(i||(this._activeRequestThreadId=a),!n?.silent){const h=this._createMessage("user",typeof t.payload=="string"?t.payload:t.title);h.threadId=a,n?.attachment!==void 0&&(h.attachment=n.attachment),this._drawer?.addMessage(h),this._messages.push(h)}if(!n?.silent&&this._hasUnavailableProductContext()&&(t.type==="user_message"||t.type==="inputText")){const h=this._i18n.productNotFoundMessage,x=this._createMessage("assistant",h);x.threadId=a,x.status="done",this._messages.push(x),this._ensureAssistantMessageRendered(x),this._drawer?.updateBotMessage(x.id,h),this._bridge?.send("isResponding",!1),this.emit("message",x),this._persistToIndexedDB().catch(()=>{});return}let s=null;const c=()=>{if(s||n?.preservePanel)return;const h=this._drawer?.getPanelContentElement();h&&(s=h.cloneNode(!0))},l=()=>{this._drawer?.isPanelLoading()&&(s?this._drawer.setPanelContent(s):this._drawer.clearPanel(),s=null)};this._drawer?.showTypingIndicator();let g="";const d=this._createMessage("assistant","");d.threadId=a,d.status="streaming",n?.silent&&(d.silent=!0),this._messages.push(d),n?.preservePanel||(this._abortControllers.forEach(h=>h.abort()),this._abortControllers.clear());const u={middlewareUrl:this.config.middlewareUrl,...this.config.accountId?{accountId:this.config.accountId}:{}};n?.attachment!==void 0&&(u.attachment=n.attachment);const f=this._getVisibleMessages().filter(h=>h!==d&&(h.content||h.role==="assistant")).slice(-50).map(h=>({role:h.role==="user"?"user":"model",content:h.content??""})),_={outputLanguage:ur(this.config.locale),parentUrl:window.location.href,windowWidth:String(window.innerWidth),windowHeight:String(window.innerHeight),selfUrl:"",id:this.config.session?.sessionId??"",userId:this.config.session?.userId??"",appId:this.config.accountId,threads:[],createdAt:this._chatCreatedAt,kvkkApproved:nn(this.config.accountId),voiceEnabled:this.config.voiceEnabled??!1,threadId:a,isControlGroup:this.config.session?.abTestVariant==="control",isMobile:this._isMobileViewport};this.config.session?.viewId!==void 0&&(_.viewId=this.config.session.viewId);const v=Vi(t,{pageContext:this.config.pageContext,backendContext:this._lastBackendContext,isMobile:this._isMobileViewport}),C={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",type:v.type,locale:this.config.locale??"tr",meta:_,context:{...this._lastBackendContext??{},messages:f,session_id:this.config.session?.sessionId??""}};this.config.session?.userId!==void 0&&(C.user_id=this.config.session.userId),this.config.session?.viewId!==void 0&&(C.view_id=this.config.session.viewId),v.payload!==void 0&&(C.payload=v.payload),this.config.pageContext?.sku!==void 0&&(C.sku=this.config.pageContext.sku),this.config.pageContext?.pageType!==void 0&&(C.page_type=this.config.pageContext.pageType);const T=crypto.randomUUID(),S=Date.now();let y=0,I=!1,D=!1;this.track(ga(this.analyticsContext(),{endpoint:"process_action",request_id:T,widget:"chat"}));let G=null;if(G=Ki(C,{onTextChunk:(h,x,w)=>{if(!i&&a!==this._activeRequestThreadId||(g+=h,this._drawer?.removeTypingIndicator(),w?.skuToProductItem&&(this._skuToProductItem={...this._skuToProductItem,...w.skuToProductItem}),w?.conversationMode&&(this._conversationMode=w.conversationMode),this.track(pa(this.analyticsContext(),{request_id:T,chunk_index:y++,widget:"chat"})),!this._drawer))return;let E=g;if(x&&rt(E)){const P=this.config.accountId;if(!nn(P)){const R=gr(E);R&&this._drawer?.showKvkkBanner(R,()=>{this._drawer?.hideKvkkBanner()}),lr(P)}E=dr(E)}const z=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(z?z.innerHTML=oe(E):(d.content=E,d.role==="assistant"&&d.threadId&&!this._threadsWithFirstBot.has(d.threadId)&&(this._threadsWithFirstBot.add(d.threadId),this._drawer.markFirstBotMessage(d.id)),this._drawer.addMessage(d)),x){d.content=E,d.status="done",on();const P=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(P){this._activeTypewriter?.cancel();const R=w?.productMentions;this._activeTypewriter=Wo({container:P,html:oe(E),onTick:()=>this._drawer?.scrollToBottomIfNeeded(),onComplete:()=>{this._activeTypewriter=null,R&&R.length>0&&P&&Go({container:P,mentions:R,onProductClick:q=>{this._sendAction({title:R.find(M=>M.sku===q)?.short_name??q,type:"launchSingleProduct",payload:{sku:q}})}})}})}}},onUISpec:(h,x,w)=>{if(!i&&a!==this._activeRequestThreadId||x!=="chat")return;const E=h.elements[h.root],z=E?.type??"unknown";this.track(ua(this.analyticsContext(),{request_id:T,chunk_index:y,component_type:z,widget:"chat"}));const P=this._buildRenderContext();if(z==="ComparisonTable"){const M=E?.props?.products;xr(Array.isArray(M)?M.length:0)}if(z==="ProductGrid"){const M=E?.children?.length??0;Er(void 0,M)}const R=w==="panel"&&this._panel?this._panel.toPanelSpec(h):h,q=!d.silent&&(w!=="panel"||z==="ProductCard")&&z!=="ActionButtons";if(w==="panel"&&this._panel){const M=!D;D=!0;const L=rr({componentType:z,similarsAppend:E?.props?.similarsAppend===!0,currentPanelType:this._panel.currentType,hasPanelContent:this._drawer?.hasPanelContent()??!1,isPanelLoading:this._drawer?.isPanelLoading()??!1,isFirstPanelContentInStream:M});L==="appendSimilars"?this._appendSimilarsToPanel(R,P):L==="append"?this._drawer?.appendPanelContent(this._renderUISpec(R,P)):(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._drawer?.setPanelContent(this._renderUISpec(R,P)),this._panel.currentType=z),z==="ProductDetailsPanel"&&t.type==="launchSingleProduct"&&this._clearUnavailableProductContext(),d.threadId&&!this._panel.threads.includes(d.threadId)&&this._panel.threads.push(d.threadId);const $=this._panel.currentType??z,b=E?.props?.panelTitle;this._panel.updateTopBar($,b),this._panel.updateExtendedMode(z)}if(z==="ProductDetailsPanel"&&!d.silent&&w==="panel"){const M=E?.props?.product;if(M){const L={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:M}}}},$=this._shadow?.querySelector(".gengage-chat-messages");if($){const b=this._renderUISpec(L,P);d.threadId&&(b.dataset.threadId=d.threadId),$.appendChild(b),b.scrollIntoView({behavior:"auto",block:"end"})}}}if(q){const M=this._shadow?.querySelector(".gengage-chat-messages");if(M){const L=this._renderUISpec(h,P);d.threadId&&(L.dataset.threadId=d.threadId),M.appendChild(L),L.scrollIntoView({behavior:"auto",block:"end"})}}if((z==="ProductGrid"||z==="ProductCard")&&d.threadId){const M=E?.children??[],L=z==="ProductGrid"?M.map($=>h.elements[$]?.props?.product).filter(Boolean):[E?.props?.product].filter(Boolean);for(const $ of L){const b=$.sku,N=$.imageUrl;b&&N&&this._thumbnailEntries.push({sku:b,imageUrl:N,threadId:d.threadId})}this._drawer?.setThumbnails(this._thumbnailEntries)}if(z==="ProductGrid"||z==="ProductDetailsPanel"){const L=(z==="ProductGrid"?(E?.children??[]).map($=>h.elements[$]?.props?.product).filter(Boolean):[E?.props?.product??E?.props].filter(Boolean)).map($=>$.imageUrl).filter($=>typeof $=="string").slice(0,5);L.length>0&&this._bridge?.send("previewImages",{images:L})}if(z==="ProductGrid"&&w==="panel"&&!this._comparisonSelectMode&&!Qo()){this._choicePrompterEl?.remove(),this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(b=>b.remove()),this._choicePrompterEl=Xo({heading:this._i18n.choicePrompterHeading,suggestion:this._i18n.choicePrompterSuggestion,ctaLabel:this._i18n.choicePrompterCta,dismissAriaLabel:this._i18n.dismissAriaLabel,onCtaClick:()=>{this._comparisonSelectMode=!0,this._choicePrompterEl=null,this._refreshComparisonUI()},onDismiss:()=>{this._choicePrompterEl=null}});const L=this._isMobileViewport||this._drawer?.isPanelCollapsed()?".gengage-chat-conversation":".gengage-chat-panel",$=this._shadow?.querySelector(L);$?$.appendChild(this._choicePrompterEl):this._choicePrompterEl=null}if(z==="ActionButtons"){const M=E?.props?.buttons;if(M&&M.length>0){const L=[],$=[];for(const b of M)if(Jo(b)){const N={label:b.label,action:b.action};b.icon&&(N.icon=b.icon),L.push(N)}else $.push(b);L.length>0&&this._drawer?.setInputAreaChips(L.map(b=>({label:b.label,onAction:()=>this._sendAction(b.action),...b.icon?{icon:b.icon}:{}}))),$.length>0&&this._drawer?.setPills($.map(b=>{const N={label:b.label,onAction:()=>this._sendAction(b.action)};return b.icon&&(N.icon=b.icon),b.image&&(N.image=b.image),b.description&&(N.description=b.description),N}))}}d.uiSpec=h},onAction:h=>{if(!(!i&&a!==this._activeRequestThreadId)&&h.type==="action"){const x={};this.config.actionHandling?.unknownActionPolicy!==void 0&&(x.unknownActionPolicy=this.config.actionHandling.unknownActionPolicy),this.config.actionHandling?.allowScriptCall!==void 0&&(x.allowScriptCall=this.config.actionHandling.allowScriptCall),Ga(h,{openChat:()=>this.open(),navigate:w=>{ee(w.url)&&(this._bridge?.send("navigate",w),w.newTab?window.open(w.url,"_blank","noopener,noreferrer"):window.location.href=w.url)},saveSession:w=>this.saveSession(w.sessionId,w.sku),addToCart:w=>{re("gengage:similar:add-to-cart",w)},scriptCall:w=>{re("gengage:chat:script-call",w),this.config.onScriptCall?.(w)}},x)}},onMetadata:h=>{if(!(!i&&a!==this._activeRequestThreadId)&&h.type==="metadata"&&h.meta){if((h.meta.panel!==void 0||h.meta.messages!==void 0||h.meta.message_id!==void 0)&&(this._lastBackendContext=h.meta),h.meta.panelLoading){I=!0,D=!1,c();const w=typeof h.meta.panelPendingType=="string"?h.meta.panelPendingType:void 0;this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(w),w&&this._panel?.updateTopBarForLoading(w)}if(h.meta.voice){const w=new CustomEvent("gengage:chat:voice",{detail:{payload:h.meta.voice},bubbles:!1,cancelable:!0}),E=window.dispatchEvent(w);if(zr(),E){const z=h.meta.voice;z.audio_base64&&(this._activeTtsHandle?.stop(),this._activeTtsHandle=go(z.audio_base64,z.content_type??"audio/ogg"))}}(h.meta.redirectTarget||h.meta.redirect)&&re("gengage:chat:redirect",{target:h.meta.redirectTarget??null,payload:h.meta.redirect??null}),h.meta.analyzeAnimation&&(I=!0,D=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(),this._panel?.updateTopBarForLoading("productDetails")),h.meta.loading&&typeof h.meta.loadingText=="string"&&(this._drawer?.addThinkingStep(h.meta.loadingText),this._bridge?.send("loadingMessage",{text:h.meta.loadingText})),h.meta.visitorDataResponse&&this._bridge?.send("engagingMessage",h.meta.visitorDataResponse),h.meta.formType&&this._bridge?.send("glovOtokoc",{type:h.meta.formType,data:h.meta.formPayload}),h.meta.launcherContent&&this._bridge?.send("launcherContent",h.meta.launcherContent),re("gengage:chat:metadata",{payload:h.meta});const x=h.meta;typeof x.prompt_tokens=="number"&&typeof x.completion_tokens=="number"&&this.track(ma(this.analyticsContext(),{model:h.model??"unknown",prompt_tokens:x.prompt_tokens,completion_tokens:x.completion_tokens,total_tokens:x.total_tokens??x.prompt_tokens+x.completion_tokens}))}},onError:h=>{if(G&&this._abortControllers.delete(G),!i&&a!==this._activeRequestThreadId)return;this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator();const x=D;if(I&&!D&&l(),I=!1,D=!1,!(d.silent||d.content!=null&&d.content.length>0||g.length>0||x))if(o||this._hasUnavailableProductContext()){const E=this._i18n.productNotFoundMessage;d.content=E,d.status="done",this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,E),this._markUnavailableProductContext()}else this.emit("error",h),this._drawer?.showError(this._i18n.errorMessage,()=>{this._lastSentAction&&this._sendAction(this._lastSentAction.action,this._lastSentAction.options)});o&&(this._pdpPrimingInFlight=!1,this._flushQueuedUserMessages()),d.status==="streaming"&&(d.status="error"),this.track(fa(this.analyticsContext(),{request_id:T,error_code:"STREAM_ERROR",error_message:h.message,widget:"chat"}))},onDone:()=>{if(G&&this._abortControllers.delete(G),!(!i&&a!==this._activeRequestThreadId)){if(this._activeRequestThreadId=null,this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),I&&!D&&l(),I=!1,D=!1,o&&!g&&!D){const h=this._i18n.productNotFoundMessage;d.content=h,this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,h),this._markUnavailableProductContext()}o&&(this._pdpPrimingInFlight=!1,this._flushQueuedUserMessages()),d.status==="streaming"&&(d.status="done",on()),this.emit("message",d),this._panel?.snapshotForMessage(d.id),this._panel?.attachClickHandler(d.id),this.track(ha(this.analyticsContext(),{request_id:T,latency_ms:Date.now()-S,chunk_count:y,widget:"chat"})),this.track(ba(this.analyticsContext(),{meter_key:"chat_request",quantity:1,unit:"request"})),this.track(va(this.analyticsContext(),{message_count:this._messages.length,history_ref:this.config.session?.sessionId??"",redaction_level:"none"})),this._persistToIndexedDB().catch(()=>{})}}},u),this._abortControllers.add(G),!n?.silent&&!i){const h=G;this._drawer?.showStopButton(()=>{h.abort(),this._abortControllers.delete(h),this._drawer?.removeTypingIndicator(),this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),d.status==="streaming"&&(d.status="done")})}}_getVisibleMessages(){const t=this._messages.filter(a=>!a.silent);if(!this._currentThreadId)return t;const n=this._currentThreadId;return t.filter(a=>!a.threadId||a.threadId<=n)}_appendSimilarsToPanel(t,n){if(!this._drawer)return;const a=this._drawer.getPanelContentElement();if(!a)return;const i=document.createElement("h3");i.className="gengage-chat-product-details-similars-heading",i.textContent=this._i18n.similarProductsLabel??"Similar Products",a.appendChild(i);const o=this._renderUISpec(t,n);o.classList.add("gengage-chat-product-details-similars"),a.appendChild(o)}_handleRollback(t){const n=this._messages.find(a=>a.id===t);n?.threadId&&this._rollbackToThread(n.threadId)}_rollbackToThread(t){this._currentThreadId=t,this._extendedModeManager?.setHiddenByUser(!1);for(const o of this._messages){const r=this._shadow?.querySelector(`[data-message-id="${CSS.escape(o.id)}"]`);r&&(o.threadId&&o.threadId>t?r.classList.add("gengage-chat-bubble--hidden"):r.classList.remove("gengage-chat-bubble--hidden"))}this._shadow?.querySelectorAll("[data-thread-id]").forEach(o=>{o instanceof HTMLElement&&o.dataset.threadId&&o.dataset.threadId>t?o.classList.add("gengage-chat-bubble--hidden"):o instanceof HTMLElement&&o.classList.remove("gengage-chat-bubble--hidden")});const n=this._messages.find(o=>o.role==="assistant"&&o.threadId===t);n&&this._panel?.restoreForMessage(n.id)||this._drawer?.clearPanel();const i=this._panel.currentType??"";this._panel?.updateTopBar(i),this._drawer?.setPills([]),this._session?.db&&this.config.session?.sessionId&&this._session?.db.loadContext(this.config.session.sessionId,t).then(o=>{o&&(this._lastBackendContext=o.context)}).catch(()=>{}),this._session?.db&&this.config.session?.sessionId&&this._session?.db.deleteContextsAfterThread(this.config.session.sessionId,t).catch(()=>{})}async _persistToIndexedDB(){!this._session||!this.config.session?.sessionId||await this._session.persist({userId:this.config.session.userId??"",appId:this.config.accountId,sessionId:this.config.session.sessionId,messages:this._messages,currentThreadId:this._currentThreadId,lastThreadId:this._lastThreadId,chatCreatedAt:this._chatCreatedAt,panelSnapshots:this._panel?.snapshots??new Map,panelThreads:this._panel?.threads??[],thumbnailEntries:this._thumbnailEntries,lastBackendContext:this._lastBackendContext,sku:this.config.pageContext?.sku})}_isSameOriginUrl(t){try{return t.trim()?new URL(t,window.location.href).origin===window.location.origin:!1}catch{return!1}}_markUnavailableProductContext(){this._productContextUnavailableSku=this.config.pageContext?.sku??null}_clearUnavailableProductContext(){this._productContextUnavailableSku=null}_hasUnavailableProductContext(){const t=this.config.pageContext?.sku;return t!==void 0&&t.length>0&&this._productContextUnavailableSku===t}_ensureAssistantMessageRendered(t){if(!(this._shadow?.querySelector(`[data-message-id="${CSS.escape(t.id)}"]`)||!this._drawer)){if(t.role==="assistant"&&t.threadId&&!this._threadsWithFirstBot.has(t.threadId)){this._threadsWithFirstBot.add(t.threadId),this._drawer.addMessage(t),this._drawer.markFirstBotMessage(t.id);return}this._drawer.addMessage(t)}}async _saveSessionAndOpenURL(t){this._session&&await this._session.saveAndOpenURL(t,()=>this._persistToIndexedDB(),this._bridge)}async _loadPayload(t,n){return this._session?this._session.loadPayload(t,n):null}async _restoreFromIndexedDB(t){if(!this._session?.db)return;const n=this.config.session?.sessionId;if(!n)return;const a=this.config.session?.userId??"",i=this.config.accountId;if(await this._session.loadFavorites(a,i),!t)return;const o=await this._session.db?.loadSession(a,i,n);if(!o||o.messages.length===0)return;const r=this.config.pageContext?.sku;if(r&&o.sku&&o.sku!==r)return;if(this._pdpLaunched=!0,this._drawer?.lockScrollForRestore(),this._currentThreadId=o.currentThreadId,this._lastThreadId=o.lastThreadId,this._chatCreatedAt=o.createdAt,o.panelThreads&&(this._panel.threads=o.panelThreads),o.thumbnailEntries&&(this._thumbnailEntries=o.thumbnailEntries,this._drawer?.setThumbnails(this._thumbnailEntries)),o.panelSnapshotHtml)for(const[c,l]of Object.entries(o.panelSnapshotHtml)){const g=document.createElement("div");g.innerHTML=oe(l),this._panel.snapshots.set(c,g)}let s=0;for(const c of o.messages){const l={id:c.id,role:c.role,timestamp:c.timestamp,status:c.status};if(c.threadId!==void 0&&(l.threadId=c.threadId),c.content!==void 0&&(l.content=c.content),c.silent&&(l.silent=!0),this._messages.push(l),l.silent)continue;l.role==="assistant"&&l.threadId&&!this._threadsWithFirstBot.has(l.threadId)&&(this._threadsWithFirstBot.add(l.threadId),this._drawer?.markFirstBotMessage(l.id)),this._drawer?.addMessage(l);const g=parseInt(c.id.replace("msg-",""),10);if(!isNaN(g)&&g>s&&(s=g),l.role==="assistant"&&l.threadId){const d=await this._loadPayload(l.threadId,l.id);d&&(l.uiSpec=d,this._restoreInlineUISpec(l),this._panel?.attachClickHandler(l.id),delete l.uiSpec)}}if(s>this._currentMessageId&&(this._currentMessageId=s),this._currentThreadId){let c=await this._session.db?.loadContext(n,this._currentThreadId);c||(c=await this._session.db?.loadLatestContext(n)),c&&(this._lastBackendContext=c.context)}if(this._currentThreadId){const c=[...this._messages].reverse().find(l=>l.role==="assistant"&&l.threadId===this._currentThreadId&&!l.silent);c&&this._panel.snapshots.has(c.id)&&this._panel?.restoreForMessage(c.id)}if(this._currentThreadId){const c=this._currentThreadId;for(const l of this._messages)l.threadId&&l.threadId>c&&this._shadow?.querySelector(`[data-message-id="${CSS.escape(l.id)}"]`)?.classList.add("gengage-chat-bubble--hidden");this._shadow?.querySelectorAll("[data-thread-id]").forEach(l=>{l instanceof HTMLElement&&l.dataset.threadId&&l.dataset.threadId>c&&l.classList.add("gengage-chat-bubble--hidden")})}if(this._panel.threads.length>0&&this._currentThreadId){const c=this._panel.threads[this._panel.threads.length-1];if(c){const l=[...this._messages].reverse().find(g=>g.role==="assistant"&&g.threadId===c);if(l?.threadId){const g=await this._loadPayload(l.threadId,l.id);if(g){const d=g.elements[g.root];d&&this._panel?.updateTopBar(d.type)}}}}setTimeout(()=>{this._drawer?.scrollToLastThread()},550)}_toggleComparisonSku(t){t===""?(this._comparisonSelectMode=!this._comparisonSelectMode,this._comparisonSelectMode||(this._comparisonSelectedSkus=[],wr())):this._comparisonSelectedSkus.indexOf(t)>=0?this._comparisonSelectedSkus=this._comparisonSelectedSkus.filter(a=>a!==t):(this._comparisonSelectedSkus=[...this._comparisonSelectedSkus,t],yr(t)),this._refreshComparisonUI()}_refreshComparisonUI(){const t=this._shadow?.querySelector(".gengage-chat-panel");if(!t)return;const n=t.querySelector(".gengage-chat-product-grid-wrapper");if(!n)return;const a=n.querySelector(".gengage-chat-product-grid");if(!a)return;const i=n.querySelector(".gengage-chat-comparison-toggle-btn");if(i&&i.classList.toggle("gengage-chat-comparison-toggle-btn--active",this._comparisonSelectMode),this._comparisonSelectMode){const r=a.querySelectorAll(".gengage-chat-product-card[data-sku]");for(const s of r){if(s.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){const d=s.parentElement.querySelector(".gengage-chat-comparison-checkbox");d&&(d.checked=this._comparisonSelectedSkus.includes(s.dataset.sku));continue}const c=s.dataset.sku,l=document.createElement("div");l.className="gengage-chat-comparison-select-wrapper";const g=document.createElement("input");g.type="checkbox",g.className="gengage-chat-comparison-checkbox",g.checked=this._comparisonSelectedSkus.includes(c),g.addEventListener("change",()=>{this._toggleComparisonSku(c)}),s.parentNode.insertBefore(l,s),l.appendChild(g),l.appendChild(s),l.style.cursor="pointer",l.addEventListener("click",d=>{d.target!==g&&(g.checked=!g.checked,this._toggleComparisonSku(c))})}}else{const r=a.querySelectorAll(".gengage-chat-comparison-select-wrapper");for(const s of r){const c=s.querySelector(".gengage-chat-product-card");c&&s.parentNode&&(s.parentNode.insertBefore(c,s),s.remove())}}const o=n.querySelector(".gengage-chat-comparison-floating-btn");if(this._comparisonSelectMode){const r=this._comparisonSelectedSkus.length,s=r>=2,c=this._i18n.compareSelected??"Compare",l=s?`${c} (${r})`:this._i18n.compareMinHint??"Select at least 2 products";if(o)o.textContent=l,o.disabled=!s,o.classList.toggle("gengage-chat-comparison-floating-btn--disabled",!s);else{const g=document.createElement("button");g.className="gengage-chat-comparison-floating-btn",g.type="button",g.textContent=l,g.disabled=!s,s||g.classList.add("gengage-chat-comparison-floating-btn--disabled"),g.addEventListener("click",()=>{this._comparisonSelectedSkus.length<2||(an(this._comparisonSelectedSkus),this._sendAction({title:c,type:"getComparisonTable",payload:{sku_list:[...this._comparisonSelectedSkus]}}))}),n.appendChild(g)}}else o?.remove()}_buildRenderContext(){const t={onAction:n=>{if(_r(n.title,n.type),n.type==="findSimilar"){const i=typeof n.payload=="object"&&n.payload!==null&&"sku"in n.payload?String(n.payload.sku):"";vr(i)}n.type==="getComparisonTable"&&an(this._comparisonSelectedSkus);const a=n.type==="addToCart"||n.type==="like";this._sendAction(n,a?{preservePanel:!0}:void 0)},onProductClick:n=>{Sr(n.sku),this.config.isDemoWebsite!==!0&&this._isSameOriginUrl(n.url)?(re("gengage:similar:product-click",{sku:n.sku,url:n.url,sessionId:this.config.session?.sessionId??null}),this._saveSessionAndOpenURL(n.url)):this._sendAction({title:n.sku,type:"launchSingleProduct",payload:{sku:n.sku}})},onAddToCart:n=>{Tr(n.sku,n.quantity);const a={...n,sessionId:this.config.session?.sessionId??null};re("gengage:chat:add-to-cart",a),this._bridge?.send("addToCart",n),this._runEventCallbacks("gengage-cart-add",a),this._sendAction({title:this._i18n.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:n.sku,cart_code:n.cartCode,quantity:n.quantity}},{preservePanel:!0})},onProductSelect:n=>{const a={root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:n}}}};this._drawer?.setPanelContent(this._renderUISpec(a,t))},i18n:this._i18n,pricing:this.config.pricing,productSort:this._productSort,onSortChange:n=>{this._productSort=n},comparisonSelectMode:this._comparisonSelectMode,comparisonSelectedSkus:this._comparisonSelectedSkus,onToggleComparisonSku:n=>{this._toggleComparisonSku(n)},favoritedSkus:this._session?.favoritedSkus??new Set,onFavoriteToggle:(n,a)=>{kr(n),this._toggleFavorite(n,a);const i=a.name??n;this._sendAction({title:i,type:"like",payload:{sku:n}},{preservePanel:!0})}};return t}async _toggleFavorite(t,n){if(!this._session)return;const a=this.config.session?.userId??"",i=this.config.accountId;await this._session.toggleFavorite(a,i,t,n)}async _runEventCallbacks(t,n){const a=this._eventCallbacks.get(t);if(!(!a||a.size===0))for(const i of a)try{const o=i(n);if((o instanceof Promise?await o:o)===!1){this._handleCallbackFailure(t,n);return}}catch{this._handleCallbackFailure(t,n);return}}_handleCallbackFailure(t,n){if(t==="gengage-cart-add"){const a=this._i18n.cartAddErrorMessage,i=this._createMessage("assistant",a);this._currentThreadId&&(i.threadId=this._currentThreadId),this._messages.push(i),this._drawer?.addMessage(i)}}_restoreInlineUISpec(t){if(!t.uiSpec||!this._drawer)return;const n=t.uiSpec,a=n.elements[n.root];if(!a)return;const i=a.type;if(i==="ActionButtons"||i==="ComparisonTable"||i==="ProductGrid"&&a.props?.similarsAppend===!0)return;const o=this._buildRenderContext(),r=this._shadow?.querySelector(".gengage-chat-messages");if(!r)return;if(i==="ProductDetailsPanel"){const c=a.props?.product;if(!c)return;const l={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:c}}}},g=this._renderUISpec(l,o);t.threadId&&(g.dataset.threadId=t.threadId),r.appendChild(g);return}const s=this._renderUISpec(n,o);t.threadId&&(s.dataset.threadId=t.threadId),r.appendChild(s)}_createMessage(t,n){return this._currentMessageId++,{id:`msg-${this._currentMessageId}`,role:t,content:n,timestamp:Date.now(),status:"done"}}_resolveI18n(t){return{...Xi(t.locale),...t.i18n}}_resolveUISpecRegistry(){const t=Wt();return da(t,this.config.renderer?.registry)}_renderUISpec(t,n){const a=this._resolveUISpecRegistry(),i=this.config.renderer?.unknownRenderer??ot,o=(c,l)=>Gt(c,l,a,i),r=this.config.renderer?.renderUISpec;return r?r(t,n,{registry:a,unknownRenderer:i,defaultRender:o}):o(t,n)}}function zg(){return new oa}ye.GengageChat=oa,ye.chatCatalog=Ig,ye.createChatWidget=zg,ye.createDefaultChatUISpecRegistry=Wt,ye.defaultChatUnknownUISpecRenderer=ot,ye.renderUISpec=Gt,Object.defineProperty(ye,Symbol.toStringTag,{value:"Module"})})(this.Gengage=this.Gengage||{});
97
97
  //# sourceMappingURL=chat.iife.js.map