@gengage/assistant-fe 0.3.39 → 0.3.40

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.
@@ -6248,7 +6248,7 @@ var fo = class Te extends Ra {
6248
6248
  this._drawer?.stageAttachment(e);
6249
6249
  }
6250
6250
  _sendMessage(e, a) {
6251
- this._contextPrimingInFlight && (this._abortAllActiveRequests(), this._contextPrimingInFlight = !1, this._queuedUserMessages = []), (!this._messages.some((i) => i.role === "user") || this._drawer?.isKvkkBannerVisible()) && (tt(this.config.accountId), this._drawer?.hideKvkkBanner()), ka(), this._messages.some((i) => i.role === "user") || La(), Pe("chat", "sendMessage", {
6251
+ this._contextPrimingInFlight && (this._abortAllActiveRequests(), this._contextPrimingInFlight = !1, this._queuedUserMessages = []), ka(), this._messages.some((i) => i.role === "user") || La(), Pe("chat", "sendMessage", {
6252
6252
  mode: this._assistantMode,
6253
6253
  hasAttachment: a !== void 0,
6254
6254
  textLength: e.length
@@ -6305,6 +6305,7 @@ var fo = class Te extends Ra {
6305
6305
  if (i || (this._activeRequestThreadId = n), !a?.silent && !i && this._drawer?.setPresentationFocus(n), !a?.silent) {
6306
6306
  const f = typeof e.payload == "string" ? e.payload : typeof e.payload?.text == "string" ? e.payload.text : e.title, C = this._messages.length > 0 ? this._messages[this._messages.length - 1] : void 0;
6307
6307
  if (!(C !== void 0 && C.role === "user" && C.content === f)) {
6308
+ (!this._messages.some((R) => R.role === "user") || this._drawer?.isKvkkBannerVisible()) && (tt(this.config.accountId), this._drawer?.hideKvkkBanner());
6308
6309
  const w = this._createMessage("user", f);
6309
6310
  w.threadId = n, a?.attachment !== void 0 && (w.attachment = a.attachment), this._drawer?.addMessage(w), a?.attachment !== void 0 && this._modeController.isBeautyConsulting && this._drawer?.setBeautyPhotoStepCard({ visible: !1 }), this._messages.push(w);
6310
6311
  }
package/dist/chat.iife.js CHANGED
@@ -173,6 +173,6 @@ button[data-gengage-part="chat-launcher-button"] img {
173
173
 
174
174
  `)}d.write("payload.value = newResult;"),d.write("return payload;");const P=d.compile();return(A,k)=>P(h,A,k)};let i;const o=Mt,s=!pa.jitless,l=s&&Ul.value,g=t.catchall;let p;e._zod.parse=(h,d)=>{p??(p=n.value);const b=h.value;return o(b)?s&&l&&d?.async===!1&&d.jitless!==!0?(i||(i=r(t.shape)),h=i(h,d),g?nr([],b,h,d,p,e):h):a(h,d):(h.issues.push({expected:"object",code:"invalid_type",input:b,inst:e}),h)}});function rr(e,t,a,n){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const r=e.filter(i=>!ot(i));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:a,errors:e.map(i=>i.issues.map(o=>Ge(o,n,Ze())))}),t)}var Ad=w("$ZodUnion",(e,t)=>{ge.init(e,t),re(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),re(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),re(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),re(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>fa(i.source)).join("|")})$`)}});const a=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(r,i)=>{if(a)return n(r,i);let o=!1;const s=[];for(const c of t.options){const l=c._zod.run({value:r.value,issues:[]},i);if(l instanceof Promise)s.push(l),o=!0;else{if(l.issues.length===0)return l;s.push(l)}}return o?Promise.all(s).then(c=>rr(c,r,e,i)):rr(s,r,e,i)}}),Td=w("$ZodIntersection",(e,t)=>{ge.init(e,t),e._zod.parse=(a,n)=>{const r=a.value,i=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([s,c])=>ir(a,s,c)):ir(a,i,o)}});function xa(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(it(e)&&it(t)){const a=Object.keys(t),n=Object.keys(e).filter(i=>a.indexOf(i)!==-1),r={...e,...t};for(const i of n){const o=xa(e[i],t[i]);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};r[i]=o.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const a=[];for(let n=0;n<e.length;n++){const r=e[n],i=t[n],o=xa(r,i);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};a.push(o.data)}return{valid:!0,data:a}}return{valid:!1,mergeErrorPath:[]}}function ir(e,t,a){const n=new Map;let r;for(const s of t.issues)if(s.code==="unrecognized_keys"){r??(r=s);for(const c of s.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else e.issues.push(s);for(const s of a.issues)if(s.code==="unrecognized_keys")for(const c of s.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else e.issues.push(s);const i=[...n].filter(([,s])=>s.l&&s.r).map(([s])=>s);if(i.length&&r&&e.issues.push({...r,keys:i}),ot(e))return e;const o=xa(t.value,a.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Ld=w("$ZodRecord",(e,t)=>{ge.init(e,t),e._zod.parse=(a,n)=>{const r=a.value;if(!it(r))return a.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),a;const i=[],o=t.keyType._zod.values;if(o){a.value={};const s=new Set;for(const l of o)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:r[l],issues:[]},n);g instanceof Promise?i.push(g.then(p=>{p.issues.length&&a.issues.push(...st(l,p.issues)),a.value[l]=p.value})):(g.issues.length&&a.issues.push(...st(l,g.issues)),a.value[l]=g.value)}let c;for(const l in r)s.has(l)||(c=c??[],c.push(l));c&&c.length>0&&a.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:c})}else{a.value={};for(const s of Reflect.ownKeys(r)){if(s==="__proto__")continue;let c=t.keyType._zod.run({value:s,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof s=="string"&&Kn.test(s)&&c.issues.length){const g=t.keyType._zod.run({value:Number(s),issues:[]},n);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(c=g)}if(c.issues.length){t.mode==="loose"?a.value[s]=r[s]:a.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(g=>Ge(g,n,Ze())),input:s,path:[s],inst:e});continue}const l=t.valueType._zod.run({value:r[s],issues:[]},n);l instanceof Promise?i.push(l.then(g=>{g.issues.length&&a.issues.push(...st(s,g.issues)),a.value[c.value]=g.value})):(l.issues.length&&a.issues.push(...st(s,l.issues)),a.value[c.value]=l.value)}}return i.length?Promise.all(i).then(()=>a):a}}),Id=w("$ZodEnum",(e,t)=>{ge.init(e,t);const a=Dn(t.entries),n=new Set(a);e._zod.values=n,e._zod.pattern=new RegExp(`^(${a.filter(r=>jl.has(typeof r)).map(r=>typeof r=="string"?Bt(r):r.toString()).join("|")})$`),e._zod.parse=(r,i)=>{const o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:a,input:o,inst:e}),r}}),Nd=w("$ZodTransform",(e,t)=>{ge.init(e,t),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new Rn(e.constructor.name);const r=t.transform(a.value,a);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(i=>(a.value=i,a));if(r instanceof Promise)throw new rt;return a.value=r,a}});function or(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var sr=w("$ZodOptional",(e,t)=>{ge.init(e,t),e._zod.optin="optional",e._zod.optout="optional",re(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),re(e._zod,"pattern",()=>{const a=t.innerType._zod.pattern;return a?new RegExp(`^(${fa(a.source)})?$`):void 0}),e._zod.parse=(a,n)=>{if(t.innerType._zod.optin==="optional"){const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>or(i,a.value)):or(r,a.value)}return a.value===void 0?a:t.innerType._zod.run(a,n)}}),zd=w("$ZodExactOptional",(e,t)=>{sr.init(e,t),re(e._zod,"values",()=>t.innerType._zod.values),re(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(a,n)=>t.innerType._zod.run(a,n)}),Md=w("$ZodNullable",(e,t)=>{ge.init(e,t),re(e._zod,"optin",()=>t.innerType._zod.optin),re(e._zod,"optout",()=>t.innerType._zod.optout),re(e._zod,"pattern",()=>{const a=t.innerType._zod.pattern;return a?new RegExp(`^(${fa(a.source)}|null)$`):void 0}),re(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(a,n)=>a.value===null?a:t.innerType._zod.run(a,n)}),Bd=w("$ZodDefault",(e,t)=>{ge.init(e,t),e._zod.optin="optional",re(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(a,n)=>{if(n.direction==="backward")return t.innerType._zod.run(a,n);if(a.value===void 0)return a.value=t.defaultValue,a;const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>cr(i,t)):cr(r,t)}});function cr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Rd=w("$ZodPrefault",(e,t)=>{ge.init(e,t),e._zod.optin="optional",re(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(a,n)=>(n.direction==="backward"||a.value===void 0&&(a.value=t.defaultValue),t.innerType._zod.run(a,n))}),Dd=w("$ZodNonOptional",(e,t)=>{ge.init(e,t),re(e._zod,"values",()=>{const a=t.innerType._zod.values;return a?new Set([...a].filter(n=>n!==void 0)):void 0}),e._zod.parse=(a,n)=>{const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>lr(i,e)):lr(r,e)}});function lr(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Od=w("$ZodCatch",(e,t)=>{ge.init(e,t),re(e._zod,"optin",()=>t.innerType._zod.optin),re(e._zod,"optout",()=>t.innerType._zod.optout),re(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(a,n)=>{if(n.direction==="backward")return t.innerType._zod.run(a,n);const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>(a.value=i.value,i.issues.length&&(a.value=t.catchValue({...a,error:{issues:i.issues.map(o=>Ge(o,n,Ze()))},input:a.value}),a.issues=[]),a)):(a.value=r.value,r.issues.length&&(a.value=t.catchValue({...a,error:{issues:r.issues.map(i=>Ge(i,n,Ze()))},input:a.value}),a.issues=[]),a)}}),Fd=w("$ZodPipe",(e,t)=>{ge.init(e,t),re(e._zod,"values",()=>t.in._zod.values),re(e._zod,"optin",()=>t.in._zod.optin),re(e._zod,"optout",()=>t.out._zod.optout),re(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(a,n)=>{if(n.direction==="backward"){const i=t.out._zod.run(a,n);return i instanceof Promise?i.then(o=>Ht(o,t.in,n)):Ht(i,t.in,n)}const r=t.in._zod.run(a,n);return r instanceof Promise?r.then(i=>Ht(i,t.out,n)):Ht(r,t.out,n)}});function Ht(e,t,a){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},a)}var $d=w("$ZodReadonly",(e,t)=>{ge.init(e,t),re(e._zod,"propValues",()=>t.innerType._zod.propValues),re(e._zod,"values",()=>t.innerType._zod.values),re(e._zod,"optin",()=>t.innerType?._zod?.optin),re(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(a,n)=>{if(n.direction==="backward")return t.innerType._zod.run(a,n);const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(gr):gr(r)}});function gr(e){return e.value=Object.freeze(e.value),e}var Hd=w("$ZodCustom",(e,t)=>{ke.init(e,t),ge.init(e,t),e._zod.parse=(a,n)=>a,e._zod.check=a=>{const n=a.value,r=t.fn(n);if(r instanceof Promise)return r.then(i=>dr(i,a,n,e));dr(r,a,n,e)}});function dr(e,t,a,n){if(!e){const r={code:"custom",input:a,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(r.params=n._zod.def.params),t.issues.push(bt(r))}}var pr,Ud=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const a=t[0];return this._map.set(e,a),a&&typeof a=="object"&&"id"in a&&this._idmap.set(a.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const a={...this.get(t)??{}};delete a.id;const n={...a,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function jd(){return new Ud}(pr=globalThis).__zod_globalRegistry??(pr.__zod_globalRegistry=jd());var vt=globalThis.__zod_globalRegistry;function Zd(e,t){return new e({type:"string",...F(t)})}function qd(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...F(t)})}function hr(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...F(t)})}function Vd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...F(t)})}function Gd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...F(t)})}function Wd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...F(t)})}function Kd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...F(t)})}function Yd(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...F(t)})}function Jd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...F(t)})}function Xd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...F(t)})}function Qd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...F(t)})}function ep(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...F(t)})}function tp(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...F(t)})}function ap(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...F(t)})}function np(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...F(t)})}function rp(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...F(t)})}function ip(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...F(t)})}function op(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...F(t)})}function sp(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...F(t)})}function cp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...F(t)})}function lp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...F(t)})}function gp(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...F(t)})}function dp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...F(t)})}function pp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...F(t)})}function hp(e,t){return new e({type:"string",format:"date",check:"string_format",...F(t)})}function up(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...F(t)})}function mp(e,t){return new e({type:"string",format:"duration",check:"string_format",...F(t)})}function fp(e,t){return new e({type:"number",checks:[],...F(t)})}function bp(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...F(t)})}function vp(e,t){return new e({type:"boolean",...F(t)})}function yp(e){return new e({type:"unknown"})}function _p(e,t){return new e({type:"never",...F(t)})}function ur(e,t){return new Jn({check:"less_than",...F(t),value:e,inclusive:!1})}function wa(e,t){return new Jn({check:"less_than",...F(t),value:e,inclusive:!0})}function mr(e,t){return new Xn({check:"greater_than",...F(t),value:e,inclusive:!1})}function ka(e,t){return new Xn({check:"greater_than",...F(t),value:e,inclusive:!0})}function fr(e,t){return new Rg({check:"multiple_of",...F(t),value:e})}function br(e,t){return new Og({check:"max_length",...F(t),maximum:e})}function Ut(e,t){return new Fg({check:"min_length",...F(t),minimum:e})}function vr(e,t){return new $g({check:"length_equals",...F(t),length:e})}function xp(e,t){return new Hg({check:"string_format",format:"regex",...F(t),pattern:e})}function wp(e){return new Ug({check:"string_format",format:"lowercase",...F(e)})}function kp(e){return new jg({check:"string_format",format:"uppercase",...F(e)})}function Cp(e,t){return new Zg({check:"string_format",format:"includes",...F(t),includes:e})}function Sp(e,t){return new qg({check:"string_format",format:"starts_with",...F(t),prefix:e})}function Ep(e,t){return new Vg({check:"string_format",format:"ends_with",...F(t),suffix:e})}function ct(e){return new Gg({check:"overwrite",tx:e})}function Pp(e){return ct(t=>t.normalize(e))}function Ap(){return ct(e=>e.trim())}function Tp(){return ct(e=>e.toLowerCase())}function Lp(){return ct(e=>e.toUpperCase())}function Ip(){return ct(e=>Hl(e))}function Np(e,t,a){return new e({type:"array",element:t,...F(a)})}function zp(e,t,a){return new e({type:"custom",check:"custom",fn:t,...F(a)})}function Mp(e){const t=Bp(a=>(a.addIssue=n=>{if(typeof n=="string")a.issues.push(bt(n,a.value,t._zod.def));else{const r=n;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=a.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),a.issues.push(bt(r))}},e(a.value,a)));return t}function Bp(e,t){const a=new ke({check:"custom",...F(t)});return a._zod.check=e,a}function yr(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??vt,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 he(e,t,a={path:[],schemaPath:[]}){var n;const r=e._zod.def,i=t.seen.get(e);if(i)return i.count++,a.schemaPath.includes(e)&&(i.cycle=a.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:a.path};t.seen.set(e,o);const s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{const l={...a,schemaPath:[...a.schemaPath,e],path:a.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,l);else{const p=o.schema,h=t.processors[r.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);h(e,t,p,l)}const g=e._zod.parent;g&&(o.ref||(o.ref=g),he(g,t,l),t.seen.get(g).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io==="input"&&xe(e)&&(delete o.schema.examples,delete o.schema.default),t.io==="input"&&o.schema._prefault&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function _r(e,t){const a=e.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const o of e.seen.entries()){const s=e.metadataRegistry.get(o[0])?.id;if(s){const c=n.get(s);if(c&&c!==o[0])throw new Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(s,o[0])}}const r=o=>{const s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(o[0])?.id,p=e.external.uri??(d=>d);if(g)return{ref:p(g)};const h=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=h,{defId:h,ref:`${p("__shared")}#/${s}/${h}`}}if(o[1]===a)return{ref:"#"};const c=`#/${s}/`,l=o[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:c+l}},i=o=>{if(o[1].schema.$ref)return;const s=o[1],{ref:c,defId:l}=r(o);s.def={...s.schema},l&&(s.defId=l);const g=s.schema;for(const p in g)delete g[p];g.$ref=c};if(e.cycles==="throw")for(const o of e.seen.entries()){const s=o[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.cycle?.join("/")}/<root>
175
175
 
176
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const s=o[1];if(t===o[0]){i(o);continue}if(e.external){const c=e.external.registry.get(o[0])?.id;if(t!==o[0]&&c){i(o);continue}}if(e.metadataRegistry.get(o[0])?.id){i(o);continue}if(s.cycle){i(o);continue}if(s.count>1&&e.reused==="ref"){i(o);continue}}}function xr(e,t){const a=e.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=o=>{const s=e.seen.get(o);if(s.ref===null)return;const c=s.def??s.schema,l={...c},g=s.ref;if(s.ref=null,g){n(g);const h=e.seen.get(g),d=h.schema;if(d.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(d)):Object.assign(c,d),Object.assign(c,l),o._zod.parent===g)for(const b in c)b==="$ref"||b==="allOf"||b in l||delete c[b];if(d.$ref&&h.def)for(const b in c)b==="$ref"||b==="allOf"||b in h.def&&JSON.stringify(c[b])===JSON.stringify(h.def[b])&&delete c[b]}const p=o._zod.parent;if(p&&p!==g){n(p);const h=e.seen.get(p);if(h?.schema.$ref&&(c.$ref=h.schema.$ref,h.def))for(const d in c)d==="$ref"||d==="allOf"||d in h.def&&JSON.stringify(c[d])===JSON.stringify(h.def[d])&&delete c[d]}e.override({zodSchema:o,jsonSchema:c,path:s.path??[]})};for(const o of[...e.seen.entries()].reverse())n(o[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const o=e.external.registry.get(t)?.id;if(!o)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(o)}Object.assign(r,a.def??a.schema);const i=e.external?.defs??{};for(const o of e.seen.entries()){const s=o[1];s.def&&s.defId&&(i[s.defId]=s.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?r.$defs=i:r.definitions=i);try{const o=JSON.parse(JSON.stringify(r));return Object.defineProperty(o,"~standard",{value:{...t["~standard"],jsonSchema:{input:jt(t,"input",e.processors),output:jt(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function xe(e,t){const a=t??{seen:new Set};if(a.seen.has(e))return!1;a.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return xe(n.element,a);if(n.type==="set")return xe(n.valueType,a);if(n.type==="lazy")return xe(n.getter(),a);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return xe(n.innerType,a);if(n.type==="intersection")return xe(n.left,a)||xe(n.right,a);if(n.type==="record"||n.type==="map")return xe(n.keyType,a)||xe(n.valueType,a);if(n.type==="pipe")return xe(n.in,a)||xe(n.out,a);if(n.type==="object"){for(const r in n.shape)if(xe(n.shape[r],a))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(xe(r,a))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(xe(r,a))return!0;return!!(n.rest&&xe(n.rest,a))}return!1}var Rp=(e,t={})=>a=>{const n=yr({...a,processors:t});return he(e,n),_r(n,e),xr(n,e)},jt=(e,t,a={})=>n=>{const{libraryOptions:r,target:i}=n??{},o=yr({...r??{},target:i,io:t,processors:a});return he(e,o),_r(o,e),xr(o,e)},Dp={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Op=(e,t,a,n)=>{const r=a;r.type="string";const{minimum:i,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof o=="number"&&(r.maxLength=o),s&&(r.format=Dp[s]??s,r.format===""&&delete r.format,s==="time"&&delete r.format),l&&(r.contentEncoding=l),c&&c.size>0){const g=[...c];g.length===1?r.pattern=g[0].source:g.length>1&&(r.allOf=[...g.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},Fp=(e,t,a,n)=>{const r=a,{minimum:i,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:g}=e._zod.bag;typeof s=="string"&&s.includes("int")?r.type="integer":r.type="number",typeof g=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=g,r.exclusiveMinimum=!0):r.exclusiveMinimum=g),typeof i=="number"&&(r.minimum=i,typeof g=="number"&&t.target!=="draft-04"&&(g>=i?delete r.minimum:delete r.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),typeof o=="number"&&(r.maximum=o,typeof l=="number"&&t.target!=="draft-04"&&(l<=o?delete r.maximum:delete r.exclusiveMaximum)),typeof c=="number"&&(r.multipleOf=c)},$p=(e,t,a,n)=>{a.type="boolean"},Hp=(e,t,a,n)=>{a.not={}},Up=(e,t,a,n)=>{},jp=(e,t,a,n)=>{const r=e._zod.def,i=Dn(r.entries);i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),a.enum=i},Zp=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},qp=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Vp=(e,t,a,n)=>{const r=a,i=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o=="number"&&(r.minItems=o),typeof s=="number"&&(r.maxItems=s),r.type="array",r.items=he(i.element,t,{...n,path:[...n.path,"items"]})},Gp=(e,t,a,n)=>{const r=a,i=e._zod.def;r.type="object",r.properties={};const o=i.shape;for(const l in o)r.properties[l]=he(o[l],t,{...n,path:[...n.path,"properties",l]});const s=new Set(Object.keys(o)),c=new Set([...s].filter(l=>{const g=i.shape[l]._zod;return t.io==="input"?g.optin===void 0:g.optout===void 0}));c.size>0&&(r.required=Array.from(c)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=he(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},Wp=(e,t,a,n)=>{const r=e._zod.def,i=r.inclusive===!1,o=r.options.map((s,c)=>he(s,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?a.oneOf=o:a.anyOf=o},Kp=(e,t,a,n)=>{const r=e._zod.def,i=he(r.left,t,{...n,path:[...n.path,"allOf",0]}),o=he(r.right,t,{...n,path:[...n.path,"allOf",1]}),s=c=>"allOf"in c&&Object.keys(c).length===1;a.allOf=[...s(i)?i.allOf:[i],...s(o)?o.allOf:[o]]},Yp=(e,t,a,n)=>{const r=a,i=e._zod.def;r.type="object";const o=i.keyType,s=o._zod.bag?.patterns;if(i.mode==="loose"&&s&&s.size>0){const l=he(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});r.patternProperties={};for(const g of s)r.patternProperties[g.source]=l}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=he(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=he(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const c=o._zod.values;if(c){const l=[...c].filter(g=>typeof g=="string"||typeof g=="number");l.length>0&&(r.required=l)}},Jp=(e,t,a,n)=>{const r=e._zod.def,i=he(r.innerType,t,n),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=r.innerType,a.nullable=!0):a.anyOf=[i,{type:"null"}]},Xp=(e,t,a,n)=>{const r=e._zod.def;he(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Qp=(e,t,a,n)=>{const r=e._zod.def;he(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.default=JSON.parse(JSON.stringify(r.defaultValue))},eh=(e,t,a,n)=>{const r=e._zod.def;he(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,t.io==="input"&&(a._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},th=(e,t,a,n)=>{const r=e._zod.def;he(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType;let o;try{o=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}a.default=o},ah=(e,t,a,n)=>{const r=e._zod.def,i=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;he(i,t,n);const o=t.seen.get(e);o.ref=i},nh=(e,t,a,n)=>{const r=e._zod.def;he(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.readOnly=!0},wr=(e,t,a,n)=>{const r=e._zod.def;he(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},rh=w("ZodISODateTime",(e,t)=>{sd.init(e,t),le.init(e,t)});function ih(e){return pp(rh,e)}var oh=w("ZodISODate",(e,t)=>{cd.init(e,t),le.init(e,t)});function sh(e){return hp(oh,e)}var ch=w("ZodISOTime",(e,t)=>{ld.init(e,t),le.init(e,t)});function lh(e){return up(ch,e)}var gh=w("ZodISODuration",(e,t)=>{gd.init(e,t),le.init(e,t)});function dh(e){return mp(gh,e)}var kr=(e,t)=>{jn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:a=>eg(e,a)},flatten:{value:a=>Ql(e,a)},addIssue:{value:a=>{e.issues.push(a),e.message=JSON.stringify(e.issues,ha,2)}},addIssues:{value:a=>{e.issues.push(...a),e.message=JSON.stringify(e.issues,ha,2)}},isEmpty:{get(){return e.issues.length===0}}})},qu=w("ZodError",kr),Le=w("ZodError",kr,{Parent:Error}),ph=va(Le),hh=ya(Le),uh=Dt(Le),mh=Ot(Le),fh=ng(Le),bh=rg(Le),vh=ig(Le),yh=og(Le),_h=sg(Le),xh=cg(Le),wh=lg(Le),kh=gg(Le),de=w("ZodType",(e,t)=>(ge.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:jt(e,"input"),output:jt(e,"output")}}),e.toJSONSchema=Rp(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...a)=>e.clone(qe(t,{checks:[...t.checks??[],...a.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(a,n)=>Ve(e,a,n),e.brand=()=>e,e.register=((a,n)=>(a.add(e,n),e)),e.parse=(a,n)=>ph(e,a,n,{callee:e.parse}),e.safeParse=(a,n)=>uh(e,a,n),e.parseAsync=async(a,n)=>hh(e,a,n,{callee:e.parseAsync}),e.safeParseAsync=async(a,n)=>mh(e,a,n),e.spa=e.safeParseAsync,e.encode=(a,n)=>fh(e,a,n),e.decode=(a,n)=>bh(e,a,n),e.encodeAsync=async(a,n)=>vh(e,a,n),e.decodeAsync=async(a,n)=>yh(e,a,n),e.safeEncode=(a,n)=>_h(e,a,n),e.safeDecode=(a,n)=>xh(e,a,n),e.safeEncodeAsync=async(a,n)=>wh(e,a,n),e.safeDecodeAsync=async(a,n)=>kh(e,a,n),e.refine=(a,n)=>e.check(mu(a,n)),e.superRefine=a=>e.check(fu(a)),e.overwrite=a=>e.check(ct(a)),e.optional=()=>Tr(e),e.exactOptional=()=>au(e),e.nullable=()=>Lr(e),e.nullish=()=>Tr(Lr(e)),e.nonoptional=a=>cu(e,a),e.array=()=>ee(e),e.or=a=>lt([e,a]),e.and=a=>Jh(e,a),e.transform=a=>Nr(e,eu(a)),e.default=a=>iu(e,a),e.prefault=a=>su(e,a),e.catch=a=>gu(e,a),e.pipe=a=>Nr(e,a),e.readonly=()=>hu(e),e.describe=a=>{const n=e.clone();return vt.add(n,{description:a}),n},Object.defineProperty(e,"description",{get(){return vt.get(e)?.description},configurable:!0}),e.meta=(...a)=>{if(a.length===0)return vt.get(e);const n=e.clone();return vt.add(n,a[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=a=>a(e),e)),Cr=w("_ZodString",(e,t)=>{_a.init(e,t),de.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Op(e,n,r,i);const a=e._zod.bag;e.format=a.format??null,e.minLength=a.minimum??null,e.maxLength=a.maximum??null,e.regex=(...n)=>e.check(xp(...n)),e.includes=(...n)=>e.check(Cp(...n)),e.startsWith=(...n)=>e.check(Sp(...n)),e.endsWith=(...n)=>e.check(Ep(...n)),e.min=(...n)=>e.check(Ut(...n)),e.max=(...n)=>e.check(br(...n)),e.length=(...n)=>e.check(vr(...n)),e.nonempty=(...n)=>e.check(Ut(1,...n)),e.lowercase=n=>e.check(wp(n)),e.uppercase=n=>e.check(kp(n)),e.trim=()=>e.check(Ap()),e.normalize=(...n)=>e.check(Pp(...n)),e.toLowerCase=()=>e.check(Tp()),e.toUpperCase=()=>e.check(Lp()),e.slugify=()=>e.check(Ip())}),Ch=w("ZodString",(e,t)=>{_a.init(e,t),Cr.init(e,t),e.email=a=>e.check(qd(Sh,a)),e.url=a=>e.check(Yd(Eh,a)),e.jwt=a=>e.check(dp(Hh,a)),e.emoji=a=>e.check(Jd(Ph,a)),e.guid=a=>e.check(hr(Sr,a)),e.uuid=a=>e.check(Vd(Zt,a)),e.uuidv4=a=>e.check(Gd(Zt,a)),e.uuidv6=a=>e.check(Wd(Zt,a)),e.uuidv7=a=>e.check(Kd(Zt,a)),e.nanoid=a=>e.check(Xd(Ah,a)),e.guid=a=>e.check(hr(Sr,a)),e.cuid=a=>e.check(Qd(Th,a)),e.cuid2=a=>e.check(ep(Lh,a)),e.ulid=a=>e.check(tp(Ih,a)),e.base64=a=>e.check(cp(Oh,a)),e.base64url=a=>e.check(lp(Fh,a)),e.xid=a=>e.check(ap(Nh,a)),e.ksuid=a=>e.check(np(zh,a)),e.ipv4=a=>e.check(rp(Mh,a)),e.ipv6=a=>e.check(ip(Bh,a)),e.cidrv4=a=>e.check(op(Rh,a)),e.cidrv6=a=>e.check(sp(Dh,a)),e.e164=a=>e.check(gp($h,a)),e.datetime=a=>e.check(ih(a)),e.date=a=>e.check(sh(a)),e.time=a=>e.check(lh(a)),e.duration=a=>e.check(dh(a))});function _(e){return Zd(Ch,e)}var le=w("ZodStringFormat",(e,t)=>{se.init(e,t),Cr.init(e,t)}),Sh=w("ZodEmail",(e,t)=>{Xg.init(e,t),le.init(e,t)}),Sr=w("ZodGUID",(e,t)=>{Yg.init(e,t),le.init(e,t)}),Zt=w("ZodUUID",(e,t)=>{Jg.init(e,t),le.init(e,t)}),Eh=w("ZodURL",(e,t)=>{Qg.init(e,t),le.init(e,t)}),Ph=w("ZodEmoji",(e,t)=>{ed.init(e,t),le.init(e,t)}),Ah=w("ZodNanoID",(e,t)=>{td.init(e,t),le.init(e,t)}),Th=w("ZodCUID",(e,t)=>{ad.init(e,t),le.init(e,t)}),Lh=w("ZodCUID2",(e,t)=>{nd.init(e,t),le.init(e,t)}),Ih=w("ZodULID",(e,t)=>{rd.init(e,t),le.init(e,t)}),Nh=w("ZodXID",(e,t)=>{id.init(e,t),le.init(e,t)}),zh=w("ZodKSUID",(e,t)=>{od.init(e,t),le.init(e,t)}),Mh=w("ZodIPv4",(e,t)=>{dd.init(e,t),le.init(e,t)}),Bh=w("ZodIPv6",(e,t)=>{pd.init(e,t),le.init(e,t)}),Rh=w("ZodCIDRv4",(e,t)=>{hd.init(e,t),le.init(e,t)}),Dh=w("ZodCIDRv6",(e,t)=>{ud.init(e,t),le.init(e,t)}),Oh=w("ZodBase64",(e,t)=>{md.init(e,t),le.init(e,t)}),Fh=w("ZodBase64URL",(e,t)=>{bd.init(e,t),le.init(e,t)}),$h=w("ZodE164",(e,t)=>{vd.init(e,t),le.init(e,t)}),Hh=w("ZodJWT",(e,t)=>{_d.init(e,t),le.init(e,t)}),Er=w("ZodNumber",(e,t)=>{er.init(e,t),de.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Fp(e,n,r,i),e.gt=(n,r)=>e.check(mr(n,r)),e.gte=(n,r)=>e.check(ka(n,r)),e.min=(n,r)=>e.check(ka(n,r)),e.lt=(n,r)=>e.check(ur(n,r)),e.lte=(n,r)=>e.check(wa(n,r)),e.max=(n,r)=>e.check(wa(n,r)),e.int=n=>e.check(Pr(n)),e.safe=n=>e.check(Pr(n)),e.positive=n=>e.check(mr(0,n)),e.nonnegative=n=>e.check(ka(0,n)),e.negative=n=>e.check(ur(0,n)),e.nonpositive=n=>e.check(wa(0,n)),e.multipleOf=(n,r)=>e.check(fr(n,r)),e.step=(n,r)=>e.check(fr(n,r)),e.finite=()=>e;const a=e._zod.bag;e.minValue=Math.max(a.minimum??Number.NEGATIVE_INFINITY,a.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(a.maximum??Number.POSITIVE_INFINITY,a.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(a.format??"").includes("int")||Number.isSafeInteger(a.multipleOf??.5),e.isFinite=!0,e.format=a.format??null});function Me(e){return fp(Er,e)}var Uh=w("ZodNumberFormat",(e,t)=>{xd.init(e,t),Er.init(e,t)});function Pr(e){return bp(Uh,e)}var jh=w("ZodBoolean",(e,t)=>{wd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>$p(e,a,n,r)});function Ye(e){return vp(jh,e)}var Zh=w("ZodUnknown",(e,t)=>{kd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Up(e,a,n,r)});function Se(){return yp(Zh)}var qh=w("ZodNever",(e,t)=>{Cd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Hp(e,a,n,r)});function Vh(e){return _p(qh,e)}var Gh=w("ZodArray",(e,t)=>{Sd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Vp(e,a,n,r),e.element=t.element,e.min=(a,n)=>e.check(Ut(a,n)),e.nonempty=a=>e.check(Ut(1,a)),e.max=(a,n)=>e.check(br(a,n)),e.length=(a,n)=>e.check(vr(a,n)),e.unwrap=()=>e.element});function ee(e,t){return Np(Gh,e,t)}var Wh=w("ZodObject",(e,t)=>{Pd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Gp(e,a,n,r),re(e,"shape",()=>t.shape),e.keyof=()=>yt(Object.keys(e._zod.def.shape)),e.catchall=a=>e.clone({...e._zod.def,catchall:a}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Se()}),e.loose=()=>e.clone({...e._zod.def,catchall:Se()}),e.strict=()=>e.clone({...e._zod.def,catchall:Vh()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=a=>Wl(e,a),e.safeExtend=a=>Kl(e,a),e.merge=a=>Yl(e,a),e.pick=a=>Vl(e,a),e.omit=a=>Gl(e,a),e.partial=(...a)=>Jl(Ar,e,a[0]),e.required=(...a)=>Xl(Ir,e,a[0])});function G(e,t){return new Wh({type:"object",shape:e??{},...F(t)})}var Kh=w("ZodUnion",(e,t)=>{Ad.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Wp(e,a,n,r),e.options=t.options});function lt(e,t){return new Kh({type:"union",options:e,...F(t)})}var Yh=w("ZodIntersection",(e,t)=>{Td.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Kp(e,a,n,r)});function Jh(e,t){return new Yh({type:"intersection",left:e,right:t})}var Xh=w("ZodRecord",(e,t)=>{Ld.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Yp(e,a,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Je(e,t,a){return new Xh({type:"record",keyType:e,valueType:t,...F(a)})}var Ca=w("ZodEnum",(e,t)=>{Id.init(e,t),de.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jp(e,n,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const a=new Set(Object.keys(t.entries));e.extract=(n,r)=>{const i={};for(const o of n)if(a.has(o))i[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Ca({...t,checks:[],...F(r),entries:i})},e.exclude=(n,r)=>{const i={...t.entries};for(const o of n)if(a.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new Ca({...t,checks:[],...F(r),entries:i})}});function yt(e,t){return new Ca({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e,...F(t)})}var Qh=w("ZodTransform",(e,t)=>{Nd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>qp(e,a,n,r),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new Rn(e.constructor.name);a.addIssue=i=>{if(typeof i=="string")a.issues.push(bt(i,a.value,t));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=a.value),o.inst??(o.inst=e),a.issues.push(bt(o))}};const r=t.transform(a.value,a);return r instanceof Promise?r.then(i=>(a.value=i,a)):(a.value=r,a)}});function eu(e){return new Qh({type:"transform",transform:e})}var Ar=w("ZodOptional",(e,t)=>{sr.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>wr(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Tr(e){return new Ar({type:"optional",innerType:e})}var tu=w("ZodExactOptional",(e,t)=>{zd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>wr(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function au(e){return new tu({type:"optional",innerType:e})}var nu=w("ZodNullable",(e,t)=>{Md.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Jp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Lr(e){return new nu({type:"nullable",innerType:e})}var ru=w("ZodDefault",(e,t)=>{Bd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Qp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function iu(e,t){return new ru({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Hn(t)}})}var ou=w("ZodPrefault",(e,t)=>{Rd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>eh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function su(e,t){return new ou({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Hn(t)}})}var Ir=w("ZodNonOptional",(e,t)=>{Dd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Xp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function cu(e,t){return new Ir({type:"nonoptional",innerType:e,...F(t)})}var lu=w("ZodCatch",(e,t)=>{Od.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>th(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function gu(e,t){return new lu({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var du=w("ZodPipe",(e,t)=>{Fd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>ah(e,a,n,r),e.in=t.in,e.out=t.out});function Nr(e,t){return new du({type:"pipe",in:e,out:t})}var pu=w("ZodReadonly",(e,t)=>{$d.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>nh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function hu(e){return new pu({type:"readonly",innerType:e})}var uu=w("ZodCustom",(e,t)=>{Hd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Zp(e,a,n,r)});function mu(e,t={}){return zp(uu,e,t)}function fu(e){return Mp(e)}var bu=G({role:yt(["user","assistant"]),content:_(),timestamp:Me().optional()}),vu=G({sku:_(),name:_(),imageUrl:_().url().optional(),price:_().optional(),originalPrice:_().optional(),url:_().url(),ctaLabel:_().optional()}),yu=G({buttons:ee(G({label:_(),action:G({title:_(),type:_(),payload:Se().optional()})}))}),_u=G({}),xu=G({label:_().optional()}),zr=G({sku:_(),name:_(),price:_(),imageUrl:_().optional(),rating:Me().optional(),reviewCount:Me().optional()}),wu=G({recommended:zr,products:ee(zr),attributes:ee(G({label:_(),values:ee(_())})),highlights:ee(_()),specialCases:ee(_()).optional(),recommendedText:_().optional(),winnerHits:Je(_(),G({positive:ee(_()).optional(),negative:ee(_()).optional()})).optional(),productActions:Je(_(),G({title:_(),type:_(),payload:Se().optional()})).optional()}),ku=G({label:_(),sentiment:yt(["positive","negative","neutral"]).optional()}),Cu=G({product:Je(_(),Se()),role:_().optional(),reason:_().optional(),labels:ee(ku).optional(),expertQualityScore:Me().optional(),reviewHighlight:_().optional(),action:G({title:_(),type:_(),payload:Se().optional()}).optional()}),Su=G({suggestions:ee(Cu)}),Eu=G({title:_().optional(),text:_().optional(),reviewCount:_().optional(),action:G({title:_(),type:_(),payload:Se().optional()})}),Pu=G({entries:ee(G({name:_(),image:_().optional(),description:_().optional(),action:G({title:_(),type:_(),payload:Se().optional()})}))}),Au=G({entries:ee(G({shortName:_(),detailedMessage:_().optional(),whyDifferent:_().optional(),image:_().optional(),action:G({title:_(),type:_(),payload:Se().optional()})}))}),Mr=G({title:_(),type:_(),payload:Se().optional()}),_t=G({name:_().optional(),value:_().optional(),option_value:_().optional(),attribute_value:_().optional(),type:_().optional(),attribute:_().optional(),option_name:_().optional(),attribute_name:_().optional(),variant_name:_().optional(),sku:_().optional(),price:lt([Me(),_()]).optional(),price_discounted:lt([Me(),_()]).optional(),image:_().optional(),imageUrl:_().optional(),image_url:_().optional(),color:_().optional(),colour:_().optional(),color_hex:_().optional(),hex:_().optional(),swatch:_().optional(),swatchColor:_().optional(),in_stock:Ye().optional(),inStock:Ye().optional()}),Tu=G({product:G({sku:_().optional(),name:_().optional(),images:ee(_()).optional(),imageUrl:_().optional(),rating:Me().optional(),reviewCount:Me().optional(),price:_().optional(),originalPrice:_().optional(),discountReason:_().optional(),discount_reason:_().optional(),campaignReason:_().optional(),campaign_reason:_().optional(),originalPriceStyle:yt(["strikethrough","inline"]).optional(),price_original_style:yt(["strikethrough","inline"]).optional(),price_discount_rate:Me().optional(),price_async:Ye().optional(),inStock:Ye().optional(),promotions:ee(_()).optional(),variants:ee(_t).optional(),variantOptions:ee(_t).optional(),variant_options:ee(_t).optional(),productVariants:ee(_t).optional(),product_variants:ee(_t).optional(),url:_().optional(),cartCode:_().optional(),description:_().optional(),description_html:_().optional(),descriptionHtml:_().optional(),facet_hits:Je(_(),Se()).optional(),facetHits:Je(_(),Se()).optional(),features:ee(G({name:_().optional(),key:_().optional(),label:_().optional(),value:lt([_(),Me(),Ye()]).optional()})).optional(),specifications:lt([Je(_(),_()),ee(G({key:_(),value:_()}))]).optional()}).optional(),action:Mr.optional()}),Lu=G({endOfList:Ye().optional()}),Iu=G({review_class:_().optional(),review_text:_().optional(),review_rating:lt([_(),Me()]).optional(),review_tag:_().optional()}),Nu=G({reviews:ee(Iu).optional()}),zu=G({productName:_().optional(),pros:ee(_()).optional(),cons:ee(_()).optional()}),Mu=G({groups:ee(G({groupName:_(),image:_().optional(),products:ee(Je(_(),Se())).optional()})).optional(),filterTags:ee(G({title:_(),action:Mr.optional()})).optional()}),Bu=G({summary:_().optional(),products_discussed:ee(_()).optional(),user_sentiment:_().optional()}),Ru=G({summary:_(),strengths:ee(_()).optional(),focus_points:ee(_()).optional(),celeb_style:_().optional(),celeb_style_reason:_().optional(),next_question:_().optional(),style_images:ee(_()).optional()}),Du=G({processing:Ye().optional(),title:_().optional(),description:_().optional(),upload_label:_().optional(),skip_label:_().optional()}),Ou={components:{MessageBubble:{schema:bu,description:"A single chat message bubble for user or assistant turns."},ProductCard:{schema:vu,description:"A product card rendered inline in the chat stream."},ActionButtons:{schema:yu,description:"A horizontal row of quick-reply action buttons."},TypingIndicator:{schema:_u,description:"An animated indicator shown while the assistant is typing."},Divider:{schema:xu,description:"A horizontal rule with an optional label."},ComparisonTable:{schema:wu,description:"A product comparison table with recommended pick, attribute rows, and highlights."},AITopPicks:{schema:Su,description:"Rich AI-curated product suggestion cards with roles, sentiment labels, scores, and review quotes."},GroundingReviewCard:{schema:Eu,description:"A card showing review grounding data with review count and CTA."},AIGroupingCards:{schema:Pu,description:"Category grouping cards with images and labels for product discovery."},AISuggestedSearchCards:{schema:Au,description:"Suggested search cards with images, descriptions, and differentiation."},ProductDetailsPanel:{schema:Tu,description:"Full product detail view with images, specs, variants, and purchase actions."},ProductGrid:{schema:Lu,description:'A scrollable grid of ProductCard children with optional "more" pagination.'},ReviewHighlights:{schema:Nu,description:"A list of highlighted customer reviews with sentiment and ratings."},ProsAndCons:{schema:zu,description:"A pros and cons list for a product."},CategoriesContainer:{schema:Mu,description:"Tabbed product groups with optional filter tag buttons."},HandoffNotice:{schema:Bu,description:"A notice shown when the conversation is escalated to a human agent."},PhotoAnalysisCard:{schema:Ru,description:"Structured photo analysis card with strengths, focus points, celeb vibe, and follow-up question."},BeautyPhotoStep:{schema:Du,description:"Transient selfie upload prompt for beauty consulting init flow."}}},Fu=new Set(["launchSingleProduct","launchProductList","launchHomepage"]);function Br(e){return e.length>120?!1:/^[a-zA-Z0-9#(),.\s%/\-]+$/.test(e)}function Sa(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function Ea(e){return e?.type==="ProductGrid"&&e.props?.similarsAppend===!0}var Rr=class gt extends Fi{constructor(...t){super(...t),this._shadow=null,this._rootEl=null,this._backdropEl=null,this._launcher=null,this._drawer=null,this._bridge=null,this._drawerVisible=!1,this._pillLauncherApply=null,this._hostScrollLockActive=!1,this._hostOverflowRestore=null,this._hostScrollLockViewport=null,this._hostScrollPinning=!1,this._preventHostDocumentTouchMove=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._preventHostDocumentWheel=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._pinHostViewportScroll=()=>{if(!this._hostScrollLockActive||!this._hostScrollLockViewport||this._hostScrollPinning)return;const a=this._hostScrollLockViewport;window.scrollX===a.x&&window.scrollY===a.y||(this._hostScrollPinning=!0,window.scrollTo(a.x,a.y),this._hostScrollPinning=!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._comparisonSelectionWarning=null,this._comparisonRefreshRafId=null,this._viewedProductSkus=new Set,this._thumbnailEntries=[],this._choicePrompterEl=null,this._openState="full",this._mobileBreakpoint=768,this._isMobileViewport=!1,this._gaPrevMainPaneExpanded=!1,this._pdpLaunched=!1,this._plpLaunched=!1,this._homepageLaunched=!1,this._entryContextPrimed=!1,this._contextPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._i18n=tt,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._localPanelHistory=[],this._currentPanelSource=null,this._session=null,this._presentation=new zn,this._eventCallbacks=new Map,this._lastSentAction=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._modeController=new As}static{this._MAX_COMPARISON_SELECTION=5}static{this._MAX_PANEL_HISTORY=10}get _assistantMode(){return this._modeController.mode}set _assistantMode(t){this._modeController.mode=t}get _uiHints(){return this._modeController.uiHints}set _uiHints(t){this._modeController.uiHints=t}async onInit(t){if(this._i18n=this._resolveI18n(t),this._chatCreatedAt=new Date().toISOString(),t.pillLauncher){const u=Pl(t.pillLauncher);t.launcherImageUrl=u.launcherImageUrl,t.headerAvatarUrl===void 0&&(t.headerAvatarUrl=t.pillLauncher.avatarUrl),this._pillLauncherApply=()=>u.apply(this._shadow??void 0)}this._shadow=this.root.attachShadow({mode:"open"});const a=document.createElement("style");a.textContent=Fl,this._shadow.appendChild(a);const n=this.root,r=(u,v)=>{v&&Br(v)&&n.style.setProperty(u,v)};if(r("--gengage-chat-header-bg",t.headerBg),r("--gengage-chat-header-foreground",t.headerForeground),t.theme)for(const[u,v]of Object.entries(t.theme))u.startsWith("--")&&typeof v=="string"&&r(u,v);this._applyDiscountedPriceColorVar(t.productPriceUi?.discountedPriceColor);const i=document.createElement("div");i.className="gengage-chat-root",i.lang=wt(t.locale),this._rootEl=i,this._shadow.appendChild(i);const o=t.variant??"floating";if(o==="inline"&&i.classList.add("gengage-chat--inline"),o!=="inline"){const u=document.createElement("div");u.className="gengage-chat-backdrop",u.setAttribute("aria-hidden","true"),u.setAttribute("role","button"),u.setAttribute("tabindex","-1"),u.setAttribute("aria-label",this._i18n.closeAriaLabel),u.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),this.close()}),this._backdropEl=u,i.prepend(u)}if(o==="floating"){const u={onClick:()=>this.open(),ariaLabel:this._i18n.openButton};t.launcherImageUrl!==void 0?u.imageUrl=t.launcherImageUrl:t.launcherSvg!==void 0&&(u.svgMarkup=t.launcherSvg),t.hideMobileLauncher!==void 0&&(u.hideMobile=t.hideMobileLauncher),t.mobileBreakpoint!==void 0&&(u.mobileBreakpoint=t.mobileBreakpoint),t.launcherTooltip!==void 0&&(u.tooltip=t.launcherTooltip),this._launcher=al(u),i.appendChild(this._launcher.container)}o==="overlay"&&i.classList.add("gengage-chat--overlay");const s=document.createElement("div");i.appendChild(s),this._drawer=new ks(s,{i18n:this._i18n,onSend:(u,v)=>this._sendMessage(u,v),onClose:()=>this.close(),onAttachment:u=>this._handleAttachment(u),onPanelToggle:()=>{this._drawer?.persistPanelState(t.accountId)},onHostShellSync:()=>{this._applyOpenStateClasses()},onRollback:u=>this._handleRollback(u),onPanelBack:()=>this._navigatePanelBack(),onPanelForward:()=>this._panel?.navigateForward(),onPanelClose:()=>{if(this._isMobileViewport){this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[];return}this._localPanelHistory=[],this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._currentPanelSource=null},headerTitle:t.headerTitle,headerAvatarUrl:t.headerAvatarUrl,launcherImageUrl:t.launcherImageUrl,headerBadge:t.headerBadge,headerCartUrl:t.headerCartUrl,showHeaderFavorites:typeof t.onFavoritesClick=="function"||t.headerFavoritesToggle===!0,onCartClick:()=>{t.headerCartUrl?this._saveSessionAndOpenURL(t.headerCartUrl):t.onCartClick?.()},onFavoritesClick:()=>{if(ui(),typeof t.onFavoritesClick=="function"){t.onFavoritesClick();return}this._openFavoritesPanel()},getMobileState:()=>this._openState??"full",getMobileViewport:()=>this._isMobileViewport,onMobileSnap:u=>{u==="close"?this.close():(this._openState=u,this._applyOpenStateClasses())},onThumbnailClick:u=>this._rollbackToThread(u),onLinkClick:u=>{this._saveSessionAndOpenURL(u)},voiceEnabled:t.voiceEnabled,voiceLang:t.locale?`${t.locale.split("-")[0]??"tr"}-${(t.locale.split("-")[1]??t.locale.split("-")[0]??"TR").toUpperCase()}`:void 0,presentation:{onPinnedToBottomChange:u=>{this._presentation.pinnedToBottom=u},onUserInteractingChange:u=>{this._presentation.userInteracting=u},onFormerMessagesHint:()=>{this._presentation.focusedThreadId&&this._hasMultipleThreadIds()&&this._drawer?.setFormerMessagesButtonVisible(!0)},shouldBlockSoftAutoScroll:()=>this._presentation.shouldBlockStreamAutoScroll(),onReleasePresentationFocus:()=>this._releasePresentationFocus()}}),this._applyUiHints(),this._extendedModeManager=new kl({onChange:u=>this._panel?.notifyExtension(u),productDetailsInPanel:(t.isDemoWebsite??!1)&&(t.productDetailsExtended??!1)}),this._panel=new Cl({drawer:()=>this._drawer,shadow:()=>this._shadow,currentThreadId:()=>this._currentThreadId,bridge:()=>this._bridge,extendedModeManager:()=>this._extendedModeManager,i18n:()=>this._i18n,rollbackToThread:u=>this._rollbackToThread(u)}),o!=="inline"&&this._drawer.getElement().classList.add("gengage-chat-drawer--hidden");const c=this._drawer.restorePanelState(t.accountId),l=t.panelMode??"auto";l==="collapsed"?this._drawer.setPanelCollapsed(!0):l==="expanded"&&this._drawer.setForceExpanded();const g=sessionStorage.getItem("gengage_restore_session_id"),p=sessionStorage.getItem("gengage_restore_sku"),h=!!(g&&p);h&&(sessionStorage.removeItem("gengage_restore_session_id"),sessionStorage.removeItem("gengage_restore_sku"));try{const u=new xl;await u.open(),this._session=new Nn(u),await this._restoreFromIndexedDB(h)}catch{this._session=new Nn(null)}this._registerPublicAPI(),t.mobileInitialState!==void 0&&(this._openState=t.mobileInitialState),this._mobileBreakpoint=t.mobileBreakpoint??768,this._syncViewportState();const d=()=>this._syncViewportState();if(window.addEventListener("resize",d,{passive:!0}),this.addCleanup(()=>window.removeEventListener("resize",d)),window.visualViewport){const u=()=>{if(!this._drawerVisible||!this._isMobileViewport)return;const v=this._drawer?.getElement();if(!v)return;const m=window.innerHeight-(window.visualViewport?.height??window.innerHeight);v.style.setProperty("--gengage-keyboard-offset",`${Math.max(0,m)}px`)};window.visualViewport.addEventListener("resize",u),this.addCleanup(()=>window.visualViewport?.removeEventListener("resize",u))}o==="inline"&&(this._drawerVisible=!0,this.isVisible=!0,this._applyOpenStateClasses(),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60));const b={namespace:"chat",onMessage:u=>this._handleBridgeMessage(u)};t.allowedOrigins!==void 0&&(b.allowedOrigins=t.allowedOrigins),this._bridge=new Hi(b),this._lastSku=this.config.pageContext?.sku,this._lastPageType=this.config.pageContext?.pageType,this._lastSkuListKey=this.config.pageContext?.skuList?.slice(0,48).join(","),this._initComplete=!0;for(const u of this._pendingActions)this._sendAction(u.action,u.options);this._pendingActions=[],this._pillLauncherApply&&o==="floating"&&(await this._pillLauncherApply(),this._pillLauncherApply=null),Te("gengage:chat:ready",{}),ii("chat"),t.onReady?.()}onUpdate(t){if(this.config.pageContext&&t.pageType!==void 0){const{sku:n,skuList:r,...i}=this.config.pageContext,o={...i};o.pageType==="pdp"&&n!==void 0&&(o.sku=n),o.pageType==="plp"&&r!==void 0&&(o.skuList=r),this.config={...this.config,pageContext:o}}let a=!1;if(t.sku!==void 0&&t.sku!==this._lastSku&&(this._lastSku=t.sku,a=!0),t.pageType!==void 0&&t.pageType!==this._lastPageType&&(this._lastPageType=t.pageType,a=!0),t.skuList!==void 0){const n=t.skuList.slice(0,48).join(",");n!==this._lastSkuListKey&&(this._lastSkuListKey=n,a=!0)}a&&this._resetForNewPage()}onShow(){this._showDrawer(),this.emit("open"),Te("gengage:chat:open",{state:this._openState}),oi("chat"),this.config.onOpen?.(),this._showWelcomeIfNeeded(),this._maybePrimeEntryContextOpening(),!this._pdpLaunched&&this.config.pageContext?.pageType==="pdp"&&this.config.pageContext?.sku&&(this._pdpLaunched=!0,this._contextPrimingInFlight=!0,this._sendAction({title:"",type:"launchSingleProduct",payload:{sku:this.config.pageContext.sku,...this._resolveContextualOpeningMessage("product")?{opening_message:this._resolveContextualOpeningMessage("product")}:{},...this._resolveContextualOpeningGuidance("product")?{opening_guidance:this._resolveContextualOpeningGuidance("product")}:{}}},{silent:!0,isContextPrime:!0,preservePills:!0})),!this._plpLaunched&&this.config.pageContext?.pageType==="plp"&&this.config.pageContext.skuList?.length&&(this._plpLaunched=!0,this._contextPrimingInFlight=!0,this._sendAction({title:"",type:"launchProductList",payload:{sku_list:this.config.pageContext.skuList.slice(0,48)}},{silent:!0,isContextPrime:!0,preservePills:!0})),!this._homepageLaunched&&this.config.pageContext?.pageType==="home"&&(this._homepageLaunched=!0,this._contextPrimingInFlight=!0,this._sendAction({title:"",type:"launchHomepage",payload:{}},{silent:!0,isContextPrime:!0,preservePills:!0}))}onHide(){(this.config.variant??"floating")==="floating"&&(this.root.style.display=""),this._hideDrawer(),this.emit("close"),Te("gengage:chat:close",{}),this.config.onClose?.()}onDestroy(){this._releaseHostDocumentScrollLock(),this._abortAllActiveRequests(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._comparisonRefreshRafId!==null&&(cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=null),this._drawer?.destroy(),Ga(),this._drawer=null,this._bridge?.destroy(),this._bridge=null,this._extendedModeManager=null,this._panel?.destroy(),this._panel=null,this._session?.close(),this._session=null,this._localPanelHistory=[],this._currentPanelSource=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,a){a?.sku!==void 0&&this.update({sku:a.sku}),this._pdpLaunched=!0,a?.state!==void 0?this._openState=a.state:this._isMobileViewport&&(this._openState="half"),this.show(),this._drawerVisible&&this._applyOpenStateClasses(),this._sendAction(t)}sendMessage(t){this._sendMessage(t)}sendAction(t,a){this._sendAction(t,a)}close(){this.hide()}saveSession(t,a){sessionStorage.setItem("gengage_restore_session_id",t),sessionStorage.setItem("gengage_restore_sku",a)}get isOpen(){return this._drawerVisible}addCallback(t,a){let n=this._eventCallbacks.get(t);return n||(n=new Set,this._eventCallbacks.set(t,n)),n.add(a),()=>{n.delete(a),n.size===0&&this._eventCallbacks.delete(t)}}_applyDiscountedPriceColorVar(t){const a=this.root;t==="client"?a.style.setProperty("--gengage-discounted-price-color","var(--client-primary)"):a.style.removeProperty("--gengage-discounted-price-color")}_abortAllActiveRequests(){for(const t of this._abortControllers)t.abort();this._abortControllers.clear()}_pruneEmptyStreamingAssistantPlaceholders(){const t=[];let a=!1;for(const n of this._messages){if(n.role==="assistant"&&(n.status==="streaming"||n.status==="done")&&(n.content==null||n.content.length===0)){if(n.threadId){this._threadsWithFirstBot.delete(n.threadId),this._presentation.finalizeAssistantGroup(n.threadId),this._shadow?.querySelectorAll(`[data-thread-id="${_e(n.threadId)}"]:not([data-message-id])`).forEach(i=>i.remove()),this._panel&&(this._panel.threads=this._panel.threads.filter(i=>i!==n.threadId));const r=this._thumbnailEntries.length;this._thumbnailEntries=this._thumbnailEntries.filter(i=>i.threadId!==n.threadId),this._thumbnailEntries.length!==r&&(a=!0)}this._drawer?.removeMessageBubble(n.id),this._panel?.snapshots.delete(n.id),this._panel?.snapshotTypes.delete(n.id);continue}t.push(n)}this._messages.length=0,this._messages.push(...t),a&&this._drawer?.setThumbnails(this._thumbnailEntries)}_resetForNewPage(){this._activeRequestThreadId=null,this._abortAllActiveRequests(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._messages.length=0,this._drawer?.clearMessages(),this._drawer?.clearPanel(),this._currentPanelSource=null,this._panel.snapshots.clear(),this._panel.threads=[],this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._viewedProductSkus.clear(),this._currentThreadId=null,this._lastThreadId=null,this._lastBackendContext=null,this._chatCreatedAt=new Date().toISOString(),this._pdpLaunched=!1,this._plpLaunched=!1,this._homepageLaunched=!1,this._entryContextPrimed=!1,this._contextPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._presentation.reset(),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1),this._modeController.reset()&&(this._drawer?.setInputPlaceholder(this._i18n.inputPlaceholder),this._drawer?.setAttachmentControlsVisible(!0),this._drawer?.setBeautyPhotoStepCard({visible:!1}))}_clearAssistantPanelLikeStreamClearPanel(){this._clearChoicePrompter(),this._drawer?.clearPanel(),this._currentPanelSource=null,this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._panel&&(this._panel.currentType=null,this._panel.updateExtendedMode(""),this._panel.updateTopBar(""))}_flushPresentationScroll(){const t=this._presentation.scrollRequest;if(!t||!this._drawer)return;let a=!1;t.type==="thread"&&t.threadId?(a=this._drawer.scrollThreadIntoView(t.threadId,t.behavior),a||(this._drawer.scrollToBottomPresentation(t.behavior),a=!0)):t.type==="bottom"&&(this._drawer.scrollToBottomPresentation(t.behavior),a=!0),a&&this._presentation.consumeScrollRequest(t.id)}_focusPresentationThread(t,a="smooth",n=!1){this._presentation.requestThreadFocus(t,a),n&&this._drawer?.setPresentationFocus(t),this._drawer?.setFormerMessagesButtonVisible(!1),setTimeout(()=>this._flushPresentationScroll(),40)}_scrollInlineIntoView(t,a){if(a){this._focusPresentationThread(a,"auto");return}t.scrollIntoView({behavior:"auto",block:"start"})}_releasePresentationFocus(){this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1)}_hasMultipleThreadIds(){const t=new Set;for(const a of this._messages)a.threadId&&t.add(a.threadId);return t.size>1}_orderedThreadIds(){const t=[],a=new Set;for(const n of this._messages)n.threadId&&!a.has(n.threadId)&&(a.add(n.threadId),t.push(n.threadId));return t}_maybeAutoAnchorUnreadAssistant(){if(!this._drawer||!this._presentation.shown)return;const t=this._orderedThreadIds();if(t.length===0)return;const a=El(t,this._presentation);if(!a)return;const n=`${a}:assistant`;this._presentation.lastAutoAnchoredGroupId!==n&&(this._presentation.userInteracting&&!this._presentation.pinnedToBottom||this._drawer.scrollThreadIntoView(a,"smooth")&&this._presentation.markGroupAutoAnchored(n))}_handleBridgeMessage(t){switch(t.type){case"openChat":this.open();break;case"closeChat":this.close();break;case"startNewChatWithLauncherAction":{const a=t.payload,n=a?.action,r=Sa(n)?n:Sa(a)?a:null;r&&this._sendAction(r,{silent:!0}),this.open();break}case"startNewChatWithDetailContext":{const a=t.payload;if(a&&typeof a=="object"){this._bridgeContext=a;const n=a.sku;if(n&&this.update({sku:n}),Sa(a.action)){this._pdpLaunched=!0,this.open(),this._sendAction(a.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._presentation.requestScrollToBottom("smooth"),setTimeout(()=>this._flushPresentationScroll(),40);break;case"addToCardHandler":this._bridge?.send("addToCardResult",t.payload);break;case"cartQuantityHandler":{const a=t.payload;a&&"quantity"in a&&typeof a.quantity=="number"&&(this._cartQuantity=a.quantity);break}case"favoritesCountHandler":{const a=t.payload?.count;typeof a=="number"&&a>=0&&this._drawer?.updateFavoritesBadge(a);break}case"minimizeRequestedByUser":this._extendedModeManager?.setHiddenByUser(!0);break;case"bgColorChange":{const a=t.payload?.color;typeof a=="string"&&Br(a)&&this._shadow&&this._shadow.host.style.setProperty("--gengage-chat-bg",a);break}default:break}}_registerPublicAPI(){window.gengage||(window.gengage={}),window.gengage.chat={open:t=>this.open(t),openWithAction:(t,a)=>this.openWithAction(t,a),sendMessage:t=>this.sendMessage(t),sendAction:(t,a)=>this.sendAction(t,a),close:()=>this.close(),saveSession:(t,a)=>this.saveSession(t,a),get isOpen(){return!1},on:(t,a)=>this.on(t,a),trackCheckout:(t,a)=>this.trackCheckout(t,a),flushMeteringSummary:t=>this.flushMeteringSummary(t),addCallback:(t,a)=>this.addCallback(t,a)},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),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60)}_showWelcomeIfNeeded(){if(this._messages.length!==0)return;const t=this._resolveOpeningContextKey(),a=this._resolveContextualOpeningActions(t);if(a.length>0&&this._drawer?.setPills(a.map(i=>({label:i.title,onAction:()=>this._sendAction(this._resolveContextualOpeningAction(i,t))}))),this._hasDedicatedContextLaunch()||this._shouldPrimeContextualOpening())return;const n=this._resolveContextualOpeningMessage(t);if(!n)return;const r={id:Ra(),role:"assistant",content:n,timestamp:Date.now(),status:"done"};this._messages.push(r),this._drawer?.addMessage(r)}_resolveOpeningContextKey(){switch(this.config.pageContext?.pageType){case"home":return"home";case"search":case"plp":return"listing";case"pdp":return"product";default:return"default"}}_resolveContextualOpeningMessage(t=this._resolveOpeningContextKey()){return this.config.openingMessagesByContext?.[t]??(t!=="default"?this.config.openingMessagesByContext?.default:void 0)??this.config.welcomeMessage}_resolveContextualOpeningGuidance(t=this._resolveOpeningContextKey()){return this.config.openingGuidanceByContext?.[t]??(t!=="default"?this.config.openingGuidanceByContext?.default:void 0)}_resolveContextualOpeningActions(t=this._resolveOpeningContextKey()){const a=this.config.welcomeActionsByContext?.[t]??(t!=="default"?this.config.welcomeActionsByContext?.default:void 0);return a?.length?a.filter(n=>typeof n?.title=="string"&&n.title.trim().length>0):(this.config.welcomeActions??[]).filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>({title:n}))}_resolveContextualOpeningAction(t,a=this._resolveOpeningContextKey()){const n=t.title.trim(),r=this.config.pageContext?.sku??this._readContextStringField("sku"),i=this._readContextStringListField("visible_skus")??[];return t.icon==="review"&&r?{title:n,type:"reviewSummary",payload:{sku:r}}:t.icon==="similar"&&r?{title:n,type:"findSimilar",payload:{sku:r}}:t.icon==="compare"&&a==="listing"&&i.length>=2?{title:n,type:"getComparisonTable",payload:{sku_list:i.slice(0,2)}}:{title:n,type:"user_message",payload:n}}_readContextStringField(t){const a=this.config.pageContext,n=a?.extra&&typeof a.extra=="object"&&!Array.isArray(a.extra)?a.extra:void 0,r=t.replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),i=a?.[t]??n?.[t]??a?.[r]??n?.[r];return typeof i=="string"&&i.trim().length>0?i.trim():void 0}_readContextStringListField(t){const a=this.config.pageContext,n=a?.extra&&typeof a.extra=="object"&&!Array.isArray(a.extra)?a.extra:void 0,r=t.replace(/_([a-z])/g,(s,c)=>c.toUpperCase()),i=a?.[t]??n?.[t]??a?.[r]??n?.[r];if(!Array.isArray(i))return;const o=i.filter(s=>typeof s=="string"&&s.trim().length>0);return o.length>0?o:void 0}_buildEntryOpeningPageDetails(){const t={};t.url=this.config.pageContext?.url??window.location.href;const a=this._readContextStringField("page_title");a&&(t.page_title=a);const n=this._readContextStringField("page_description");n&&(t.page_description=n);const r=this._readContextStringField("search_query");r&&(t.search_query=r);const i=this._readContextStringListField("visible_skus");i?.length&&(t.visible_skus=i);const o=this._readContextStringListField("popular_searches");o?.length&&(t.popular_searches=o);const s=this.config.pageContext?.categoryTree??this._readContextStringListField("category_path");return s?.length&&(t.category_path=s),Object.keys(t).length>0?t:void 0}_hasDedicatedContextLaunch(){const t=this.config.pageContext;return t?!!(t.pageType==="pdp"&&t.sku||t.pageType==="plp"&&t.skuList?.length||t.pageType==="home"):!1}_shouldPrimeContextualOpening(){return this._messages.length!==0||this._entryContextPrimed||this._contextPrimingInFlight||this._hasDedicatedContextLaunch()?!1:!!(this.config.openingMessagesByContext||this.config.openingGuidanceByContext||this.config.welcomeActionsByContext)}_maybePrimeEntryContextOpening(){const t=this._resolveOpeningContextKey();if(!this._shouldPrimeContextualOpening())return;this._entryContextPrimed=!0;const a={text:"",is_entry_context_opening:1,opening_context_key:t},n=this._buildEntryOpeningPageDetails();n&&(a.page_details=n);const r=this._resolveContextualOpeningMessage(t);r&&(a.opening_message=r);const i=this._resolveContextualOpeningGuidance(t);i&&(a.opening_guidance=i),this._sendAction({title:"",type:"user_message",payload:a},{silent:!0,preservePills:!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),this._presentation.setShown(!1),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!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()}}_isMaximizedForHostChrome(){if(!this._drawerVisible)return!1;const t=this.config.variant??"floating";return t==="inline"?!1:t==="overlay"?!0:!(!(this._drawer?.isPanelVisible()??!1)||!this._isMobileViewport&&(this._drawer?.isPanelCollapsed()??!1))}_shouldLockHostDocumentScroll(){if(!this._drawerVisible)return!1;const t=this.config.variant??"floating";return t==="inline"?!1:t==="overlay"||this._isMobileViewport?!0:this._drawer?.isPanelVisible()??!1}_applyOpenStateClasses(){if(!this._rootEl)return;const t=this._drawerVisible&&this._isMobileViewport&&this._openState==="half",a=this._drawerVisible&&this._isMobileViewport&&this._openState==="full",n=this._isMaximizedForHostChrome();if(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",a),this._rootEl.classList.toggle("gengage-chat-root--maximized-host-chrome",n),this._backdropEl){const r=n&&(this.config.variant??"floating")!=="inline";this._backdropEl.setAttribute("aria-hidden",r?"false":"true")}this._syncHostDocumentScrollLock(),this._maybeTrackChatbotMainPaneGa()}_mainPaneExpandedForAnalytics(){const t=this._drawer;return t?.isPanelVisible()?this._isMobileViewport?!0:!t.isPanelCollapsed():!1}_maybeTrackChatbotMainPaneGa(){const t=this._mainPaneExpandedForAnalytics();t&&!this._gaPrevMainPaneExpanded&&bi(),this._gaPrevMainPaneExpanded=t}_syncHostDocumentScrollLock(){if(!(typeof document>"u")){if((this.config.variant??"floating")==="inline"){this._releaseHostDocumentScrollLock();return}this._shouldLockHostDocumentScroll()?this._applyHostDocumentScrollLock():this._releaseHostDocumentScrollLock()}}_hostScrollEventShouldReachChatScroller(t){try{const a=t.composedPath();if(a.length===0)return!0;if(!a.includes(this.root))return!1;for(const n of a){if(n===this.root)break;if(!(n instanceof HTMLElement))continue;if(this._backdropEl&&(n===this._backdropEl||this._backdropEl.contains(n)))return!1;const r=window.getComputedStyle(n),i=(r.overflowY==="auto"||r.overflowY==="scroll")&&n.scrollHeight>n.clientHeight+1,o=(r.overflowX==="auto"||r.overflowX==="scroll")&&n.scrollWidth>n.clientWidth+1;if(i||o)return!0}return!1}catch{return!1}}_applyHostDocumentScrollLock(){if(!(typeof document>"u"||typeof window>"u")){if(!this._hostOverflowRestore){const t=document.documentElement,a=document.body;this._hostOverflowRestore={htmlOverflow:t.style.overflow,bodyOverflow:a?.style.overflow??"",htmlOverscroll:t.style.overscrollBehavior,bodyOverscroll:a?.style.overscrollBehavior??""},t.style.overflow="hidden",t.style.overscrollBehavior="none",a&&(a.style.overflow="hidden",a.style.overscrollBehavior="none"),this._hostScrollLockViewport={x:window.scrollX,y:window.scrollY}}this._hostScrollLockActive||(window.addEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0,passive:!1}),window.addEventListener("wheel",this._preventHostDocumentWheel,{capture:!0,passive:!1}),document.addEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0,passive:!1}),document.addEventListener("wheel",this._preventHostDocumentWheel,{capture:!0,passive:!1}),window.addEventListener("scroll",this._pinHostViewportScroll,{capture:!0,passive:!0}),this._hostScrollLockActive=!0)}}_releaseHostDocumentScrollLock(){if(!(typeof document>"u")&&(typeof window<"u"&&(window.removeEventListener("scroll",this._pinHostViewportScroll,{capture:!0}),window.removeEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0}),window.removeEventListener("wheel",this._preventHostDocumentWheel,{capture:!0})),this._hostScrollLockActive&&(document.removeEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0}),document.removeEventListener("wheel",this._preventHostDocumentWheel,{capture:!0}),this._hostScrollLockActive=!1),this._hostScrollLockViewport=null,this._hostScrollPinning=!1,this._hostOverflowRestore)){const t=document.documentElement,a=document.body;t.style.overflow=this._hostOverflowRestore.htmlOverflow,t.style.overscrollBehavior=this._hostOverflowRestore.htmlOverscroll,a&&(a.style.overflow=this._hostOverflowRestore.bodyOverflow,a.style.overscrollBehavior=this._hostOverflowRestore.bodyOverscroll),this._hostOverflowRestore=null}}_handleAttachment(t){const a=Ki(t);if(!a.ok){Te("gengage:global:error",{message:a.reason==="invalid_type"?this._i18n.invalidFileType:this._i18n.fileTooLarge,source:"chat"});return}this._drawer?.stageAttachment(t)}_sendMessage(t,a){this._contextPrimingInFlight&&(this._abortAllActiveRequests(),this._contextPrimingInFlight=!1,this._queuedUserMessages=[]),(!this._messages.some(r=>r.role==="user")||this._drawer?.isKvkkBannerVisible())&&(da(this.config.accountId),this._drawer?.hideKvkkBanner()),yi(),this._messages.some(r=>r.role==="user")||_i(),De("chat","sendMessage",{mode:this._assistantMode,hasAttachment:a!==void 0,textLength:t.length});const n=a!==void 0?{title:t,type:this._modeController.resolveAttachmentActionType(),payload:t?{text:t}:{}}:{title:t,type:"user_message",payload:t};a!==void 0?this._sendAction(n,{attachment:a}):this._sendAction(n)}_flushQueuedUserMessages(){if(this._contextPrimingInFlight||this._queuedUserMessages.length===0)return;const t=[...this._queuedUserMessages];this._queuedUserMessages=[];for(const a of t)this._sendMessage(a.text,a.attachment)}_applyUiHints(){this._modeController.applyUiHints(this._drawer,this._i18n.inputPlaceholder,()=>{this._clearChoicePrompter()})}_handleRedirectMetadata(t){this._modeController.handleRedirect(t)}_sendAction(t,a){if(this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._lastSentAction={action:t,options:a},!this._initComplete){this._pendingActions.length<10&&this._pendingActions.push({action:t,options:a});return}if(this._clearChoicePrompter(),a?.preservePanel||fl(),!a?.preservePanel&&this._comparisonSelectMode&&t.type!=="getComparisonTable"&&(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[]),a?.preservePanel||(this._localPanelHistory=[]),this._currentThreadId&&this._lastThreadId&&this._lastThreadId>this._currentThreadId){const y=this._currentThreadId,E=this._messages.filter(S=>S.threadId!==void 0&&S.threadId>y);this._messages=this._messages.filter(S=>!S.threadId||S.threadId<=y);for(const S of E)this._shadow?.querySelector(`[data-message-id="${_e(S.id)}"]`)?.remove(),this._panel.snapshots.delete(S.id),this._panel.snapshotTypes.delete(S.id);this._shadow?.querySelectorAll("[data-thread-id]")?.forEach(S=>{S instanceof HTMLElement&&S.dataset.threadId&&S.dataset.threadId>y&&S.remove()})}a?.preservePills||this._drawer?.setPills([]),this._drawer?.clearInputAreaChips(),this._bridge?.send("isResponding",!0);const n=Ra();this._currentThreadId=n,this._lastThreadId=n,this._panel&&!Fu.has(t.type)&&(this._panel.lastActionType=t.type);const r=a?.preservePanel===!0,i=a?.silent===!0&&a?.isContextPrime===!0,o=i&&t.type==="launchSingleProduct";if(r||(this._activeRequestThreadId=n),!a?.silent&&!r&&this._drawer?.setPresentationFocus(n),!a?.silent){const y=typeof t.payload=="string"?t.payload:typeof t.payload?.text=="string"?t.payload.text:t.title,E=this._messages.length>0?this._messages[this._messages.length-1]:void 0;if(!(E!==void 0&&E.role==="user"&&E.content===y)){const S=this._createMessage("user",y);S.threadId=n,a?.attachment!==void 0&&(S.attachment=a.attachment),this._drawer?.addMessage(S),a?.attachment!==void 0&&this._modeController.isBeautyConsulting&&this._drawer?.setBeautyPhotoStepCard({visible:!1}),this._messages.push(S)}}if(!a?.silent&&this._assistantMode==="shopping"&&this._hasUnavailableProductContext()&&(t.type==="user_message"||t.type==="inputText")){const y=this._i18n.productNotFoundMessage,E=this._createMessage("assistant",y);E.threadId=n,E.status="done",this._messages.push(E),this._ensureAssistantMessageRendered(E),this._drawer?.updateBotMessage(E.id,y),this._drawer?.setPresentationFocus(n),this._bridge?.send("isResponding",!1),this.emit("message",E),this._persistToIndexedDB().catch(()=>{});return}let s=this._currentPanelSource,c=!1;const l=t.type==="user_message"||t.type==="inputText",g=()=>{c||a?.preservePanel||(s=this._currentPanelSource,c=!0)},p=()=>{if(this._drawer?.isPanelLoading()){if(!l&&s){const y=this._buildRenderContext(),E=this._renderPanelFromSource(s,y);this._drawer.setPanelContent(E),this._drawer.setDividerPreviewEnabled(this._shouldUseDividerPreviewForSource(s)),this._currentPanelSource=s}else this._drawer.clearPanel(),this._currentPanelSource=null;s=null}};t.type==="getComparisonTable"&&(this._drawer?.showPanelLoading("comparisonTable"),this._panel?.updateTopBarForLoading("comparisonTable")),!a?.silent&&!r&&this._pruneEmptyStreamingAssistantPlaceholders(),this._drawer?.showTypingIndicator();let h="";const d=this._createMessage("assistant","");d.threadId=n,d.status="streaming",a?.silent&&(d.silent=!0),this._messages.push(d),this._presentation.registerAssistantActivity(n),this._focusPresentationThread(n,"smooth",a?.silent||r),a?.preservePanel||(this._contextPrimingInFlight&&!i&&(this._contextPrimingInFlight=!1,this._queuedUserMessages=[]),this._abortAllActiveRequests());const b={middlewareUrl:this.config.middlewareUrl,...this.config.accountId?{accountId:this.config.accountId}:{}};a?.attachment!==void 0&&(b.attachment=a.attachment);const u=this._getVisibleMessages().filter(y=>y!==d&&(y.content||y.role==="assistant")).slice(-50).map(y=>({role:y.role==="user"?"user":"model",content:y.content??""})),v={outputLanguage:Ol(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:Bn(this.config.accountId),voiceEnabled:this.config.voiceEnabled??!1,threadId:n,isControlGroup:this.config.session?.abTestVariant==="control",isMobile:this._isMobileViewport};this._modeController.isShopping||(v.assistantMode=this._modeController.mode),this.config.session?.viewId!==void 0&&(v.viewId=this.config.session.viewId);const m=Wo(t,{pageContext:this.config.pageContext,backendContext:this._lastBackendContext,isMobile:this._isMobileViewport}),P={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",type:m.type,locale:wt(this.config.locale),meta:v,context:{...this._lastBackendContext??{},messages:u,session_id:this.config.session?.sessionId??""}};this.config.session?.userId!==void 0&&(P.user_id=this.config.session.userId),this.config.session?.viewId!==void 0&&(P.view_id=this.config.session.viewId),m.payload!==void 0&&(P.payload=m.payload),this.config.pageContext?.sku!==void 0&&(P.sku=this.config.pageContext.sku),this.config.pageContext?.pageType!==void 0&&(P.page_type=this.config.pageContext.pageType);const A=crypto.randomUUID(),k=Date.now();let x=0,N=!1,T=!1,I=!1,$=!1,ae=!1;const oe=Ts();let ve=null,O=null;const f=()=>{if(this._drawer&&!$){if(!I){this._drawer.setPanelAiZoneState("hidden");return}ae?this._drawer.setPanelAiZoneState("hidden"):this._drawer.setPanelAiZoneState("analyzing",{analyzingLabel:this._i18n.aiAnalysisAnalyzingLabel})}},L=y=>{if(!ve||!this._drawer)return;const E=this._buildRenderContext();E.isStreaming=y;const S=this._renderUISpec(ve,E);$=!0,this._drawer.setPanelAiZoneState("results",{resultEl:S}),ve=null},D=(y,E,S)=>{if(y==="ProductGrid"||y==="CategoriesContainer"){I=!0,L(S),f();return}E!=="appendSimilars"&&E!=="append"&&(I=!1,$=!1,ve=null,this._drawer?.setPanelAiZoneState("hidden"))},B=y=>(y==="ProductGrid"||y==="CategoriesContainer")&&(I||$||ve!==null),j=(y,E,S)=>{if(!this._drawer||!this._panel)return;const z=y.elements[y.root];if(S==="ProductGrid"&&z){const M=oa(z);if(M.isConsulting){const R=this._drawer.getPanelContentElement();if(R&&el(R,M,E)){this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._drawer.setComparisonDockContent(null),this._currentPanelSource={kind:"spec",spec:y},this._panel.currentType=S,this._drawer.resyncPanelTopBarFromCurrentContent();return}}}this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._drawer.setComparisonDockContent(null),this._drawer.setPanelContent(this._renderUISpec(y,E),{preserveAiZone:B(S)}),this._currentPanelSource={kind:"spec",spec:y},this._panel.currentType=S},Z=(y,E,S,z)=>{if(!this._panel)return;this._drawer?.setDividerPreviewEnabled((this._panel.currentType??y)==="ProductGrid"),y==="ProductDetailsPanel"&&t.type==="launchSingleProduct"&&this._clearUnavailableProductContext(),d.threadId&&!this._panel.threads.includes(d.threadId)&&this._panel.threads.push(d.threadId);const M=this._panel.currentType??y,R=E?.props?.panelTitle;this._panel.updateTopBar(M,R),this._panel.updateExtendedMode(y),this._isMobileViewport&&o&&this._drawer?.hideMobilePanel(),D(y,S,z)};this.track($r(this.analyticsContext(),{endpoint:"process_action",request_id:A,widget:"chat"}));let q=null;if(q=Jo(P,{onTextChunk:(y,E,S)=>{if(!r&&n!==this._activeRequestThreadId||(h+=y,this._drawer?.removeTypingIndicator(),S?.skuToProductItem&&(this._skuToProductItem={...this._skuToProductItem,...S.skuToProductItem}),S?.conversationMode&&(this._conversationMode=S.conversationMode),S?.renderHint&&(d.renderHint=S.renderHint),this.track(Hr(this.analyticsContext(),{request_id:A,chunk_index:x++,widget:"chat"})),!this._drawer))return;let z=h;const M=S?.kvkk===!0||o&&ga(z);if(E&&M){const H=this.config.accountId;if(!Bn(H)){const ne=Rl(z);ne?this._drawer?.showKvkkBanner(ne,()=>{this._drawer?.hideKvkkBanner(),da(H)}):da(H)}z=Bl(z)}const R=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(R?R.innerHTML=Ae(z):(d.content=z,d.role==="assistant"&&d.threadId&&!this._threadsWithFirstBot.has(d.threadId)&&(this._threadsWithFirstBot.add(d.threadId),this._drawer.markFirstBotMessage(d.id)),this._drawer.addMessage(d)),E)if(d.content=z,d.status="done",La(),Is(d))this._drawer?.updateBotMessage(d.id,z,"photo_analysis",d.photoAnalysis),d.threadId&&this._focusPresentationThread(d.threadId,"auto");else{const H=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(H){this._activeTypewriter?.cancel();const ne=S?.productMentions;this._activeTypewriter=ll({container:H,html:Ae(z),onTick:()=>this._drawer?.scrollToBottomIfNeeded(),onComplete:()=>{this._activeTypewriter=null,ne&&ne.length>0&&H&&gl({container:H,mentions:ne,onProductClick:te=>{this._sendAction({title:ne.find(U=>U.sku===te)?.short_name??te,type:"launchSingleProduct",payload:{sku:te}})}})}})}}},onUISpec:(y,E,S,z)=>{if(!r&&n!==this._activeRequestThreadId||E!=="chat")return;z&&(this._clearAssistantPanelLikeStreamClearPanel(),N=!1,O=null);const M=y.elements[y.root],R=M?.type??"unknown";if(Ls(R,M?.props??{},oe,{drawer:this._drawer,ensureRendered:()=>this._ensureAssistantMessageRendered(d),cancelTypewriter:()=>{this._activeTypewriter?.cancel(),this._activeTypewriter=null},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:ae},d)){R==="PhotoAnalysisCard"&&d.threadId&&this._focusPresentationThread(d.threadId,"auto");return}const H=Ea(M),ne=this.config.productDetailsExtended!==!0&&(R==="ProductDetailsPanel"||H);ne&&!z&&(this._clearAssistantPanelLikeStreamClearPanel(),N=!1);const te=R==="ProductDetailsPanel"&&S!=="panel"?"panel":S;this.track(Ur(this.analyticsContext(),{request_id:A,chunk_index:x,component_type:R,widget:"chat"}));const U=this._buildRenderContext();if(U.isStreaming=!0,R==="ComparisonTable"){const V=M?.props?.products;pi(Array.isArray(V)?V.length:0)}if(R==="ProductGrid"){const V=M?.children?.length??0;mi(void 0,V)}const ce=te==="panel"&&this._panel?this._panel.toPanelSpec(y):y;if(te==="panel"&&this._panel&&!ne&&R==="ProductGrid"&&M){const V=oa(M);if(V.isConsulting&&!Qc(V)){O=y;return}V.isConsulting&&(O=null)}if(te==="panel"&&this._panel&&!ne){const V=!T;T=!0;const Y=M?.props?.replacePanel===!0?"replace":Sl({componentType:R,similarsAppend:M?.props?.similarsAppend===!0,currentPanelType:this._panel.currentType,hasPanelContent:this._drawer?.hasPanelContent()??!1,isPanelLoading:this._drawer?.isPanelLoading()??!1,isFirstPanelContentInStream:V});U.panelProductListHeading=void 0,R==="ProductGrid"&&(Y==="appendSimilars"?U.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products":this._applyPanelListHeadingToContext(U,{kind:"spec",spec:ce})),Y==="appendSimilars"?this._appendSimilarsToPanel(ce,U):Y==="append"?(this._drawer?.appendPanelContent(this._renderUISpec(ce,U)),this._comparisonSelectMode&&this._refreshComparisonUI()):j(ce,U,R),Z(R,M,Y,!0)}if(R==="ProductDetailsPanel"&&te==="panel"&&(!d.silent||o)){const V=M?.props?.product;if(V){const Y={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:V}}}},me=this._shadow?.querySelector(".gengage-chat-messages");if(me){const J=this._renderUISpec(Y,U);d.threadId&&(J.dataset.threadId=d.threadId);const ie=this._shadow?.querySelector(`[data-message-id="${d.id}"]`);ie&&ie.parentNode===me?ie.after(J):me.appendChild(J),this._scrollInlineIntoView(J,d.threadId),this._drawer?.refreshPresentationCollapsed(),T=!0}}}const Q=R==="AITopPicks"||R==="AIGroupingCards",$e=R==="ActionButtons"?M?.props?.buttons:void 0,xt=R==="ActionButtons"&&this._modeController.mode!=="shopping"&&Array.isArray($e)&&$e.length>0&&$e.every(V=>V.action?.type==="inputText");let C=!1,K=!1;if(ne&&H&&(U.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products"),Q&&(!d.silent||i))if(I){const V=this._renderUISpec(y,U);$=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:V}),C=!0,ve=null}else ve=y,K=!0;const pe=i&&(R==="GroundingReviewCard"||Q);if(!Q&&(!d.silent||pe)&&(te!=="panel"||R==="ProductCard"||ne&&R==="ProductGrid"&&!H)&&(R!=="ActionButtons"||xt)&&!C&&!(K&&Q)){const V=this._shadow?.querySelector(".gengage-chat-messages");if(V){const Y=this._renderUISpec(y,U);d.threadId&&(Y.dataset.threadId=d.threadId),V.appendChild(Y),this._scrollInlineIntoView(Y,d.threadId),this._drawer?.refreshPresentationCollapsed(),ne&&R==="ProductGrid"&&(T=!0)}}if((R==="ProductGrid"||R==="ProductCard")&&d.threadId){const V=M?.children??[],Y=R==="ProductGrid"?V.map(me=>y.elements[me]?.props?.product).filter(Boolean):[M?.props?.product].filter(Boolean);for(const me of Y){const J=me.sku,ie=me.imageUrl;J&&ie&&this._thumbnailEntries.push({sku:J,imageUrl:ie,threadId:d.threadId}),J&&this._viewedProductSkus.add(J)}this._drawer?.setThumbnails(this._thumbnailEntries)}if(R==="ProductGrid"||R==="ProductDetailsPanel"){const V=(R==="ProductGrid"?(M?.children??[]).map(Y=>y.elements[Y]?.props?.product).filter(Boolean):[M?.props?.product??M?.props].filter(Boolean)).map(Y=>Y.imageUrl).filter(Y=>typeof Y=="string").slice(0,5);V.length>0&&this._bridge?.send("previewImages",{images:V})}const ue=M?.children?.length??0;if(R==="ProductGrid"&&te==="panel"&&!ne&&ue>1&&!this._modeController.isChoicePrompterHidden&&!this._comparisonSelectMode&&!bl(this._currentThreadId??"")&&(this._clearChoicePrompter(),this._choicePrompterEl=ml({heading:this._i18n.choicePrompterHeading,suggestion:this._i18n.choicePrompterSuggestion,ctaLabel:this._i18n.choicePrompterCta,threadId:this._currentThreadId??"",dismissAriaLabel:this._i18n.dismissAriaLabel,onCtaClick:()=>{this._comparisonSelectMode=!0,this._choicePrompterEl=null,this._refreshComparisonUI()},onDismiss:()=>{this._choicePrompterEl=null}}),this._mountChoicePrompter()&&this._isMobileViewport&&window.visualViewport)){const V=this._choicePrompterEl,Y=()=>{window.visualViewport.height/window.innerHeight<.75&&(V.remove(),this._choicePrompterEl===V&&(this._choicePrompterEl=null),window.visualViewport.removeEventListener("resize",Y))};window.visualViewport.addEventListener("resize",Y)}if(R==="ActionButtons"){const V=M?.props?.buttons;if(V&&V.length>0&&!xt){const Y=[],me=[];for(const J of V)if(hl(J)){const ie={label:J.label,action:J.action};J.icon&&(ie.icon=J.icon),Y.push(ie)}else me.push(J);Y.length>0&&this._drawer?.setInputAreaChips(Y.map(J=>({label:J.label,onAction:()=>this._sendAction(J.action),...J.icon?{icon:J.icon}:{}}))),me.length>0&&this._drawer?.setPills(me.map(J=>{const ie={label:J.label,onAction:()=>this._sendAction(J.action)};return J.icon&&(ie.icon=J.icon),J.image&&(ie.image=J.image),J.description&&(ie.description=J.description),ie}))}}f(),d.uiSpec=y},onAction:y=>{if(!(!r&&n!==this._activeRequestThreadId)&&y.type==="action"){const E={};this.config.actionHandling?.unknownActionPolicy!==void 0&&(E.unknownActionPolicy=this.config.actionHandling.unknownActionPolicy),this.config.actionHandling?.allowScriptCall!==void 0&&(E.allowScriptCall=this.config.actionHandling.allowScriptCall),qi(y,{openChat:()=>this.open(),navigate:S=>{ye(S.url)&&(this._bridge?.send("navigate",S),S.newTab?window.open(S.url,"_blank","noopener,noreferrer"):window.location.href=S.url)},saveSession:S=>this.saveSession(S.sessionId,S.sku),addToCart:S=>{Te("gengage:similar:add-to-cart",S)},scriptCall:S=>{Te("gengage:chat:script-call",S),this.config.onScriptCall?.(S)}},E)}},onMetadata:y=>{if(!(!r&&n!==this._activeRequestThreadId)&&y.type==="metadata"&&y.meta){if(y.meta.panel!==void 0||y.meta.messages!==void 0||y.meta.message_id!==void 0){this._lastBackendContext=y.meta;const S=Yt(y.meta.panel);S&&(this._modeController.updateFromContext(S),this._applyUiHints())}if(y.meta.panelLoading){const S=typeof y.meta.panelPendingType=="string"?y.meta.panelPendingType:void 0;this.config.productDetailsExtended!==!0&&(S==="productDetails"||S==="productDetailsSimilars")||(N=!0,T=!1,g(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(S),S&&this._panel?.updateTopBarForLoading(S))}if(y.meta.voice){const S=new CustomEvent("gengage:chat:voice",{detail:{payload:y.meta.voice},bubbles:!1,cancelable:!0}),z=window.dispatchEvent(S);if(xi(),z){const M=y.meta.voice;M.audio_base64&&(this._activeTtsHandle?.stop(),this._activeTtsHandle=rl(M.audio_base64,M.content_type??"audio/ogg"))}}if((y.meta.redirectTarget||y.meta.redirect)&&(Te("gengage:chat:redirect",{target:y.meta.redirectTarget??null,payload:y.meta.redirect??null}),De("redirect","redirect dispatched",{target:y.meta.redirectTarget??null}),this._handleRedirectMetadata(y.meta.redirect)),y.meta.analyzeAnimation&&this.config.productDetailsExtended===!0&&(N=!0,T=!1,g(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(),this._panel?.updateTopBarForLoading("productDetails")),y.meta.loading){const S=Array.isArray(y.meta.thinkingMessages)?y.meta.thinkingMessages.filter(M=>typeof M=="string"):[],z=typeof y.meta.loadingText=="string"?y.meta.loadingText:void 0;if(S.length>0){const M=z&&this._modeController.shouldCondenseThinking()?[...S.slice(0,2),z]:S;this._drawer?.setThinkingSteps(M)}typeof z=="string"&&z.length>0&&(this._drawer?.addThinkingStep(z),this._bridge?.send("loadingMessage",{text:z}))}y.meta.visitorDataResponse&&this._bridge?.send("engagingMessage",y.meta.visitorDataResponse),y.meta.formType&&this._bridge?.send("glovOtokoc",{type:y.meta.formType,data:y.meta.formPayload}),y.meta.launcherContent&&this._bridge?.send("launcherContent",y.meta.launcherContent),Te("gengage:chat:metadata",{payload:y.meta});const E=y.meta;typeof E.prompt_tokens=="number"&&typeof E.completion_tokens=="number"&&this.track(qr(this.analyticsContext(),{model:y.model??"unknown",prompt_tokens:E.prompt_tokens,completion_tokens:E.completion_tokens,total_tokens:E.total_tokens??E.prompt_tokens+E.completion_tokens}))}},onError:y=>{if(q&&this._abortControllers.delete(q),!r&&n!==this._activeRequestThreadId)return;ae=!0,this._activeTypewriter?.cancel(),this._activeTypewriter=null,f(),ve=null,O=null,this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),this._drawer?.clearInputAreaChips(),zs(oe,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const E=T;N&&!T&&p(),N=!1,T=!1;const S=d.content!=null&&d.content.length>0||h.length>0||E,z=d.silent||S,M=typeof navigator<"u"&&navigator.onLine===!1&&Ba(y),R=()=>{this._shadow?.querySelector(`[data-message-id="${_e(d.id)}"]`)?.remove();const te=this._messages.indexOf(d);te>=0&&this._messages.splice(te,1)};let H=!1;const ne=()=>{if(M)return;this.emit("error",y);const te=y.message;te===this._lastErrorMessage?this._consecutiveErrorCount++:(this._consecutiveErrorCount=1,this._lastErrorMessage=te);const U=y.message.trim(),ce=U.length>0?U:this._i18n.errorMessage,Q={onRetry:()=>{this._lastSentAction&&this._sendAction(this._lastSentAction.action,this._lastSentAction.options)},onNewQuestion:()=>{this._drawer?.focusInput()}};if(this._consecutiveErrorCount>=2){R(),H=!0,this._drawer?.showErrorWithRecovery(this._i18n.accountInactiveMessage,Q);return}if(Nl(y,ce)){R(),H=!0,this._drawer?.showErrorWithRecovery(ce,Q);return}d.content=ce,d.status="done";const $e=Ae(ce.replace(/\r\n/g,`
176
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const s=o[1];if(t===o[0]){i(o);continue}if(e.external){const c=e.external.registry.get(o[0])?.id;if(t!==o[0]&&c){i(o);continue}}if(e.metadataRegistry.get(o[0])?.id){i(o);continue}if(s.cycle){i(o);continue}if(s.count>1&&e.reused==="ref"){i(o);continue}}}function xr(e,t){const a=e.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=o=>{const s=e.seen.get(o);if(s.ref===null)return;const c=s.def??s.schema,l={...c},g=s.ref;if(s.ref=null,g){n(g);const h=e.seen.get(g),d=h.schema;if(d.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(d)):Object.assign(c,d),Object.assign(c,l),o._zod.parent===g)for(const b in c)b==="$ref"||b==="allOf"||b in l||delete c[b];if(d.$ref&&h.def)for(const b in c)b==="$ref"||b==="allOf"||b in h.def&&JSON.stringify(c[b])===JSON.stringify(h.def[b])&&delete c[b]}const p=o._zod.parent;if(p&&p!==g){n(p);const h=e.seen.get(p);if(h?.schema.$ref&&(c.$ref=h.schema.$ref,h.def))for(const d in c)d==="$ref"||d==="allOf"||d in h.def&&JSON.stringify(c[d])===JSON.stringify(h.def[d])&&delete c[d]}e.override({zodSchema:o,jsonSchema:c,path:s.path??[]})};for(const o of[...e.seen.entries()].reverse())n(o[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const o=e.external.registry.get(t)?.id;if(!o)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(o)}Object.assign(r,a.def??a.schema);const i=e.external?.defs??{};for(const o of e.seen.entries()){const s=o[1];s.def&&s.defId&&(i[s.defId]=s.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?r.$defs=i:r.definitions=i);try{const o=JSON.parse(JSON.stringify(r));return Object.defineProperty(o,"~standard",{value:{...t["~standard"],jsonSchema:{input:jt(t,"input",e.processors),output:jt(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function xe(e,t){const a=t??{seen:new Set};if(a.seen.has(e))return!1;a.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return xe(n.element,a);if(n.type==="set")return xe(n.valueType,a);if(n.type==="lazy")return xe(n.getter(),a);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return xe(n.innerType,a);if(n.type==="intersection")return xe(n.left,a)||xe(n.right,a);if(n.type==="record"||n.type==="map")return xe(n.keyType,a)||xe(n.valueType,a);if(n.type==="pipe")return xe(n.in,a)||xe(n.out,a);if(n.type==="object"){for(const r in n.shape)if(xe(n.shape[r],a))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(xe(r,a))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(xe(r,a))return!0;return!!(n.rest&&xe(n.rest,a))}return!1}var Rp=(e,t={})=>a=>{const n=yr({...a,processors:t});return he(e,n),_r(n,e),xr(n,e)},jt=(e,t,a={})=>n=>{const{libraryOptions:r,target:i}=n??{},o=yr({...r??{},target:i,io:t,processors:a});return he(e,o),_r(o,e),xr(o,e)},Dp={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Op=(e,t,a,n)=>{const r=a;r.type="string";const{minimum:i,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof o=="number"&&(r.maxLength=o),s&&(r.format=Dp[s]??s,r.format===""&&delete r.format,s==="time"&&delete r.format),l&&(r.contentEncoding=l),c&&c.size>0){const g=[...c];g.length===1?r.pattern=g[0].source:g.length>1&&(r.allOf=[...g.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},Fp=(e,t,a,n)=>{const r=a,{minimum:i,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:g}=e._zod.bag;typeof s=="string"&&s.includes("int")?r.type="integer":r.type="number",typeof g=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=g,r.exclusiveMinimum=!0):r.exclusiveMinimum=g),typeof i=="number"&&(r.minimum=i,typeof g=="number"&&t.target!=="draft-04"&&(g>=i?delete r.minimum:delete r.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),typeof o=="number"&&(r.maximum=o,typeof l=="number"&&t.target!=="draft-04"&&(l<=o?delete r.maximum:delete r.exclusiveMaximum)),typeof c=="number"&&(r.multipleOf=c)},$p=(e,t,a,n)=>{a.type="boolean"},Hp=(e,t,a,n)=>{a.not={}},Up=(e,t,a,n)=>{},jp=(e,t,a,n)=>{const r=e._zod.def,i=Dn(r.entries);i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),a.enum=i},Zp=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},qp=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Vp=(e,t,a,n)=>{const r=a,i=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o=="number"&&(r.minItems=o),typeof s=="number"&&(r.maxItems=s),r.type="array",r.items=he(i.element,t,{...n,path:[...n.path,"items"]})},Gp=(e,t,a,n)=>{const r=a,i=e._zod.def;r.type="object",r.properties={};const o=i.shape;for(const l in o)r.properties[l]=he(o[l],t,{...n,path:[...n.path,"properties",l]});const s=new Set(Object.keys(o)),c=new Set([...s].filter(l=>{const g=i.shape[l]._zod;return t.io==="input"?g.optin===void 0:g.optout===void 0}));c.size>0&&(r.required=Array.from(c)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=he(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},Wp=(e,t,a,n)=>{const r=e._zod.def,i=r.inclusive===!1,o=r.options.map((s,c)=>he(s,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?a.oneOf=o:a.anyOf=o},Kp=(e,t,a,n)=>{const r=e._zod.def,i=he(r.left,t,{...n,path:[...n.path,"allOf",0]}),o=he(r.right,t,{...n,path:[...n.path,"allOf",1]}),s=c=>"allOf"in c&&Object.keys(c).length===1;a.allOf=[...s(i)?i.allOf:[i],...s(o)?o.allOf:[o]]},Yp=(e,t,a,n)=>{const r=a,i=e._zod.def;r.type="object";const o=i.keyType,s=o._zod.bag?.patterns;if(i.mode==="loose"&&s&&s.size>0){const l=he(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});r.patternProperties={};for(const g of s)r.patternProperties[g.source]=l}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=he(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=he(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const c=o._zod.values;if(c){const l=[...c].filter(g=>typeof g=="string"||typeof g=="number");l.length>0&&(r.required=l)}},Jp=(e,t,a,n)=>{const r=e._zod.def,i=he(r.innerType,t,n),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=r.innerType,a.nullable=!0):a.anyOf=[i,{type:"null"}]},Xp=(e,t,a,n)=>{const r=e._zod.def;he(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Qp=(e,t,a,n)=>{const r=e._zod.def;he(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.default=JSON.parse(JSON.stringify(r.defaultValue))},eh=(e,t,a,n)=>{const r=e._zod.def;he(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,t.io==="input"&&(a._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},th=(e,t,a,n)=>{const r=e._zod.def;he(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType;let o;try{o=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}a.default=o},ah=(e,t,a,n)=>{const r=e._zod.def,i=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;he(i,t,n);const o=t.seen.get(e);o.ref=i},nh=(e,t,a,n)=>{const r=e._zod.def;he(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.readOnly=!0},wr=(e,t,a,n)=>{const r=e._zod.def;he(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},rh=w("ZodISODateTime",(e,t)=>{sd.init(e,t),le.init(e,t)});function ih(e){return pp(rh,e)}var oh=w("ZodISODate",(e,t)=>{cd.init(e,t),le.init(e,t)});function sh(e){return hp(oh,e)}var ch=w("ZodISOTime",(e,t)=>{ld.init(e,t),le.init(e,t)});function lh(e){return up(ch,e)}var gh=w("ZodISODuration",(e,t)=>{gd.init(e,t),le.init(e,t)});function dh(e){return mp(gh,e)}var kr=(e,t)=>{jn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:a=>eg(e,a)},flatten:{value:a=>Ql(e,a)},addIssue:{value:a=>{e.issues.push(a),e.message=JSON.stringify(e.issues,ha,2)}},addIssues:{value:a=>{e.issues.push(...a),e.message=JSON.stringify(e.issues,ha,2)}},isEmpty:{get(){return e.issues.length===0}}})},qu=w("ZodError",kr),Le=w("ZodError",kr,{Parent:Error}),ph=va(Le),hh=ya(Le),uh=Dt(Le),mh=Ot(Le),fh=ng(Le),bh=rg(Le),vh=ig(Le),yh=og(Le),_h=sg(Le),xh=cg(Le),wh=lg(Le),kh=gg(Le),de=w("ZodType",(e,t)=>(ge.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:jt(e,"input"),output:jt(e,"output")}}),e.toJSONSchema=Rp(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...a)=>e.clone(qe(t,{checks:[...t.checks??[],...a.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(a,n)=>Ve(e,a,n),e.brand=()=>e,e.register=((a,n)=>(a.add(e,n),e)),e.parse=(a,n)=>ph(e,a,n,{callee:e.parse}),e.safeParse=(a,n)=>uh(e,a,n),e.parseAsync=async(a,n)=>hh(e,a,n,{callee:e.parseAsync}),e.safeParseAsync=async(a,n)=>mh(e,a,n),e.spa=e.safeParseAsync,e.encode=(a,n)=>fh(e,a,n),e.decode=(a,n)=>bh(e,a,n),e.encodeAsync=async(a,n)=>vh(e,a,n),e.decodeAsync=async(a,n)=>yh(e,a,n),e.safeEncode=(a,n)=>_h(e,a,n),e.safeDecode=(a,n)=>xh(e,a,n),e.safeEncodeAsync=async(a,n)=>wh(e,a,n),e.safeDecodeAsync=async(a,n)=>kh(e,a,n),e.refine=(a,n)=>e.check(mu(a,n)),e.superRefine=a=>e.check(fu(a)),e.overwrite=a=>e.check(ct(a)),e.optional=()=>Tr(e),e.exactOptional=()=>au(e),e.nullable=()=>Lr(e),e.nullish=()=>Tr(Lr(e)),e.nonoptional=a=>cu(e,a),e.array=()=>ee(e),e.or=a=>lt([e,a]),e.and=a=>Jh(e,a),e.transform=a=>Nr(e,eu(a)),e.default=a=>iu(e,a),e.prefault=a=>su(e,a),e.catch=a=>gu(e,a),e.pipe=a=>Nr(e,a),e.readonly=()=>hu(e),e.describe=a=>{const n=e.clone();return vt.add(n,{description:a}),n},Object.defineProperty(e,"description",{get(){return vt.get(e)?.description},configurable:!0}),e.meta=(...a)=>{if(a.length===0)return vt.get(e);const n=e.clone();return vt.add(n,a[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=a=>a(e),e)),Cr=w("_ZodString",(e,t)=>{_a.init(e,t),de.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Op(e,n,r,i);const a=e._zod.bag;e.format=a.format??null,e.minLength=a.minimum??null,e.maxLength=a.maximum??null,e.regex=(...n)=>e.check(xp(...n)),e.includes=(...n)=>e.check(Cp(...n)),e.startsWith=(...n)=>e.check(Sp(...n)),e.endsWith=(...n)=>e.check(Ep(...n)),e.min=(...n)=>e.check(Ut(...n)),e.max=(...n)=>e.check(br(...n)),e.length=(...n)=>e.check(vr(...n)),e.nonempty=(...n)=>e.check(Ut(1,...n)),e.lowercase=n=>e.check(wp(n)),e.uppercase=n=>e.check(kp(n)),e.trim=()=>e.check(Ap()),e.normalize=(...n)=>e.check(Pp(...n)),e.toLowerCase=()=>e.check(Tp()),e.toUpperCase=()=>e.check(Lp()),e.slugify=()=>e.check(Ip())}),Ch=w("ZodString",(e,t)=>{_a.init(e,t),Cr.init(e,t),e.email=a=>e.check(qd(Sh,a)),e.url=a=>e.check(Yd(Eh,a)),e.jwt=a=>e.check(dp(Hh,a)),e.emoji=a=>e.check(Jd(Ph,a)),e.guid=a=>e.check(hr(Sr,a)),e.uuid=a=>e.check(Vd(Zt,a)),e.uuidv4=a=>e.check(Gd(Zt,a)),e.uuidv6=a=>e.check(Wd(Zt,a)),e.uuidv7=a=>e.check(Kd(Zt,a)),e.nanoid=a=>e.check(Xd(Ah,a)),e.guid=a=>e.check(hr(Sr,a)),e.cuid=a=>e.check(Qd(Th,a)),e.cuid2=a=>e.check(ep(Lh,a)),e.ulid=a=>e.check(tp(Ih,a)),e.base64=a=>e.check(cp(Oh,a)),e.base64url=a=>e.check(lp(Fh,a)),e.xid=a=>e.check(ap(Nh,a)),e.ksuid=a=>e.check(np(zh,a)),e.ipv4=a=>e.check(rp(Mh,a)),e.ipv6=a=>e.check(ip(Bh,a)),e.cidrv4=a=>e.check(op(Rh,a)),e.cidrv6=a=>e.check(sp(Dh,a)),e.e164=a=>e.check(gp($h,a)),e.datetime=a=>e.check(ih(a)),e.date=a=>e.check(sh(a)),e.time=a=>e.check(lh(a)),e.duration=a=>e.check(dh(a))});function _(e){return Zd(Ch,e)}var le=w("ZodStringFormat",(e,t)=>{se.init(e,t),Cr.init(e,t)}),Sh=w("ZodEmail",(e,t)=>{Xg.init(e,t),le.init(e,t)}),Sr=w("ZodGUID",(e,t)=>{Yg.init(e,t),le.init(e,t)}),Zt=w("ZodUUID",(e,t)=>{Jg.init(e,t),le.init(e,t)}),Eh=w("ZodURL",(e,t)=>{Qg.init(e,t),le.init(e,t)}),Ph=w("ZodEmoji",(e,t)=>{ed.init(e,t),le.init(e,t)}),Ah=w("ZodNanoID",(e,t)=>{td.init(e,t),le.init(e,t)}),Th=w("ZodCUID",(e,t)=>{ad.init(e,t),le.init(e,t)}),Lh=w("ZodCUID2",(e,t)=>{nd.init(e,t),le.init(e,t)}),Ih=w("ZodULID",(e,t)=>{rd.init(e,t),le.init(e,t)}),Nh=w("ZodXID",(e,t)=>{id.init(e,t),le.init(e,t)}),zh=w("ZodKSUID",(e,t)=>{od.init(e,t),le.init(e,t)}),Mh=w("ZodIPv4",(e,t)=>{dd.init(e,t),le.init(e,t)}),Bh=w("ZodIPv6",(e,t)=>{pd.init(e,t),le.init(e,t)}),Rh=w("ZodCIDRv4",(e,t)=>{hd.init(e,t),le.init(e,t)}),Dh=w("ZodCIDRv6",(e,t)=>{ud.init(e,t),le.init(e,t)}),Oh=w("ZodBase64",(e,t)=>{md.init(e,t),le.init(e,t)}),Fh=w("ZodBase64URL",(e,t)=>{bd.init(e,t),le.init(e,t)}),$h=w("ZodE164",(e,t)=>{vd.init(e,t),le.init(e,t)}),Hh=w("ZodJWT",(e,t)=>{_d.init(e,t),le.init(e,t)}),Er=w("ZodNumber",(e,t)=>{er.init(e,t),de.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Fp(e,n,r,i),e.gt=(n,r)=>e.check(mr(n,r)),e.gte=(n,r)=>e.check(ka(n,r)),e.min=(n,r)=>e.check(ka(n,r)),e.lt=(n,r)=>e.check(ur(n,r)),e.lte=(n,r)=>e.check(wa(n,r)),e.max=(n,r)=>e.check(wa(n,r)),e.int=n=>e.check(Pr(n)),e.safe=n=>e.check(Pr(n)),e.positive=n=>e.check(mr(0,n)),e.nonnegative=n=>e.check(ka(0,n)),e.negative=n=>e.check(ur(0,n)),e.nonpositive=n=>e.check(wa(0,n)),e.multipleOf=(n,r)=>e.check(fr(n,r)),e.step=(n,r)=>e.check(fr(n,r)),e.finite=()=>e;const a=e._zod.bag;e.minValue=Math.max(a.minimum??Number.NEGATIVE_INFINITY,a.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(a.maximum??Number.POSITIVE_INFINITY,a.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(a.format??"").includes("int")||Number.isSafeInteger(a.multipleOf??.5),e.isFinite=!0,e.format=a.format??null});function Me(e){return fp(Er,e)}var Uh=w("ZodNumberFormat",(e,t)=>{xd.init(e,t),Er.init(e,t)});function Pr(e){return bp(Uh,e)}var jh=w("ZodBoolean",(e,t)=>{wd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>$p(e,a,n,r)});function Ye(e){return vp(jh,e)}var Zh=w("ZodUnknown",(e,t)=>{kd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Up(e,a,n,r)});function Se(){return yp(Zh)}var qh=w("ZodNever",(e,t)=>{Cd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Hp(e,a,n,r)});function Vh(e){return _p(qh,e)}var Gh=w("ZodArray",(e,t)=>{Sd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Vp(e,a,n,r),e.element=t.element,e.min=(a,n)=>e.check(Ut(a,n)),e.nonempty=a=>e.check(Ut(1,a)),e.max=(a,n)=>e.check(br(a,n)),e.length=(a,n)=>e.check(vr(a,n)),e.unwrap=()=>e.element});function ee(e,t){return Np(Gh,e,t)}var Wh=w("ZodObject",(e,t)=>{Pd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Gp(e,a,n,r),re(e,"shape",()=>t.shape),e.keyof=()=>yt(Object.keys(e._zod.def.shape)),e.catchall=a=>e.clone({...e._zod.def,catchall:a}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Se()}),e.loose=()=>e.clone({...e._zod.def,catchall:Se()}),e.strict=()=>e.clone({...e._zod.def,catchall:Vh()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=a=>Wl(e,a),e.safeExtend=a=>Kl(e,a),e.merge=a=>Yl(e,a),e.pick=a=>Vl(e,a),e.omit=a=>Gl(e,a),e.partial=(...a)=>Jl(Ar,e,a[0]),e.required=(...a)=>Xl(Ir,e,a[0])});function G(e,t){return new Wh({type:"object",shape:e??{},...F(t)})}var Kh=w("ZodUnion",(e,t)=>{Ad.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Wp(e,a,n,r),e.options=t.options});function lt(e,t){return new Kh({type:"union",options:e,...F(t)})}var Yh=w("ZodIntersection",(e,t)=>{Td.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Kp(e,a,n,r)});function Jh(e,t){return new Yh({type:"intersection",left:e,right:t})}var Xh=w("ZodRecord",(e,t)=>{Ld.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Yp(e,a,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Je(e,t,a){return new Xh({type:"record",keyType:e,valueType:t,...F(a)})}var Ca=w("ZodEnum",(e,t)=>{Id.init(e,t),de.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jp(e,n,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const a=new Set(Object.keys(t.entries));e.extract=(n,r)=>{const i={};for(const o of n)if(a.has(o))i[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Ca({...t,checks:[],...F(r),entries:i})},e.exclude=(n,r)=>{const i={...t.entries};for(const o of n)if(a.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new Ca({...t,checks:[],...F(r),entries:i})}});function yt(e,t){return new Ca({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e,...F(t)})}var Qh=w("ZodTransform",(e,t)=>{Nd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>qp(e,a,n,r),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new Rn(e.constructor.name);a.addIssue=i=>{if(typeof i=="string")a.issues.push(bt(i,a.value,t));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=a.value),o.inst??(o.inst=e),a.issues.push(bt(o))}};const r=t.transform(a.value,a);return r instanceof Promise?r.then(i=>(a.value=i,a)):(a.value=r,a)}});function eu(e){return new Qh({type:"transform",transform:e})}var Ar=w("ZodOptional",(e,t)=>{sr.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>wr(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Tr(e){return new Ar({type:"optional",innerType:e})}var tu=w("ZodExactOptional",(e,t)=>{zd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>wr(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function au(e){return new tu({type:"optional",innerType:e})}var nu=w("ZodNullable",(e,t)=>{Md.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Jp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Lr(e){return new nu({type:"nullable",innerType:e})}var ru=w("ZodDefault",(e,t)=>{Bd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Qp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function iu(e,t){return new ru({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Hn(t)}})}var ou=w("ZodPrefault",(e,t)=>{Rd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>eh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function su(e,t){return new ou({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Hn(t)}})}var Ir=w("ZodNonOptional",(e,t)=>{Dd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Xp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function cu(e,t){return new Ir({type:"nonoptional",innerType:e,...F(t)})}var lu=w("ZodCatch",(e,t)=>{Od.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>th(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function gu(e,t){return new lu({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var du=w("ZodPipe",(e,t)=>{Fd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>ah(e,a,n,r),e.in=t.in,e.out=t.out});function Nr(e,t){return new du({type:"pipe",in:e,out:t})}var pu=w("ZodReadonly",(e,t)=>{$d.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>nh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function hu(e){return new pu({type:"readonly",innerType:e})}var uu=w("ZodCustom",(e,t)=>{Hd.init(e,t),de.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Zp(e,a,n,r)});function mu(e,t={}){return zp(uu,e,t)}function fu(e){return Mp(e)}var bu=G({role:yt(["user","assistant"]),content:_(),timestamp:Me().optional()}),vu=G({sku:_(),name:_(),imageUrl:_().url().optional(),price:_().optional(),originalPrice:_().optional(),url:_().url(),ctaLabel:_().optional()}),yu=G({buttons:ee(G({label:_(),action:G({title:_(),type:_(),payload:Se().optional()})}))}),_u=G({}),xu=G({label:_().optional()}),zr=G({sku:_(),name:_(),price:_(),imageUrl:_().optional(),rating:Me().optional(),reviewCount:Me().optional()}),wu=G({recommended:zr,products:ee(zr),attributes:ee(G({label:_(),values:ee(_())})),highlights:ee(_()),specialCases:ee(_()).optional(),recommendedText:_().optional(),winnerHits:Je(_(),G({positive:ee(_()).optional(),negative:ee(_()).optional()})).optional(),productActions:Je(_(),G({title:_(),type:_(),payload:Se().optional()})).optional()}),ku=G({label:_(),sentiment:yt(["positive","negative","neutral"]).optional()}),Cu=G({product:Je(_(),Se()),role:_().optional(),reason:_().optional(),labels:ee(ku).optional(),expertQualityScore:Me().optional(),reviewHighlight:_().optional(),action:G({title:_(),type:_(),payload:Se().optional()}).optional()}),Su=G({suggestions:ee(Cu)}),Eu=G({title:_().optional(),text:_().optional(),reviewCount:_().optional(),action:G({title:_(),type:_(),payload:Se().optional()})}),Pu=G({entries:ee(G({name:_(),image:_().optional(),description:_().optional(),action:G({title:_(),type:_(),payload:Se().optional()})}))}),Au=G({entries:ee(G({shortName:_(),detailedMessage:_().optional(),whyDifferent:_().optional(),image:_().optional(),action:G({title:_(),type:_(),payload:Se().optional()})}))}),Mr=G({title:_(),type:_(),payload:Se().optional()}),_t=G({name:_().optional(),value:_().optional(),option_value:_().optional(),attribute_value:_().optional(),type:_().optional(),attribute:_().optional(),option_name:_().optional(),attribute_name:_().optional(),variant_name:_().optional(),sku:_().optional(),price:lt([Me(),_()]).optional(),price_discounted:lt([Me(),_()]).optional(),image:_().optional(),imageUrl:_().optional(),image_url:_().optional(),color:_().optional(),colour:_().optional(),color_hex:_().optional(),hex:_().optional(),swatch:_().optional(),swatchColor:_().optional(),in_stock:Ye().optional(),inStock:Ye().optional()}),Tu=G({product:G({sku:_().optional(),name:_().optional(),images:ee(_()).optional(),imageUrl:_().optional(),rating:Me().optional(),reviewCount:Me().optional(),price:_().optional(),originalPrice:_().optional(),discountReason:_().optional(),discount_reason:_().optional(),campaignReason:_().optional(),campaign_reason:_().optional(),originalPriceStyle:yt(["strikethrough","inline"]).optional(),price_original_style:yt(["strikethrough","inline"]).optional(),price_discount_rate:Me().optional(),price_async:Ye().optional(),inStock:Ye().optional(),promotions:ee(_()).optional(),variants:ee(_t).optional(),variantOptions:ee(_t).optional(),variant_options:ee(_t).optional(),productVariants:ee(_t).optional(),product_variants:ee(_t).optional(),url:_().optional(),cartCode:_().optional(),description:_().optional(),description_html:_().optional(),descriptionHtml:_().optional(),facet_hits:Je(_(),Se()).optional(),facetHits:Je(_(),Se()).optional(),features:ee(G({name:_().optional(),key:_().optional(),label:_().optional(),value:lt([_(),Me(),Ye()]).optional()})).optional(),specifications:lt([Je(_(),_()),ee(G({key:_(),value:_()}))]).optional()}).optional(),action:Mr.optional()}),Lu=G({endOfList:Ye().optional()}),Iu=G({review_class:_().optional(),review_text:_().optional(),review_rating:lt([_(),Me()]).optional(),review_tag:_().optional()}),Nu=G({reviews:ee(Iu).optional()}),zu=G({productName:_().optional(),pros:ee(_()).optional(),cons:ee(_()).optional()}),Mu=G({groups:ee(G({groupName:_(),image:_().optional(),products:ee(Je(_(),Se())).optional()})).optional(),filterTags:ee(G({title:_(),action:Mr.optional()})).optional()}),Bu=G({summary:_().optional(),products_discussed:ee(_()).optional(),user_sentiment:_().optional()}),Ru=G({summary:_(),strengths:ee(_()).optional(),focus_points:ee(_()).optional(),celeb_style:_().optional(),celeb_style_reason:_().optional(),next_question:_().optional(),style_images:ee(_()).optional()}),Du=G({processing:Ye().optional(),title:_().optional(),description:_().optional(),upload_label:_().optional(),skip_label:_().optional()}),Ou={components:{MessageBubble:{schema:bu,description:"A single chat message bubble for user or assistant turns."},ProductCard:{schema:vu,description:"A product card rendered inline in the chat stream."},ActionButtons:{schema:yu,description:"A horizontal row of quick-reply action buttons."},TypingIndicator:{schema:_u,description:"An animated indicator shown while the assistant is typing."},Divider:{schema:xu,description:"A horizontal rule with an optional label."},ComparisonTable:{schema:wu,description:"A product comparison table with recommended pick, attribute rows, and highlights."},AITopPicks:{schema:Su,description:"Rich AI-curated product suggestion cards with roles, sentiment labels, scores, and review quotes."},GroundingReviewCard:{schema:Eu,description:"A card showing review grounding data with review count and CTA."},AIGroupingCards:{schema:Pu,description:"Category grouping cards with images and labels for product discovery."},AISuggestedSearchCards:{schema:Au,description:"Suggested search cards with images, descriptions, and differentiation."},ProductDetailsPanel:{schema:Tu,description:"Full product detail view with images, specs, variants, and purchase actions."},ProductGrid:{schema:Lu,description:'A scrollable grid of ProductCard children with optional "more" pagination.'},ReviewHighlights:{schema:Nu,description:"A list of highlighted customer reviews with sentiment and ratings."},ProsAndCons:{schema:zu,description:"A pros and cons list for a product."},CategoriesContainer:{schema:Mu,description:"Tabbed product groups with optional filter tag buttons."},HandoffNotice:{schema:Bu,description:"A notice shown when the conversation is escalated to a human agent."},PhotoAnalysisCard:{schema:Ru,description:"Structured photo analysis card with strengths, focus points, celeb vibe, and follow-up question."},BeautyPhotoStep:{schema:Du,description:"Transient selfie upload prompt for beauty consulting init flow."}}},Fu=new Set(["launchSingleProduct","launchProductList","launchHomepage"]);function Br(e){return e.length>120?!1:/^[a-zA-Z0-9#(),.\s%/\-]+$/.test(e)}function Sa(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function Ea(e){return e?.type==="ProductGrid"&&e.props?.similarsAppend===!0}var Rr=class gt extends Fi{constructor(...t){super(...t),this._shadow=null,this._rootEl=null,this._backdropEl=null,this._launcher=null,this._drawer=null,this._bridge=null,this._drawerVisible=!1,this._pillLauncherApply=null,this._hostScrollLockActive=!1,this._hostOverflowRestore=null,this._hostScrollLockViewport=null,this._hostScrollPinning=!1,this._preventHostDocumentTouchMove=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._preventHostDocumentWheel=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._pinHostViewportScroll=()=>{if(!this._hostScrollLockActive||!this._hostScrollLockViewport||this._hostScrollPinning)return;const a=this._hostScrollLockViewport;window.scrollX===a.x&&window.scrollY===a.y||(this._hostScrollPinning=!0,window.scrollTo(a.x,a.y),this._hostScrollPinning=!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._comparisonSelectionWarning=null,this._comparisonRefreshRafId=null,this._viewedProductSkus=new Set,this._thumbnailEntries=[],this._choicePrompterEl=null,this._openState="full",this._mobileBreakpoint=768,this._isMobileViewport=!1,this._gaPrevMainPaneExpanded=!1,this._pdpLaunched=!1,this._plpLaunched=!1,this._homepageLaunched=!1,this._entryContextPrimed=!1,this._contextPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._i18n=tt,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._localPanelHistory=[],this._currentPanelSource=null,this._session=null,this._presentation=new zn,this._eventCallbacks=new Map,this._lastSentAction=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._modeController=new As}static{this._MAX_COMPARISON_SELECTION=5}static{this._MAX_PANEL_HISTORY=10}get _assistantMode(){return this._modeController.mode}set _assistantMode(t){this._modeController.mode=t}get _uiHints(){return this._modeController.uiHints}set _uiHints(t){this._modeController.uiHints=t}async onInit(t){if(this._i18n=this._resolveI18n(t),this._chatCreatedAt=new Date().toISOString(),t.pillLauncher){const u=Pl(t.pillLauncher);t.launcherImageUrl=u.launcherImageUrl,t.headerAvatarUrl===void 0&&(t.headerAvatarUrl=t.pillLauncher.avatarUrl),this._pillLauncherApply=()=>u.apply(this._shadow??void 0)}this._shadow=this.root.attachShadow({mode:"open"});const a=document.createElement("style");a.textContent=Fl,this._shadow.appendChild(a);const n=this.root,r=(u,v)=>{v&&Br(v)&&n.style.setProperty(u,v)};if(r("--gengage-chat-header-bg",t.headerBg),r("--gengage-chat-header-foreground",t.headerForeground),t.theme)for(const[u,v]of Object.entries(t.theme))u.startsWith("--")&&typeof v=="string"&&r(u,v);this._applyDiscountedPriceColorVar(t.productPriceUi?.discountedPriceColor);const i=document.createElement("div");i.className="gengage-chat-root",i.lang=wt(t.locale),this._rootEl=i,this._shadow.appendChild(i);const o=t.variant??"floating";if(o==="inline"&&i.classList.add("gengage-chat--inline"),o!=="inline"){const u=document.createElement("div");u.className="gengage-chat-backdrop",u.setAttribute("aria-hidden","true"),u.setAttribute("role","button"),u.setAttribute("tabindex","-1"),u.setAttribute("aria-label",this._i18n.closeAriaLabel),u.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),this.close()}),this._backdropEl=u,i.prepend(u)}if(o==="floating"){const u={onClick:()=>this.open(),ariaLabel:this._i18n.openButton};t.launcherImageUrl!==void 0?u.imageUrl=t.launcherImageUrl:t.launcherSvg!==void 0&&(u.svgMarkup=t.launcherSvg),t.hideMobileLauncher!==void 0&&(u.hideMobile=t.hideMobileLauncher),t.mobileBreakpoint!==void 0&&(u.mobileBreakpoint=t.mobileBreakpoint),t.launcherTooltip!==void 0&&(u.tooltip=t.launcherTooltip),this._launcher=al(u),i.appendChild(this._launcher.container)}o==="overlay"&&i.classList.add("gengage-chat--overlay");const s=document.createElement("div");i.appendChild(s),this._drawer=new ks(s,{i18n:this._i18n,onSend:(u,v)=>this._sendMessage(u,v),onClose:()=>this.close(),onAttachment:u=>this._handleAttachment(u),onPanelToggle:()=>{this._drawer?.persistPanelState(t.accountId)},onHostShellSync:()=>{this._applyOpenStateClasses()},onRollback:u=>this._handleRollback(u),onPanelBack:()=>this._navigatePanelBack(),onPanelForward:()=>this._panel?.navigateForward(),onPanelClose:()=>{if(this._isMobileViewport){this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[];return}this._localPanelHistory=[],this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._currentPanelSource=null},headerTitle:t.headerTitle,headerAvatarUrl:t.headerAvatarUrl,launcherImageUrl:t.launcherImageUrl,headerBadge:t.headerBadge,headerCartUrl:t.headerCartUrl,showHeaderFavorites:typeof t.onFavoritesClick=="function"||t.headerFavoritesToggle===!0,onCartClick:()=>{t.headerCartUrl?this._saveSessionAndOpenURL(t.headerCartUrl):t.onCartClick?.()},onFavoritesClick:()=>{if(ui(),typeof t.onFavoritesClick=="function"){t.onFavoritesClick();return}this._openFavoritesPanel()},getMobileState:()=>this._openState??"full",getMobileViewport:()=>this._isMobileViewport,onMobileSnap:u=>{u==="close"?this.close():(this._openState=u,this._applyOpenStateClasses())},onThumbnailClick:u=>this._rollbackToThread(u),onLinkClick:u=>{this._saveSessionAndOpenURL(u)},voiceEnabled:t.voiceEnabled,voiceLang:t.locale?`${t.locale.split("-")[0]??"tr"}-${(t.locale.split("-")[1]??t.locale.split("-")[0]??"TR").toUpperCase()}`:void 0,presentation:{onPinnedToBottomChange:u=>{this._presentation.pinnedToBottom=u},onUserInteractingChange:u=>{this._presentation.userInteracting=u},onFormerMessagesHint:()=>{this._presentation.focusedThreadId&&this._hasMultipleThreadIds()&&this._drawer?.setFormerMessagesButtonVisible(!0)},shouldBlockSoftAutoScroll:()=>this._presentation.shouldBlockStreamAutoScroll(),onReleasePresentationFocus:()=>this._releasePresentationFocus()}}),this._applyUiHints(),this._extendedModeManager=new kl({onChange:u=>this._panel?.notifyExtension(u),productDetailsInPanel:(t.isDemoWebsite??!1)&&(t.productDetailsExtended??!1)}),this._panel=new Cl({drawer:()=>this._drawer,shadow:()=>this._shadow,currentThreadId:()=>this._currentThreadId,bridge:()=>this._bridge,extendedModeManager:()=>this._extendedModeManager,i18n:()=>this._i18n,rollbackToThread:u=>this._rollbackToThread(u)}),o!=="inline"&&this._drawer.getElement().classList.add("gengage-chat-drawer--hidden");const c=this._drawer.restorePanelState(t.accountId),l=t.panelMode??"auto";l==="collapsed"?this._drawer.setPanelCollapsed(!0):l==="expanded"&&this._drawer.setForceExpanded();const g=sessionStorage.getItem("gengage_restore_session_id"),p=sessionStorage.getItem("gengage_restore_sku"),h=!!(g&&p);h&&(sessionStorage.removeItem("gengage_restore_session_id"),sessionStorage.removeItem("gengage_restore_sku"));try{const u=new xl;await u.open(),this._session=new Nn(u),await this._restoreFromIndexedDB(h)}catch{this._session=new Nn(null)}this._registerPublicAPI(),t.mobileInitialState!==void 0&&(this._openState=t.mobileInitialState),this._mobileBreakpoint=t.mobileBreakpoint??768,this._syncViewportState();const d=()=>this._syncViewportState();if(window.addEventListener("resize",d,{passive:!0}),this.addCleanup(()=>window.removeEventListener("resize",d)),window.visualViewport){const u=()=>{if(!this._drawerVisible||!this._isMobileViewport)return;const v=this._drawer?.getElement();if(!v)return;const m=window.innerHeight-(window.visualViewport?.height??window.innerHeight);v.style.setProperty("--gengage-keyboard-offset",`${Math.max(0,m)}px`)};window.visualViewport.addEventListener("resize",u),this.addCleanup(()=>window.visualViewport?.removeEventListener("resize",u))}o==="inline"&&(this._drawerVisible=!0,this.isVisible=!0,this._applyOpenStateClasses(),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60));const b={namespace:"chat",onMessage:u=>this._handleBridgeMessage(u)};t.allowedOrigins!==void 0&&(b.allowedOrigins=t.allowedOrigins),this._bridge=new Hi(b),this._lastSku=this.config.pageContext?.sku,this._lastPageType=this.config.pageContext?.pageType,this._lastSkuListKey=this.config.pageContext?.skuList?.slice(0,48).join(","),this._initComplete=!0;for(const u of this._pendingActions)this._sendAction(u.action,u.options);this._pendingActions=[],this._pillLauncherApply&&o==="floating"&&(await this._pillLauncherApply(),this._pillLauncherApply=null),Te("gengage:chat:ready",{}),ii("chat"),t.onReady?.()}onUpdate(t){if(this.config.pageContext&&t.pageType!==void 0){const{sku:n,skuList:r,...i}=this.config.pageContext,o={...i};o.pageType==="pdp"&&n!==void 0&&(o.sku=n),o.pageType==="plp"&&r!==void 0&&(o.skuList=r),this.config={...this.config,pageContext:o}}let a=!1;if(t.sku!==void 0&&t.sku!==this._lastSku&&(this._lastSku=t.sku,a=!0),t.pageType!==void 0&&t.pageType!==this._lastPageType&&(this._lastPageType=t.pageType,a=!0),t.skuList!==void 0){const n=t.skuList.slice(0,48).join(",");n!==this._lastSkuListKey&&(this._lastSkuListKey=n,a=!0)}a&&this._resetForNewPage()}onShow(){this._showDrawer(),this.emit("open"),Te("gengage:chat:open",{state:this._openState}),oi("chat"),this.config.onOpen?.(),this._showWelcomeIfNeeded(),this._maybePrimeEntryContextOpening(),!this._pdpLaunched&&this.config.pageContext?.pageType==="pdp"&&this.config.pageContext?.sku&&(this._pdpLaunched=!0,this._contextPrimingInFlight=!0,this._sendAction({title:"",type:"launchSingleProduct",payload:{sku:this.config.pageContext.sku,...this._resolveContextualOpeningMessage("product")?{opening_message:this._resolveContextualOpeningMessage("product")}:{},...this._resolveContextualOpeningGuidance("product")?{opening_guidance:this._resolveContextualOpeningGuidance("product")}:{}}},{silent:!0,isContextPrime:!0,preservePills:!0})),!this._plpLaunched&&this.config.pageContext?.pageType==="plp"&&this.config.pageContext.skuList?.length&&(this._plpLaunched=!0,this._contextPrimingInFlight=!0,this._sendAction({title:"",type:"launchProductList",payload:{sku_list:this.config.pageContext.skuList.slice(0,48)}},{silent:!0,isContextPrime:!0,preservePills:!0})),!this._homepageLaunched&&this.config.pageContext?.pageType==="home"&&(this._homepageLaunched=!0,this._contextPrimingInFlight=!0,this._sendAction({title:"",type:"launchHomepage",payload:{}},{silent:!0,isContextPrime:!0,preservePills:!0}))}onHide(){(this.config.variant??"floating")==="floating"&&(this.root.style.display=""),this._hideDrawer(),this.emit("close"),Te("gengage:chat:close",{}),this.config.onClose?.()}onDestroy(){this._releaseHostDocumentScrollLock(),this._abortAllActiveRequests(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._comparisonRefreshRafId!==null&&(cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=null),this._drawer?.destroy(),Ga(),this._drawer=null,this._bridge?.destroy(),this._bridge=null,this._extendedModeManager=null,this._panel?.destroy(),this._panel=null,this._session?.close(),this._session=null,this._localPanelHistory=[],this._currentPanelSource=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,a){a?.sku!==void 0&&this.update({sku:a.sku}),this._pdpLaunched=!0,a?.state!==void 0?this._openState=a.state:this._isMobileViewport&&(this._openState="half"),this.show(),this._drawerVisible&&this._applyOpenStateClasses(),this._sendAction(t)}sendMessage(t){this._sendMessage(t)}sendAction(t,a){this._sendAction(t,a)}close(){this.hide()}saveSession(t,a){sessionStorage.setItem("gengage_restore_session_id",t),sessionStorage.setItem("gengage_restore_sku",a)}get isOpen(){return this._drawerVisible}addCallback(t,a){let n=this._eventCallbacks.get(t);return n||(n=new Set,this._eventCallbacks.set(t,n)),n.add(a),()=>{n.delete(a),n.size===0&&this._eventCallbacks.delete(t)}}_applyDiscountedPriceColorVar(t){const a=this.root;t==="client"?a.style.setProperty("--gengage-discounted-price-color","var(--client-primary)"):a.style.removeProperty("--gengage-discounted-price-color")}_abortAllActiveRequests(){for(const t of this._abortControllers)t.abort();this._abortControllers.clear()}_pruneEmptyStreamingAssistantPlaceholders(){const t=[];let a=!1;for(const n of this._messages){if(n.role==="assistant"&&(n.status==="streaming"||n.status==="done")&&(n.content==null||n.content.length===0)){if(n.threadId){this._threadsWithFirstBot.delete(n.threadId),this._presentation.finalizeAssistantGroup(n.threadId),this._shadow?.querySelectorAll(`[data-thread-id="${_e(n.threadId)}"]:not([data-message-id])`).forEach(i=>i.remove()),this._panel&&(this._panel.threads=this._panel.threads.filter(i=>i!==n.threadId));const r=this._thumbnailEntries.length;this._thumbnailEntries=this._thumbnailEntries.filter(i=>i.threadId!==n.threadId),this._thumbnailEntries.length!==r&&(a=!0)}this._drawer?.removeMessageBubble(n.id),this._panel?.snapshots.delete(n.id),this._panel?.snapshotTypes.delete(n.id);continue}t.push(n)}this._messages.length=0,this._messages.push(...t),a&&this._drawer?.setThumbnails(this._thumbnailEntries)}_resetForNewPage(){this._activeRequestThreadId=null,this._abortAllActiveRequests(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._messages.length=0,this._drawer?.clearMessages(),this._drawer?.clearPanel(),this._currentPanelSource=null,this._panel.snapshots.clear(),this._panel.threads=[],this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._viewedProductSkus.clear(),this._currentThreadId=null,this._lastThreadId=null,this._lastBackendContext=null,this._chatCreatedAt=new Date().toISOString(),this._pdpLaunched=!1,this._plpLaunched=!1,this._homepageLaunched=!1,this._entryContextPrimed=!1,this._contextPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._presentation.reset(),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1),this._modeController.reset()&&(this._drawer?.setInputPlaceholder(this._i18n.inputPlaceholder),this._drawer?.setAttachmentControlsVisible(!0),this._drawer?.setBeautyPhotoStepCard({visible:!1}))}_clearAssistantPanelLikeStreamClearPanel(){this._clearChoicePrompter(),this._drawer?.clearPanel(),this._currentPanelSource=null,this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._panel&&(this._panel.currentType=null,this._panel.updateExtendedMode(""),this._panel.updateTopBar(""))}_flushPresentationScroll(){const t=this._presentation.scrollRequest;if(!t||!this._drawer)return;let a=!1;t.type==="thread"&&t.threadId?(a=this._drawer.scrollThreadIntoView(t.threadId,t.behavior),a||(this._drawer.scrollToBottomPresentation(t.behavior),a=!0)):t.type==="bottom"&&(this._drawer.scrollToBottomPresentation(t.behavior),a=!0),a&&this._presentation.consumeScrollRequest(t.id)}_focusPresentationThread(t,a="smooth",n=!1){this._presentation.requestThreadFocus(t,a),n&&this._drawer?.setPresentationFocus(t),this._drawer?.setFormerMessagesButtonVisible(!1),setTimeout(()=>this._flushPresentationScroll(),40)}_scrollInlineIntoView(t,a){if(a){this._focusPresentationThread(a,"auto");return}t.scrollIntoView({behavior:"auto",block:"start"})}_releasePresentationFocus(){this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1)}_hasMultipleThreadIds(){const t=new Set;for(const a of this._messages)a.threadId&&t.add(a.threadId);return t.size>1}_orderedThreadIds(){const t=[],a=new Set;for(const n of this._messages)n.threadId&&!a.has(n.threadId)&&(a.add(n.threadId),t.push(n.threadId));return t}_maybeAutoAnchorUnreadAssistant(){if(!this._drawer||!this._presentation.shown)return;const t=this._orderedThreadIds();if(t.length===0)return;const a=El(t,this._presentation);if(!a)return;const n=`${a}:assistant`;this._presentation.lastAutoAnchoredGroupId!==n&&(this._presentation.userInteracting&&!this._presentation.pinnedToBottom||this._drawer.scrollThreadIntoView(a,"smooth")&&this._presentation.markGroupAutoAnchored(n))}_handleBridgeMessage(t){switch(t.type){case"openChat":this.open();break;case"closeChat":this.close();break;case"startNewChatWithLauncherAction":{const a=t.payload,n=a?.action,r=Sa(n)?n:Sa(a)?a:null;r&&this._sendAction(r,{silent:!0}),this.open();break}case"startNewChatWithDetailContext":{const a=t.payload;if(a&&typeof a=="object"){this._bridgeContext=a;const n=a.sku;if(n&&this.update({sku:n}),Sa(a.action)){this._pdpLaunched=!0,this.open(),this._sendAction(a.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._presentation.requestScrollToBottom("smooth"),setTimeout(()=>this._flushPresentationScroll(),40);break;case"addToCardHandler":this._bridge?.send("addToCardResult",t.payload);break;case"cartQuantityHandler":{const a=t.payload;a&&"quantity"in a&&typeof a.quantity=="number"&&(this._cartQuantity=a.quantity);break}case"favoritesCountHandler":{const a=t.payload?.count;typeof a=="number"&&a>=0&&this._drawer?.updateFavoritesBadge(a);break}case"minimizeRequestedByUser":this._extendedModeManager?.setHiddenByUser(!0);break;case"bgColorChange":{const a=t.payload?.color;typeof a=="string"&&Br(a)&&this._shadow&&this._shadow.host.style.setProperty("--gengage-chat-bg",a);break}default:break}}_registerPublicAPI(){window.gengage||(window.gengage={}),window.gengage.chat={open:t=>this.open(t),openWithAction:(t,a)=>this.openWithAction(t,a),sendMessage:t=>this.sendMessage(t),sendAction:(t,a)=>this.sendAction(t,a),close:()=>this.close(),saveSession:(t,a)=>this.saveSession(t,a),get isOpen(){return!1},on:(t,a)=>this.on(t,a),trackCheckout:(t,a)=>this.trackCheckout(t,a),flushMeteringSummary:t=>this.flushMeteringSummary(t),addCallback:(t,a)=>this.addCallback(t,a)},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),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60)}_showWelcomeIfNeeded(){if(this._messages.length!==0)return;const t=this._resolveOpeningContextKey(),a=this._resolveContextualOpeningActions(t);if(a.length>0&&this._drawer?.setPills(a.map(i=>({label:i.title,onAction:()=>this._sendAction(this._resolveContextualOpeningAction(i,t))}))),this._hasDedicatedContextLaunch()||this._shouldPrimeContextualOpening())return;const n=this._resolveContextualOpeningMessage(t);if(!n)return;const r={id:Ra(),role:"assistant",content:n,timestamp:Date.now(),status:"done"};this._messages.push(r),this._drawer?.addMessage(r)}_resolveOpeningContextKey(){switch(this.config.pageContext?.pageType){case"home":return"home";case"search":case"plp":return"listing";case"pdp":return"product";default:return"default"}}_resolveContextualOpeningMessage(t=this._resolveOpeningContextKey()){return this.config.openingMessagesByContext?.[t]??(t!=="default"?this.config.openingMessagesByContext?.default:void 0)??this.config.welcomeMessage}_resolveContextualOpeningGuidance(t=this._resolveOpeningContextKey()){return this.config.openingGuidanceByContext?.[t]??(t!=="default"?this.config.openingGuidanceByContext?.default:void 0)}_resolveContextualOpeningActions(t=this._resolveOpeningContextKey()){const a=this.config.welcomeActionsByContext?.[t]??(t!=="default"?this.config.welcomeActionsByContext?.default:void 0);return a?.length?a.filter(n=>typeof n?.title=="string"&&n.title.trim().length>0):(this.config.welcomeActions??[]).filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>({title:n}))}_resolveContextualOpeningAction(t,a=this._resolveOpeningContextKey()){const n=t.title.trim(),r=this.config.pageContext?.sku??this._readContextStringField("sku"),i=this._readContextStringListField("visible_skus")??[];return t.icon==="review"&&r?{title:n,type:"reviewSummary",payload:{sku:r}}:t.icon==="similar"&&r?{title:n,type:"findSimilar",payload:{sku:r}}:t.icon==="compare"&&a==="listing"&&i.length>=2?{title:n,type:"getComparisonTable",payload:{sku_list:i.slice(0,2)}}:{title:n,type:"user_message",payload:n}}_readContextStringField(t){const a=this.config.pageContext,n=a?.extra&&typeof a.extra=="object"&&!Array.isArray(a.extra)?a.extra:void 0,r=t.replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),i=a?.[t]??n?.[t]??a?.[r]??n?.[r];return typeof i=="string"&&i.trim().length>0?i.trim():void 0}_readContextStringListField(t){const a=this.config.pageContext,n=a?.extra&&typeof a.extra=="object"&&!Array.isArray(a.extra)?a.extra:void 0,r=t.replace(/_([a-z])/g,(s,c)=>c.toUpperCase()),i=a?.[t]??n?.[t]??a?.[r]??n?.[r];if(!Array.isArray(i))return;const o=i.filter(s=>typeof s=="string"&&s.trim().length>0);return o.length>0?o:void 0}_buildEntryOpeningPageDetails(){const t={};t.url=this.config.pageContext?.url??window.location.href;const a=this._readContextStringField("page_title");a&&(t.page_title=a);const n=this._readContextStringField("page_description");n&&(t.page_description=n);const r=this._readContextStringField("search_query");r&&(t.search_query=r);const i=this._readContextStringListField("visible_skus");i?.length&&(t.visible_skus=i);const o=this._readContextStringListField("popular_searches");o?.length&&(t.popular_searches=o);const s=this.config.pageContext?.categoryTree??this._readContextStringListField("category_path");return s?.length&&(t.category_path=s),Object.keys(t).length>0?t:void 0}_hasDedicatedContextLaunch(){const t=this.config.pageContext;return t?!!(t.pageType==="pdp"&&t.sku||t.pageType==="plp"&&t.skuList?.length||t.pageType==="home"):!1}_shouldPrimeContextualOpening(){return this._messages.length!==0||this._entryContextPrimed||this._contextPrimingInFlight||this._hasDedicatedContextLaunch()?!1:!!(this.config.openingMessagesByContext||this.config.openingGuidanceByContext||this.config.welcomeActionsByContext)}_maybePrimeEntryContextOpening(){const t=this._resolveOpeningContextKey();if(!this._shouldPrimeContextualOpening())return;this._entryContextPrimed=!0;const a={text:"",is_entry_context_opening:1,opening_context_key:t},n=this._buildEntryOpeningPageDetails();n&&(a.page_details=n);const r=this._resolveContextualOpeningMessage(t);r&&(a.opening_message=r);const i=this._resolveContextualOpeningGuidance(t);i&&(a.opening_guidance=i),this._sendAction({title:"",type:"user_message",payload:a},{silent:!0,preservePills:!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),this._presentation.setShown(!1),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!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()}}_isMaximizedForHostChrome(){if(!this._drawerVisible)return!1;const t=this.config.variant??"floating";return t==="inline"?!1:t==="overlay"?!0:!(!(this._drawer?.isPanelVisible()??!1)||!this._isMobileViewport&&(this._drawer?.isPanelCollapsed()??!1))}_shouldLockHostDocumentScroll(){if(!this._drawerVisible)return!1;const t=this.config.variant??"floating";return t==="inline"?!1:t==="overlay"||this._isMobileViewport?!0:this._drawer?.isPanelVisible()??!1}_applyOpenStateClasses(){if(!this._rootEl)return;const t=this._drawerVisible&&this._isMobileViewport&&this._openState==="half",a=this._drawerVisible&&this._isMobileViewport&&this._openState==="full",n=this._isMaximizedForHostChrome();if(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",a),this._rootEl.classList.toggle("gengage-chat-root--maximized-host-chrome",n),this._backdropEl){const r=n&&(this.config.variant??"floating")!=="inline";this._backdropEl.setAttribute("aria-hidden",r?"false":"true")}this._syncHostDocumentScrollLock(),this._maybeTrackChatbotMainPaneGa()}_mainPaneExpandedForAnalytics(){const t=this._drawer;return t?.isPanelVisible()?this._isMobileViewport?!0:!t.isPanelCollapsed():!1}_maybeTrackChatbotMainPaneGa(){const t=this._mainPaneExpandedForAnalytics();t&&!this._gaPrevMainPaneExpanded&&bi(),this._gaPrevMainPaneExpanded=t}_syncHostDocumentScrollLock(){if(!(typeof document>"u")){if((this.config.variant??"floating")==="inline"){this._releaseHostDocumentScrollLock();return}this._shouldLockHostDocumentScroll()?this._applyHostDocumentScrollLock():this._releaseHostDocumentScrollLock()}}_hostScrollEventShouldReachChatScroller(t){try{const a=t.composedPath();if(a.length===0)return!0;if(!a.includes(this.root))return!1;for(const n of a){if(n===this.root)break;if(!(n instanceof HTMLElement))continue;if(this._backdropEl&&(n===this._backdropEl||this._backdropEl.contains(n)))return!1;const r=window.getComputedStyle(n),i=(r.overflowY==="auto"||r.overflowY==="scroll")&&n.scrollHeight>n.clientHeight+1,o=(r.overflowX==="auto"||r.overflowX==="scroll")&&n.scrollWidth>n.clientWidth+1;if(i||o)return!0}return!1}catch{return!1}}_applyHostDocumentScrollLock(){if(!(typeof document>"u"||typeof window>"u")){if(!this._hostOverflowRestore){const t=document.documentElement,a=document.body;this._hostOverflowRestore={htmlOverflow:t.style.overflow,bodyOverflow:a?.style.overflow??"",htmlOverscroll:t.style.overscrollBehavior,bodyOverscroll:a?.style.overscrollBehavior??""},t.style.overflow="hidden",t.style.overscrollBehavior="none",a&&(a.style.overflow="hidden",a.style.overscrollBehavior="none"),this._hostScrollLockViewport={x:window.scrollX,y:window.scrollY}}this._hostScrollLockActive||(window.addEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0,passive:!1}),window.addEventListener("wheel",this._preventHostDocumentWheel,{capture:!0,passive:!1}),document.addEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0,passive:!1}),document.addEventListener("wheel",this._preventHostDocumentWheel,{capture:!0,passive:!1}),window.addEventListener("scroll",this._pinHostViewportScroll,{capture:!0,passive:!0}),this._hostScrollLockActive=!0)}}_releaseHostDocumentScrollLock(){if(!(typeof document>"u")&&(typeof window<"u"&&(window.removeEventListener("scroll",this._pinHostViewportScroll,{capture:!0}),window.removeEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0}),window.removeEventListener("wheel",this._preventHostDocumentWheel,{capture:!0})),this._hostScrollLockActive&&(document.removeEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0}),document.removeEventListener("wheel",this._preventHostDocumentWheel,{capture:!0}),this._hostScrollLockActive=!1),this._hostScrollLockViewport=null,this._hostScrollPinning=!1,this._hostOverflowRestore)){const t=document.documentElement,a=document.body;t.style.overflow=this._hostOverflowRestore.htmlOverflow,t.style.overscrollBehavior=this._hostOverflowRestore.htmlOverscroll,a&&(a.style.overflow=this._hostOverflowRestore.bodyOverflow,a.style.overscrollBehavior=this._hostOverflowRestore.bodyOverscroll),this._hostOverflowRestore=null}}_handleAttachment(t){const a=Ki(t);if(!a.ok){Te("gengage:global:error",{message:a.reason==="invalid_type"?this._i18n.invalidFileType:this._i18n.fileTooLarge,source:"chat"});return}this._drawer?.stageAttachment(t)}_sendMessage(t,a){this._contextPrimingInFlight&&(this._abortAllActiveRequests(),this._contextPrimingInFlight=!1,this._queuedUserMessages=[]),yi(),this._messages.some(r=>r.role==="user")||_i(),De("chat","sendMessage",{mode:this._assistantMode,hasAttachment:a!==void 0,textLength:t.length});const n=a!==void 0?{title:t,type:this._modeController.resolveAttachmentActionType(),payload:t?{text:t}:{}}:{title:t,type:"user_message",payload:t};a!==void 0?this._sendAction(n,{attachment:a}):this._sendAction(n)}_flushQueuedUserMessages(){if(this._contextPrimingInFlight||this._queuedUserMessages.length===0)return;const t=[...this._queuedUserMessages];this._queuedUserMessages=[];for(const a of t)this._sendMessage(a.text,a.attachment)}_applyUiHints(){this._modeController.applyUiHints(this._drawer,this._i18n.inputPlaceholder,()=>{this._clearChoicePrompter()})}_handleRedirectMetadata(t){this._modeController.handleRedirect(t)}_sendAction(t,a){if(this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._lastSentAction={action:t,options:a},!this._initComplete){this._pendingActions.length<10&&this._pendingActions.push({action:t,options:a});return}if(this._clearChoicePrompter(),a?.preservePanel||fl(),!a?.preservePanel&&this._comparisonSelectMode&&t.type!=="getComparisonTable"&&(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[]),a?.preservePanel||(this._localPanelHistory=[]),this._currentThreadId&&this._lastThreadId&&this._lastThreadId>this._currentThreadId){const y=this._currentThreadId,E=this._messages.filter(S=>S.threadId!==void 0&&S.threadId>y);this._messages=this._messages.filter(S=>!S.threadId||S.threadId<=y);for(const S of E)this._shadow?.querySelector(`[data-message-id="${_e(S.id)}"]`)?.remove(),this._panel.snapshots.delete(S.id),this._panel.snapshotTypes.delete(S.id);this._shadow?.querySelectorAll("[data-thread-id]")?.forEach(S=>{S instanceof HTMLElement&&S.dataset.threadId&&S.dataset.threadId>y&&S.remove()})}a?.preservePills||this._drawer?.setPills([]),this._drawer?.clearInputAreaChips(),this._bridge?.send("isResponding",!0);const n=Ra();this._currentThreadId=n,this._lastThreadId=n,this._panel&&!Fu.has(t.type)&&(this._panel.lastActionType=t.type);const r=a?.preservePanel===!0,i=a?.silent===!0&&a?.isContextPrime===!0,o=i&&t.type==="launchSingleProduct";if(r||(this._activeRequestThreadId=n),!a?.silent&&!r&&this._drawer?.setPresentationFocus(n),!a?.silent){const y=typeof t.payload=="string"?t.payload:typeof t.payload?.text=="string"?t.payload.text:t.title,E=this._messages.length>0?this._messages[this._messages.length-1]:void 0;if(!(E!==void 0&&E.role==="user"&&E.content===y)){(!this._messages.some(z=>z.role==="user")||this._drawer?.isKvkkBannerVisible())&&(da(this.config.accountId),this._drawer?.hideKvkkBanner());const S=this._createMessage("user",y);S.threadId=n,a?.attachment!==void 0&&(S.attachment=a.attachment),this._drawer?.addMessage(S),a?.attachment!==void 0&&this._modeController.isBeautyConsulting&&this._drawer?.setBeautyPhotoStepCard({visible:!1}),this._messages.push(S)}}if(!a?.silent&&this._assistantMode==="shopping"&&this._hasUnavailableProductContext()&&(t.type==="user_message"||t.type==="inputText")){const y=this._i18n.productNotFoundMessage,E=this._createMessage("assistant",y);E.threadId=n,E.status="done",this._messages.push(E),this._ensureAssistantMessageRendered(E),this._drawer?.updateBotMessage(E.id,y),this._drawer?.setPresentationFocus(n),this._bridge?.send("isResponding",!1),this.emit("message",E),this._persistToIndexedDB().catch(()=>{});return}let s=this._currentPanelSource,c=!1;const l=t.type==="user_message"||t.type==="inputText",g=()=>{c||a?.preservePanel||(s=this._currentPanelSource,c=!0)},p=()=>{if(this._drawer?.isPanelLoading()){if(!l&&s){const y=this._buildRenderContext(),E=this._renderPanelFromSource(s,y);this._drawer.setPanelContent(E),this._drawer.setDividerPreviewEnabled(this._shouldUseDividerPreviewForSource(s)),this._currentPanelSource=s}else this._drawer.clearPanel(),this._currentPanelSource=null;s=null}};t.type==="getComparisonTable"&&(this._drawer?.showPanelLoading("comparisonTable"),this._panel?.updateTopBarForLoading("comparisonTable")),!a?.silent&&!r&&this._pruneEmptyStreamingAssistantPlaceholders(),this._drawer?.showTypingIndicator();let h="";const d=this._createMessage("assistant","");d.threadId=n,d.status="streaming",a?.silent&&(d.silent=!0),this._messages.push(d),this._presentation.registerAssistantActivity(n),this._focusPresentationThread(n,"smooth",a?.silent||r),a?.preservePanel||(this._contextPrimingInFlight&&!i&&(this._contextPrimingInFlight=!1,this._queuedUserMessages=[]),this._abortAllActiveRequests());const b={middlewareUrl:this.config.middlewareUrl,...this.config.accountId?{accountId:this.config.accountId}:{}};a?.attachment!==void 0&&(b.attachment=a.attachment);const u=this._getVisibleMessages().filter(y=>y!==d&&(y.content||y.role==="assistant")).slice(-50).map(y=>({role:y.role==="user"?"user":"model",content:y.content??""})),v={outputLanguage:Ol(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:Bn(this.config.accountId),voiceEnabled:this.config.voiceEnabled??!1,threadId:n,isControlGroup:this.config.session?.abTestVariant==="control",isMobile:this._isMobileViewport};this._modeController.isShopping||(v.assistantMode=this._modeController.mode),this.config.session?.viewId!==void 0&&(v.viewId=this.config.session.viewId);const m=Wo(t,{pageContext:this.config.pageContext,backendContext:this._lastBackendContext,isMobile:this._isMobileViewport}),P={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",type:m.type,locale:wt(this.config.locale),meta:v,context:{...this._lastBackendContext??{},messages:u,session_id:this.config.session?.sessionId??""}};this.config.session?.userId!==void 0&&(P.user_id=this.config.session.userId),this.config.session?.viewId!==void 0&&(P.view_id=this.config.session.viewId),m.payload!==void 0&&(P.payload=m.payload),this.config.pageContext?.sku!==void 0&&(P.sku=this.config.pageContext.sku),this.config.pageContext?.pageType!==void 0&&(P.page_type=this.config.pageContext.pageType);const A=crypto.randomUUID(),k=Date.now();let x=0,N=!1,T=!1,I=!1,$=!1,ae=!1;const oe=Ts();let ve=null,O=null;const f=()=>{if(this._drawer&&!$){if(!I){this._drawer.setPanelAiZoneState("hidden");return}ae?this._drawer.setPanelAiZoneState("hidden"):this._drawer.setPanelAiZoneState("analyzing",{analyzingLabel:this._i18n.aiAnalysisAnalyzingLabel})}},L=y=>{if(!ve||!this._drawer)return;const E=this._buildRenderContext();E.isStreaming=y;const S=this._renderUISpec(ve,E);$=!0,this._drawer.setPanelAiZoneState("results",{resultEl:S}),ve=null},D=(y,E,S)=>{if(y==="ProductGrid"||y==="CategoriesContainer"){I=!0,L(S),f();return}E!=="appendSimilars"&&E!=="append"&&(I=!1,$=!1,ve=null,this._drawer?.setPanelAiZoneState("hidden"))},B=y=>(y==="ProductGrid"||y==="CategoriesContainer")&&(I||$||ve!==null),j=(y,E,S)=>{if(!this._drawer||!this._panel)return;const z=y.elements[y.root];if(S==="ProductGrid"&&z){const M=oa(z);if(M.isConsulting){const R=this._drawer.getPanelContentElement();if(R&&el(R,M,E)){this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._drawer.setComparisonDockContent(null),this._currentPanelSource={kind:"spec",spec:y},this._panel.currentType=S,this._drawer.resyncPanelTopBarFromCurrentContent();return}}}this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._drawer.setComparisonDockContent(null),this._drawer.setPanelContent(this._renderUISpec(y,E),{preserveAiZone:B(S)}),this._currentPanelSource={kind:"spec",spec:y},this._panel.currentType=S},Z=(y,E,S,z)=>{if(!this._panel)return;this._drawer?.setDividerPreviewEnabled((this._panel.currentType??y)==="ProductGrid"),y==="ProductDetailsPanel"&&t.type==="launchSingleProduct"&&this._clearUnavailableProductContext(),d.threadId&&!this._panel.threads.includes(d.threadId)&&this._panel.threads.push(d.threadId);const M=this._panel.currentType??y,R=E?.props?.panelTitle;this._panel.updateTopBar(M,R),this._panel.updateExtendedMode(y),this._isMobileViewport&&o&&this._drawer?.hideMobilePanel(),D(y,S,z)};this.track($r(this.analyticsContext(),{endpoint:"process_action",request_id:A,widget:"chat"}));let q=null;if(q=Jo(P,{onTextChunk:(y,E,S)=>{if(!r&&n!==this._activeRequestThreadId||(h+=y,this._drawer?.removeTypingIndicator(),S?.skuToProductItem&&(this._skuToProductItem={...this._skuToProductItem,...S.skuToProductItem}),S?.conversationMode&&(this._conversationMode=S.conversationMode),S?.renderHint&&(d.renderHint=S.renderHint),this.track(Hr(this.analyticsContext(),{request_id:A,chunk_index:x++,widget:"chat"})),!this._drawer))return;let z=h;const M=S?.kvkk===!0||o&&ga(z);if(E&&M){const H=this.config.accountId;if(!Bn(H)){const ne=Rl(z);ne?this._drawer?.showKvkkBanner(ne,()=>{this._drawer?.hideKvkkBanner(),da(H)}):da(H)}z=Bl(z)}const R=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(R?R.innerHTML=Ae(z):(d.content=z,d.role==="assistant"&&d.threadId&&!this._threadsWithFirstBot.has(d.threadId)&&(this._threadsWithFirstBot.add(d.threadId),this._drawer.markFirstBotMessage(d.id)),this._drawer.addMessage(d)),E)if(d.content=z,d.status="done",La(),Is(d))this._drawer?.updateBotMessage(d.id,z,"photo_analysis",d.photoAnalysis),d.threadId&&this._focusPresentationThread(d.threadId,"auto");else{const H=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(H){this._activeTypewriter?.cancel();const ne=S?.productMentions;this._activeTypewriter=ll({container:H,html:Ae(z),onTick:()=>this._drawer?.scrollToBottomIfNeeded(),onComplete:()=>{this._activeTypewriter=null,ne&&ne.length>0&&H&&gl({container:H,mentions:ne,onProductClick:te=>{this._sendAction({title:ne.find(U=>U.sku===te)?.short_name??te,type:"launchSingleProduct",payload:{sku:te}})}})}})}}},onUISpec:(y,E,S,z)=>{if(!r&&n!==this._activeRequestThreadId||E!=="chat")return;z&&(this._clearAssistantPanelLikeStreamClearPanel(),N=!1,O=null);const M=y.elements[y.root],R=M?.type??"unknown";if(Ls(R,M?.props??{},oe,{drawer:this._drawer,ensureRendered:()=>this._ensureAssistantMessageRendered(d),cancelTypewriter:()=>{this._activeTypewriter?.cancel(),this._activeTypewriter=null},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:ae},d)){R==="PhotoAnalysisCard"&&d.threadId&&this._focusPresentationThread(d.threadId,"auto");return}const H=Ea(M),ne=this.config.productDetailsExtended!==!0&&(R==="ProductDetailsPanel"||H);ne&&!z&&(this._clearAssistantPanelLikeStreamClearPanel(),N=!1);const te=R==="ProductDetailsPanel"&&S!=="panel"?"panel":S;this.track(Ur(this.analyticsContext(),{request_id:A,chunk_index:x,component_type:R,widget:"chat"}));const U=this._buildRenderContext();if(U.isStreaming=!0,R==="ComparisonTable"){const V=M?.props?.products;pi(Array.isArray(V)?V.length:0)}if(R==="ProductGrid"){const V=M?.children?.length??0;mi(void 0,V)}const ce=te==="panel"&&this._panel?this._panel.toPanelSpec(y):y;if(te==="panel"&&this._panel&&!ne&&R==="ProductGrid"&&M){const V=oa(M);if(V.isConsulting&&!Qc(V)){O=y;return}V.isConsulting&&(O=null)}if(te==="panel"&&this._panel&&!ne){const V=!T;T=!0;const Y=M?.props?.replacePanel===!0?"replace":Sl({componentType:R,similarsAppend:M?.props?.similarsAppend===!0,currentPanelType:this._panel.currentType,hasPanelContent:this._drawer?.hasPanelContent()??!1,isPanelLoading:this._drawer?.isPanelLoading()??!1,isFirstPanelContentInStream:V});U.panelProductListHeading=void 0,R==="ProductGrid"&&(Y==="appendSimilars"?U.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products":this._applyPanelListHeadingToContext(U,{kind:"spec",spec:ce})),Y==="appendSimilars"?this._appendSimilarsToPanel(ce,U):Y==="append"?(this._drawer?.appendPanelContent(this._renderUISpec(ce,U)),this._comparisonSelectMode&&this._refreshComparisonUI()):j(ce,U,R),Z(R,M,Y,!0)}if(R==="ProductDetailsPanel"&&te==="panel"&&(!d.silent||o)){const V=M?.props?.product;if(V){const Y={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:V}}}},me=this._shadow?.querySelector(".gengage-chat-messages");if(me){const J=this._renderUISpec(Y,U);d.threadId&&(J.dataset.threadId=d.threadId);const ie=this._shadow?.querySelector(`[data-message-id="${d.id}"]`);ie&&ie.parentNode===me?ie.after(J):me.appendChild(J),this._scrollInlineIntoView(J,d.threadId),this._drawer?.refreshPresentationCollapsed(),T=!0}}}const Q=R==="AITopPicks"||R==="AIGroupingCards",$e=R==="ActionButtons"?M?.props?.buttons:void 0,xt=R==="ActionButtons"&&this._modeController.mode!=="shopping"&&Array.isArray($e)&&$e.length>0&&$e.every(V=>V.action?.type==="inputText");let C=!1,K=!1;if(ne&&H&&(U.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products"),Q&&(!d.silent||i))if(I){const V=this._renderUISpec(y,U);$=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:V}),C=!0,ve=null}else ve=y,K=!0;const pe=i&&(R==="GroundingReviewCard"||Q);if(!Q&&(!d.silent||pe)&&(te!=="panel"||R==="ProductCard"||ne&&R==="ProductGrid"&&!H)&&(R!=="ActionButtons"||xt)&&!C&&!(K&&Q)){const V=this._shadow?.querySelector(".gengage-chat-messages");if(V){const Y=this._renderUISpec(y,U);d.threadId&&(Y.dataset.threadId=d.threadId),V.appendChild(Y),this._scrollInlineIntoView(Y,d.threadId),this._drawer?.refreshPresentationCollapsed(),ne&&R==="ProductGrid"&&(T=!0)}}if((R==="ProductGrid"||R==="ProductCard")&&d.threadId){const V=M?.children??[],Y=R==="ProductGrid"?V.map(me=>y.elements[me]?.props?.product).filter(Boolean):[M?.props?.product].filter(Boolean);for(const me of Y){const J=me.sku,ie=me.imageUrl;J&&ie&&this._thumbnailEntries.push({sku:J,imageUrl:ie,threadId:d.threadId}),J&&this._viewedProductSkus.add(J)}this._drawer?.setThumbnails(this._thumbnailEntries)}if(R==="ProductGrid"||R==="ProductDetailsPanel"){const V=(R==="ProductGrid"?(M?.children??[]).map(Y=>y.elements[Y]?.props?.product).filter(Boolean):[M?.props?.product??M?.props].filter(Boolean)).map(Y=>Y.imageUrl).filter(Y=>typeof Y=="string").slice(0,5);V.length>0&&this._bridge?.send("previewImages",{images:V})}const ue=M?.children?.length??0;if(R==="ProductGrid"&&te==="panel"&&!ne&&ue>1&&!this._modeController.isChoicePrompterHidden&&!this._comparisonSelectMode&&!bl(this._currentThreadId??"")&&(this._clearChoicePrompter(),this._choicePrompterEl=ml({heading:this._i18n.choicePrompterHeading,suggestion:this._i18n.choicePrompterSuggestion,ctaLabel:this._i18n.choicePrompterCta,threadId:this._currentThreadId??"",dismissAriaLabel:this._i18n.dismissAriaLabel,onCtaClick:()=>{this._comparisonSelectMode=!0,this._choicePrompterEl=null,this._refreshComparisonUI()},onDismiss:()=>{this._choicePrompterEl=null}}),this._mountChoicePrompter()&&this._isMobileViewport&&window.visualViewport)){const V=this._choicePrompterEl,Y=()=>{window.visualViewport.height/window.innerHeight<.75&&(V.remove(),this._choicePrompterEl===V&&(this._choicePrompterEl=null),window.visualViewport.removeEventListener("resize",Y))};window.visualViewport.addEventListener("resize",Y)}if(R==="ActionButtons"){const V=M?.props?.buttons;if(V&&V.length>0&&!xt){const Y=[],me=[];for(const J of V)if(hl(J)){const ie={label:J.label,action:J.action};J.icon&&(ie.icon=J.icon),Y.push(ie)}else me.push(J);Y.length>0&&this._drawer?.setInputAreaChips(Y.map(J=>({label:J.label,onAction:()=>this._sendAction(J.action),...J.icon?{icon:J.icon}:{}}))),me.length>0&&this._drawer?.setPills(me.map(J=>{const ie={label:J.label,onAction:()=>this._sendAction(J.action)};return J.icon&&(ie.icon=J.icon),J.image&&(ie.image=J.image),J.description&&(ie.description=J.description),ie}))}}f(),d.uiSpec=y},onAction:y=>{if(!(!r&&n!==this._activeRequestThreadId)&&y.type==="action"){const E={};this.config.actionHandling?.unknownActionPolicy!==void 0&&(E.unknownActionPolicy=this.config.actionHandling.unknownActionPolicy),this.config.actionHandling?.allowScriptCall!==void 0&&(E.allowScriptCall=this.config.actionHandling.allowScriptCall),qi(y,{openChat:()=>this.open(),navigate:S=>{ye(S.url)&&(this._bridge?.send("navigate",S),S.newTab?window.open(S.url,"_blank","noopener,noreferrer"):window.location.href=S.url)},saveSession:S=>this.saveSession(S.sessionId,S.sku),addToCart:S=>{Te("gengage:similar:add-to-cart",S)},scriptCall:S=>{Te("gengage:chat:script-call",S),this.config.onScriptCall?.(S)}},E)}},onMetadata:y=>{if(!(!r&&n!==this._activeRequestThreadId)&&y.type==="metadata"&&y.meta){if(y.meta.panel!==void 0||y.meta.messages!==void 0||y.meta.message_id!==void 0){this._lastBackendContext=y.meta;const S=Yt(y.meta.panel);S&&(this._modeController.updateFromContext(S),this._applyUiHints())}if(y.meta.panelLoading){const S=typeof y.meta.panelPendingType=="string"?y.meta.panelPendingType:void 0;this.config.productDetailsExtended!==!0&&(S==="productDetails"||S==="productDetailsSimilars")||(N=!0,T=!1,g(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(S),S&&this._panel?.updateTopBarForLoading(S))}if(y.meta.voice){const S=new CustomEvent("gengage:chat:voice",{detail:{payload:y.meta.voice},bubbles:!1,cancelable:!0}),z=window.dispatchEvent(S);if(xi(),z){const M=y.meta.voice;M.audio_base64&&(this._activeTtsHandle?.stop(),this._activeTtsHandle=rl(M.audio_base64,M.content_type??"audio/ogg"))}}if((y.meta.redirectTarget||y.meta.redirect)&&(Te("gengage:chat:redirect",{target:y.meta.redirectTarget??null,payload:y.meta.redirect??null}),De("redirect","redirect dispatched",{target:y.meta.redirectTarget??null}),this._handleRedirectMetadata(y.meta.redirect)),y.meta.analyzeAnimation&&this.config.productDetailsExtended===!0&&(N=!0,T=!1,g(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(),this._panel?.updateTopBarForLoading("productDetails")),y.meta.loading){const S=Array.isArray(y.meta.thinkingMessages)?y.meta.thinkingMessages.filter(M=>typeof M=="string"):[],z=typeof y.meta.loadingText=="string"?y.meta.loadingText:void 0;if(S.length>0){const M=z&&this._modeController.shouldCondenseThinking()?[...S.slice(0,2),z]:S;this._drawer?.setThinkingSteps(M)}typeof z=="string"&&z.length>0&&(this._drawer?.addThinkingStep(z),this._bridge?.send("loadingMessage",{text:z}))}y.meta.visitorDataResponse&&this._bridge?.send("engagingMessage",y.meta.visitorDataResponse),y.meta.formType&&this._bridge?.send("glovOtokoc",{type:y.meta.formType,data:y.meta.formPayload}),y.meta.launcherContent&&this._bridge?.send("launcherContent",y.meta.launcherContent),Te("gengage:chat:metadata",{payload:y.meta});const E=y.meta;typeof E.prompt_tokens=="number"&&typeof E.completion_tokens=="number"&&this.track(qr(this.analyticsContext(),{model:y.model??"unknown",prompt_tokens:E.prompt_tokens,completion_tokens:E.completion_tokens,total_tokens:E.total_tokens??E.prompt_tokens+E.completion_tokens}))}},onError:y=>{if(q&&this._abortControllers.delete(q),!r&&n!==this._activeRequestThreadId)return;ae=!0,this._activeTypewriter?.cancel(),this._activeTypewriter=null,f(),ve=null,O=null,this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),this._drawer?.clearInputAreaChips(),zs(oe,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const E=T;N&&!T&&p(),N=!1,T=!1;const S=d.content!=null&&d.content.length>0||h.length>0||E,z=d.silent||S,M=typeof navigator<"u"&&navigator.onLine===!1&&Ba(y),R=()=>{this._shadow?.querySelector(`[data-message-id="${_e(d.id)}"]`)?.remove();const te=this._messages.indexOf(d);te>=0&&this._messages.splice(te,1)};let H=!1;const ne=()=>{if(M)return;this.emit("error",y);const te=y.message;te===this._lastErrorMessage?this._consecutiveErrorCount++:(this._consecutiveErrorCount=1,this._lastErrorMessage=te);const U=y.message.trim(),ce=U.length>0?U:this._i18n.errorMessage,Q={onRetry:()=>{this._lastSentAction&&this._sendAction(this._lastSentAction.action,this._lastSentAction.options)},onNewQuestion:()=>{this._drawer?.focusInput()}};if(this._consecutiveErrorCount>=2){R(),H=!0,this._drawer?.showErrorWithRecovery(this._i18n.accountInactiveMessage,Q);return}if(Nl(y,ce)){R(),H=!0,this._drawer?.showErrorWithRecovery(ce,Q);return}d.content=ce,d.status="done";const $e=Ae(ce.replace(/\r\n/g,`
177
177
  `).split(`
178
178
  `).join("<br />"));this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,$e),this._drawer?.showRecoveryPillsOnly(Q)};if(i&&!S)if(o||this._hasUnavailableProductContext()){this._drawer?.setPills([]);const te=this._i18n.productNotFoundMessage;d.content=te,d.status="done",this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,te),this._markUnavailableProductContext()}else d.status="done";else if(z)this._drawer?.setPills([]),d.silent||ne();else if(ne(),M)return;i&&(this._contextPrimingInFlight=!1,this._flushQueuedUserMessages()),!H&&d.status==="streaming"&&(d.status="error"),M||this.track(Zr(this.analyticsContext(),{request_id:A,error_code:"STREAM_ERROR",error_message:y.message,widget:"chat"}))},onDone:()=>{if(q&&this._abortControllers.delete(q),!r&&n!==this._activeRequestThreadId)return;if(ae=!0,O&&this._panel&&this._drawer){const z=this._buildRenderContext();z.isStreaming=!1;const M=O.elements[O.root],R=this._panel.toPanelSpec(O);this._applyPanelListHeadingToContext(z,{kind:"spec",spec:R});const H=M?.type??"ProductGrid";j(R,z,H),Z(H,M,"replace",!1),T=!0}O=null,ve&&L(!1),f(),this._activeRequestThreadId=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),Ns(oe,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const y=T;if(N&&!T&&p(),N=!1,o&&!h&&!y){const z=this._i18n.productNotFoundMessage;d.content=z,this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,z),this._markUnavailableProductContext()}if(T=!1,i){this._contextPrimingInFlight=!1;const z=this._queuedUserMessages.length>0;this._flushQueuedUserMessages(),!z&&o&&this._ensurePdpPrimeSuggestedUiIfNeeded()}d.status==="streaming"&&(d.status="done",La()),this._presentation.finalizeAssistantGroup(n);const E=this._shadow?.querySelector(".gengage-chat-comparison-toggle-btn--hidden");E&&(E.classList.remove("gengage-chat-comparison-toggle-btn--hidden"),E.classList.add("gengage-chat-comparison-toggle-btn--reveal")),this.emit("message",d);const S=this._currentPanelSource;this._panel?.snapshotForMessage(d.id,S?()=>{const z=this._buildRenderContext();return this._renderPanelFromSource(S,z)}:void 0),this.track(jr(this.analyticsContext(),{request_id:A,latency_ms:Date.now()-k,chunk_count:x,widget:"chat"})),this.track(Vr(this.analyticsContext(),{meter_key:"chat_request",quantity:1,unit:"request"})),this.track(Wr(this.analyticsContext(),{message_count:this._messages.length,history_ref:this.config.session?.sessionId??"",redaction_level:"none"})),this._persistToIndexedDB().catch(()=>{})}},b),this._abortControllers.add(q),!a?.silent&&!r){const y=q;this._drawer?.showStopButton(()=>{y.abort(),this._abortControllers.delete(y),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(n=>!n.silent);if(!this._currentThreadId)return t;const a=this._currentThreadId;return t.filter(n=>!n.threadId||n.threadId<=a)}_appendSimilarsToPanel(t,a){if(!this._drawer)return;const n=this._drawer.getPanelContentElement();if(!n)return;a.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products";const r=this._renderUISpec(t,a);r.classList.add("gengage-chat-product-details-similars"),n.appendChild(r),this._mergePanelSourceWithSimilars(t)}_coerceSkuKey(t){return typeof t=="string"?t.trim():typeof t=="number"&&Number.isFinite(t)?String(t).trim():""}_productSkuKey(t){return t?this._coerceSkuKey(t.sku):""}_pdpPageContextSkuKey(){const t=this.config.pageContext?.pageType;return typeof t!="string"||t.toLowerCase()!=="pdp"?null:this._coerceSkuKey(this.config.pageContext?.sku)||null}_getCurrentPanelProductSku(){const t=this._currentPanelSource;if(!t)return null;let a=null;if(t.kind==="spec"?a=t.spec:t.kind==="productDetailsWithSimilars"&&(a=t.pdpSpec),!a)return null;const n=a.elements[a.root];if(!n||n.type!=="ProductDetailsPanel")return null;const r=n.props,i=r?.product??r;return i&&this._coerceSkuKey(i.sku)||null}_activeSkuForProductSummaryClick(){const t=this._getCurrentPanelProductSku();return t||this._pdpPageContextSkuKey()}_mergePanelSourceWithSimilars(t){const a=this._currentPanelSource;a?.kind==="spec"&&this._panel?.currentType==="ProductDetailsPanel"&&(this._currentPanelSource={kind:"productDetailsWithSimilars",pdpSpec:a.spec,similarsSpec:t})}_renderProductDetailsWithSimilars(t,a,n){this._applyPanelListHeadingToContext(n,{kind:"productDetailsWithSimilars",pdpSpec:t,similarsSpec:a});const r=this._renderUISpec(t,n),i=this._renderUISpec(a,n);return i.classList.add("gengage-chat-product-details-similars"),r.appendChild(i),r}_applyPanelListHeadingToContext(t,a){if(t.panelProductListHeading=void 0,!!this._panel){if(a.kind==="spec"){const n=a.spec.elements[a.spec.root];n?.type==="ProductGrid"&&(n.children?.length??0)>0&&(t.panelProductListHeading=this._panel.titleForComponent("ProductGrid",n.props?.panelTitle??void 0))}else if(a.kind==="productDetailsWithSimilars"){const n=a.similarsSpec.elements[a.similarsSpec.root];n?.type==="ProductGrid"&&(n.children?.length??0)>0&&(t.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products")}}}_renderPanelFromSource(t,a){return this._applyPanelListHeadingToContext(a,t),t.kind==="favorites"?this._buildFavoritesPageEl():t.kind==="productDetailsWithSimilars"?this._renderProductDetailsWithSimilars(t.pdpSpec,t.similarsSpec,a):this._renderUISpec(t.spec,a)}_handleRollback(t){const a=this._messages.find(n=>n.id===t);a?.threadId&&this._rollbackToThread(a.threadId)}_ensurePdpPrimeSuggestedUiIfNeeded(){const t=this.config.pageContext?.sku;if(!t||!this._drawer||this._hasUnavailableProductContext())return;const a="product",n=this._resolveContextualOpeningActions(a);if(n.length>0){this._drawer.setInputAreaChips(n.map(r=>({label:r.title,onAction:()=>this._sendAction(this._resolveContextualOpeningAction(r,a)),...r.icon?{icon:r.icon}:{}})));return}this._drawer.setInputAreaChips([{label:this._i18n.groundingReviewCta,icon:"review",onAction:()=>this._sendAction({title:this._i18n.customerReviewsTitle,type:"reviewSummary",payload:{sku:t}})},{label:this._i18n.findSimilarLabel,icon:"similar",onAction:()=>this._sendAction({title:this._i18n.findSimilarLabel,type:"findSimilar",payload:{sku:t}})}])}_rollbackToThread(t){if(this._panel&&this._panel.threads.length>0&&!this._panel.threads.includes(t)&&!this._messages.some(i=>i.threadId===t))return;this._currentThreadId=t,this._extendedModeManager?.setHiddenByUser(!1),this._lastThreadId!=null&&t===this._lastThreadId?(this._presentation.setFocusedThreadId(t),this._drawer?.setPresentationFocus(t)):(this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null)),this._drawer?.setFormerMessagesButtonVisible(!1);for(const i of this._messages){const o=this._shadow?.querySelector(`[data-message-id="${_e(i.id)}"]`);o&&(i.threadId&&i.threadId>t?o.classList.add("gengage-chat-bubble--hidden"):o.classList.remove("gengage-chat-bubble--hidden"))}this._shadow?.querySelectorAll("[data-thread-id]").forEach(i=>{i instanceof HTMLElement&&i.dataset.threadId&&i.dataset.threadId>t?i.classList.add("gengage-chat-bubble--hidden"):i instanceof HTMLElement&&i.classList.remove("gengage-chat-bubble--hidden")});const a=this._messages.find(i=>i.role==="assistant"&&i.threadId===t),n=a?this._panel?.restoreForMessage(a.id):!1;n||(this._drawer?.clearPanel(),this._currentPanelSource=null),n&&a&&(this._currentPanelSource=null);const r=this._panel.currentType??"";if(this._panel?.updateTopBar(r),this._drawer?.setPills([]),requestAnimationFrame(()=>{this._drawer?.scrollThreadIntoView(t,"auto")}),this._session?.db&&this.config.session?.sessionId){const i=this.config.session.sessionId;(async()=>{try{const o=await this._session?.db?.loadContext(i,t);o&&(this._lastBackendContext=o.context),await this._session?.db?.deleteContextsAfterThread(i,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="${_e(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,a){return this._session?this._session.loadPayload(t,a):null}async _restoreFromIndexedDB(t){if(!this._session?.db)return;const a=this.config.session?.sessionId;if(!a)return;const n=this.config.session?.userId??"",r=this.config.accountId;if(await this._session.loadFavorites(n,r),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size),!t)return;const i=await this._session.db?.loadSession(n,r,a);if(!i||i.messages.length===0)return;const o=this.config.pageContext?.sku;if(o&&i.sku&&i.sku!==o)return;if(this._pdpLaunched=!0,this._drawer?.lockScrollForRestore(),this._currentThreadId=i.currentThreadId,this._lastThreadId=i.lastThreadId,this._currentThreadId&&this._lastThreadId&&this._currentThreadId>this._lastThreadId&&(this._currentThreadId=this._lastThreadId),this._chatCreatedAt=i.createdAt,i.panelThreads&&(this._panel.threads=i.panelThreads),i.thumbnailEntries&&(this._thumbnailEntries=i.thumbnailEntries,this._drawer?.setThumbnails(this._thumbnailEntries)),i.panelSnapshotHtml)for(const[c,l]of Object.entries(i.panelSnapshotHtml)){const g=document.createElement("div");g.innerHTML=Ae(l),this._panel.snapshots.set(c,g)}let s=0;for(const c of i.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 p=await this._loadPayload(l.threadId,l.id);p&&(l.uiSpec=p,this._restoreInlineUISpec(l),delete l.uiSpec)}}if(s>this._currentMessageId&&(this._currentMessageId=s),this._currentThreadId){let c=await this._session.db?.loadContext(a,this._currentThreadId);c||(c=await this._session.db?.loadLatestContext(a)),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="${_e(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 p=g.elements[g.root];p&&this._panel?.updateTopBar(p.type)}}}}this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null),setTimeout(()=>{this._drawer?.scrollToLastThread()},550)}_navigatePanelBack(){const t=this._localPanelHistory.pop();if(t){const a=this._buildRenderContext(),n=this._renderPanelFromSource(t.source,a);this._drawer?.setPanelContent(n),this._drawer?.setDividerPreviewEnabled(this._shouldUseDividerPreviewForSource(t.source)),this._currentPanelSource=t.source;const r=this._localPanelHistory.length>0||(this._panel?.threads.length??0)>1;this._drawer?.updatePanelTopBar(r,!1,t.title);return}if(this._isMobileViewport){this._drawer?.hideMobilePanel();return}this._panel?.navigateBack()}_shouldUseDividerPreviewForSpec(t){return t.elements[t.root]?.type==="ProductGrid"}_shouldUseDividerPreviewForSource(t){return t?.kind==="spec"?this._shouldUseDividerPreviewForSpec(t.spec):!1}_toggleComparisonSku(t){if(t==="")this._comparisonSelectMode=!this._comparisonSelectMode,this._comparisonSelectionWarning=null,this._comparisonSelectMode&&(vl(this._currentThreadId??""),this._clearChoicePrompter()),this._comparisonSelectMode||(this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,di());else if(this._comparisonSelectedSkus.indexOf(t)>=0)this._comparisonSelectedSkus=this._comparisonSelectedSkus.filter(a=>a!==t),this._comparisonSelectionWarning=null;else{if(this._comparisonSelectedSkus.length>=gt._MAX_COMPARISON_SELECTION){this._comparisonSelectionWarning=this._i18n.compareMaxHint??`You can select up to ${gt._MAX_COMPARISON_SELECTION} products`,this._comparisonRefreshRafId!==null&&cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=requestAnimationFrame(()=>{this._comparisonRefreshRafId=null,this._refreshComparisonUI()});return}this._comparisonSelectedSkus=[...this._comparisonSelectedSkus,t],this._comparisonSelectionWarning=null,li(t)}this._comparisonRefreshRafId!==null&&cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=requestAnimationFrame(()=>{this._comparisonRefreshRafId=null,this._refreshComparisonUI()})}_refreshComparisonUI(){const t=this._shadow?.querySelector(".gengage-chat-panel");if(!t){this._drawer?.setComparisonDockContent(null);return}const a=t.querySelector(".gengage-chat-product-grid-wrapper"),n=a?.querySelector(".gengage-chat-product-grid");if(!a||!n){this._drawer?.setComparisonDockContent(null);return}const r=a.querySelector(".gengage-chat-comparison-toggle-btn");if(r&&r.classList.toggle("gengage-chat-comparison-toggle-btn--active",this._comparisonSelectMode),this._comparisonSelectMode){const i=n.querySelectorAll(".gengage-chat-product-card[data-sku]");for(const o of i){if(o.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){const d=o.parentElement,b=this._comparisonSelectedSkus.includes(o.dataset.sku);d.classList.toggle("gengage-chat-comparison-select-wrapper--selected",b);const u=d.querySelector(".gengage-chat-comparison-checkbox");if(u){u.dataset.selected=b?"true":"false",u.setAttribute("aria-pressed",b?"true":"false");const v=u.querySelector(".gengage-chat-comparison-checkbox-icon"),m=u.querySelector(".gengage-chat-comparison-checkbox-label");v&&(v.innerHTML=b?'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>':'<span class="gengage-chat-comparison-checkbox-dot"></span>'),m&&(m.textContent=b?this._i18n.comparisonSelectedLabel??"Selected":this._i18n.comparisonSelectLabel??"Select to compare")}continue}const s=o.dataset.sku,c=document.createElement("div");c.className="gengage-chat-comparison-select-wrapper";const l=this._comparisonSelectedSkus.includes(s);l&&c.classList.add("gengage-chat-comparison-select-wrapper--selected");const g=document.createElement("button");g.type="button",g.className="gengage-chat-comparison-checkbox",g.dataset.selected=l?"true":"false",g.setAttribute("aria-pressed",l?"true":"false");const p=document.createElement("span");p.className="gengage-chat-comparison-checkbox-icon",p.innerHTML=l?'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>':'<span class="gengage-chat-comparison-checkbox-dot"></span>';const h=document.createElement("span");h.className="gengage-chat-comparison-checkbox-label",h.textContent=l?this._i18n.comparisonSelectedLabel??"Selected":this._i18n.comparisonSelectLabel??"Select to compare",g.appendChild(p),g.appendChild(h),g.addEventListener("click",d=>{d.stopPropagation(),this._toggleComparisonSku(s)}),o.parentNode.insertBefore(c,o),c.appendChild(g),c.appendChild(o),c.classList.add("gds-clickable"),c.addEventListener("click",d=>{d.target.closest(".gengage-chat-comparison-checkbox")||(d.stopPropagation(),this._toggleComparisonSku(s))})}}else{const i=n.querySelectorAll(".gengage-chat-comparison-select-wrapper");for(const o of i){const s=o.querySelector(".gengage-chat-product-card");s&&o.parentNode&&(o.parentNode.insertBefore(s,o),o.remove())}}if(a.querySelector(".gengage-chat-comparison-floating-btn")?.remove(),this._comparisonSelectMode){const i=dn(this._comparisonSelectedSkus,this._buildRenderContext());this._isMobileViewport?this._drawer?.setComparisonDockContent(i):(this._drawer?.setComparisonDockContent(null),a.appendChild(i))}else this._drawer?.setComparisonDockContent(null)}_clearChoicePrompter(){this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(t=>t.remove())}_mountChoicePrompter(){if(!this._choicePrompterEl)return!1;if(this._isMobileViewport)return this._drawer?.setComparisonDockContent(this._choicePrompterEl),!0;const t=this._shadow?.querySelector(".gengage-chat-panel-float");return t?(t.appendChild(this._choicePrompterEl),!0):(this._choicePrompterEl=null,!1)}_parseAddToCartActionPayload(t){if(typeof t!="object"||t===null)return null;const a=t,n=this._coerceAddToCartString(a.sku),r=this._coerceAddToCartString(a.cartCode??a.cart_code);let i=1;return typeof a.quantity=="number"&&Number.isFinite(a.quantity)&&a.quantity>0&&(i=Math.max(1,Math.floor(a.quantity))),!n||!r?null:{sku:n,cartCode:r,quantity:i}}_coerceAddToCartString(t){return typeof t=="string"&&t.length>0?t:typeof t=="number"&&Number.isFinite(t)?String(t):""}_runChatAddToCartFlow(t){if(this.config.onAddToCart!==void 0)try{const r=this.config.onAddToCart(t);r instanceof Promise&&r.catch(i=>console.error("[gengage] onAddToCart",i))}catch(r){console.error("[gengage] onAddToCart",r)}vi(t.sku,t.quantity);const a={...t,sessionId:this.config.session?.sessionId??null};Te("gengage:chat:add-to-cart",a),this._bridge?.send("addToCart",t),this._runEventCallbacks("gengage-cart-add",a),this.track(Kr(this.analyticsContext(),{attribution_source:"chat",attribution_action_id:crypto.randomUUID(),cart_value:0,currency:this.config.pricing?.currencyCode??"TRY",line_items:t.quantity,sku:t.sku})),this._sendAction({title:this._i18n.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:t.sku,cart_code:t.cartCode,quantity:t.quantity}},{preservePanel:!0});const n=this._i18n.addedToCartToast??"Added to cart";this._drawer?.showCartToast(n),this._drawer?.flashCartBadge()}_buildRenderContext(){const t={locale:wt(this.config.locale),onAction:a=>{if(si(a.title,a.type),a.type==="addToCart"){const r=this._parseAddToCartActionPayload(a.payload);if(r){this._runChatAddToCartFlow(r);return}}if(a.type==="launchSingleProduct"){this._drawer?.setDividerPreviewEnabled(!1);const r=typeof a.payload=="object"&&a.payload!==null&&"sku"in a.payload?a.payload.sku:void 0,i=this._coerceSkuKey(r),o=this._activeSkuForProductSummaryClick();if(i&&o&&i===o)return;i&&Ta(i,a.title)}if(a.type==="findSimilar"){const r=typeof a.payload=="object"&&a.payload!==null&&"sku"in a.payload?String(a.payload.sku):"";ci(r)}if(a.type==="getComparisonTable"){const r=a.payload,i=r&&typeof r=="object"?r:null,o=i&&typeof i.gengage_analytics_source=="string"?i.gengage_analytics_source:"";let s=[];i&&Array.isArray(i.sku_list)&&(s=i.sku_list.filter(c=>typeof c=="string")),o==="floating_compare_dock"?fi(s):gi(s.length>0?s:this._comparisonSelectedSkus)}const n=a.type==="addToCart"||a.type==="like";this._sendAction(a,n?{preservePanel:!0}:void 0)},onProductClick:a=>{const n=this.config.isDemoWebsite!==!0&&this._isSameOriginUrl(a.url);if(!n){const r=this._coerceSkuKey(a.sku),i=this._activeSkuForProductSummaryClick();if(r&&i&&r===i)return}if(n)Te("gengage:similar:product-click",{sku:a.sku,url:a.url,sessionId:this.config.session?.sessionId??null,...a.name!==void 0&&a.name!==""?{productName:a.name}:{}}),this._saveSessionAndOpenURL(a.url);else{Ta(a.sku);const r=a.name?.trim()?a.name.trim():a.sku;this._sendAction({title:r,type:"launchSingleProduct",payload:{sku:a.sku}})}},onAddToCart:a=>{this._runChatAddToCartFlow(a)},onProductSelect:a=>{const n=this._productSkuKey(a),r=this._activeSkuForProductSummaryClick();if(n&&r&&n===r)return;if(this._currentPanelSource){const l=this._drawer?.getPanelTopBarTitle()??"";this._localPanelHistory.push({source:this._currentPanelSource,title:l}),this._localPanelHistory.length>gt._MAX_PANEL_HISTORY&&this._localPanelHistory.shift()}const i=this._buildRenderContext(),o={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:a}}}},s=this._shadow?.querySelector(".gengage-chat-messages");if(s){const l=this._renderUISpec(o,i);this._currentThreadId&&(l.dataset.threadId=this._currentThreadId),s.appendChild(l),this._scrollInlineIntoView(l,this._currentThreadId),this._drawer?.refreshPresentationCollapsed()}if(this.config.productDetailsExtended!==!0){this._clearAssistantPanelLikeStreamClearPanel();return}const c={root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:a}}}};this._drawer?.setPanelContent(this._renderUISpec(c,t)),this._drawer?.setDividerPreviewEnabled(!1),this._currentPanelSource={kind:"spec",spec:c},this._panel&&(this._panel.currentType="ProductDetailsPanel"),this._drawer?.updatePanelTopBar(!0,!1,this._i18n.panelTitleProductDetails)},i18n:this._i18n,pricing:this.config.pricing,productPriceUi:this.config.productPriceUi,productSort:this._productSort,onSortChange:a=>{this._productSort=a},comparisonSelectMode:this._comparisonSelectMode,comparisonSelectedSkus:this._comparisonSelectedSkus,comparisonMaxSelection:gt._MAX_COMPARISON_SELECTION,comparisonSelectionWarning:this._comparisonSelectionWarning,onToggleComparisonSku:a=>{this._toggleComparisonSku(a)},favoritedSkus:this._session?.favoritedSkus??new Set,onFavoriteToggle:(a,n)=>{this._toggleProductFavorite(a,n)},isMobile:this._isMobileViewport};return t}async _toggleFavorite(t,a){if(!this._session)return;const n=this.config.session?.userId??"",r=this.config.accountId;await this._session.toggleFavorite(n,r,t,a),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size)}_revertFavoriteHeartUi(t){const a=this._shadow?.querySelectorAll(`[data-gengage-favorite-sku="${_e(t)}"]`);if(a?.length)for(const n of a){if(!(n instanceof HTMLButtonElement))continue;n.classList.toggle("gengage-chat-favorite-btn--active");const r=n.querySelector("svg");r&&r.setAttribute("fill",n.classList.contains("gengage-chat-favorite-btn--active")?"currentColor":"none")}}async _toggleProductFavorite(t,a){const n=!(this._session?.favoritedSkus.has(t)??!1),r={sku:t,product:a,favorited:n,sessionId:this.config.session?.sessionId??null};Te("gengage:chat:product-favorite",r),this._bridge?.send("productFavorite",r);const i=this._eventCallbacks.get("gengage-product-favorite");if(i&&i.size>0){for(const o of i)try{const s=o(r);if((s instanceof Promise?await s:s)===!1){this._revertFavoriteHeartUi(t),this._handleCallbackFailure("gengage-product-favorite",r);return}}catch{this._revertFavoriteHeartUi(t),this._handleCallbackFailure("gengage-product-favorite",r);return}this._session&&(n?this._session.favoritedSkus.add(t):this._session.favoritedSkus.delete(t),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size));return}if(await this._toggleFavorite(t,a),n){hi(t);const o=a.name??t;this._sendAction({title:o,type:"like",payload:{sku:t}},{preservePanel:!0})}}_openFavoritesPanel(){if(this._drawer){if(this._currentPanelSource){const t=this._drawer.getPanelTopBarTitle()??"";this._localPanelHistory.push({source:this._currentPanelSource,title:t}),this._localPanelHistory.length>gt._MAX_PANEL_HISTORY&&this._localPanelHistory.shift()}this._drawer.setPanelContent(this._buildFavoritesPageEl()),this._drawer.setDividerPreviewEnabled(!1),this._currentPanelSource={kind:"favorites"},this._drawer.updatePanelTopBar(!0,!1,this._i18n.favoritesPageTitle)}}_buildFavoritesPageEl(){const t=this._session?.getFavoriteProducts()??[];if(t.length===0){const i=document.createElement("div");i.className="gengage-chat-favorites-empty";const o=document.createElement("div");o.className="gengage-chat-favorites-empty-icon",o.innerHTML='<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>',i.appendChild(o);const s=document.createElement("p");return s.textContent=this._i18n.emptyFavoritesMessage,i.appendChild(s),i}const a={},n=[];for(const[i,o]of t.entries()){const s=`card_${i}`;n.push(s),a[s]={type:"ProductCard",props:{product:{sku:o.sku,name:o.name,imageUrl:o.imageUrl,price:o.price}}}}a.grid={type:"ProductGrid",children:n};const r={root:"grid",elements:a};return this._renderUISpec(r,this._buildRenderContext())}async _runEventCallbacks(t,a){const n=this._eventCallbacks.get(t);if(!(!n||n.size===0))for(const r of n)try{const i=r(a);if((i instanceof Promise?await i:i)===!1){this._handleCallbackFailure(t,a);return}}catch{this._handleCallbackFailure(t,a);return}}_handleCallbackFailure(t,a){if(t==="gengage-cart-add"){const n=this._i18n.cartAddErrorMessage,r=this._createMessage("assistant",n);this._currentThreadId&&(r.threadId=this._currentThreadId),this._messages.push(r),this._drawer?.addMessage(r)}if(t==="gengage-product-favorite"){const n=this._i18n.favoriteToggleErrorMessage,r=this._createMessage("assistant",n);this._currentThreadId&&(r.threadId=this._currentThreadId),this._messages.push(r),this._drawer?.addMessage(r)}}_restoreInlineUISpec(t){if(!t.uiSpec||!this._drawer)return;const a=t.uiSpec,n=a.elements[a.root];if(!n)return;const r=n.type;if(r==="ActionButtons"||r==="ComparisonTable"||Ea(n))return;const i=this._buildRenderContext(),o=this._shadow?.querySelector(".gengage-chat-messages");if(!o)return;if(r==="ProductDetailsPanel"){const c=n.props?.product;if(!c)return;const l={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:c}}}},g=this._renderUISpec(l,i);t.threadId&&(g.dataset.threadId=t.threadId),o.appendChild(g),this._drawer?.refreshPresentationCollapsed();return}const s=this._renderUISpec(a,i);t.threadId&&(s.dataset.threadId=t.threadId),o.appendChild(s),this._drawer?.refreshPresentationCollapsed()}_createMessage(t,a){return this._currentMessageId++,{id:`msg-${this._currentMessageId}`,role:t,content:a,timestamp:Date.now(),status:"done"}}_resolveI18n(t){return{...is(t.locale),...t.i18n}}_resolveUISpecRegistry(){return Fr(hn(),this.config.renderer?.registry)}_renderUISpec(t,a){const n=this._resolveUISpecRegistry(),r=this.config.renderer?.unknownRenderer??ea,i=(s,c)=>un(s,c,n,r),o=this.config.renderer?.renderUISpec;return o?o(t,a,{registry:n,unknownRenderer:r,defaultRender:i}):i(t,a)}};function $u(){return new Rr}Ee.CHAT_SCROLL_ELEMENT_ID=kt,Ee.ChatPresentationState=zn,Ee.GengageChat=Rr,Ee.chatCatalog=Ou,Ee.createChatWidget=$u,Ee.createDefaultChatUISpecRegistry=hn,Ee.defaultChatUnknownUISpecRenderer=ea,Ee.getChatScrollElement=as,Ee.invalidateChatScrollCache=Ga,Ee.isSimilarsAppendGrid=Ea,Ee.renderUISpec=un})(this.Gengage=this.Gengage||{});
package/dist/chat.js CHANGED
@@ -1,4 +1,4 @@
1
- import { c as e, f as t, i as r, l as s, m as n, n as i, o as l, p as C, r as c, s as h, t as o } from "./chat-BdYYhBg0.js";
1
+ import { c as e, f as t, i as r, l as s, m as n, n as i, o as l, p as C, r as c, s as h, t as o } from "./chat-B3jWM_Qc.js";
2
2
  export {
3
3
  t as CHAT_SCROLL_ELEMENT_ID,
4
4
  l as ChatPresentationState,
@@ -1,5 +1,5 @@
1
1
  import { f as u } from "./schemas-DnAo0x7A.js";
2
- import { h, l as f } from "./native-webview-DkvOte_j.js";
2
+ import { h, l as f } from "./native-webview-Dxc_PMzL.js";
3
3
  var m = {
4
4
  enabled: !0,
5
5
  endpoint: "/analytics",
package/dist/common.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { C as a, S as t, b as s, d as r, f as n, g as i, h as o, m as c, p as m, v as l, w as g, x as d, y as u } from "./schemas-DnAo0x7A.js";
2
2
  import { $ as E, G as S, J as h, K as v, Q as y, V as f, X as C, Y as A, Z as T, _ as w, a as U, b as W, c as I, d as P, et as b, f as D, g as R, h as k, i as G, it as O, l as N, m as _, n as x, nt as L, p as M, q as z, rt as B, s as H, tt as K, u as F, v as V, y as Q } from "./locale-MM0U5eeR.js";
3
- import { a as Z, d as J, h as X, u as Y } from "./chat-BdYYhBg0.js";
3
+ import { a as Z, d as J, h as X, u as Y } from "./chat-B3jWM_Qc.js";
4
4
  import { n as j, t as ee } from "./connection-warning-n88bjkqL.js";
5
- import { a as te, c as se, d as re, f as ne, h as ie, i as oe, l as ce, m as me, n as le, o as ge, p as de, r as ue, s as pe, u as Ee } from "./native-webview-DkvOte_j.js";
6
- import { a as he, c as ve, d as ye, f as fe, i as Ce, l as Ae, n as Te, o as we, p as Ue, r as We, s as Ie, t as Pe, u as be } from "./common-DmixzWHZ.js";
5
+ import { a as te, c as se, d as re, f as ne, h as ie, i as oe, l as ce, m as me, n as le, o as ge, p as de, r as ue, s as pe, u as Ee } from "./native-webview-Dxc_PMzL.js";
6
+ import { a as he, c as ve, d as ye, f as fe, i as Ce, l as Ae, n as Te, o as we, p as Ue, r as We, s as Ie, t as Pe, u as be } from "./common-VU6Di_KE.js";
7
7
  export {
8
8
  Ee as AccountRuntimeConfigSchema,
9
9
  re as AnalyticsAuthModeSchema,
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { C as a, b as t, d as s, f as i, w as n, x as r } from "./schemas-DnAo0x7A.js";
2
2
  import { V as c, _ as m, b as l, d, f as g, g as p, l as u, p as f, u as S, v as C, y as h } from "./locale-MM0U5eeR.js";
3
- import { a as y, c as A, d as I, h as R, l as T, n as W, s as w, t as D, u as E } from "./chat-BdYYhBg0.js";
3
+ import { a as y, c as A, d as I, h as R, l as T, n as W, s as w, t as D, u as E } from "./chat-B3jWM_Qc.js";
4
4
  import { t as N } from "./connection-warning-n88bjkqL.js";
5
5
  import { a as P, i as G, n as _, o as k, t as Q } from "./qna-DrlYm1d8.js";
6
6
  import { a as L, i as x, n as B, o as M, t as F } from "./simrel-BjNqBbmw.js";
7
7
  import { n as H, t as K } from "./simbut-Cb5RfaAp.js";
8
- import { a as Z, c as j, d as q, f as J, h as X, i as Y, l as $, m as ee, n as ae, o as te, p as se, r as ie, s as ne, u as re } from "./native-webview-DkvOte_j.js";
9
- import { a as ce, c as me, d as le, i as de, l as ge, n as pe, o as ue, p as fe, r as Se, s as Ce, t as he, u as Ue } from "./common-DmixzWHZ.js";
8
+ import { a as Z, c as j, d as q, f as J, h as X, i as Y, l as $, m as ee, n as ae, o as te, p as se, r as ie, s as ne, u as re } from "./native-webview-Dxc_PMzL.js";
9
+ import { a as ce, c as me, d as le, i as de, l as ge, n as pe, o as ue, p as fe, r as Se, s as Ce, t as he, u as Ue } from "./common-VU6Di_KE.js";
10
10
  export {
11
11
  re as AccountRuntimeConfigSchema,
12
12
  q as AnalyticsAuthModeSchema,
@@ -1,6 +1,6 @@
1
1
  import { a as k, c as h, i as D, o as f, r as m, t as A } from "./schemas-DnAo0x7A.js";
2
2
  import { U as H, h as Q, j, r as M, y as K } from "./locale-MM0U5eeR.js";
3
- import { t as V } from "./chat-BdYYhBg0.js";
3
+ import { t as V } from "./chat-B3jWM_Qc.js";
4
4
  import { t as $ } from "./qna-DrlYm1d8.js";
5
5
  import { t as G } from "./simrel-BjNqBbmw.js";
6
6
  import { t as Y } from "./simbut-Cb5RfaAp.js";