@gamaro.io/widget 1.1.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -305,6 +305,11 @@ from the API key** — you do not pass it from the integration. Each `pk_*` key
305
305
  bound to exactly one Agent, and each Agent is bound to one vertical. Switching
306
306
  vertical = creating a new Agent + new key.
307
307
 
308
+ The SDK no longer forwards the vertical to the embedded chat: the server derives
309
+ it from the key on every request. The `vertical` field of the Application config
310
+ response is **deprecated** — still served for already-published widgets, removed
311
+ in the next major version. Do not read it from your integration.
312
+
308
313
  ### Real-Estate flow
309
314
 
310
315
  When the resolved vertical is `real-estate`, the widget runs in qualification
package/dist/loader.d.ts CHANGED
@@ -28,7 +28,6 @@ export declare class GamaroWidget implements GamaroAPI {
28
28
  private fetchAbortController;
29
29
  private iframeLoadAbortController;
30
30
  private _applicationId;
31
- private vertical;
32
31
  private instanceId;
33
32
  private pendingCommands;
34
33
  private eventHandlers;
package/dist/widget.es.js CHANGED
@@ -4174,7 +4174,7 @@ var bu = R({
4174
4174
  applicationId: k().uuid().describe("Application UUID"),
4175
4175
  applicationSlug: k().max(100).describe("Application slug (kebab-case)"),
4176
4176
  applicationName: k().max(200).describe("Application display name"),
4177
- vertical: k().max(50).describe("Vertical resolved from Application config"),
4177
+ vertical: k().max(50).describe("Deprecated: the widget no longer reads it. Still served for already-published widgets that validate it; removed in the next major."),
4178
4178
  theme: gt.nullable().describe("Application theme"),
4179
4179
  allowedOrigins: mt(k().max(200)).max(50).describe("Allowed origins for this application"),
4180
4180
  monitoring: F().describe("Monitoring enabled flag"),
@@ -4426,7 +4426,7 @@ var ye = {
4426
4426
  return this._applicationId;
4427
4427
  }
4428
4428
  constructor(e) {
4429
- this.version = ru, this.iframe = null, this.container = null, this.skeletonButton = null, this.isOpen = !1, this.isReady = !1, this.isInitialized = !1, this.isDestroyed = !1, this.fetchAbortController = null, this.iframeLoadAbortController = null, this._applicationId = "", this.vertical = "", this.pendingCommands = [], this.eventHandlers = /* @__PURE__ */ new Map(), this.cleanupListener = null, this.currentViewportMode = "desktop", this.mobileMediaQuery = null, this.tabletMediaQuery = null, this.debounceTimer = null, this.viewportChangeHandler = null, this.originalConfig = { ...e }, this.config = {
4429
+ this.version = ru, this.iframe = null, this.container = null, this.skeletonButton = null, this.isOpen = !1, this.isReady = !1, this.isInitialized = !1, this.isDestroyed = !1, this.fetchAbortController = null, this.iframeLoadAbortController = null, this._applicationId = "", this.pendingCommands = [], this.eventHandlers = /* @__PURE__ */ new Map(), this.cleanupListener = null, this.currentViewportMode = "desktop", this.mobileMediaQuery = null, this.tabletMediaQuery = null, this.debounceTimer = null, this.viewportChangeHandler = null, this.originalConfig = { ...e }, this.config = {
4430
4430
  position: "bottom-right",
4431
4431
  open: !1,
4432
4432
  baseUrl: _e,
@@ -4478,7 +4478,7 @@ var ye = {
4478
4478
  }
4479
4479
  applyServerConfig(e) {
4480
4480
  if (this.isDestroyed) return;
4481
- this._applicationId = e.applicationId, this.vertical = e.vertical;
4481
+ this._applicationId = e.applicationId;
4482
4482
  const t = e.widget ?? {};
4483
4483
  this.config = {
4484
4484
  ...this.config,
@@ -4573,7 +4573,7 @@ var ye = {
4573
4573
  }
4574
4574
  buildIframeUrl() {
4575
4575
  const e = this.config.baseUrl ?? _e, t = new URL("/app/widget/embed", e);
4576
- return this.vertical && t.searchParams.set("vertical", this.vertical), this.config.theme && t.searchParams.set("theme", pn(this.config.theme)), this.config.position === "inline" && t.searchParams.set("mode", "inline"), this.config.open && t.searchParams.set("open", "true"), this.config.showProfile && t.searchParams.set("showProfile", "true"), this.config.language && t.searchParams.set("language", this.config.language), this.config.apiKey && t.searchParams.set("apiKey", this.config.apiKey), t.searchParams.set("hostOrigin", window.location.origin), t.toString();
4576
+ return this.config.theme && t.searchParams.set("theme", pn(this.config.theme)), this.config.position === "inline" && t.searchParams.set("mode", "inline"), this.config.open && t.searchParams.set("open", "true"), this.config.showProfile && t.searchParams.set("showProfile", "true"), this.config.language && t.searchParams.set("language", this.config.language), this.config.apiKey && t.searchParams.set("apiKey", this.config.apiKey), t.searchParams.set("hostOrigin", window.location.origin), t.toString();
4577
4577
  }
4578
4578
  setupViewportListener() {
4579
4579
  if (this.config.position === "inline" || this.config.responsive?.enabled === !1) return;
@@ -79,4 +79,4 @@ ${t.join(`
79
79
 
80
80
  `)}return b.write("payload.value = newResult;"),b.write("return payload;"),b.compile()};let s;const a=ye,c=!j.jitless,f=c&&En.value,d=t.catchall;let h;e._zod.parse=(p,m)=>{h??(h=n.value);const v=p.value;return a(v)?c&&f&&m?.async===!1&&m.jitless!==!0?(s||(s=o(t.shape)),p=s(p,m),d?ir([],v,p,m,h,e,m?.abortEarly===!0):p):r(p,m):(p.issues.push({expected:"object",code:"invalid_type",input:v,inst:e}),p)}});function or(e,t,r,n){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const i=e.filter(o=>!F(o));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(s=>ee(s,n,J())))}),t)}var Bo=l("$ZodUnion",(e,t)=>{S.init(e,t),y(e,"optin",n=>n.def.options.some(i=>i._zod.optin==="defaulted")?"defaulted":n.def.options.some(i=>i._zod.optin!==void 0)?"optional":void 0),y(e,"optout",n=>n.def.options.some(i=>i._zod.optout==="optional")?"optional":void 0),y(e,"values",n=>{if(n.def.options.every(i=>i._zod.values))return new Set(n.def.options.flatMap(i=>Array.from(i._zod.values)))}),y(e,"pattern",n=>{if(n.def.options.every(i=>i._zod.pattern)){const i=n.def.options.map(o=>o._zod.pattern);return new RegExp(`^(${i.map(o=>We(o.source)).join("|")})$`)}});const r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let o=!1;const s=[];for(const a of t.options){const c=a._zod.run({value:n.value,issues:[]},i);if(c instanceof Promise)s.push(c),o=!0;else{if(c.issues.length===0)return c;s.push(c)}}return o?Promise.all(s).then(a=>or(a,n,e,i)):or(s,n,e,i)}}),Jo=l("$ZodIntersection",(e,t)=>{S.init(e,t),e._zod.parse=(r,n)=>{const i=r.value,o=t.left._zod.run({value:i,issues:[]},n),s=t.right._zod.run({value:i,issues:[]},n);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([a,c])=>sr(r,a,c)):sr(r,o,s)}});function nt(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(se(e)&&se(t)){const r=Object.keys(t),n=Object.keys(e).filter(o=>r.indexOf(o)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,"__proto__")&&delete i.__proto__;for(const o of n){if(o==="__proto__")continue;const s=nt(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const i=e[n],o=t[n],s=nt(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function sr(e,t,r){const n=new Map;let i;const o=new Map,s=(u,f)=>{let d;if(u.code==="unrecognized_keys"&&!u.path?.length)i??(i=u),d=u.keys;else if(u.code==="invalid_key"&&u.origin==="record"&&u.path?.length===1){const h=String(u.path[0]);o.has(h)||o.set(h,u),d=[h]}else return!1;for(const h of d)n.has(h)||n.set(h,{}),n.get(h)[f]=!0;return!0};for(const u of t.issues)s(u,"l")||e.issues.push(u);for(const u of r.issues)s(u,"r")||e.issues.push(u);const a=[...n].filter(([,u])=>u.l&&u.r).map(([u])=>u);if(a.length){const u=i?a.filter(f=>i.keys.includes(f)):[];u.length&&e.issues.push({...i,keys:u});for(const f of a)!u.includes(f)&&o.has(f)&&e.issues.push(o.get(f))}const c=nt(t.value,r.value);if(!c.valid){if(F(e))return e;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Vo=l("$ZodEnum",(e,t)=>{S.init(e,t);const r=Le(t.entries),n=new Set(r);e._zod.values=n,y(e,"pattern",i=>{const o=Le(i.def.entries).filter(s=>$n.has(typeof s));return new RegExp(o.length?`^(${o.map(s=>we(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(i,o)=>{const s=i.value;return n.has(s)||i.issues.push({code:"invalid_value",values:r,input:s,inst:e}),i}}),Ko=l("$ZodTransform",(e,t)=>{S.init(e,t),e._zod.optin="optional",j.memoizer?.guard(e),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Lt(e.constructor.name);const i=t.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(r.value=o,r));if(i instanceof Promise)throw new Y;return r.value=i,r}});function ar(e,t){return e.value=t.issues.length?void 0:t.value,e}var cr=l("$ZodOptional",(e,t)=>{S.init(e,t),y(e,"optin",r=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",y(e,"values",r=>{const n=r.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),y(e,"pattern",r=>{const n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${We(n.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(r.value===void 0){if(t.innerType._zod.optin!=="defaulted")return r;const i=t.innerType._zod.run({value:r.value,issues:[]},n);return i instanceof Promise?i.then(o=>ar(r,o)):ar(r,i)}return t.innerType._zod.run(r,n)}}),Go=l("$ZodExactOptional",(e,t)=>{cr.init(e,t),y(e,"values",r=>r.def.innerType._zod.values),y(e,"pattern",r=>r.def.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),Ho=l("$ZodNullable",(e,t)=>{S.init(e,t),y(e,"optin",r=>r.def.innerType._zod.optin),y(e,"optout",r=>r.def.innerType._zod.optout),y(e,"pattern",r=>{const n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${We(n.source)}|null)$`):void 0}),y(e,"values",r=>r.def.innerType._zod.values?new Set([...r.def.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),qo=l("$ZodDefault",(e,t)=>{S.init(e,t),e._zod.optin="defaulted",y(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>ur(o,t)):ur(i,t)}});function ur(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Yo=l("$ZodPrefault",(e,t)=>{S.init(e,t),e._zod.optin="defaulted",y(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),Xo=l("$ZodNonOptional",(e,t)=>{S.init(e,t),y(e,"values",r=>{const n=r.def.innerType._zod.values;return n?new Set([...n].filter(i=>i!==void 0)):void 0}),e._zod.parse=(r,n)=>{const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>lr(o,e)):lr(i,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}function fr(e,t,r,n){return t.issues.length?(e.value=r.catchValue({...t,value:e.value,error:{issues:t.issues.map(i=>ee(i,n,J()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var Qo=l("$ZodCatch",(e,t)=>{S.init(e,t),y(e,"optin",r=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),y(e,"optout",r=>r.def.innerType._zod.optout),y(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);const i=t.innerType._zod.run({value:r.value,issues:[]},n);return i instanceof Promise?i.then(o=>fr(r,o,t,n)):fr(r,i,t,n)}}),es=l("$ZodPipe",(e,t)=>{S.init(e,t),y(e,"values",r=>r.def.in._zod.values),y(e,"optin",r=>r.def.in._zod.optin),y(e,"optout",r=>r.def.out._zod.optout),y(e,"propValues",r=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){const o=t.out._zod.run(r,n);return o instanceof Promise?o.then(s=>$e(s,t.in,n)):$e(o,t.in,n)}const i=t.in._zod.run(r,n);return i instanceof Promise?i.then(o=>$e(o,t.out,n)):$e(i,t.out,n)}});function $e(e,t,r){return e.issues.some(n=>n.code!=="unrecognized_keys")?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}var ts=l("$ZodReadonly",(e,t)=>{S.init(e,t),y(e,"propValues",r=>r.def.innerType._zod.propValues),y(e,"values",r=>r.def.innerType._zod.values),y(e,"optin",r=>r.def.innerType?._zod?.optin),y(e,"optout",r=>r.def.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(dr):dr(i)}});function dr(e){return e.memo||(e.value=Object.freeze(e.value)),e}var rs=l("$ZodCustom",(e,t)=>{P.init(e,t),S.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(o=>hr(o,r,n,e));hr(i,r,n,e)}});function hr(e,t,r,n){if(!e){const i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),t.issues.push(ce(i))}}var ns=class extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}},it="~memo",pr=[];function mr(e){return e!==null&&typeof e=="object"}function ot(e){return e.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}var gr=new WeakMap,ue=0,Ie=1,le=2;function Ae(e,t,r){const n=gr.get(e);if(n!==void 0)return n?le:ue;if(t.has(e))return le;t.add(e);let i=ue;const o=u=>{if(i!==le&&u?._zod){const f=Ae(u,t,r);f>i&&(i=f)}},s=(u,f)=>{let d=ue;for(const h of Reflect.ownKeys(u)){const p=Object.getOwnPropertyDescriptor(u,h);if(f&&!p.enumerable)continue;const m=p.get?Ie:p.value?._zod?Ae(p.value,t,r):ue;m>d&&(d=m)}return d},a=u=>{u>i&&(i=u)},c=e._zod.def;switch(c.type){case"object":{const u=St(c);a(u?s(u,!0):Ie),o(c.catchall);break}case"array":o(c.element);break;case"tuple":for(const u of c.items)o(u);o(c.rest);break;case"record":case"map":o(c.keyType),o(c.valueType);break;case"set":o(c.valueType);break;case"union":for(const u of c.options)o(u);break;case"intersection":o(c.left),o(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":o(c.innerType);break;case"pipe":o(c.in),o(c.out);break;case"function":o(c.input),o(c.output);break;case"lazy":{const u=c._cachedInner??(r?e._zod.innerType:void 0);a(u?Ae(u,t,!1):Ie);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(const u in c){const f=Object.getOwnPropertyDescriptor(c,u);if(!f||f.get)continue;const d=f.value;if(!(!d||typeof d!="object")){if(d._zod)o(d);else if(Array.isArray(d))for(const h of d)o(h)}}}return t.delete(e),is(e,i)}function is(e,t){return t!==Ie&&gr.set(e,t===le),t}function os(e,t){let r=e.buckets.get(t);return r||(r=new WeakMap,e.buckets.set(t,r)),r}var Te,Pe=[],ss={alloc(e,t,r){const n=Te;if(!n)return r;Te=void 0;const i={value:r,issues:null};return n.set(t.value,i),Pe.push(i),r},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const r=e._zod.parse,n=(i,o)=>{if(o.direction!=="backward"&&cs(o,i.value))throw new ns;return r(i,o)};e._zod.parse=n,e._zod.run===r&&(e._zod.run=n)})},attach(e){var t;let r,n=!1,i,o;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const s=e._zod.parse,a=(c,u)=>{if(r===void 0){const _=Ae(e,new Set,!1);if(_===ue)return e._zod.parse=s,e._zod.run===a&&(e._zod.run=s),s(c,u);_===le||n?r=!0:n=!0}const f=c.value;if(!mr(f))return s(c,u);let d=u[it];d||(d={buckets:new WeakMap,backEdges:void 0},u[it]=d);let h;i===u?h=o:(h=os(d,e),i=u,o=h);const p=h.get(f);if(p)return c.value=p.value,p.issues?p.issues.length&&c.issues.push(...ot(p.issues)):(c.memo=!0,d.backEdges??(d.backEdges=new WeakSet),d.backEdges.add(p.value)),c;Te=h;const m=Pe.length,v=s(c,u);Te=void 0;const b=Pe.length>m?Pe.pop():void 0;return v instanceof Promise?v.then(_=>(b&&(b.issues=_.issues.length?ot(_.issues):pr),_)):(b&&(b.issues=v.issues.length?ot(v.issues):pr),v)};e._zod.parse=a,e._zod.run===s&&(e._zod.run=a)})}};function as(){return ss}function cs(e,t){const r=e[it]?.backEdges;return r!==void 0&&mr(t)&&r.has(t)}var us=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}const r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};function i(o,s){return o==="number"&&typeof s=="number"&&!Number.isFinite(s)?String(s):n[o]??o}return o=>{switch(o.code){case"invalid_type":return`Invalid input: expected ${i(o.expected)}, received ${i(Dn(o.input),o.input)}`;case"invalid_value":return o.values.length===1?`Invalid input: expected ${Tt(o.values[0])}`:`Invalid option: expected one of ${zt(o.values,"|")}`;case"too_big":{const s=o.exact?"exactly ":o.inclusive?"<=":"<",a=t(o.origin);return a?`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{const s=o.exact?"exactly ":o.inclusive?">=":">",a=t(o.origin);return a?`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${a.unit}`:`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${zt(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return o.options&&Array.isArray(o.options)&&o.options.length>0?`Invalid discriminator value. Expected ${o.options.map(s=>`'${s}'`).join(" | ")}`:o.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function ls(){return{localeError:us()}}var vr,fs=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.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 r={...this.get(t)??{}};delete r.id;const n={...r,...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 ds(){return new fs}(vr=globalThis).__zod_globalRegistry??(vr.__zod_globalRegistry=ds());var fe=globalThis.__zod_globalRegistry;function br(e){return e.checks&&(e.checks=[...e.checks]),e}function hs(e,t){return new e(br({type:"string",...g(t)}))}function ps(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...g(t)})}function ms(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...g(t)})}function gs(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...g(t)})}function vs(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...g(t)})}function bs(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...g(t)})}function _s(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...g(t)})}function ys(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...g(t)})}function ws(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...g(t)})}function ks(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...g(t)})}function Os(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...g(t)})}function zs(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...g(t)})}function Ss(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...g(t)})}function Es(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...g(t)})}function $s(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...g(t)})}function Is(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...g(t)})}function As(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...g(t)})}function Ts(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...g(t)})}function Ps(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...g(t)})}function Zs(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...g(t)})}function Cs(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...g(t)})}function Rs(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...g(t)})}function Ns(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...g(t)})}function js(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...g(t)})}function Ms(e,t){return new e({type:"string",format:"date",check:"string_format",...g(t)})}function Ds(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...g(t)})}function xs(e,t){return new e({type:"string",format:"duration",check:"string_format",...g(t)})}function Ls(e,t){return new e(br({type:"number",checks:[],...g(t)}))}function Fs(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...g(t)})}function Us(e,t){return new e({type:"boolean",...g(t)})}function Ws(e){return new e({type:"unknown"})}function Bs(e,t){return new e({type:"never",...g(t)})}function _r(e,t){return new Vt({check:"less_than",...g(t),value:e,inclusive:!1})}function st(e,t){return new Vt({check:"less_than",...g(t),value:e,inclusive:!0})}function yr(e,t){return new Kt({check:"greater_than",...g(t),value:e,inclusive:!1})}function at(e,t){return new Kt({check:"greater_than",...g(t),value:e,inclusive:!0})}function wr(e,t){return new Ui({check:"multiple_of",...g(t),value:e})}function kr(e,t){return new Bi({check:"max_length",...g(t),maximum:e})}function Ze(e,t){return new Ji({check:"min_length",...g(t),minimum:e})}function Or(e,t){return new Vi({check:"length_equals",...g(t),length:e})}function Js(e,t){return new Ki({check:"string_format",format:"regex",...g(t),pattern:e})}function Vs(e){return new Gi({check:"string_format",format:"lowercase",...g(e)})}function Ks(e){return new Hi({check:"string_format",format:"uppercase",...g(e)})}function Gs(e,t){return new qi({check:"string_format",format:"includes",...g(t),includes:e})}function Hs(e,t){return new Yi({check:"string_format",format:"starts_with",...g(t),prefix:e})}function qs(e,t){return new Xi({check:"string_format",format:"ends_with",...g(t),suffix:e})}function te(e){return new Qi({check:"overwrite",tx:e})}function Ys(e){return te(t=>t.normalize(e))}function Xs(){return te(e=>e.trim())}function Qs(){return te(e=>e.toLowerCase())}function ea(){return te(e=>e.toUpperCase())}function ta(){return te(e=>Sn(e))}function ra(e,t,r){return new e({type:"array",element:t,...g(r)})}function na(e,t,r){const n=g(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function ia(e,t,r){return new e({type:"custom",check:"custom",fn:t,...g(r)})}function oa(e,t){const r=sa(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(ce(i,n.value,r._zod.def));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),"input"in o||(o.input=n.value),o.inst??(o.inst=r),o.continue??(o.continue=!r._zod.def.abort),n.issues.push(ce(o))}},e(n.value,n)),t);return r}function sa(e,t){const r=new P({check:"custom",...g(t)});return r._zod.check=e,r}function de(e,...t){for(const r of t)for(const n of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,n)&&H(e,n,r[n]);return e}function zr(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??fe,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function re(e,t,r,n,i){const o=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:n.path,message:i}):t.unrepresentable;if(o==="any")return!1;if(o===void 0||o==="throw")throw new Error(i);return Object.assign(r,o),!0}function A(e,t,r={path:[],schemaPath:[]}){var n;const i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;const s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const u={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,u);else{const d=s.schema,h=t.processors[i.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);h(e,t,d,u)}const f=e._zod.parent;f&&(s.ref||(s.ref=f),A(f,t,u),t.seen.get(f).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&de(s.schema,c),t.io==="input"&&T(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((n=s.schema).default??(n.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function Sr(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Er(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;const n=new Map;for(const s of e.seen.entries()){const a=e.metadataRegistry.get(s[0])?.id;if(a){const c=n.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,s[0])}}const i=s=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const d=e.external.registry.get(s[0])?.id,h=e.external.uri??(m=>m);if(d)return{ref:h(d)};const p=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=p,{defId:p,ref:`${h("__shared")}#/${a}/${Sr(p)}`}}const c="#",u=`${c}/${a}/`;if(s[1]===r&&!s[1].schema.id)return{ref:c};const f=s[1].schema.id??`__schema${e.counter++}`;return{defId:f,ref:u+Sr(f)}},o=s=>{if(s[1].schema.$ref)return;const a=s[1],{ref:c,defId:u}=i(s);a.def={...a.schema},u&&(a.defId=u);const f=a.schema;for(const d in f)delete f[d];f.$ref=c};if(e.cycles==="throw")for(const s of e.seen.entries()){const a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
81
81
 
82
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const a=s[1];if(t===s[0]){o(s);continue}if(e.external){const c=e.external.registry.get(s[0])?.id;if(t!==s[0]&&c){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}a.count>1&&e.reused==="ref"&&o(s)}e.external&&(e.sharedDefsExtractedFor=e.external)}function $r(e){const t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;const r=[];for(const n of t){if(!n||typeof n!="object")return;$r(n);const i=Object.keys(n);if(i.length!==1||i[0]!=="type")return;const o=n.type;for(const s of Array.isArray(o)?o:[o]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Ir=new Set(["type","properties","required","additionalProperties"]),Ar=["oneOf","anyOf"];function Tr(e){const t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function ct(e){const t=[];for(const o of e){if(typeof o!="object"||o.type!=="object")return null;for(const s in o)if(!Ir.has(s))return null;t.push(o)}const r={},n=new Set;for(const o of t){for(const s in o.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;const a=[];for(const u of t){const f=u.properties?.[s]??Tr(u);f!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(f))||a.push(f))}const c=a.length===1?a[0]:ct(a)??{allOf:a};H(r,s,c)}for(const s of o.required??[])n.add(s)}const i={type:"object",properties:r};if(n.size&&(i.required=[...n]),t.every(o=>o.additionalProperties===!1))i.additionalProperties=!1;else{const o=[];for(const s of t){const a=Tr(s);a&&!o.some(c=>JSON.stringify(c)===JSON.stringify(a))&&o.push(a)}o.length===1?i.additionalProperties=o[0]:o.length>1&&(i.additionalProperties={allOf:o})}return i}function aa(e){const t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(const i of Ir)if(i in e)return;const r=t.filter(i=>Ar.some(o=>Array.isArray(i[o])));let n=null;if(!r.length)n=ct(t);else{const i=r[0],o=Ar.find(c=>Array.isArray(i[c]));if(Object.keys(i).length!==1)return;const s=t.filter(c=>c!==i),a=i[o].map(c=>ct([...s,c]));if(a.some(c=>!c))return;n={[o]:a}}n&&(delete e.allOf,de(e,n))}function Pr(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=a=>{const c=e.seen.get(a);if(c.ref===null)return;const u=c.def??c.schema,f={...u},d=c.ref;if(c.ref=null,d){n(d);const p=e.seen.get(d),m=p.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):de(u,m),de(u,f),a._zod.parent===d)for(const v in u)v==="$ref"||v==="allOf"||v in f||delete u[v];if(m.$ref&&p.def)for(const v in u)v==="$ref"||v==="allOf"||v in p.def&&JSON.stringify(u[v])===JSON.stringify(p.def[v])&&delete u[v]}const h=a._zod.parent;if(h&&h!==d){n(h);const p=e.seen.get(h);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(const m in u)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(u[m])===JSON.stringify(p.def[m])&&delete u[m]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(const a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(const a of e.seen.entries())$r(a[1].def??a[1].schema);for(const a of e.deferred)a();if(e.intersections.length){const a=new Map;for(const c of e.seen.values())for(const u of[c.schema,c.def]){const f=u?.allOf;if(!Array.isArray(f))continue;const d=a.get(f);d?d.push(u):a.set(f,[u])}for(const c of e.intersections)for(const u of a.get(c)??[])aa(u)}}const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(a)}de(i,r.defId?r.schema:r.def??r.schema);const o=e.metadataRegistry.get(t)?.id;o!==void 0&&i.id===o&&delete i.id;const s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(const a of e.seen.entries()){const c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,H(s,c.defId,c.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{const a=JSON.parse(JSON.stringify(i));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ce(t,"input",e.processors),output:Ce(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function T(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return T(n.element,r);if(n.type==="set")return T(n.valueType,r);if(n.type==="lazy")return T(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return T(n.innerType,r);if(n.type==="intersection")return T(n.left,r)||T(n.right,r);if(n.type==="record"||n.type==="map")return T(n.keyType,r)||T(n.valueType,r);if(n.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:T(n.in,r)||T(n.out,r);if(n.type==="object"){for(const i in n.shape)if(T(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(const i of n.options)if(T(i,r))return!0;return!1}if(n.type==="tuple"){for(const i of n.items)if(T(i,r))return!0;return!!(n.rest&&T(n.rest,r))}return!1}var ca=(e,t={})=>r=>{const n=zr({...r,processors:t});return A(e,n),Er(n,e),Pr(n,e)},Ce=(e,t,r={})=>n=>{const{libraryOptions:i,target:o}=n??{},s=zr({...i??{},target:o,io:t,processors:r});return A(e,s),Er(s,e),Pr(s,e)},ne=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},ie=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},Zr=(e,t)=>{ne(e,"minimum",t),ie(e,"maximum",t)},Cr=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},Rr=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Nr=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},jr=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Mr=(e,t)=>ne(e,"minimum",t.minimum),Dr=(e,t)=>ie(e,"maximum",t.maximum),xr=e=>(t,r)=>{jr(t,r.format);const[n,i]=e[r.format];ne(t,"minimum",n),ie(t,"maximum",i)},ua={greater_than:(e,t)=>ne(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>ie(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Cr(e,t.value),number_format:xr(Pt),bigint_format:xr(An),min_length:Mr,max_length:Dr,length_equals:(e,t)=>Zr(e,t.length),min_size:Mr,max_size:Dr,size_equals:(e,t)=>Zr(e,t.size),string_format:(e,t)=>{jr(e,t.format),t.pattern&&Rr(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Nr(e,t.mime)};function M(e){const t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(const o of n)ua[o._zod.def.check]?.(t,o._zod.def);const i=e._zod.bag;i.minimum!==void 0&&ne(t,"minimum",i.minimum),i.exclusiveMinimum!==void 0&&ne(t,"exclusiveMinimum",i.exclusiveMinimum),i.maximum!==void 0&&ie(t,"maximum",i.maximum),i.exclusiveMaximum!==void 0&&ie(t,"exclusiveMaximum",i.exclusiveMaximum),i.multipleOf!==void 0&&Cr(t,i.multipleOf),i.format!==void 0&&(t.format??(t.format=i.format),i.format.includes("int")&&(t.isInt=!0)),i.mime&&Nr(t,i.mime);for(const o of i.patterns??[])Rr(t,o);return t}var la={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},fa=new Map([[er,Ai],[rt,Ti]]),da=e=>fa.get(e)??e,ha=(e,t,r,n)=>{const i=r;i.type="string";const{minimum:o,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:f}=M(e);if(typeof o=="number"&&(i.minLength=o),typeof s=="number"&&(i.maxLength=s),a&&(i.format=la[a]??a,i.format===""&&delete i.format,(a==="time"||f)&&delete i.format),u&&(i.contentEncoding=u),c&&c.size>0){const d=[...c].map(da);d.length===1?i.pattern=d[0].source:d.length>1&&(i.allOf=[...d.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},pa=(e,t,r,n)=>{const i=r,{minimum:o,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:f}=M(e);i.type=f?"integer":"number";const d=typeof u=="number"&&u>=(o??Number.NEGATIVE_INFINITY),h=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=t.target==="draft-04"||t.target==="openapi-3.0";if(d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof o=="number"&&(i.minimum=o),h?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof s=="number"&&(i.maximum=s),a){const m=new Set;for(const _ of a)Number.isFinite(_)&&_!==0?m.add(Math.abs(_)):re(e,t,i,n,`A multipleOf divisor of ${_} cannot be represented in JSON Schema`);const[v,...b]=m;v!==void 0&&(i.multipleOf=v),b.length&&(i.allOf=[...i.allOf??[],...b.map(_=>({multipleOf:_}))])}},ma=(e,t,r,n)=>{r.type="boolean"},ga=(e,t,r,n)=>{r.not={}},va=(e,t,r,n)=>{},ba=(e,t,r,n)=>{const i=e._zod.def,o=Le(i.entries);if(o.length===0){r.not={};return}o.every(s=>typeof s=="number")&&(r.type="number"),o.every(s=>typeof s=="string")&&(r.type="string"),r.enum=o},_a=(e,t,r,n)=>{re(e,t,r,n,"Custom types cannot be represented in JSON Schema")},ya=(e,t,r,n)=>{re(e,t,r,n,"Transforms cannot be represented in JSON Schema")},wa=(e,t,r,n)=>{const i=r,o=e._zod.def,{minimum:s,maximum:a}=M(e);typeof s=="number"&&(i.minItems=s),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=A(o.element,t,{...n,path:[...n.path,"items"]})};function ut(e){const t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?ut(t.out):t.type==="catch"?ut(t.innerType):e._zod.optin}var ka=(e,t,r,n)=>{const i=r,o=e._zod.def,s=o.shape;if(Object.getOwnPropertySymbols(s).length&&re(e,t,i,n,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(const c in s)H(i.properties,c,A(s[c],t,{...n,path:[...n.path,"properties",c]}));const a=[];for(const c of Object.keys(s)){const u=o.shape[c];(t.io==="input"?ut(u)===void 0:u._zod.optout===void 0)&&a.push(c)}a.length>0&&(i.required=a),o.catchall?._zod.def.type==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=A(o.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},Oa=(e,t,r,n)=>{const i=e._zod.def,o=i.inclusive===!1,s=i.options.map((a,c)=>A(a,t,{...n,path:[...n.path,o?"oneOf":"anyOf",c]}));o?r.oneOf=s:r.anyOf=s},za=(e,t,r,n)=>{const i=e._zod.def,o=A(i.left,t,{...n,path:[...n.path,"allOf",0]}),s=A(i.right,t,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];r.allOf=c,t.intersections.push(c)},Sa=(e,t,r,n)=>{const i=e._zod.def,o=A(i.innerType,t,n),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=i.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]},Ea=(e,t,r,n)=>{const i=e._zod.def;A(i.innerType,t,n);const o=t.seen.get(e);o.ref=i.innerType},lt=Symbol();function Lr(e,t,r,n,i){let o=!1;const s=JSON.stringify(e,(a,c)=>typeof c!="bigint"?c:(o=!0,null));return o?(re(t,r,n,i,"BigInt defaults cannot be represented in JSON Schema"),lt):JSON.parse(s)}var $a=(e,t,r,n)=>{const i=e._zod.def;A(i.innerType,t,n);const o=t.seen.get(e);o.ref=i.innerType;const s=Lr(i.defaultValue,e,t,r,n);s!==lt&&(r.default=s)},Ia=(e,t,r,n)=>{const i=e._zod.def;A(i.innerType,t,n);const o=t.seen.get(e);if(o.ref=i.innerType,t.io!=="input")return;const s=Lr(i.defaultValue,e,t,r,n);s!==lt&&(r._prefault=s)},Aa=(e,t,r,n)=>{const i=e._zod.def;A(i.innerType,t,n);const o=t.seen.get(e);o.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{re(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},Ta=(e,t,r,n)=>{const i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?i.out:i.in:i.out;A(s,t,n);const a=t.seen.get(e);a.ref=s},Pa=(e,t,r,n)=>{const i=e._zod.def;A(i.innerType,t,n);const o=t.seen.get(e);o.ref=i.innerType,r.readOnly=!0},Fr=(e,t,r,n)=>{const i=e._zod.def;A(i.innerType,t,n);const o=t.seen.get(e);o.ref=i.innerType},Ur=new WeakSet([Object.prototype,Error.prototype]);function Re(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){const n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var Za=(e,t)=>{qn.init(e,t),e.name="ZodError";const r=Object.getPrototypeOf(e);Ur.has(r)||(Ur.add(r),Re(r,"format",n=>i=>Qn(n,i)),Re(r,"flatten",n=>i=>Xn(n,i)),Re(r,"addIssue",n=>i=>{n.issues.push(i),n.message=JSON.stringify(n.issues,Fe,2)}),Re(r,"addIssues",n=>i=>{n.issues.push(...i),n.message=JSON.stringify(n.issues,Fe,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},R=l("ZodError",Za,void 0,{Parent:Error}),Ca=He(R),Ra=qe(R),Na=Ye(R),ja=Xe(R),Ma=oi(R),Da=si(R),xa=ai(R),La=ci(R),Fa=ui(R),Ua=li(R),Wa=fi(R),Ba=di(R);function Ja(){j.localeError||J(ls())}function ft(){j.memoizer||J({memoizer:as()})}var E=l("ZodType",(e,t)=>(Ja(),S.init(e,t),e.def=t,e.type=t.type,e),{check(...e){const t=this.def;return this.clone(C(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return U(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Lc(e,t))},superRefine(e,t){return this.check(Fc(e,t))},overwrite(e){return this.check(te(e))},optional(){return Hr(this)},exactOptional(){return $c(this)},nullable(){return Yr(this)},nullish(){return Hr(Yr(this))},nonoptional(e){return Cc(this,e)},array(){return dt(this)},or(e){return Kr([this,e])},and(e){return zc(this,e)},transform(e){return Qr(this,Ec(e))},default(e){return Tc(this,e)},prefault(e){return Zc(this,e)},catch(e){return Nc(this,e)},pipe(e){return Qr(this,e)},readonly(){return Dc(this)},describe(e){const t=this.clone();return fe.add(t,{description:e}),t},meta(...e){if(e.length===0)return fe.get(this);const t=this.clone();return fe.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return jt(this,"~standard",{...Ht(this),jsonSchema:{input:Ce(this,"input"),output:Ce(this,"output")}})},set"~standard"(e){W(this,"~standard",e)},parse:function e(t,r){return Ca(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await Ra(this,t,r,{callee:e})},safeParse(e,t){return Na(this,e,t)},async safeParseAsync(e,t){return ja(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){W(this,"spa",e)},validate(e,t){return ri(this,e,t)},validateAsync(e,t){return ii(this,e,t)},encode:function e(t,r){return Ma(this,t,r,{callee:e})},decode:function e(t,r){return Da(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await xa(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await La(this,t,r,{callee:e})},safeEncode(e,t){return Fa(this,e,t)},safeDecode(e,t){return Ua(this,e,t)},async safeEncodeAsync(e,t){return Wa(this,e,t)},async safeDecodeAsync(e,t){return Ba(this,e,t)},toJSONSchema(e){return ca(this,{})(e)},get description(){return fe.get(this)?.description},get _def(){return this._zod.def}}),Wr=l("_ZodString",(e,t)=>{tt.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>ha(e,r,n,i)},Mt({format:e=>M(e).format??null,minLength:e=>M(e).minimum??null,maxLength:e=>M(e).maximum??null},{regex(...e){return this.check(Js(...e))},includes(...e){return this.check(Gs(...e))},startsWith(...e){return this.check(Hs(...e))},endsWith(...e){return this.check(qs(...e))},min(...e){return this.check(Ze(...e))},max(...e){return this.check(kr(...e))},length(...e){return this.check(Or(...e))},nonempty(...e){return this.check(Ze(1,...e))},lowercase(e){return this.check(Vs(e))},uppercase(e){return this.check(Ks(e))},trim(){return this.check(Xs())},normalize(...e){return this.check(Ys(...e))},toLowerCase(){return this.check(Qs())},toUpperCase(){return this.check(ea())},slugify(){return this.check(ta())}})),Va=l("ZodString",(e,t)=>{tt.init(e,t),Wr.init(e,t)},{email(e){return this.check(ps(Ya,e))},url(e){return this.check(ys(Qa,e))},jwt(e){return this.check(Ns(pc,e))},emoji(e){return this.check(ws(ec,e))},guid(e){return this.check(ms(Xa,e))},uuid(e){return this.check(gs(Ne,e))},uuidv4(e){return this.check(vs(Ne,e))},uuidv6(e){return this.check(bs(Ne,e))},uuidv7(e){return this.check(_s(Ne,e))},nanoid(e){return this.check(ks(tc,e))},cuid(e){return this.check(Os(rc,e))},cuid2(e){return this.check(zs(nc,e))},ulid(e){return this.check(Ss(ic,e))},base64(e){return this.check(Zs(fc,e))},base64url(e){return this.check(Cs(dc,e))},xid(e){return this.check(Es(oc,e))},ksuid(e){return this.check($s(sc,e))},ipv4(e){return this.check(Is(ac,e))},ipv6(e){return this.check(As(cc,e))},cidrv4(e){return this.check(Ts(uc,e))},cidrv6(e){return this.check(Ps(lc,e))},e164(e){return this.check(Rs(hc,e))},datetime(e){return this.check(js(Ka,e))},date(e){return this.check(Ms(Ga,e))},time(e){return this.check(Ds(Ha,e))},duration(e){return this.check(xs(qa,e))}});function w(e){return hs(Va,e)}var z=l("ZodStringFormat",(e,t)=>{O.init(e,t),Wr.init(e,t)}),Ka=l("ZodISODateTime",(e,t)=>{yo.init(e,t),z.init(e,t)}),Ga=l("ZodISODate",(e,t)=>{wo.init(e,t),z.init(e,t)}),Ha=l("ZodISOTime",(e,t)=>{ko.init(e,t),z.init(e,t)}),qa=l("ZodISODuration",(e,t)=>{Oo.init(e,t),z.init(e,t)}),Ya=l("ZodEmail",(e,t)=>{oo.init(e,t),z.init(e,t)}),Xa=l("ZodGUID",(e,t)=>{no.init(e,t),z.init(e,t)}),Ne=l("ZodUUID",(e,t)=>{io.init(e,t),z.init(e,t)}),Qa=l("ZodURL",(e,t)=>{fo.init(e,t),z.init(e,t)}),ec=l("ZodEmoji",(e,t)=>{ho.init(e,t),z.init(e,t)}),tc=l("ZodNanoID",(e,t)=>{po.init(e,t),z.init(e,t)}),rc=l("ZodCUID",(e,t)=>{mo.init(e,t),z.init(e,t)}),nc=l("ZodCUID2",(e,t)=>{go.init(e,t),z.init(e,t)}),ic=l("ZodULID",(e,t)=>{vo.init(e,t),z.init(e,t)}),oc=l("ZodXID",(e,t)=>{bo.init(e,t),z.init(e,t)}),sc=l("ZodKSUID",(e,t)=>{_o.init(e,t),z.init(e,t)}),ac=l("ZodIPv4",(e,t)=>{zo.init(e,t),z.init(e,t)}),cc=l("ZodIPv6",(e,t)=>{Eo.init(e,t),z.init(e,t)}),uc=l("ZodCIDRv4",(e,t)=>{$o.init(e,t),z.init(e,t)}),lc=l("ZodCIDRv6",(e,t)=>{Ao.init(e,t),z.init(e,t)}),fc=l("ZodBase64",(e,t)=>{To.init(e,t),z.init(e,t)}),dc=l("ZodBase64URL",(e,t)=>{Zo.init(e,t),z.init(e,t)}),hc=l("ZodE164",(e,t)=>{Co.init(e,t),z.init(e,t)}),pc=l("ZodJWT",(e,t)=>{No.init(e,t),z.init(e,t)}),Br=l("ZodNumber",(e,t)=>{tr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>pa(e,r,n,i),e.isFinite=!0},Mt({minValue:e=>{const{minimum:t,exclusiveMinimum:r}=M(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{const{maximum:t,exclusiveMaximum:r}=M(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{const{isInt:t,multipleOf:r}=M(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>M(e).format??null},{gt(e,t){return this.check(yr(e,t))},gte(e,t){return this.check(at(e,t))},min(e,t){return this.check(at(e,t))},lt(e,t){return this.check(_r(e,t))},lte(e,t){return this.check(st(e,t))},max(e,t){return this.check(st(e,t))},int(e){return this.check(Jr(e))},safe(e){return this.check(Jr(e))},positive(e){return this.check(yr(0,e))},nonnegative(e){return this.check(at(0,e))},negative(e){return this.check(_r(0,e))},nonpositive(e){return this.check(st(0,e))},multipleOf(e,t){return this.check(wr(e,t))},step(e,t){return this.check(wr(e,t))},finite(){return this}}));function je(e){return Ls(Br,e)}var mc=l("ZodNumberFormat",(e,t)=>{jo.init(e,t),Br.init(e,t)});function Jr(e){return Fs(mc,e)}var gc=l("ZodBoolean",(e,t)=>{Mo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>ma(e,r,n,i)});function V(e){return Us(gc,e)}var vc=l("ZodUnknown",(e,t)=>{Do.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>va(e,r,n,i)});function Vr(){return Ws(vc)}var bc=l("ZodNever",(e,t)=>{xo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>ga(e,r,n,i)});function _c(e){return Bs(bc,e)}var yc=l("ZodArray",(e,t)=>{ft(),Lo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>wa(e,r,n,i),e.element=t.element},{min(e,t){return this.check(Ze(e,t))},nonempty(e){return this.check(Ze(1,e))},max(e,t){return this.check(kr(e,t))},length(e,t){return this.check(Or(e,t))},unwrap(){return this.element}});function dt(e,t){return ra(yc,e,t)}var wc=l("ZodObject",(e,t)=>{ft(),Wo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>ka(e,r,n,i),Wn(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Z(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(C(this._zod.def,{catchall:e}))},passthrough(){return this.clone(C(this._zod.def,{catchall:Vr()}))},loose(){return this.clone(C(this._zod.def,{catchall:Vr()}))},strict(){return this.clone(C(this._zod.def,{catchall:_c()}))},strip(){return this.clone(C(this._zod.def,{catchall:void 0}))},extend(e){return Zn(this,e)},safeExtend(e){return Cn(this,e)},merge(e){return Rn(this,e)},pick(e){return Tn(this,e)},omit(e){return Pn(this,e)},partial(...e){return Ct(Gr,this,e[0])},exactPartial(...e){return Ct(qr,this,e[0],"exactPartial")},required(...e){return Nn(Xr,this,e[0])}});function N(e,t){const r={type:"object",shape:e??{},...g(t)};return new wc(r)}var kc=l("ZodUnion",(e,t)=>{Bo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Oa(e,r,n,i),e.options=t.options});function Kr(e,t){return new kc({type:"union",options:e,...g(t)})}var Oc=l("ZodIntersection",(e,t)=>{Jo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>za(e,r,n,i)});function zc(e,t){return new Oc({type:"intersection",left:e,right:t})}var ht=l("ZodEnum",(e,t)=>{Vo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(n,i,o)=>ba(e,n,i,o),e.enum=t.entries,e.options=[...e._zod.values];const r=new Set(Object.keys(t.entries));e.extract=(n,i)=>{const o={};for(const s of n)if(r.has(s))o[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new ht({...t,checks:[],...g(i),entries:o})},e.exclude=(n,i)=>{const o={...t.entries};for(const s of n)if(r.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new ht({...t,checks:[],...g(i),entries:o})}});function Z(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new ht({type:"enum",entries:r,...g(t)})}var Sc=l("ZodTransform",(e,t)=>{ft(),Ko.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>ya(e,r,n,i),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Lt(e.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(ce(o,r.value,t));else{const s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=e),r.issues.push(ce(s))}};const i=t.transform(r.value,r);return i instanceof Promise?i.then(o=>(r.value=o,r)):(r.value=i,r)}});function Ec(e){return new Sc({type:"transform",transform:e})}var Gr=l("ZodOptional",(e,t)=>{cr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Fr(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Hr(e){return new Gr({type:"optional",innerType:e})}var qr=l("ZodExactOptional",(e,t)=>{Go.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Fr(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function $c(e){return new qr({type:"optional",innerType:e})}var Ic=l("ZodNullable",(e,t)=>{Ho.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Sa(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Yr(e){return new Ic({type:"nullable",innerType:e})}var Ac=l("ZodDefault",(e,t)=>{qo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>$a(e,r,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Tc(e,t){return new Ac({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():At(t)}})}var Pc=l("ZodPrefault",(e,t)=>{Yo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Ia(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Zc(e,t){return new Pc({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():At(t)}})}var Xr=l("ZodNonOptional",(e,t)=>{Xo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Ea(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Cc(e,t){return new Xr({type:"nonoptional",innerType:e,...g(t)})}var Rc=l("ZodCatch",(e,t)=>{Qo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Aa(e,r,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Nc(e,t){return new Rc({type:"catch",innerType:e,catchValue:typeof t=="function"?t:Jn(t)})}var jc=l("ZodPipe",(e,t)=>{es.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Ta(e,r,n,i),e.in=t.in,e.out=t.out});function Qr(e,t){return new jc({type:"pipe",in:e,out:t})}var Mc=l("ZodReadonly",(e,t)=>{ts.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Pa(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Dc(e){return new Mc({type:"readonly",innerType:e})}var en=l("ZodCustom",(e,t)=>{rs.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>_a(e,r,n,i)});function xc(e,t){return na(en,e??(()=>!0),t)}function Lc(e,t={}){return ia(en,e,t)}function Fc(e,t){return oa(e,t)}var pt=/^#[0-9a-fA-F]{6}$/,mt="Color must be a 6-digit hex code (e.g. '#3B82F6'). Short hex, rgb(), and named colors are not supported.",Me=N({primaryColor:w().max(20).regex(pt,mt).describe("Primary brand color (hex format, e.g., '#3B82F6')").optional(),backgroundColor:w().max(20).regex(pt,mt).describe("Background color for the widget container").optional(),textColor:w().max(20).regex(pt,mt).describe("Text color").optional(),borderRadius:je().describe("Border radius in pixels").optional(),fontFamily:w().max(100).describe("Font family").optional(),colorScheme:Z(["light","dark","auto"]).describe("Widget color scheme: 'light' (default), 'dark', or 'auto' (follows the visitor's prefers-color-scheme).").optional()}),Ou=Z(["mobile","tablet","desktop"]).describe("Viewport mode: mobile (<480px), tablet (480-768px), desktop (>768px)"),gt=Z(["bottom-right","bottom-left","inline"]).describe("Widget position on the page"),Uc=N({mobile:je().min(0).max(1e3).describe("Max width for mobile viewport (default: 480)").optional(),tablet:je().min(0).max(2e3).describe("Max width for tablet viewport (default: 768)").optional()}),Wc=N({enabled:V().describe("Enable responsive behavior (default: true)").optional(),breakpoints:Uc.describe("Custom breakpoint values").optional()}),zu=300,Bc=N({theme:Me.describe("Custom theme configuration").optional(),position:gt.describe("Widget position (default: 'bottom-right')").optional(),open:V().describe("Initial open state (default: false)").optional(),container:Kr([xc(e=>e instanceof HTMLElement),w().max(200)]).describe("Container element for inline mode").optional(),baseUrl:w().url().max(200).describe("Base URL for the widget embed (default: production URL)").optional(),debug:V().describe("Enable debug logging").optional(),responsive:Wc.describe("Responsive behavior configuration").optional(),showProfile:V().describe("Force the profile panel visible in the widget header from the start of the conversation. The panel already shows on its own once the visitor's profile has data, regardless of this flag (default: false).").optional(),language:w().max(10).describe("Language for UI labels (e.g., 'fr', 'en'). Defaults to browser language.").optional(),apiKey:w().max(100).describe("Publishable API key (pk_*) for application authentication"),email:w().email().max(255).describe("Pre-identified user email (host-attested identity)").optional(),userId:w().max(255).describe("Host-side unique user identifier").optional(),userHash:w().max(128).describe("HMAC-SHA256 of email (or userId), signed with identity secret").optional(),initialMessage:w().max(300).describe("Auto-sent first visitor message, injected once via postMessage when the widget is ready (e.g. a demo deep-link). Never carried on the iframe URL. The authoritative bound is enforced again at the embed's trust boundary (useEmbedChatHandlers' INIT handler), this schema is not the sole enforcement point.").optional()}),Jc=N({theme:Me.describe("Full visual theme palette applied by the widget. Admin-configured, no client-side override.").optional(),position:gt.describe("Default launcher position. `inline` only applies when integrator supplies `data-container`.").optional(),language:w().max(10).describe("Locale forced for widget UI labels (ISO 639-1). Falls back to browser language when null.").optional(),showProfile:V().describe("Forces the profile panel visible from the start of the conversation. The panel already shows on its own once the visitor's profile has data, regardless of this flag.").optional(),open:V().describe("Default open state on load. Host can still call `window.Gamaro.open()` programmatically.").optional(),brand:N({title:w().max(60).describe("Custom widget header title. Falls back to a vertical-specific default (e.g. 'Gamaro Chat' for B2B) when unset.").optional(),avatarUrl:w().url().max(2048).describe("Public URL of the custom widget avatar (PNG or JPEG). MUST originate from the branding-upload endpoint — arbitrary external URLs are rejected at the API boundary.").optional()}).strict().describe("White-label branding overrides (issue #1083 Piste 5). Both fields are optional.").optional()}).strict(),tn=N({applicationId:w().uuid().describe("Application UUID"),applicationSlug:w().max(100).describe("Application slug (kebab-case)"),applicationName:w().max(200).describe("Application display name"),vertical:w().max(50).describe("Vertical resolved from Application config"),theme:Me.nullable().describe("Application theme"),allowedOrigins:dt(w().max(200)).max(50).describe("Allowed origins for this application"),monitoring:V().describe("Monitoring enabled flag"),primaryObjective:N({id:w().uuid(),type:w(),label:w(),ctaLabel:w().nullable()}).nullable().describe("Primary conversion objective"),identityVerificationRequired:V().describe("Whether HMAC identity verification is required"),widget:Jc.nullable().describe("Admin-configured widget runtime config (theme, position, language, showProfile, open). Null when the application has not yet persisted a widget_config JSONB.")}),Vc=Z(["user","assistant"]).describe("Message sender role"),Kc=N({role:Vc.describe("Message sender role"),content:w().max(1e4).describe("Message content (max 10000 characters)")}),Gc={INIT:"gamaro:init",OPEN:"gamaro:open",CLOSE:"gamaro:close",RESET:"gamaro:reset",SET_THEME:"gamaro:setTheme",VIEWPORT:"gamaro:viewport",IDENTIFY:"gamaro:identify",READY:"gamaro:ready",PROFILE_UPDATE:"gamaro:profile-update",MESSAGE:"gamaro:message",QUALIFIED:"gamaro:qualified",ERROR:"gamaro:error",QUOTA_WARNING:"gamaro:quota-warning",QUOTA_EXCEEDED:"gamaro:quota-exceeded",FUNNEL_STAGE_CHANGE:"gamaro:funnel-stage-change",CTA_SHOWN:"gamaro:cta-shown",CTA_CLICKED:"gamaro:cta-clicked",LEAD_CAPTURED:"gamaro:lead-captured",IDENTITY_VERIFIED:"gamaro:identity-verified"},Su=N({reason:Z(["timeout","error"]).describe("Why the iframe load failed (timeout vs. transport error)"),attempts:je().int().min(1).describe("Total attempts made before giving up (e.g. 3 = 1 + 2 retries)")}).describe("Payload emitted with the widget-unavailable SDK event (#867)"),Hc=Z(["prospect","partner","unknown"]).describe("Type of user"),qc=Z(["ecommerce","real-estate","automotive","travel","recruitment","other"]).describe("Business sector"),Yc=Z(["startup","pme","eti","grand-groupe"]).describe("Company size category"),Xc=Z(["< 10k","10k-50k","50k-200k","> 200k"]).describe("Monthly website traffic"),Qc=Z(["lead-qualification","personalization","cart-abandonment","conversion","other"]).describe("Business objective"),eu=Z(["shopify","woocommerce","prestashop","custom","none"]).describe("E-commerce platform"),tu=Z(["immediate","1-month","3-months","exploring"]).describe("Implementation timeline"),ru=Z(["< 500","500-2000","2000-5000","> 5000"]).describe("Monthly budget range in EUR"),nu=N({userType:Hc.optional().describe("User type: prospect, partner, or unknown"),sector:qc.optional().describe("Business sector"),companySize:Yc.optional().describe("Company size range"),monthlyTraffic:Xc.optional().describe("Monthly website traffic"),objectives:dt(Qc).max(5).describe("List of business objectives (max 5)").optional(),platform:eu.optional().describe("E-commerce platform"),timeline:tu.optional().describe("Project timeline"),budgetRange:ru.optional().describe("Monthly budget range")}),X=class extends Error{constructor(e,t){super(e),this.code=t,this.name="ConfigFetchError"}},rn=1e4;async function nn(e,t,r){const n=t.endsWith("/")?t:`${t}/`,i=new URL("api/application/config",n),o=new AbortController,s=setTimeout(()=>o.abort(),rn),a=r?AbortSignal.any([o.signal,r]):o.signal;let c;try{c=await fetch(i.toString(),{signal:a,headers:{"x-gamaro-key":e}})}catch(d){throw clearTimeout(s),r?.aborted?new X("Config fetch aborted by caller","ABORTED"):d instanceof DOMException&&d.name==="AbortError"?new X(`Config fetch timed out after ${rn}ms`,"TIMEOUT"):new X(`Network error fetching application config: ${d instanceof Error?d.message:String(d)}`,"NETWORK_ERROR")}if(clearTimeout(s),!c.ok){const d=await c.text().catch(()=>"");throw new X(`HTTP ${c.status} fetching application config: ${d}`,`HTTP_${c.status}`)}const u=await c.json(),f=tn.safeParse(u);if(!f.success)throw new X(`Invalid application config response: ${f.error.message}`,"PARSE_ERROR");return f.data}var Eu=5e3,iu=[1e3,3e3],oe=class extends Error{constructor(e,t){super(`Iframe load failed after ${t} attempt(s): ${e}`),this.reason=e,this.attempts=t,this.name="IframeLoadError"}};function ou(e,t){return new Promise((r,n)=>{if(t?.aborted){n(new DOMException("Aborted","AbortError"));return}const i=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))},o=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e);t?.addEventListener("abort",i,{once:!0})})}function su(e,t){return new Promise((r,n)=>{if(e.signal?.aborted){n(new DOMException("Aborted","AbortError"));return}const i=e.buildIframe(),o=e.timeoutMs??5e3;let s=!1,a=!1,c=!1,u=null,f=null,d=null,h=null,p=null;const m=()=>{u!==null&&(clearTimeout(u),u=null),f&&i.removeEventListener("load",f),d&&i.removeEventListener("error",d),h&&window.removeEventListener("message",h),p&&e.signal?.removeEventListener("abort",p)},v=()=>{m(),!s&&i.parentNode&&i.parentNode.removeChild(i)},b=()=>{a&&c&&!s&&(s=!0,m(),r(i))};if(f=()=>{a=!0,b()},d=()=>{v(),n(new oe("error",t+1))},h=_=>{_.source&&(_.source&&_.source!==i.contentWindow||kt(_.origin,e.allowedOrigins)&&Ot(_)&&_.data.type===Gc.READY&&(c=!0,b()))},p=()=>{v(),n(new DOMException("Aborted","AbortError"))},i.addEventListener("load",f),i.addEventListener("error",d),window.addEventListener("message",h),e.signal?.addEventListener("abort",p,{once:!0}),u=setTimeout(()=>{v(),n(new oe("timeout",t+1))},o),e.signal?.aborted){v(),n(new DOMException("Aborted","AbortError"));return}e.container.appendChild(i)})}async function au(e){const t=e.backoffMs??iu,r=t.length+1;for(let n=0;n<r;n++){e.onStateChange?.({kind:"loading",attempt:n});try{const i=await su(e,n);return e.onStateChange?.({kind:"loaded",iframe:i}),i}catch(i){if(i instanceof DOMException&&i.name==="AbortError")throw i;const o=i instanceof oe?i.reason:"error";if(n===r-1)throw e.onStateChange?.({kind:"failed",reason:o,attempts:r}),ve(`Iframe load failed permanently after ${r} attempt(s) (reason: ${o})`),new oe(o,r);const s=t[n]??1e3;e.onStateChange?.({kind:"retrying",attempt:n+1,reason:o}),be(`Iframe load attempt ${n+1} ${o==="timeout"?"timed out":"errored"}, retrying in ${s}ms`),await ou(s,e.signal)}}throw new oe("error",r)}var cu="0.1.0",De="https://gamaro.io/app",uu=[1e3,2e3,3e3,4e3],lu=.3,fu=0,du={mobile:480,tablet:768},on={mobile:{width:"100vw",height:"100vh"},tablet:{width:"90vw",height:"80vh"},desktop:{width:"380px",height:"600px"}},hu=100,pu={position:"fixed",zIndex:"999999",border:"none",overflow:"hidden"},he=`${Q.slow}ms`,sn=`${Q.base}ms`,mu=[`width ${he} ${K.emphasized}`,`height ${he} ${K.emphasized}`,`border-radius ${he} ${K.emphasized}`,`box-shadow ${he} ${K.emphasized}`,`transform ${he} ${K.emphasized}`].join(", "),gu=[`opacity ${sn} ${K.standard}`,`background ${sn} ${K.standard}`].join(", ");function an(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}var xe={"bottom-right":{bottom:"20px",right:"20px"},"bottom-left":{bottom:"20px",left:"20px"}},vu={width:"100%",height:"100%",border:"none",backgroundColor:"transparent"},cn=class{get applicationId(){return this._applicationId}constructor(e){this.version=cu,this.iframe=null,this.container=null,this.skeletonButton=null,this.isOpen=!1,this.isReady=!1,this.isInitialized=!1,this.isDestroyed=!1,this.fetchAbortController=null,this.iframeLoadAbortController=null,this._applicationId="",this.vertical="",this.pendingCommands=[],this.eventHandlers=new Map,this.cleanupListener=null,this.currentViewportMode="desktop",this.mobileMediaQuery=null,this.tabletMediaQuery=null,this.debounceTimer=null,this.viewportChangeHandler=null,this.originalConfig={...e},this.config={position:"bottom-right",open:!1,baseUrl:De,debug:!1,...e},this.instanceId=++fu,this.debugLog=mn(this.config.debug??!1),this.renderSkeleton(),this.resolveConfig()}renderSkeleton(){this.config.position!=="inline"&&(this.container=this.createContainer(),this.renderSkeletonInto(this.container),document.body.appendChild(this.container))}renderSkeletonInto(e){const t=document.createElement("button");return t.type="button",t.setAttribute("aria-label","Loading widget…"),t.style.cssText=["width: 100%","height: 100%","border: none","border-radius: 50%","background: #9ca3af","cursor: default","opacity: 0.6",`transition: ${an()?"none":gu}`].join(";"),e.appendChild(t),this.skeletonButton=t,t}setSkeletonStateUnavailable(){this.skeletonButton&&(this.skeletonButton.dataset.state="unavailable",this.skeletonButton.style.transition="none",this.skeletonButton.style.opacity="0.4",this.skeletonButton.style.cursor="not-allowed",this.skeletonButton.setAttribute("aria-label","Widget temporarily unavailable"))}resolveConfig(){const e=this.config.baseUrl??De;this.fetchAbortController=new AbortController;const t=r=>nn(this.config.apiKey,e,this.fetchAbortController?.signal).then(n=>this.applyServerConfig(n)).catch(n=>{const i=n instanceof X?n.code:"UNKNOWN_ERROR",o=n instanceof Error?n.message:"Unknown config fetch error";if(i==="ABORTED"||this.isDestroyed)return;const s=uu[r];if(s!==void 0&&this.isTransientFetchError(i)){const a=s*(1+(Math.random()*2-1)*lu);return be(`Config fetch failed transiently (${i}), retrying in ${Math.round(a)}ms`),new Promise(c=>setTimeout(()=>{this.isDestroyed||c(t(r+1))},a))}ve(`Config fetch failed — widget stays in degraded mode: ${o}`),this.emit("error",{code:i,message:o})});t(0)}isTransientFetchError(e){return e==="NETWORK_ERROR"||e==="TIMEOUT"||e.startsWith("HTTP_5")}applyServerConfig(e){if(this.isDestroyed)return;this._applicationId=e.applicationId,this.vertical=e.vertical;const t=e.widget??{};this.config={...this.config,theme:{...e.theme??{},...t.theme??{},...this.originalConfig.theme??{}},position:this.originalConfig.position??t.position??this.config.position,language:this.originalConfig.language??t.language??this.config.language,showProfile:this.originalConfig.showProfile??t.showProfile??this.config.showProfile,open:this.originalConfig.open??t.open??this.config.open},this.init().then(()=>be(`Widget v${this.version} ready (app: ${e.applicationSlug})`))}flushPendingCommands(){const e=this.pendingCommands;this.pendingCommands=[],e.forEach(t=>t())}async init(){if(this.isDestroyed)return;this.container?.remove(),this.skeletonButton=null,this.container=this.createContainer();let e=null;this.config.position!=="inline"&&(e=this.renderSkeletonInto(this.container)),this.attachContainerToDom(),this.iframeLoadAbortController=new AbortController;let t;try{t=await au({buildIframe:()=>this.createIframe(),container:this.container,allowedOrigins:[this.resolveReadyOrigin()],signal:this.iframeLoadAbortController.signal,onStateChange:r=>{r.kind==="failed"&&this.setSkeletonStateUnavailable()}})}catch(r){if(this.isDestroyed||r instanceof DOMException&&r.name==="AbortError")return;r instanceof oe?(this.emit("widget-unavailable",{reason:r.reason,attempts:r.attempts}),this.emit("error",{code:"IFRAME_UNAVAILABLE",message:`Iframe load failed after ${r.attempts} attempt(s): ${r.reason}`})):this.emit("error",{code:"IFRAME_UNAVAILABLE",message:r instanceof Error?r.message:String(r)});return}if(this.isDestroyed){t.remove();return}this.iframe=t,e?.remove(),this.skeletonButton=null,this.isReady=!0,this.sendConfig(),this.emit("ready",void 0),this.cleanupListener=bn({onMessage:r=>this.handleMessage(r),debug:this.config.debug,sourceWindow:this.iframe.contentWindow,allowedOrigins:[this.resolveReadyOrigin()]}),this.config.open&&(this.isOpen=!0,this.updateVisibility()),this.setupViewportListener(),this.isInitialized=!0,this.flushPendingCommands(),this.log("Widget initialized",this.config)}resolveReadyOrigin(){const e=this.config.baseUrl??De;try{return new URL(e).origin}catch{return e}}attachContainerToDom(){this.container&&(this.config.position==="inline"&&this.config.container?(typeof this.config.container=="string"?document.querySelector(this.config.container):this.config.container)?.appendChild(this.container):document.body.appendChild(this.container))}createContainer(){const e=document.createElement("div");if(e.id=`gamaro-widget-container-${this.instanceId}`,this.config.position==="inline")Object.assign(e.style,{position:"relative",width:"100%",height:"100%",border:"none",borderRadius:"16px",overflow:"hidden",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.1)"});else{Object.assign(e.style,pu);const t=xe[this.config.position??"bottom-right"];Object.assign(e.style,t),e.style.width="60px",e.style.height="60px",e.style.borderRadius="50%"}return e}createIframe(){const e=document.createElement("iframe");return e.id=`gamaro-widget-iframe-${this.instanceId}`,e.src=this.buildIframeUrl(),e.setAttribute("title","Gamaro Chat Widget"),e.setAttribute("allow","clipboard-write; geolocation"),Object.assign(e.style,vu),e}buildIframeUrl(){const e=this.config.baseUrl??De,t=new URL("/app/widget/embed",e);return this.vertical&&t.searchParams.set("vertical",this.vertical),this.config.theme&&t.searchParams.set("theme",_n(this.config.theme)),this.config.position==="inline"&&t.searchParams.set("mode","inline"),this.config.open&&t.searchParams.set("open","true"),this.config.showProfile&&t.searchParams.set("showProfile","true"),this.config.language&&t.searchParams.set("language",this.config.language),this.config.apiKey&&t.searchParams.set("apiKey",this.config.apiKey),t.searchParams.set("hostOrigin",window.location.origin),t.toString()}setupViewportListener(){if(this.config.position==="inline"||this.config.responsive?.enabled===!1)return;const e={...du,...this.config.responsive?.breakpoints};this.mobileMediaQuery=window.matchMedia(`(max-width: ${e.mobile}px)`),this.tabletMediaQuery=window.matchMedia(`(max-width: ${e.tablet}px)`),this.viewportChangeHandler=()=>this.handleViewportChange(),this.mobileMediaQuery.addEventListener("change",this.viewportChangeHandler),this.tabletMediaQuery.addEventListener("change",this.viewportChangeHandler),this.currentViewportMode=this.getViewportMode(),this.log("Initial viewport mode:",this.currentViewportMode)}handleViewportChange(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{const e=this.getViewportMode();e!==this.currentViewportMode&&(this.currentViewportMode=e,this.log("Viewport changed:",e),this.isOpen&&this.updateContainerForViewport(e),this.iframe&&this.isReady&&G(this.iframe,{type:"gamaro:viewport",mode:e},this.resolveReadyOrigin()))},hu)}getViewportMode(){return this.mobileMediaQuery?.matches?"mobile":this.tabletMediaQuery?.matches?"tablet":"desktop"}applyContainerTransition(){this.container&&(this.container.style.transition=an()?"none":mu)}updateContainerForViewport(e){if(!this.container)return;this.applyContainerTransition();const t=on[e];if(e==="mobile")Object.assign(this.container.style,{width:t.width,height:t.height,inset:"0",bottom:"auto",right:"auto",left:"auto",borderRadius:"0",maxWidth:"none",transform:"none"});else if(e==="tablet"){const r=xe[this.config.position??"bottom-right"];Object.assign(this.container.style,{width:t.width,height:t.height,inset:"auto",maxWidth:"500px",borderRadius:"16px",left:"50%",right:"auto",transform:"translateX(-50%)",bottom:r.bottom??"20px"})}else{const r=xe[this.config.position??"bottom-right"];Object.assign(this.container.style,{width:t.width,height:t.height,inset:"auto",maxWidth:"none",borderRadius:"16px",transform:"none",...r})}}handleMessage(e){switch(this.log("Received event:",e),e.type){case"gamaro:ready":if(this.isReady)break;this.isReady=!0,this.sendConfig(),this.emit("ready",void 0);break;case"gamaro:profile-update":this.emit("profile-update",void 0);break;case"gamaro:message":this.emit("message",e.message);break;case"gamaro:qualified":this.emit("qualified",void 0);break;case"gamaro:error":this.emit("error",{code:e.code,message:e.message});break;case"gamaro:open":this.isOpen=!0,this.updateVisibility(),this.emit("open",void 0);break;case"gamaro:close":this.isOpen=!1,this.updateVisibility(),this.emit("close",void 0);break;case"gamaro:quota-warning":this.emit("quota-warning",{remaining:e.remaining,limit:e.limit});break;case"gamaro:quota-exceeded":this.emit("quota-exceeded",void 0);break;case"gamaro:identity-verified":this.emit("identity-verified",{email:e.email,userId:e.userId});break;case"gamaro:funnel-stage-change":this.emit("funnel-stage-change",{stage:e.stage,previousStage:e.previousStage});break;case"gamaro:cta-shown":case"gamaro:cta-clicked":{const{ctaType:t,objectiveId:r}=e;this.emit(e.type==="gamaro:cta-shown"?"cta-shown":"cta-clicked",{ctaType:t,...r&&{objectiveId:r}});break}case"gamaro:lead-captured":this.emit("lead-captured",{hasEmail:e.hasEmail,hasPhone:e.hasPhone})}}sendConfig(){if(!this.iframe||!this.isReady)return;const{container:e,...t}=this.config,r={type:"gamaro:init",config:t};G(this.iframe,r,this.resolveReadyOrigin())}updateVisibility(){if(this.container&&this.config.position!=="inline")if(this.applyContainerTransition(),this.isOpen){if(this.config.responsive?.enabled!==!1)this.updateContainerForViewport(this.currentViewportMode);else{const e=on.desktop;this.container.style.width=e.width,this.container.style.height=e.height,this.container.style.borderRadius="16px"}this.container.style.boxShadow="0 10px 40px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(0, 0, 0, 0.05)"}else{const e=xe[this.config.position??"bottom-right"];Object.assign(this.container.style,{width:"60px",height:"60px",borderRadius:"50%",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",inset:"auto",maxWidth:"none",transform:"none",...e})}}emit(e,t){const r=this.eventHandlers.get(e);r&&r.forEach(n=>{try{n(t)}catch(i){ve(`Error in event handler for "${e}":`,i)}})}open(){if(!this.isInitialized){this.pendingCommands.push(()=>this.open());return}this.iframe&&(this.isOpen=!0,this.updateVisibility(),this.isReady&&G(this.iframe,{type:"gamaro:open"},this.resolveReadyOrigin()))}close(){if(!this.isInitialized){this.pendingCommands.push(()=>this.close());return}this.iframe&&(this.isOpen=!1,this.updateVisibility(),this.isReady&&G(this.iframe,{type:"gamaro:close"},this.resolveReadyOrigin()))}reset(){if(!this.isInitialized){this.pendingCommands.push(()=>this.reset());return}!this.iframe||!this.isReady||G(this.iframe,{type:"gamaro:reset"},this.resolveReadyOrigin())}identify(e){if(this.config={...this.config,email:e.email,userId:e.userId,userHash:e.userHash},!this.isInitialized){this.pendingCommands.push(()=>this.identify(e));return}this.iframe&&this.isReady&&G(this.iframe,{type:"gamaro:identify",email:e.email,userId:e.userId,userHash:e.userHash},this.resolveReadyOrigin())}setTheme(e){if(this.config.theme={...this.config.theme,...e},!this.isInitialized){this.pendingCommands.push(()=>this.setTheme(e));return}this.iframe&&this.isReady&&G(this.iframe,{type:"gamaro:setTheme",theme:this.config.theme},this.resolveReadyOrigin())}setColorScheme(e){this.setTheme({colorScheme:e})}on(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,new Set),this.eventHandlers.get(e).add(t)}off(e,t){const r=this.eventHandlers.get(e);r&&r.delete(t)}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.fetchAbortController?.abort(),this.fetchAbortController=null,this.iframeLoadAbortController?.abort(),this.iframeLoadAbortController=null,this.cleanupListener?.(),this.viewportChangeHandler&&(this.mobileMediaQuery?.removeEventListener("change",this.viewportChangeHandler),this.tabletMediaQuery?.removeEventListener("change",this.viewportChangeHandler),this.viewportChangeHandler=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.container?.remove(),this.iframe=null,this.container=null,this.skeletonButton=null,this.mobileMediaQuery=null,this.tabletMediaQuery=null,this.eventHandlers.clear(),this.pendingCommands=[])}log(e,...t){const r=t.map(n=>{if(n==null||typeof n!="object")return n;if(n instanceof HTMLElement)return`[HTMLElement: ${n.tagName}]`;try{const i=new WeakSet;return JSON.parse(JSON.stringify(n,(o,s)=>{if(s instanceof HTMLElement)return`[HTMLElement: ${s.tagName}]`;if(typeof s=="object"&&s!==null){if(i.has(s))return"[Circular]";i.add(s)}return s}))}catch{return"[Unserializable]"}});this.debugLog(e,...r)}};function un(e){return new cn(e)}var vt=new WeakSet;function ln(e){const t=e.getAttribute("data-api-key")??void 0;if(!t)return ve("Missing required data-api-key attribute on script tag"),null;const r=e.dataset.container,n=e.dataset.baseUrl,i=e.dataset.debug==="true",o=e.dataset.email,s=e.getAttribute("data-user-id")??void 0,a=e.getAttribute("data-user-hash")??void 0;return{apiKey:t,container:r,baseUrl:n,debug:i,...o&&{email:o},...s&&{userId:s},...a&&{userHash:a}}}function fn(){if(document.currentScript instanceof HTMLScriptElement)return document.currentScript;const e=document.querySelectorAll("script[src]");for(const t of e){const r=t.src.toLowerCase();if(r.includes("gamaro")||r.includes("widget"))return t}return null}function bt(){const e=document.querySelectorAll("script[data-api-key]");if(e.length===0){const t=fn();t&&t.hasAttribute("data-api-key")&&!vt.has(t)&&dn(t);return}for(const t of e)dn(t)}function dn(e){if(vt.has(e))return;vt.add(e);const t=ln(e);if(!t)return;const r=un(t);window.Gamaro||(window.Gamaro=r),window.GamaroApps||(window.GamaroApps=new Map),r.on("ready",()=>{r.applicationId&&window.GamaroApps&&window.GamaroApps.set(r.applicationId,r)}),be(`Widget v${r.version} initializing...`)}typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",bt):bt()),I.ConfigFetchError=X,I.GamaroWidget=cn,I.__autoInit=bt,I.__getCurrentScript=fn,I.__parseScriptAttributes=ln,I.applicationConfigResponseSchema=tn,I.b2bProfileSchema=nu,I.createWidget=un,I.fetchApplicationConfig=nn,I.themeConfigSchema=Me,I.widgetConfigSchema=Bc,I.widgetMessageSchema=Kc,I.widgetPositionSchema=gt});
82
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const a=s[1];if(t===s[0]){o(s);continue}if(e.external){const c=e.external.registry.get(s[0])?.id;if(t!==s[0]&&c){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}a.count>1&&e.reused==="ref"&&o(s)}e.external&&(e.sharedDefsExtractedFor=e.external)}function $r(e){const t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;const r=[];for(const n of t){if(!n||typeof n!="object")return;$r(n);const i=Object.keys(n);if(i.length!==1||i[0]!=="type")return;const o=n.type;for(const s of Array.isArray(o)?o:[o]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Ir=new Set(["type","properties","required","additionalProperties"]),Ar=["oneOf","anyOf"];function Tr(e){const t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function ct(e){const t=[];for(const o of e){if(typeof o!="object"||o.type!=="object")return null;for(const s in o)if(!Ir.has(s))return null;t.push(o)}const r={},n=new Set;for(const o of t){for(const s in o.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;const a=[];for(const u of t){const f=u.properties?.[s]??Tr(u);f!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(f))||a.push(f))}const c=a.length===1?a[0]:ct(a)??{allOf:a};H(r,s,c)}for(const s of o.required??[])n.add(s)}const i={type:"object",properties:r};if(n.size&&(i.required=[...n]),t.every(o=>o.additionalProperties===!1))i.additionalProperties=!1;else{const o=[];for(const s of t){const a=Tr(s);a&&!o.some(c=>JSON.stringify(c)===JSON.stringify(a))&&o.push(a)}o.length===1?i.additionalProperties=o[0]:o.length>1&&(i.additionalProperties={allOf:o})}return i}function aa(e){const t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(const i of Ir)if(i in e)return;const r=t.filter(i=>Ar.some(o=>Array.isArray(i[o])));let n=null;if(!r.length)n=ct(t);else{const i=r[0],o=Ar.find(c=>Array.isArray(i[c]));if(Object.keys(i).length!==1)return;const s=t.filter(c=>c!==i),a=i[o].map(c=>ct([...s,c]));if(a.some(c=>!c))return;n={[o]:a}}n&&(delete e.allOf,de(e,n))}function Pr(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=a=>{const c=e.seen.get(a);if(c.ref===null)return;const u=c.def??c.schema,f={...u},d=c.ref;if(c.ref=null,d){n(d);const p=e.seen.get(d),m=p.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):de(u,m),de(u,f),a._zod.parent===d)for(const v in u)v==="$ref"||v==="allOf"||v in f||delete u[v];if(m.$ref&&p.def)for(const v in u)v==="$ref"||v==="allOf"||v in p.def&&JSON.stringify(u[v])===JSON.stringify(p.def[v])&&delete u[v]}const h=a._zod.parent;if(h&&h!==d){n(h);const p=e.seen.get(h);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(const m in u)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(u[m])===JSON.stringify(p.def[m])&&delete u[m]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(const a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(const a of e.seen.entries())$r(a[1].def??a[1].schema);for(const a of e.deferred)a();if(e.intersections.length){const a=new Map;for(const c of e.seen.values())for(const u of[c.schema,c.def]){const f=u?.allOf;if(!Array.isArray(f))continue;const d=a.get(f);d?d.push(u):a.set(f,[u])}for(const c of e.intersections)for(const u of a.get(c)??[])aa(u)}}const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(a)}de(i,r.defId?r.schema:r.def??r.schema);const o=e.metadataRegistry.get(t)?.id;o!==void 0&&i.id===o&&delete i.id;const s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(const a of e.seen.entries()){const c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,H(s,c.defId,c.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{const a=JSON.parse(JSON.stringify(i));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ce(t,"input",e.processors),output:Ce(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function T(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return T(n.element,r);if(n.type==="set")return T(n.valueType,r);if(n.type==="lazy")return T(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return T(n.innerType,r);if(n.type==="intersection")return T(n.left,r)||T(n.right,r);if(n.type==="record"||n.type==="map")return T(n.keyType,r)||T(n.valueType,r);if(n.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:T(n.in,r)||T(n.out,r);if(n.type==="object"){for(const i in n.shape)if(T(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(const i of n.options)if(T(i,r))return!0;return!1}if(n.type==="tuple"){for(const i of n.items)if(T(i,r))return!0;return!!(n.rest&&T(n.rest,r))}return!1}var ca=(e,t={})=>r=>{const n=zr({...r,processors:t});return A(e,n),Er(n,e),Pr(n,e)},Ce=(e,t,r={})=>n=>{const{libraryOptions:i,target:o}=n??{},s=zr({...i??{},target:o,io:t,processors:r});return A(e,s),Er(s,e),Pr(s,e)},ne=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},ie=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},Zr=(e,t)=>{ne(e,"minimum",t),ie(e,"maximum",t)},Cr=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},Rr=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Nr=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},jr=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Mr=(e,t)=>ne(e,"minimum",t.minimum),Dr=(e,t)=>ie(e,"maximum",t.maximum),xr=e=>(t,r)=>{jr(t,r.format);const[n,i]=e[r.format];ne(t,"minimum",n),ie(t,"maximum",i)},ua={greater_than:(e,t)=>ne(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>ie(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Cr(e,t.value),number_format:xr(Pt),bigint_format:xr(An),min_length:Mr,max_length:Dr,length_equals:(e,t)=>Zr(e,t.length),min_size:Mr,max_size:Dr,size_equals:(e,t)=>Zr(e,t.size),string_format:(e,t)=>{jr(e,t.format),t.pattern&&Rr(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Nr(e,t.mime)};function M(e){const t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(const o of n)ua[o._zod.def.check]?.(t,o._zod.def);const i=e._zod.bag;i.minimum!==void 0&&ne(t,"minimum",i.minimum),i.exclusiveMinimum!==void 0&&ne(t,"exclusiveMinimum",i.exclusiveMinimum),i.maximum!==void 0&&ie(t,"maximum",i.maximum),i.exclusiveMaximum!==void 0&&ie(t,"exclusiveMaximum",i.exclusiveMaximum),i.multipleOf!==void 0&&Cr(t,i.multipleOf),i.format!==void 0&&(t.format??(t.format=i.format),i.format.includes("int")&&(t.isInt=!0)),i.mime&&Nr(t,i.mime);for(const o of i.patterns??[])Rr(t,o);return t}var la={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},fa=new Map([[er,Ai],[rt,Ti]]),da=e=>fa.get(e)??e,ha=(e,t,r,n)=>{const i=r;i.type="string";const{minimum:o,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:f}=M(e);if(typeof o=="number"&&(i.minLength=o),typeof s=="number"&&(i.maxLength=s),a&&(i.format=la[a]??a,i.format===""&&delete i.format,(a==="time"||f)&&delete i.format),u&&(i.contentEncoding=u),c&&c.size>0){const d=[...c].map(da);d.length===1?i.pattern=d[0].source:d.length>1&&(i.allOf=[...d.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},pa=(e,t,r,n)=>{const i=r,{minimum:o,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:f}=M(e);i.type=f?"integer":"number";const d=typeof u=="number"&&u>=(o??Number.NEGATIVE_INFINITY),h=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=t.target==="draft-04"||t.target==="openapi-3.0";if(d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof o=="number"&&(i.minimum=o),h?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof s=="number"&&(i.maximum=s),a){const m=new Set;for(const _ of a)Number.isFinite(_)&&_!==0?m.add(Math.abs(_)):re(e,t,i,n,`A multipleOf divisor of ${_} cannot be represented in JSON Schema`);const[v,...b]=m;v!==void 0&&(i.multipleOf=v),b.length&&(i.allOf=[...i.allOf??[],...b.map(_=>({multipleOf:_}))])}},ma=(e,t,r,n)=>{r.type="boolean"},ga=(e,t,r,n)=>{r.not={}},va=(e,t,r,n)=>{},ba=(e,t,r,n)=>{const i=e._zod.def,o=Le(i.entries);if(o.length===0){r.not={};return}o.every(s=>typeof s=="number")&&(r.type="number"),o.every(s=>typeof s=="string")&&(r.type="string"),r.enum=o},_a=(e,t,r,n)=>{re(e,t,r,n,"Custom types cannot be represented in JSON Schema")},ya=(e,t,r,n)=>{re(e,t,r,n,"Transforms cannot be represented in JSON Schema")},wa=(e,t,r,n)=>{const i=r,o=e._zod.def,{minimum:s,maximum:a}=M(e);typeof s=="number"&&(i.minItems=s),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=A(o.element,t,{...n,path:[...n.path,"items"]})};function ut(e){const t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?ut(t.out):t.type==="catch"?ut(t.innerType):e._zod.optin}var ka=(e,t,r,n)=>{const i=r,o=e._zod.def,s=o.shape;if(Object.getOwnPropertySymbols(s).length&&re(e,t,i,n,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(const c in s)H(i.properties,c,A(s[c],t,{...n,path:[...n.path,"properties",c]}));const a=[];for(const c of Object.keys(s)){const u=o.shape[c];(t.io==="input"?ut(u)===void 0:u._zod.optout===void 0)&&a.push(c)}a.length>0&&(i.required=a),o.catchall?._zod.def.type==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=A(o.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},Oa=(e,t,r,n)=>{const i=e._zod.def,o=i.inclusive===!1,s=i.options.map((a,c)=>A(a,t,{...n,path:[...n.path,o?"oneOf":"anyOf",c]}));o?r.oneOf=s:r.anyOf=s},za=(e,t,r,n)=>{const i=e._zod.def,o=A(i.left,t,{...n,path:[...n.path,"allOf",0]}),s=A(i.right,t,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];r.allOf=c,t.intersections.push(c)},Sa=(e,t,r,n)=>{const i=e._zod.def,o=A(i.innerType,t,n),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=i.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]},Ea=(e,t,r,n)=>{const i=e._zod.def;A(i.innerType,t,n);const o=t.seen.get(e);o.ref=i.innerType},lt=Symbol();function Lr(e,t,r,n,i){let o=!1;const s=JSON.stringify(e,(a,c)=>typeof c!="bigint"?c:(o=!0,null));return o?(re(t,r,n,i,"BigInt defaults cannot be represented in JSON Schema"),lt):JSON.parse(s)}var $a=(e,t,r,n)=>{const i=e._zod.def;A(i.innerType,t,n);const o=t.seen.get(e);o.ref=i.innerType;const s=Lr(i.defaultValue,e,t,r,n);s!==lt&&(r.default=s)},Ia=(e,t,r,n)=>{const i=e._zod.def;A(i.innerType,t,n);const o=t.seen.get(e);if(o.ref=i.innerType,t.io!=="input")return;const s=Lr(i.defaultValue,e,t,r,n);s!==lt&&(r._prefault=s)},Aa=(e,t,r,n)=>{const i=e._zod.def;A(i.innerType,t,n);const o=t.seen.get(e);o.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{re(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},Ta=(e,t,r,n)=>{const i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?i.out:i.in:i.out;A(s,t,n);const a=t.seen.get(e);a.ref=s},Pa=(e,t,r,n)=>{const i=e._zod.def;A(i.innerType,t,n);const o=t.seen.get(e);o.ref=i.innerType,r.readOnly=!0},Fr=(e,t,r,n)=>{const i=e._zod.def;A(i.innerType,t,n);const o=t.seen.get(e);o.ref=i.innerType},Ur=new WeakSet([Object.prototype,Error.prototype]);function Re(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){const n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var Za=(e,t)=>{qn.init(e,t),e.name="ZodError";const r=Object.getPrototypeOf(e);Ur.has(r)||(Ur.add(r),Re(r,"format",n=>i=>Qn(n,i)),Re(r,"flatten",n=>i=>Xn(n,i)),Re(r,"addIssue",n=>i=>{n.issues.push(i),n.message=JSON.stringify(n.issues,Fe,2)}),Re(r,"addIssues",n=>i=>{n.issues.push(...i),n.message=JSON.stringify(n.issues,Fe,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},R=l("ZodError",Za,void 0,{Parent:Error}),Ca=He(R),Ra=qe(R),Na=Ye(R),ja=Xe(R),Ma=oi(R),Da=si(R),xa=ai(R),La=ci(R),Fa=ui(R),Ua=li(R),Wa=fi(R),Ba=di(R);function Ja(){j.localeError||J(ls())}function ft(){j.memoizer||J({memoizer:as()})}var E=l("ZodType",(e,t)=>(Ja(),S.init(e,t),e.def=t,e.type=t.type,e),{check(...e){const t=this.def;return this.clone(C(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return U(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Lc(e,t))},superRefine(e,t){return this.check(Fc(e,t))},overwrite(e){return this.check(te(e))},optional(){return Hr(this)},exactOptional(){return $c(this)},nullable(){return Yr(this)},nullish(){return Hr(Yr(this))},nonoptional(e){return Cc(this,e)},array(){return dt(this)},or(e){return Kr([this,e])},and(e){return zc(this,e)},transform(e){return Qr(this,Ec(e))},default(e){return Tc(this,e)},prefault(e){return Zc(this,e)},catch(e){return Nc(this,e)},pipe(e){return Qr(this,e)},readonly(){return Dc(this)},describe(e){const t=this.clone();return fe.add(t,{description:e}),t},meta(...e){if(e.length===0)return fe.get(this);const t=this.clone();return fe.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return jt(this,"~standard",{...Ht(this),jsonSchema:{input:Ce(this,"input"),output:Ce(this,"output")}})},set"~standard"(e){W(this,"~standard",e)},parse:function e(t,r){return Ca(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await Ra(this,t,r,{callee:e})},safeParse(e,t){return Na(this,e,t)},async safeParseAsync(e,t){return ja(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){W(this,"spa",e)},validate(e,t){return ri(this,e,t)},validateAsync(e,t){return ii(this,e,t)},encode:function e(t,r){return Ma(this,t,r,{callee:e})},decode:function e(t,r){return Da(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await xa(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await La(this,t,r,{callee:e})},safeEncode(e,t){return Fa(this,e,t)},safeDecode(e,t){return Ua(this,e,t)},async safeEncodeAsync(e,t){return Wa(this,e,t)},async safeDecodeAsync(e,t){return Ba(this,e,t)},toJSONSchema(e){return ca(this,{})(e)},get description(){return fe.get(this)?.description},get _def(){return this._zod.def}}),Wr=l("_ZodString",(e,t)=>{tt.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>ha(e,r,n,i)},Mt({format:e=>M(e).format??null,minLength:e=>M(e).minimum??null,maxLength:e=>M(e).maximum??null},{regex(...e){return this.check(Js(...e))},includes(...e){return this.check(Gs(...e))},startsWith(...e){return this.check(Hs(...e))},endsWith(...e){return this.check(qs(...e))},min(...e){return this.check(Ze(...e))},max(...e){return this.check(kr(...e))},length(...e){return this.check(Or(...e))},nonempty(...e){return this.check(Ze(1,...e))},lowercase(e){return this.check(Vs(e))},uppercase(e){return this.check(Ks(e))},trim(){return this.check(Xs())},normalize(...e){return this.check(Ys(...e))},toLowerCase(){return this.check(Qs())},toUpperCase(){return this.check(ea())},slugify(){return this.check(ta())}})),Va=l("ZodString",(e,t)=>{tt.init(e,t),Wr.init(e,t)},{email(e){return this.check(ps(Ya,e))},url(e){return this.check(ys(Qa,e))},jwt(e){return this.check(Ns(pc,e))},emoji(e){return this.check(ws(ec,e))},guid(e){return this.check(ms(Xa,e))},uuid(e){return this.check(gs(Ne,e))},uuidv4(e){return this.check(vs(Ne,e))},uuidv6(e){return this.check(bs(Ne,e))},uuidv7(e){return this.check(_s(Ne,e))},nanoid(e){return this.check(ks(tc,e))},cuid(e){return this.check(Os(rc,e))},cuid2(e){return this.check(zs(nc,e))},ulid(e){return this.check(Ss(ic,e))},base64(e){return this.check(Zs(fc,e))},base64url(e){return this.check(Cs(dc,e))},xid(e){return this.check(Es(oc,e))},ksuid(e){return this.check($s(sc,e))},ipv4(e){return this.check(Is(ac,e))},ipv6(e){return this.check(As(cc,e))},cidrv4(e){return this.check(Ts(uc,e))},cidrv6(e){return this.check(Ps(lc,e))},e164(e){return this.check(Rs(hc,e))},datetime(e){return this.check(js(Ka,e))},date(e){return this.check(Ms(Ga,e))},time(e){return this.check(Ds(Ha,e))},duration(e){return this.check(xs(qa,e))}});function w(e){return hs(Va,e)}var z=l("ZodStringFormat",(e,t)=>{O.init(e,t),Wr.init(e,t)}),Ka=l("ZodISODateTime",(e,t)=>{yo.init(e,t),z.init(e,t)}),Ga=l("ZodISODate",(e,t)=>{wo.init(e,t),z.init(e,t)}),Ha=l("ZodISOTime",(e,t)=>{ko.init(e,t),z.init(e,t)}),qa=l("ZodISODuration",(e,t)=>{Oo.init(e,t),z.init(e,t)}),Ya=l("ZodEmail",(e,t)=>{oo.init(e,t),z.init(e,t)}),Xa=l("ZodGUID",(e,t)=>{no.init(e,t),z.init(e,t)}),Ne=l("ZodUUID",(e,t)=>{io.init(e,t),z.init(e,t)}),Qa=l("ZodURL",(e,t)=>{fo.init(e,t),z.init(e,t)}),ec=l("ZodEmoji",(e,t)=>{ho.init(e,t),z.init(e,t)}),tc=l("ZodNanoID",(e,t)=>{po.init(e,t),z.init(e,t)}),rc=l("ZodCUID",(e,t)=>{mo.init(e,t),z.init(e,t)}),nc=l("ZodCUID2",(e,t)=>{go.init(e,t),z.init(e,t)}),ic=l("ZodULID",(e,t)=>{vo.init(e,t),z.init(e,t)}),oc=l("ZodXID",(e,t)=>{bo.init(e,t),z.init(e,t)}),sc=l("ZodKSUID",(e,t)=>{_o.init(e,t),z.init(e,t)}),ac=l("ZodIPv4",(e,t)=>{zo.init(e,t),z.init(e,t)}),cc=l("ZodIPv6",(e,t)=>{Eo.init(e,t),z.init(e,t)}),uc=l("ZodCIDRv4",(e,t)=>{$o.init(e,t),z.init(e,t)}),lc=l("ZodCIDRv6",(e,t)=>{Ao.init(e,t),z.init(e,t)}),fc=l("ZodBase64",(e,t)=>{To.init(e,t),z.init(e,t)}),dc=l("ZodBase64URL",(e,t)=>{Zo.init(e,t),z.init(e,t)}),hc=l("ZodE164",(e,t)=>{Co.init(e,t),z.init(e,t)}),pc=l("ZodJWT",(e,t)=>{No.init(e,t),z.init(e,t)}),Br=l("ZodNumber",(e,t)=>{tr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>pa(e,r,n,i),e.isFinite=!0},Mt({minValue:e=>{const{minimum:t,exclusiveMinimum:r}=M(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{const{maximum:t,exclusiveMaximum:r}=M(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{const{isInt:t,multipleOf:r}=M(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>M(e).format??null},{gt(e,t){return this.check(yr(e,t))},gte(e,t){return this.check(at(e,t))},min(e,t){return this.check(at(e,t))},lt(e,t){return this.check(_r(e,t))},lte(e,t){return this.check(st(e,t))},max(e,t){return this.check(st(e,t))},int(e){return this.check(Jr(e))},safe(e){return this.check(Jr(e))},positive(e){return this.check(yr(0,e))},nonnegative(e){return this.check(at(0,e))},negative(e){return this.check(_r(0,e))},nonpositive(e){return this.check(st(0,e))},multipleOf(e,t){return this.check(wr(e,t))},step(e,t){return this.check(wr(e,t))},finite(){return this}}));function je(e){return Ls(Br,e)}var mc=l("ZodNumberFormat",(e,t)=>{jo.init(e,t),Br.init(e,t)});function Jr(e){return Fs(mc,e)}var gc=l("ZodBoolean",(e,t)=>{Mo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>ma(e,r,n,i)});function V(e){return Us(gc,e)}var vc=l("ZodUnknown",(e,t)=>{Do.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>va(e,r,n,i)});function Vr(){return Ws(vc)}var bc=l("ZodNever",(e,t)=>{xo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>ga(e,r,n,i)});function _c(e){return Bs(bc,e)}var yc=l("ZodArray",(e,t)=>{ft(),Lo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>wa(e,r,n,i),e.element=t.element},{min(e,t){return this.check(Ze(e,t))},nonempty(e){return this.check(Ze(1,e))},max(e,t){return this.check(kr(e,t))},length(e,t){return this.check(Or(e,t))},unwrap(){return this.element}});function dt(e,t){return ra(yc,e,t)}var wc=l("ZodObject",(e,t)=>{ft(),Wo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>ka(e,r,n,i),Wn(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Z(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(C(this._zod.def,{catchall:e}))},passthrough(){return this.clone(C(this._zod.def,{catchall:Vr()}))},loose(){return this.clone(C(this._zod.def,{catchall:Vr()}))},strict(){return this.clone(C(this._zod.def,{catchall:_c()}))},strip(){return this.clone(C(this._zod.def,{catchall:void 0}))},extend(e){return Zn(this,e)},safeExtend(e){return Cn(this,e)},merge(e){return Rn(this,e)},pick(e){return Tn(this,e)},omit(e){return Pn(this,e)},partial(...e){return Ct(Gr,this,e[0])},exactPartial(...e){return Ct(qr,this,e[0],"exactPartial")},required(...e){return Nn(Xr,this,e[0])}});function N(e,t){const r={type:"object",shape:e??{},...g(t)};return new wc(r)}var kc=l("ZodUnion",(e,t)=>{Bo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Oa(e,r,n,i),e.options=t.options});function Kr(e,t){return new kc({type:"union",options:e,...g(t)})}var Oc=l("ZodIntersection",(e,t)=>{Jo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>za(e,r,n,i)});function zc(e,t){return new Oc({type:"intersection",left:e,right:t})}var ht=l("ZodEnum",(e,t)=>{Vo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(n,i,o)=>ba(e,n,i,o),e.enum=t.entries,e.options=[...e._zod.values];const r=new Set(Object.keys(t.entries));e.extract=(n,i)=>{const o={};for(const s of n)if(r.has(s))o[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new ht({...t,checks:[],...g(i),entries:o})},e.exclude=(n,i)=>{const o={...t.entries};for(const s of n)if(r.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new ht({...t,checks:[],...g(i),entries:o})}});function Z(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new ht({type:"enum",entries:r,...g(t)})}var Sc=l("ZodTransform",(e,t)=>{ft(),Ko.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>ya(e,r,n,i),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Lt(e.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(ce(o,r.value,t));else{const s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=e),r.issues.push(ce(s))}};const i=t.transform(r.value,r);return i instanceof Promise?i.then(o=>(r.value=o,r)):(r.value=i,r)}});function Ec(e){return new Sc({type:"transform",transform:e})}var Gr=l("ZodOptional",(e,t)=>{cr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Fr(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Hr(e){return new Gr({type:"optional",innerType:e})}var qr=l("ZodExactOptional",(e,t)=>{Go.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Fr(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function $c(e){return new qr({type:"optional",innerType:e})}var Ic=l("ZodNullable",(e,t)=>{Ho.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Sa(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Yr(e){return new Ic({type:"nullable",innerType:e})}var Ac=l("ZodDefault",(e,t)=>{qo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>$a(e,r,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Tc(e,t){return new Ac({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():At(t)}})}var Pc=l("ZodPrefault",(e,t)=>{Yo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Ia(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Zc(e,t){return new Pc({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():At(t)}})}var Xr=l("ZodNonOptional",(e,t)=>{Xo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Ea(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Cc(e,t){return new Xr({type:"nonoptional",innerType:e,...g(t)})}var Rc=l("ZodCatch",(e,t)=>{Qo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Aa(e,r,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Nc(e,t){return new Rc({type:"catch",innerType:e,catchValue:typeof t=="function"?t:Jn(t)})}var jc=l("ZodPipe",(e,t)=>{es.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Ta(e,r,n,i),e.in=t.in,e.out=t.out});function Qr(e,t){return new jc({type:"pipe",in:e,out:t})}var Mc=l("ZodReadonly",(e,t)=>{ts.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Pa(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Dc(e){return new Mc({type:"readonly",innerType:e})}var en=l("ZodCustom",(e,t)=>{rs.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,n,i)=>_a(e,r,n,i)});function xc(e,t){return na(en,e??(()=>!0),t)}function Lc(e,t={}){return ia(en,e,t)}function Fc(e,t){return oa(e,t)}var pt=/^#[0-9a-fA-F]{6}$/,mt="Color must be a 6-digit hex code (e.g. '#3B82F6'). Short hex, rgb(), and named colors are not supported.",Me=N({primaryColor:w().max(20).regex(pt,mt).describe("Primary brand color (hex format, e.g., '#3B82F6')").optional(),backgroundColor:w().max(20).regex(pt,mt).describe("Background color for the widget container").optional(),textColor:w().max(20).regex(pt,mt).describe("Text color").optional(),borderRadius:je().describe("Border radius in pixels").optional(),fontFamily:w().max(100).describe("Font family").optional(),colorScheme:Z(["light","dark","auto"]).describe("Widget color scheme: 'light' (default), 'dark', or 'auto' (follows the visitor's prefers-color-scheme).").optional()}),Ou=Z(["mobile","tablet","desktop"]).describe("Viewport mode: mobile (<480px), tablet (480-768px), desktop (>768px)"),gt=Z(["bottom-right","bottom-left","inline"]).describe("Widget position on the page"),Uc=N({mobile:je().min(0).max(1e3).describe("Max width for mobile viewport (default: 480)").optional(),tablet:je().min(0).max(2e3).describe("Max width for tablet viewport (default: 768)").optional()}),Wc=N({enabled:V().describe("Enable responsive behavior (default: true)").optional(),breakpoints:Uc.describe("Custom breakpoint values").optional()}),zu=300,Bc=N({theme:Me.describe("Custom theme configuration").optional(),position:gt.describe("Widget position (default: 'bottom-right')").optional(),open:V().describe("Initial open state (default: false)").optional(),container:Kr([xc(e=>e instanceof HTMLElement),w().max(200)]).describe("Container element for inline mode").optional(),baseUrl:w().url().max(200).describe("Base URL for the widget embed (default: production URL)").optional(),debug:V().describe("Enable debug logging").optional(),responsive:Wc.describe("Responsive behavior configuration").optional(),showProfile:V().describe("Force the profile panel visible in the widget header from the start of the conversation. The panel already shows on its own once the visitor's profile has data, regardless of this flag (default: false).").optional(),language:w().max(10).describe("Language for UI labels (e.g., 'fr', 'en'). Defaults to browser language.").optional(),apiKey:w().max(100).describe("Publishable API key (pk_*) for application authentication"),email:w().email().max(255).describe("Pre-identified user email (host-attested identity)").optional(),userId:w().max(255).describe("Host-side unique user identifier").optional(),userHash:w().max(128).describe("HMAC-SHA256 of email (or userId), signed with identity secret").optional(),initialMessage:w().max(300).describe("Auto-sent first visitor message, injected once via postMessage when the widget is ready (e.g. a demo deep-link). Never carried on the iframe URL. The authoritative bound is enforced again at the embed's trust boundary (useEmbedChatHandlers' INIT handler), this schema is not the sole enforcement point.").optional()}),Jc=N({theme:Me.describe("Full visual theme palette applied by the widget. Admin-configured, no client-side override.").optional(),position:gt.describe("Default launcher position. `inline` only applies when integrator supplies `data-container`.").optional(),language:w().max(10).describe("Locale forced for widget UI labels (ISO 639-1). Falls back to browser language when null.").optional(),showProfile:V().describe("Forces the profile panel visible from the start of the conversation. The panel already shows on its own once the visitor's profile has data, regardless of this flag.").optional(),open:V().describe("Default open state on load. Host can still call `window.Gamaro.open()` programmatically.").optional(),brand:N({title:w().max(60).describe("Custom widget header title. Falls back to a vertical-specific default (e.g. 'Gamaro Chat' for B2B) when unset.").optional(),avatarUrl:w().url().max(2048).describe("Public URL of the custom widget avatar (PNG or JPEG). MUST originate from the branding-upload endpoint — arbitrary external URLs are rejected at the API boundary.").optional()}).strict().describe("White-label branding overrides (issue #1083 Piste 5). Both fields are optional.").optional()}).strict(),tn=N({applicationId:w().uuid().describe("Application UUID"),applicationSlug:w().max(100).describe("Application slug (kebab-case)"),applicationName:w().max(200).describe("Application display name"),vertical:w().max(50).describe("Deprecated: the widget no longer reads it. Still served for already-published widgets that validate it; removed in the next major."),theme:Me.nullable().describe("Application theme"),allowedOrigins:dt(w().max(200)).max(50).describe("Allowed origins for this application"),monitoring:V().describe("Monitoring enabled flag"),primaryObjective:N({id:w().uuid(),type:w(),label:w(),ctaLabel:w().nullable()}).nullable().describe("Primary conversion objective"),identityVerificationRequired:V().describe("Whether HMAC identity verification is required"),widget:Jc.nullable().describe("Admin-configured widget runtime config (theme, position, language, showProfile, open). Null when the application has not yet persisted a widget_config JSONB.")}),Vc=Z(["user","assistant"]).describe("Message sender role"),Kc=N({role:Vc.describe("Message sender role"),content:w().max(1e4).describe("Message content (max 10000 characters)")}),Gc={INIT:"gamaro:init",OPEN:"gamaro:open",CLOSE:"gamaro:close",RESET:"gamaro:reset",SET_THEME:"gamaro:setTheme",VIEWPORT:"gamaro:viewport",IDENTIFY:"gamaro:identify",READY:"gamaro:ready",PROFILE_UPDATE:"gamaro:profile-update",MESSAGE:"gamaro:message",QUALIFIED:"gamaro:qualified",ERROR:"gamaro:error",QUOTA_WARNING:"gamaro:quota-warning",QUOTA_EXCEEDED:"gamaro:quota-exceeded",FUNNEL_STAGE_CHANGE:"gamaro:funnel-stage-change",CTA_SHOWN:"gamaro:cta-shown",CTA_CLICKED:"gamaro:cta-clicked",LEAD_CAPTURED:"gamaro:lead-captured",IDENTITY_VERIFIED:"gamaro:identity-verified"},Su=N({reason:Z(["timeout","error"]).describe("Why the iframe load failed (timeout vs. transport error)"),attempts:je().int().min(1).describe("Total attempts made before giving up (e.g. 3 = 1 + 2 retries)")}).describe("Payload emitted with the widget-unavailable SDK event (#867)"),Hc=Z(["prospect","partner","unknown"]).describe("Type of user"),qc=Z(["ecommerce","real-estate","automotive","travel","recruitment","other"]).describe("Business sector"),Yc=Z(["startup","pme","eti","grand-groupe"]).describe("Company size category"),Xc=Z(["< 10k","10k-50k","50k-200k","> 200k"]).describe("Monthly website traffic"),Qc=Z(["lead-qualification","personalization","cart-abandonment","conversion","other"]).describe("Business objective"),eu=Z(["shopify","woocommerce","prestashop","custom","none"]).describe("E-commerce platform"),tu=Z(["immediate","1-month","3-months","exploring"]).describe("Implementation timeline"),ru=Z(["< 500","500-2000","2000-5000","> 5000"]).describe("Monthly budget range in EUR"),nu=N({userType:Hc.optional().describe("User type: prospect, partner, or unknown"),sector:qc.optional().describe("Business sector"),companySize:Yc.optional().describe("Company size range"),monthlyTraffic:Xc.optional().describe("Monthly website traffic"),objectives:dt(Qc).max(5).describe("List of business objectives (max 5)").optional(),platform:eu.optional().describe("E-commerce platform"),timeline:tu.optional().describe("Project timeline"),budgetRange:ru.optional().describe("Monthly budget range")}),X=class extends Error{constructor(e,t){super(e),this.code=t,this.name="ConfigFetchError"}},rn=1e4;async function nn(e,t,r){const n=t.endsWith("/")?t:`${t}/`,i=new URL("api/application/config",n),o=new AbortController,s=setTimeout(()=>o.abort(),rn),a=r?AbortSignal.any([o.signal,r]):o.signal;let c;try{c=await fetch(i.toString(),{signal:a,headers:{"x-gamaro-key":e}})}catch(d){throw clearTimeout(s),r?.aborted?new X("Config fetch aborted by caller","ABORTED"):d instanceof DOMException&&d.name==="AbortError"?new X(`Config fetch timed out after ${rn}ms`,"TIMEOUT"):new X(`Network error fetching application config: ${d instanceof Error?d.message:String(d)}`,"NETWORK_ERROR")}if(clearTimeout(s),!c.ok){const d=await c.text().catch(()=>"");throw new X(`HTTP ${c.status} fetching application config: ${d}`,`HTTP_${c.status}`)}const u=await c.json(),f=tn.safeParse(u);if(!f.success)throw new X(`Invalid application config response: ${f.error.message}`,"PARSE_ERROR");return f.data}var Eu=5e3,iu=[1e3,3e3],oe=class extends Error{constructor(e,t){super(`Iframe load failed after ${t} attempt(s): ${e}`),this.reason=e,this.attempts=t,this.name="IframeLoadError"}};function ou(e,t){return new Promise((r,n)=>{if(t?.aborted){n(new DOMException("Aborted","AbortError"));return}const i=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))},o=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e);t?.addEventListener("abort",i,{once:!0})})}function su(e,t){return new Promise((r,n)=>{if(e.signal?.aborted){n(new DOMException("Aborted","AbortError"));return}const i=e.buildIframe(),o=e.timeoutMs??5e3;let s=!1,a=!1,c=!1,u=null,f=null,d=null,h=null,p=null;const m=()=>{u!==null&&(clearTimeout(u),u=null),f&&i.removeEventListener("load",f),d&&i.removeEventListener("error",d),h&&window.removeEventListener("message",h),p&&e.signal?.removeEventListener("abort",p)},v=()=>{m(),!s&&i.parentNode&&i.parentNode.removeChild(i)},b=()=>{a&&c&&!s&&(s=!0,m(),r(i))};if(f=()=>{a=!0,b()},d=()=>{v(),n(new oe("error",t+1))},h=_=>{_.source&&(_.source&&_.source!==i.contentWindow||kt(_.origin,e.allowedOrigins)&&Ot(_)&&_.data.type===Gc.READY&&(c=!0,b()))},p=()=>{v(),n(new DOMException("Aborted","AbortError"))},i.addEventListener("load",f),i.addEventListener("error",d),window.addEventListener("message",h),e.signal?.addEventListener("abort",p,{once:!0}),u=setTimeout(()=>{v(),n(new oe("timeout",t+1))},o),e.signal?.aborted){v(),n(new DOMException("Aborted","AbortError"));return}e.container.appendChild(i)})}async function au(e){const t=e.backoffMs??iu,r=t.length+1;for(let n=0;n<r;n++){e.onStateChange?.({kind:"loading",attempt:n});try{const i=await su(e,n);return e.onStateChange?.({kind:"loaded",iframe:i}),i}catch(i){if(i instanceof DOMException&&i.name==="AbortError")throw i;const o=i instanceof oe?i.reason:"error";if(n===r-1)throw e.onStateChange?.({kind:"failed",reason:o,attempts:r}),ve(`Iframe load failed permanently after ${r} attempt(s) (reason: ${o})`),new oe(o,r);const s=t[n]??1e3;e.onStateChange?.({kind:"retrying",attempt:n+1,reason:o}),be(`Iframe load attempt ${n+1} ${o==="timeout"?"timed out":"errored"}, retrying in ${s}ms`),await ou(s,e.signal)}}throw new oe("error",r)}var cu="0.1.0",De="https://gamaro.io/app",uu=[1e3,2e3,3e3,4e3],lu=.3,fu=0,du={mobile:480,tablet:768},on={mobile:{width:"100vw",height:"100vh"},tablet:{width:"90vw",height:"80vh"},desktop:{width:"380px",height:"600px"}},hu=100,pu={position:"fixed",zIndex:"999999",border:"none",overflow:"hidden"},he=`${Q.slow}ms`,sn=`${Q.base}ms`,mu=[`width ${he} ${K.emphasized}`,`height ${he} ${K.emphasized}`,`border-radius ${he} ${K.emphasized}`,`box-shadow ${he} ${K.emphasized}`,`transform ${he} ${K.emphasized}`].join(", "),gu=[`opacity ${sn} ${K.standard}`,`background ${sn} ${K.standard}`].join(", ");function an(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}var xe={"bottom-right":{bottom:"20px",right:"20px"},"bottom-left":{bottom:"20px",left:"20px"}},vu={width:"100%",height:"100%",border:"none",backgroundColor:"transparent"},cn=class{get applicationId(){return this._applicationId}constructor(e){this.version=cu,this.iframe=null,this.container=null,this.skeletonButton=null,this.isOpen=!1,this.isReady=!1,this.isInitialized=!1,this.isDestroyed=!1,this.fetchAbortController=null,this.iframeLoadAbortController=null,this._applicationId="",this.pendingCommands=[],this.eventHandlers=new Map,this.cleanupListener=null,this.currentViewportMode="desktop",this.mobileMediaQuery=null,this.tabletMediaQuery=null,this.debounceTimer=null,this.viewportChangeHandler=null,this.originalConfig={...e},this.config={position:"bottom-right",open:!1,baseUrl:De,debug:!1,...e},this.instanceId=++fu,this.debugLog=mn(this.config.debug??!1),this.renderSkeleton(),this.resolveConfig()}renderSkeleton(){this.config.position!=="inline"&&(this.container=this.createContainer(),this.renderSkeletonInto(this.container),document.body.appendChild(this.container))}renderSkeletonInto(e){const t=document.createElement("button");return t.type="button",t.setAttribute("aria-label","Loading widget…"),t.style.cssText=["width: 100%","height: 100%","border: none","border-radius: 50%","background: #9ca3af","cursor: default","opacity: 0.6",`transition: ${an()?"none":gu}`].join(";"),e.appendChild(t),this.skeletonButton=t,t}setSkeletonStateUnavailable(){this.skeletonButton&&(this.skeletonButton.dataset.state="unavailable",this.skeletonButton.style.transition="none",this.skeletonButton.style.opacity="0.4",this.skeletonButton.style.cursor="not-allowed",this.skeletonButton.setAttribute("aria-label","Widget temporarily unavailable"))}resolveConfig(){const e=this.config.baseUrl??De;this.fetchAbortController=new AbortController;const t=r=>nn(this.config.apiKey,e,this.fetchAbortController?.signal).then(n=>this.applyServerConfig(n)).catch(n=>{const i=n instanceof X?n.code:"UNKNOWN_ERROR",o=n instanceof Error?n.message:"Unknown config fetch error";if(i==="ABORTED"||this.isDestroyed)return;const s=uu[r];if(s!==void 0&&this.isTransientFetchError(i)){const a=s*(1+(Math.random()*2-1)*lu);return be(`Config fetch failed transiently (${i}), retrying in ${Math.round(a)}ms`),new Promise(c=>setTimeout(()=>{this.isDestroyed||c(t(r+1))},a))}ve(`Config fetch failed — widget stays in degraded mode: ${o}`),this.emit("error",{code:i,message:o})});t(0)}isTransientFetchError(e){return e==="NETWORK_ERROR"||e==="TIMEOUT"||e.startsWith("HTTP_5")}applyServerConfig(e){if(this.isDestroyed)return;this._applicationId=e.applicationId;const t=e.widget??{};this.config={...this.config,theme:{...e.theme??{},...t.theme??{},...this.originalConfig.theme??{}},position:this.originalConfig.position??t.position??this.config.position,language:this.originalConfig.language??t.language??this.config.language,showProfile:this.originalConfig.showProfile??t.showProfile??this.config.showProfile,open:this.originalConfig.open??t.open??this.config.open},this.init().then(()=>be(`Widget v${this.version} ready (app: ${e.applicationSlug})`))}flushPendingCommands(){const e=this.pendingCommands;this.pendingCommands=[],e.forEach(t=>t())}async init(){if(this.isDestroyed)return;this.container?.remove(),this.skeletonButton=null,this.container=this.createContainer();let e=null;this.config.position!=="inline"&&(e=this.renderSkeletonInto(this.container)),this.attachContainerToDom(),this.iframeLoadAbortController=new AbortController;let t;try{t=await au({buildIframe:()=>this.createIframe(),container:this.container,allowedOrigins:[this.resolveReadyOrigin()],signal:this.iframeLoadAbortController.signal,onStateChange:r=>{r.kind==="failed"&&this.setSkeletonStateUnavailable()}})}catch(r){if(this.isDestroyed||r instanceof DOMException&&r.name==="AbortError")return;r instanceof oe?(this.emit("widget-unavailable",{reason:r.reason,attempts:r.attempts}),this.emit("error",{code:"IFRAME_UNAVAILABLE",message:`Iframe load failed after ${r.attempts} attempt(s): ${r.reason}`})):this.emit("error",{code:"IFRAME_UNAVAILABLE",message:r instanceof Error?r.message:String(r)});return}if(this.isDestroyed){t.remove();return}this.iframe=t,e?.remove(),this.skeletonButton=null,this.isReady=!0,this.sendConfig(),this.emit("ready",void 0),this.cleanupListener=bn({onMessage:r=>this.handleMessage(r),debug:this.config.debug,sourceWindow:this.iframe.contentWindow,allowedOrigins:[this.resolveReadyOrigin()]}),this.config.open&&(this.isOpen=!0,this.updateVisibility()),this.setupViewportListener(),this.isInitialized=!0,this.flushPendingCommands(),this.log("Widget initialized",this.config)}resolveReadyOrigin(){const e=this.config.baseUrl??De;try{return new URL(e).origin}catch{return e}}attachContainerToDom(){this.container&&(this.config.position==="inline"&&this.config.container?(typeof this.config.container=="string"?document.querySelector(this.config.container):this.config.container)?.appendChild(this.container):document.body.appendChild(this.container))}createContainer(){const e=document.createElement("div");if(e.id=`gamaro-widget-container-${this.instanceId}`,this.config.position==="inline")Object.assign(e.style,{position:"relative",width:"100%",height:"100%",border:"none",borderRadius:"16px",overflow:"hidden",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.1)"});else{Object.assign(e.style,pu);const t=xe[this.config.position??"bottom-right"];Object.assign(e.style,t),e.style.width="60px",e.style.height="60px",e.style.borderRadius="50%"}return e}createIframe(){const e=document.createElement("iframe");return e.id=`gamaro-widget-iframe-${this.instanceId}`,e.src=this.buildIframeUrl(),e.setAttribute("title","Gamaro Chat Widget"),e.setAttribute("allow","clipboard-write; geolocation"),Object.assign(e.style,vu),e}buildIframeUrl(){const e=this.config.baseUrl??De,t=new URL("/app/widget/embed",e);return this.config.theme&&t.searchParams.set("theme",_n(this.config.theme)),this.config.position==="inline"&&t.searchParams.set("mode","inline"),this.config.open&&t.searchParams.set("open","true"),this.config.showProfile&&t.searchParams.set("showProfile","true"),this.config.language&&t.searchParams.set("language",this.config.language),this.config.apiKey&&t.searchParams.set("apiKey",this.config.apiKey),t.searchParams.set("hostOrigin",window.location.origin),t.toString()}setupViewportListener(){if(this.config.position==="inline"||this.config.responsive?.enabled===!1)return;const e={...du,...this.config.responsive?.breakpoints};this.mobileMediaQuery=window.matchMedia(`(max-width: ${e.mobile}px)`),this.tabletMediaQuery=window.matchMedia(`(max-width: ${e.tablet}px)`),this.viewportChangeHandler=()=>this.handleViewportChange(),this.mobileMediaQuery.addEventListener("change",this.viewportChangeHandler),this.tabletMediaQuery.addEventListener("change",this.viewportChangeHandler),this.currentViewportMode=this.getViewportMode(),this.log("Initial viewport mode:",this.currentViewportMode)}handleViewportChange(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{const e=this.getViewportMode();e!==this.currentViewportMode&&(this.currentViewportMode=e,this.log("Viewport changed:",e),this.isOpen&&this.updateContainerForViewport(e),this.iframe&&this.isReady&&G(this.iframe,{type:"gamaro:viewport",mode:e},this.resolveReadyOrigin()))},hu)}getViewportMode(){return this.mobileMediaQuery?.matches?"mobile":this.tabletMediaQuery?.matches?"tablet":"desktop"}applyContainerTransition(){this.container&&(this.container.style.transition=an()?"none":mu)}updateContainerForViewport(e){if(!this.container)return;this.applyContainerTransition();const t=on[e];if(e==="mobile")Object.assign(this.container.style,{width:t.width,height:t.height,inset:"0",bottom:"auto",right:"auto",left:"auto",borderRadius:"0",maxWidth:"none",transform:"none"});else if(e==="tablet"){const r=xe[this.config.position??"bottom-right"];Object.assign(this.container.style,{width:t.width,height:t.height,inset:"auto",maxWidth:"500px",borderRadius:"16px",left:"50%",right:"auto",transform:"translateX(-50%)",bottom:r.bottom??"20px"})}else{const r=xe[this.config.position??"bottom-right"];Object.assign(this.container.style,{width:t.width,height:t.height,inset:"auto",maxWidth:"none",borderRadius:"16px",transform:"none",...r})}}handleMessage(e){switch(this.log("Received event:",e),e.type){case"gamaro:ready":if(this.isReady)break;this.isReady=!0,this.sendConfig(),this.emit("ready",void 0);break;case"gamaro:profile-update":this.emit("profile-update",void 0);break;case"gamaro:message":this.emit("message",e.message);break;case"gamaro:qualified":this.emit("qualified",void 0);break;case"gamaro:error":this.emit("error",{code:e.code,message:e.message});break;case"gamaro:open":this.isOpen=!0,this.updateVisibility(),this.emit("open",void 0);break;case"gamaro:close":this.isOpen=!1,this.updateVisibility(),this.emit("close",void 0);break;case"gamaro:quota-warning":this.emit("quota-warning",{remaining:e.remaining,limit:e.limit});break;case"gamaro:quota-exceeded":this.emit("quota-exceeded",void 0);break;case"gamaro:identity-verified":this.emit("identity-verified",{email:e.email,userId:e.userId});break;case"gamaro:funnel-stage-change":this.emit("funnel-stage-change",{stage:e.stage,previousStage:e.previousStage});break;case"gamaro:cta-shown":case"gamaro:cta-clicked":{const{ctaType:t,objectiveId:r}=e;this.emit(e.type==="gamaro:cta-shown"?"cta-shown":"cta-clicked",{ctaType:t,...r&&{objectiveId:r}});break}case"gamaro:lead-captured":this.emit("lead-captured",{hasEmail:e.hasEmail,hasPhone:e.hasPhone})}}sendConfig(){if(!this.iframe||!this.isReady)return;const{container:e,...t}=this.config,r={type:"gamaro:init",config:t};G(this.iframe,r,this.resolveReadyOrigin())}updateVisibility(){if(this.container&&this.config.position!=="inline")if(this.applyContainerTransition(),this.isOpen){if(this.config.responsive?.enabled!==!1)this.updateContainerForViewport(this.currentViewportMode);else{const e=on.desktop;this.container.style.width=e.width,this.container.style.height=e.height,this.container.style.borderRadius="16px"}this.container.style.boxShadow="0 10px 40px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(0, 0, 0, 0.05)"}else{const e=xe[this.config.position??"bottom-right"];Object.assign(this.container.style,{width:"60px",height:"60px",borderRadius:"50%",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",inset:"auto",maxWidth:"none",transform:"none",...e})}}emit(e,t){const r=this.eventHandlers.get(e);r&&r.forEach(n=>{try{n(t)}catch(i){ve(`Error in event handler for "${e}":`,i)}})}open(){if(!this.isInitialized){this.pendingCommands.push(()=>this.open());return}this.iframe&&(this.isOpen=!0,this.updateVisibility(),this.isReady&&G(this.iframe,{type:"gamaro:open"},this.resolveReadyOrigin()))}close(){if(!this.isInitialized){this.pendingCommands.push(()=>this.close());return}this.iframe&&(this.isOpen=!1,this.updateVisibility(),this.isReady&&G(this.iframe,{type:"gamaro:close"},this.resolveReadyOrigin()))}reset(){if(!this.isInitialized){this.pendingCommands.push(()=>this.reset());return}!this.iframe||!this.isReady||G(this.iframe,{type:"gamaro:reset"},this.resolveReadyOrigin())}identify(e){if(this.config={...this.config,email:e.email,userId:e.userId,userHash:e.userHash},!this.isInitialized){this.pendingCommands.push(()=>this.identify(e));return}this.iframe&&this.isReady&&G(this.iframe,{type:"gamaro:identify",email:e.email,userId:e.userId,userHash:e.userHash},this.resolveReadyOrigin())}setTheme(e){if(this.config.theme={...this.config.theme,...e},!this.isInitialized){this.pendingCommands.push(()=>this.setTheme(e));return}this.iframe&&this.isReady&&G(this.iframe,{type:"gamaro:setTheme",theme:this.config.theme},this.resolveReadyOrigin())}setColorScheme(e){this.setTheme({colorScheme:e})}on(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,new Set),this.eventHandlers.get(e).add(t)}off(e,t){const r=this.eventHandlers.get(e);r&&r.delete(t)}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.fetchAbortController?.abort(),this.fetchAbortController=null,this.iframeLoadAbortController?.abort(),this.iframeLoadAbortController=null,this.cleanupListener?.(),this.viewportChangeHandler&&(this.mobileMediaQuery?.removeEventListener("change",this.viewportChangeHandler),this.tabletMediaQuery?.removeEventListener("change",this.viewportChangeHandler),this.viewportChangeHandler=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.container?.remove(),this.iframe=null,this.container=null,this.skeletonButton=null,this.mobileMediaQuery=null,this.tabletMediaQuery=null,this.eventHandlers.clear(),this.pendingCommands=[])}log(e,...t){const r=t.map(n=>{if(n==null||typeof n!="object")return n;if(n instanceof HTMLElement)return`[HTMLElement: ${n.tagName}]`;try{const i=new WeakSet;return JSON.parse(JSON.stringify(n,(o,s)=>{if(s instanceof HTMLElement)return`[HTMLElement: ${s.tagName}]`;if(typeof s=="object"&&s!==null){if(i.has(s))return"[Circular]";i.add(s)}return s}))}catch{return"[Unserializable]"}});this.debugLog(e,...r)}};function un(e){return new cn(e)}var vt=new WeakSet;function ln(e){const t=e.getAttribute("data-api-key")??void 0;if(!t)return ve("Missing required data-api-key attribute on script tag"),null;const r=e.dataset.container,n=e.dataset.baseUrl,i=e.dataset.debug==="true",o=e.dataset.email,s=e.getAttribute("data-user-id")??void 0,a=e.getAttribute("data-user-hash")??void 0;return{apiKey:t,container:r,baseUrl:n,debug:i,...o&&{email:o},...s&&{userId:s},...a&&{userHash:a}}}function fn(){if(document.currentScript instanceof HTMLScriptElement)return document.currentScript;const e=document.querySelectorAll("script[src]");for(const t of e){const r=t.src.toLowerCase();if(r.includes("gamaro")||r.includes("widget"))return t}return null}function bt(){const e=document.querySelectorAll("script[data-api-key]");if(e.length===0){const t=fn();t&&t.hasAttribute("data-api-key")&&!vt.has(t)&&dn(t);return}for(const t of e)dn(t)}function dn(e){if(vt.has(e))return;vt.add(e);const t=ln(e);if(!t)return;const r=un(t);window.Gamaro||(window.Gamaro=r),window.GamaroApps||(window.GamaroApps=new Map),r.on("ready",()=>{r.applicationId&&window.GamaroApps&&window.GamaroApps.set(r.applicationId,r)}),be(`Widget v${r.version} initializing...`)}typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",bt):bt()),I.ConfigFetchError=X,I.GamaroWidget=cn,I.__autoInit=bt,I.__getCurrentScript=fn,I.__parseScriptAttributes=ln,I.applicationConfigResponseSchema=tn,I.b2bProfileSchema=nu,I.createWidget=un,I.fetchApplicationConfig=nn,I.themeConfigSchema=Me,I.widgetConfigSchema=Bc,I.widgetMessageSchema=Kc,I.widgetPositionSchema=gt});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gamaro.io/widget",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "Gamaro Widget SDK - Embed conversational qualification into your website.",
5
5
  "type": "module",
6
6
  "main": "./dist/widget.umd.js",
@@ -56,7 +56,7 @@
56
56
  }
57
57
  ],
58
58
  "dependencies": {
59
- "@gamaro.io/core-types": "1.1.1",
59
+ "@gamaro.io/core-types": "1.1.2",
60
60
  "zod": "4.6.5"
61
61
  },
62
62
  "devDependencies": {