@elementor/angie-sdk 1.0.5 → 1.0.7

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.
@@ -5,7 +5,7 @@ import { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
5
5
  * between different browser contexts (iframes, workers, tabs, windows, etc.).
6
6
  */
7
7
  export declare class BrowserContextTransport implements Transport {
8
- sessionId: string;
8
+ sessionId?: string;
9
9
  onmessage?: (message: JSONRPCMessage) => void;
10
10
  onerror?: (error: Error) => void;
11
11
  onclose?: () => void;
@@ -15,15 +15,9 @@ export declare class BrowserContextTransport implements Transport {
15
15
  /**
16
16
  * Creates a new BrowserContextTransport using an existing MessagePort.
17
17
  *
18
- * @param { MessagePort } port The MessagePort to use for communication.
19
- * @param { string } sessionId Optional session ID. If not provided, one will be generated.
18
+ * @param { MessagePort } port The MessagePort to use for communication.
20
19
  */
21
- constructor(port: MessagePort, sessionId?: string);
22
- /**
23
- * Internal method to generate a session ID.
24
- * This is separated so it can be used by static methods.
25
- */
26
- private static generateSessionId;
20
+ constructor(port: MessagePort);
27
21
  /**
28
22
  * Starts processing messages on the transport.
29
23
  * This starts the underlying MessagePort if it hasn't been started yet.
@@ -43,9 +37,4 @@ export declare class BrowserContextTransport implements Transport {
43
37
  * This method will call onclose if it's defined.
44
38
  */
45
39
  close(): Promise<void>;
46
- /**
47
- * Generates a simple unique identifier using timestamp and random values.
48
- * This is not a true UUID but is sufficient for session identification.
49
- */
50
- private generateId;
51
40
  }
package/dist/iframe.d.ts CHANGED
@@ -1,27 +1,8 @@
1
- declare global {
2
- interface Window {
3
- angieConfig?: {
4
- version: string;
5
- };
6
- }
7
- }
8
- export declare enum MessageEventType {
9
- SDK_ANGIE_ALL_SERVERS_REGISTERED = "sdk-angie-all-servers-registered",
10
- SDK_ANGIE_READY_PING = "sdk-angie-ready-ping",
11
- SDK_REQUEST_CLIENT_CREATION = "sdk-request-client-creation",
12
- SDK_TRIGGER_ANGIE = "sdk-trigger-angie",
13
- SDK_TRIGGER_ANGIE_RESPONSE = "sdk-trigger-angie-response",
14
- ANGIE_SIDEBAR_RESIZED = "angie-sidebar-resized",
15
- ANGIE_SIDEBAR_TOGGLED = "angie-sidebar-toggled",
16
- ANGIE_CHAT_TOGGLE = "angie-chat-toggle",
17
- ANGIE_STUDIO_TOGGLE = "angie-studio-toggle",
18
- ANGIE_NAVIGATE_TO_URL = "angie/navigate-to-url",
19
- ANGIE_PAGE_RELOAD = "angie/page-reload"
20
- }
21
1
  type OpenIframeProps = {
22
2
  origin?: string;
23
3
  uiTheme: string;
24
4
  isRTL: boolean;
25
5
  };
6
+ export declare const disableNavigationPrevention: () => Promise<void>;
26
7
  export declare const openIframe: (props: OpenIframeProps) => Promise<void>;
27
8
  export {};
package/dist/index.d.ts CHANGED
@@ -2,8 +2,10 @@ export { AngieMcpSdk } from './angie-mcp-sdk';
2
2
  export { AngieDetector } from './angie-detector';
3
3
  export { RegistrationQueue } from './registration-queue';
4
4
  export { ClientManager } from './client-manager';
5
- export { ANGIE_SIDEBAR_STATE_OPEN, applyWidth, getAngieSidebarSavedState, initAngieSidebar, initializeResize, loadState, loadWidth, saveWidth, type AngieSidebarState, } from './sidebar';
5
+ export { ANGIE_SIDEBAR_STATE_OPEN, applyWidth, getAngieSidebarSavedState, initAngieSidebar, initializeResize, loadState, loadWidth, saveState, saveWidth, type AngieSidebarState, } from './sidebar';
6
6
  export { waitForDocumentReady, toggleAngieSidebar } from './utils';
7
7
  export { navigateAngieIframe } from './navigation-utils';
8
8
  export { getAngieIframe } from './angie-iframe-utils';
9
+ export { disableNavigationPrevention } from './iframe';
9
10
  export * from './types';
11
+ export { BrowserContextTransport } from './browser-context-transport';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- const e={none:0,error:1,warn:2,info:3,debug:4},t={error:"error",warn:"warn",info:"info",log:"info",debug:"debug"},n=(t,n)=>e[t]<=e[n],s=e=>"string"==typeof e?e:JSON.stringify(e),r=(e,t)=>`${s(e)} > ${s(t)}`,a=(e,t)=>{let n=`[${s(e)}]`;return typeof window<"u"?{text:`%c${n}`,style:`color: ${t.color||"#00bcd4"}; font-weight: bold;`}:{text:n}},i=(e,s,r,i)=>(...o)=>{if(!n(t[e],i()))return;if(!s)return void console[e](...o);let{text:d,style:c}=a(s,r);c?console[e](d,c,...o):console[e](d,...o)},o=(e,t)=>{let n=t.logLevel??"debug",s=()=>n;return{log:i("log",e,t,s),info:i("info",e,t,s),warn:i("warn",e,t,s),error:i("error",e,t,s),debug:i("debug",e,t,s),setLogLevel:e=>{n=e},extend:s=>o(e?r(e,s):s,{...t,logLevel:n})}},d=o("angie-sdk",{color:"#00bcd4",logLevel:"debug",color:"#00BCD4",logLevel:"error"}),c=e=>d.extend(e);var u,l,h,p,g,m,f;!function(e){e.POST_MESSAGE="postMessage"}(u||(u={})),function(e){e.POST_MESSAGE="postMessage"}(l||(l={})),function(e){e.STREAMABLE_HTTP="streamableHttp",e.SSE="sse"}(h||(h={})),function(e){e.LOCAL="local",e.REMOTE="remote"}(p||(p={})),function(e){e.SDK_ANGIE_READY_PING="sdk-angie-ready-ping",e.SDK_ANGIE_REFRESH_PING="sdk-angie-refresh-ping",e.SDK_REQUEST_CLIENT_CREATION="sdk-request-client-creation",e.SDK_REQUEST_INIT_SERVER="sdk-request-init-server",e.SDK_TRIGGER_ANGIE="sdk-trigger-angie",e.SDK_TRIGGER_ANGIE_RESPONSE="sdk-trigger-angie-response"}(g||(g={})),function(e){e.SET="ANGIE_SET_LOCALSTORAGE",e.GET="ANGIE_GET_LOCALSTORAGE"}(m||(m={})),function(e){e.RESET_HASH="reset-hash",e.HOST_READY="host/ready",e.ANGIE_LOADED="angie/loaded",e.ANGIE_READY="angie/ready"}(f||(f={}));const y=c("angie-detector");class _{isAngieReady=!1;readyPromise;readyResolve;constructor(){if(this.readyPromise=new Promise(e=>{this.readyResolve=e}),"undefined"==typeof window)return;let e=0;const t=()=>{if(this.isAngieReady||e>=500)return void(!this.isAngieReady&&e>=500&&this.handleDetectionTimeout());const n=new MessageChannel;n.port1.onmessage=e=>{this.handleAngieReady(e.data),n.port1.close(),n.port2.close()};const s={type:g.SDK_ANGIE_READY_PING,timestamp:Date.now()};window.postMessage(s,window.location.origin,[n.port2]),e++,setTimeout(t,500)};t()}handleAngieReady(e){this.isAngieReady=!0;const t={isReady:!0,version:e.version,capabilities:e.capabilities};this.readyResolve&&this.readyResolve(t)}handleDetectionTimeout(){this.readyResolve&&this.readyResolve({isReady:!1}),y.warn("Detection timeout - Angie may not be available")}isReady(){return this.isAngieReady}async waitForReady(){return this.readyPromise}}var v,w;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},e.getValidEnumValues=t=>{const n=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),s={};for(const e of n)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(const n of e)if(t(n))return n},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(v||(v={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(w||(w={}));const b=v.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),x=e=>{switch(typeof e){case"undefined":return b.undefined;case"string":return b.string;case"number":return Number.isNaN(e)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(e)?b.array:null===e?b.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?b.promise:"undefined"!=typeof Map&&e instanceof Map?b.map:"undefined"!=typeof Set&&e instanceof Set?b.set:"undefined"!=typeof Date&&e instanceof Date?b.date:b.object;default:return b.unknown}},k=v.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class E extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},n={_errors:[]},s=e=>{for(const r of e.issues)if("invalid_union"===r.code)r.unionErrors.map(s);else if("invalid_return_type"===r.code)s(r.returnTypeError);else if("invalid_arguments"===r.code)s(r.argumentsError);else if(0===r.path.length)n._errors.push(t(r));else{let e=n,s=0;for(;s<r.path.length;){const n=r.path[s];s===r.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(r))):e[n]=e[n]||{_errors:[]},e=e[n],s++}}};return s(this),n}static assert(e){if(!(e instanceof E))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,v.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},n=[];for(const s of this.issues)if(s.path.length>0){const n=s.path[0];t[n]=t[n]||[],t[n].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}E.create=e=>new E(e);const S=(e,t)=>{let n;switch(e.code){case k.invalid_type:n=e.received===b.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case k.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,v.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:n=`Unrecognized key(s) in object: ${v.joinValues(e.keys,", ")}`;break;case k.invalid_union:n="Invalid input";break;case k.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${v.joinValues(e.options)}`;break;case k.invalid_enum_value:n=`Invalid enum value. Expected ${v.joinValues(e.options)}, received '${e.received}'`;break;case k.invalid_arguments:n="Invalid function arguments";break;case k.invalid_return_type:n="Invalid function return type";break;case k.invalid_date:n="Invalid date";break;case k.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:v.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case k.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case k.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case k.custom:n="Invalid input";break;case k.invalid_intersection_types:n="Intersection results could not be merged";break;case k.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case k.not_finite:n="Number must be finite";break;default:n=t.defaultError,v.assertNever(e)}return{message:n}};let T=S;var A;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(A||(A={}));function I(e,t){const n=T,s=(e=>{const{data:t,path:n,errorMaps:s,issueData:r}=e,a=[...n,...r.path||[]],i={...r,path:a};if(void 0!==r.message)return{...r,path:a,message:r.message};let o="";const d=s.filter(e=>!!e).slice().reverse();for(const e of d)o=e(i,{data:t,defaultError:o}).message;return{...r,path:a,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===S?void 0:S].filter(e=>!!e)});e.common.issues.push(s)}class R{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const s of t){if("aborted"===s.status)return O;"dirty"===s.status&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const e of t){const t=await e.key,s=await e.value;n.push({key:t,value:s})}return R.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const s of t){const{key:t,value:r}=s;if("aborted"===t.status)return O;if("aborted"===r.status)return O;"dirty"===t.status&&e.dirty(),"dirty"===r.status&&e.dirty(),"__proto__"===t.value||void 0===r.value&&!s.alwaysSet||(n[t.value]=r.value)}return{status:e.value,value:n}}}const O=Object.freeze({status:"aborted"}),C=e=>({status:"dirty",value:e}),N=e=>({status:"valid",value:e}),P=e=>"aborted"===e.status,L=e=>"dirty"===e.status,Z=e=>"valid"===e.status,D=e=>"undefined"!=typeof Promise&&e instanceof Promise;class ${constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const j=(e,t)=>{if(Z(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new E(e.common.issues);return this._error=t,this._error}}};function M(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:s,description:r}=e;if(t&&(n||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:r}:{errorMap:(t,r)=>{const{message:a}=e;return"invalid_enum_value"===t.code?{message:a??r.defaultError}:void 0===r.data?{message:a??s??r.defaultError}:"invalid_type"!==t.code?{message:r.defaultError}:{message:a??n??r.defaultError}},description:r}}class G{get description(){return this._def.description}_getType(e){return x(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:x(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new R,ctx:{common:e.parent.common,data:e.data,parsedType:x(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(D(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:x(e)},s=this._parseSync({data:e,path:n.path,parent:n});return j(n,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:x(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return Z(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Z(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:x(e)},s=this._parse({data:e,path:n.path,parent:n}),r=await(D(s)?s:Promise.resolve(s));return j(n,r)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const r=e(t),a=()=>s.addIssue({code:k.custom,...n(t)});return"undefined"!=typeof Promise&&r instanceof Promise?r.then(e=>!!e||(a(),!1)):!!r||(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>!!e(n)||(s.addIssue("function"==typeof t?t(n,s):t),!1))}_refinement(e){return new Ue({schema:this,typeName:Qe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return qe.create(this,this._def)}nullable(){return Fe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ke.create(this)}promise(){return Ge.create(this,this._def)}or(e){return Te.create([this,e],this._def)}and(e){return Oe.create(this,e,this._def)}transform(e){return new Ue({...M(this._def),schema:this,typeName:Qe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ze({...M(this._def),innerType:this,defaultValue:t,typeName:Qe.ZodDefault})}brand(){return new Be({typeName:Qe.ZodBranded,type:this,...M(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ke({...M(this._def),innerType:this,catchValue:t,typeName:Qe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return He.create(this,e)}readonly(){return We.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const U=/^c[^\s-]{8,}$/i,q=/^[0-9a-z]+$/,F=/^[0-9A-HJKMNP-TV-Z]{26}$/i,z=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,K=/^[a-z0-9_-]{21}$/i,V=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,B=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,H=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let W;const Q=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Y=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,X=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,J=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ee=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,te=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ne="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",se=new RegExp(`^${ne}$`);function re(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function ae(e){return new RegExp(`^${re(e)}$`)}function ie(e){let t=`${ne}T${re(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function oe(e,t){return!("v4"!==t&&t||!Q.test(e))||!("v6"!==t&&t||!X.test(e))}function de(e,t){if(!V.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(s));return!("object"!=typeof r||null===r||"typ"in r&&"JWT"!==r?.typ||!r.alg||t&&r.alg!==t)}catch{return!1}}function ce(e,t){return!("v4"!==t&&t||!Y.test(e))||!("v6"!==t&&t||!J.test(e))}class ue extends G{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==b.string){const t=this._getOrReturnCtx(e);return I(t,{code:k.invalid_type,expected:b.string,received:t.parsedType}),O}const t=new R;let n;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(n=this._getOrReturnCtx(e,n),I(n,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("max"===s.kind)e.data.length>s.value&&(n=this._getOrReturnCtx(e,n),I(n,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("length"===s.kind){const r=e.data.length>s.value,a=e.data.length<s.value;(r||a)&&(n=this._getOrReturnCtx(e,n),r?I(n,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&I(n,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)H.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:"email",code:k.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)W||(W=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),W.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:"emoji",code:k.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)z.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:"uuid",code:k.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)K.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:"nanoid",code:k.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)U.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:"cuid",code:k.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)q.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:"cuid2",code:k.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)F.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:"ulid",code:k.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),I(n,{validation:"url",code:k.invalid_string,message:s.message}),t.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:"regex",code:k.invalid_string,message:s.message}),t.dirty())):"trim"===s.kind?e.data=e.data.trim():"includes"===s.kind?e.data.includes(s.value,s.position)||(n=this._getOrReturnCtx(e,n),I(n,{code:k.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),t.dirty()):"toLowerCase"===s.kind?e.data=e.data.toLowerCase():"toUpperCase"===s.kind?e.data=e.data.toUpperCase():"startsWith"===s.kind?e.data.startsWith(s.value)||(n=this._getOrReturnCtx(e,n),I(n,{code:k.invalid_string,validation:{startsWith:s.value},message:s.message}),t.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(n=this._getOrReturnCtx(e,n),I(n,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty()):"datetime"===s.kind?ie(s).test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:k.invalid_string,validation:"datetime",message:s.message}),t.dirty()):"date"===s.kind?se.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:k.invalid_string,validation:"date",message:s.message}),t.dirty()):"time"===s.kind?ae(s).test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:k.invalid_string,validation:"time",message:s.message}),t.dirty()):"duration"===s.kind?B.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:"duration",code:k.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?oe(e.data,s.version)||(n=this._getOrReturnCtx(e,n),I(n,{validation:"ip",code:k.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?de(e.data,s.alg)||(n=this._getOrReturnCtx(e,n),I(n,{validation:"jwt",code:k.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?ce(e.data,s.version)||(n=this._getOrReturnCtx(e,n),I(n,{validation:"cidr",code:k.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?ee.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:"base64",code:k.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?te.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:"base64url",code:k.invalid_string,message:s.message}),t.dirty()):v.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:k.invalid_string,...A.errToObj(n)})}_addCheck(e){return new ue({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...A.errToObj(e)})}url(e){return this._addCheck({kind:"url",...A.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...A.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...A.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...A.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...A.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...A.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...A.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...A.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...A.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...A.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...A.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...A.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...A.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...A.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...A.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...A.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...A.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...A.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...A.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...A.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...A.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...A.errToObj(t)})}nonempty(e){return this.min(1,A.errToObj(e))}trim(){return new ue({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ue({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ue({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function le(e,t){const n=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,r=n>s?n:s;return Number.parseInt(e.toFixed(r).replace(".",""))%Number.parseInt(t.toFixed(r).replace(".",""))/10**r}ue.create=e=>new ue({checks:[],typeName:Qe.ZodString,coerce:e?.coerce??!1,...M(e)});class he extends G{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==b.number){const t=this._getOrReturnCtx(e);return I(t,{code:k.invalid_type,expected:b.number,received:t.parsedType}),O}let t;const n=new R;for(const s of this._def.checks)"int"===s.kind?v.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),I(t,{code:k.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty()):"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),I(t,{code:k.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),I(t,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):"multipleOf"===s.kind?0!==le(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),I(t,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),I(t,{code:k.not_finite,message:s.message}),n.dirty()):v.assertNever(s);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,A.toString(t))}gt(e,t){return this.setLimit("min",e,!1,A.toString(t))}lte(e,t){return this.setLimit("max",e,!0,A.toString(t))}lt(e,t){return this.setLimit("max",e,!1,A.toString(t))}setLimit(e,t,n,s){return new he({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:A.toString(s)}]})}_addCheck(e){return new he({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:A.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:A.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:A.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:A.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:A.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:A.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:A.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:A.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:A.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&v.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if("finite"===n.kind||"int"===n.kind||"multipleOf"===n.kind)return!0;"min"===n.kind?(null===t||n.value>t)&&(t=n.value):"max"===n.kind&&(null===e||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}he.create=e=>new he({checks:[],typeName:Qe.ZodNumber,coerce:e?.coerce||!1,...M(e)});class pe extends G{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==b.bigint)return this._getInvalidInput(e);let t;const n=new R;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),I(t,{code:k.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),I(t,{code:k.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),I(t,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):v.assertNever(s);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return I(t,{code:k.invalid_type,expected:b.bigint,received:t.parsedType}),O}gte(e,t){return this.setLimit("min",e,!0,A.toString(t))}gt(e,t){return this.setLimit("min",e,!1,A.toString(t))}lte(e,t){return this.setLimit("max",e,!0,A.toString(t))}lt(e,t){return this.setLimit("max",e,!1,A.toString(t))}setLimit(e,t,n,s){return new pe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:A.toString(s)}]})}_addCheck(e){return new pe({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:A.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:A.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:A.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:A.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:A.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}pe.create=e=>new pe({checks:[],typeName:Qe.ZodBigInt,coerce:e?.coerce??!1,...M(e)});class ge extends G{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==b.boolean){const t=this._getOrReturnCtx(e);return I(t,{code:k.invalid_type,expected:b.boolean,received:t.parsedType}),O}return N(e.data)}}ge.create=e=>new ge({typeName:Qe.ZodBoolean,coerce:e?.coerce||!1,...M(e)});class me extends G{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==b.date){const t=this._getOrReturnCtx(e);return I(t,{code:k.invalid_type,expected:b.date,received:t.parsedType}),O}if(Number.isNaN(e.data.getTime()))return I(this._getOrReturnCtx(e),{code:k.invalid_date}),O;const t=new R;let n;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(n=this._getOrReturnCtx(e,n),I(n,{code:k.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(n=this._getOrReturnCtx(e,n),I(n,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):v.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new me({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:A.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:A.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}me.create=e=>new me({checks:[],coerce:e?.coerce||!1,typeName:Qe.ZodDate,...M(e)});class fe extends G{_parse(e){if(this._getType(e)!==b.symbol){const t=this._getOrReturnCtx(e);return I(t,{code:k.invalid_type,expected:b.symbol,received:t.parsedType}),O}return N(e.data)}}fe.create=e=>new fe({typeName:Qe.ZodSymbol,...M(e)});class ye extends G{_parse(e){if(this._getType(e)!==b.undefined){const t=this._getOrReturnCtx(e);return I(t,{code:k.invalid_type,expected:b.undefined,received:t.parsedType}),O}return N(e.data)}}ye.create=e=>new ye({typeName:Qe.ZodUndefined,...M(e)});class _e extends G{_parse(e){if(this._getType(e)!==b.null){const t=this._getOrReturnCtx(e);return I(t,{code:k.invalid_type,expected:b.null,received:t.parsedType}),O}return N(e.data)}}_e.create=e=>new _e({typeName:Qe.ZodNull,...M(e)});class ve extends G{constructor(){super(...arguments),this._any=!0}_parse(e){return N(e.data)}}ve.create=e=>new ve({typeName:Qe.ZodAny,...M(e)});class we extends G{constructor(){super(...arguments),this._unknown=!0}_parse(e){return N(e.data)}}we.create=e=>new we({typeName:Qe.ZodUnknown,...M(e)});class be extends G{_parse(e){const t=this._getOrReturnCtx(e);return I(t,{code:k.invalid_type,expected:b.never,received:t.parsedType}),O}}be.create=e=>new be({typeName:Qe.ZodNever,...M(e)});class xe extends G{_parse(e){if(this._getType(e)!==b.undefined){const t=this._getOrReturnCtx(e);return I(t,{code:k.invalid_type,expected:b.void,received:t.parsedType}),O}return N(e.data)}}xe.create=e=>new xe({typeName:Qe.ZodVoid,...M(e)});class ke extends G{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==b.array)return I(t,{code:k.invalid_type,expected:b.array,received:t.parsedType}),O;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,r=t.data.length<s.exactLength.value;(e||r)&&(I(t,{code:e?k.too_big:k.too_small,minimum:r?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(I(t,{code:k.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(I(t,{code:k.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>s.type._parseAsync(new $(t,e,t.path,n)))).then(e=>R.mergeArray(n,e));const r=[...t.data].map((e,n)=>s.type._parseSync(new $(t,e,t.path,n)));return R.mergeArray(n,r)}get element(){return this._def.type}min(e,t){return new ke({...this._def,minLength:{value:e,message:A.toString(t)}})}max(e,t){return new ke({...this._def,maxLength:{value:e,message:A.toString(t)}})}length(e,t){return new ke({...this._def,exactLength:{value:e,message:A.toString(t)}})}nonempty(e){return this.min(1,e)}}function Ee(e){if(e instanceof Se){const t={};for(const n in e.shape){const s=e.shape[n];t[n]=qe.create(Ee(s))}return new Se({...e._def,shape:()=>t})}return e instanceof ke?new ke({...e._def,type:Ee(e.element)}):e instanceof qe?qe.create(Ee(e.unwrap())):e instanceof Fe?Fe.create(Ee(e.unwrap())):e instanceof Ce?Ce.create(e.items.map(e=>Ee(e))):e}ke.create=(e,t)=>new ke({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Qe.ZodArray,...M(t)});class Se extends G{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=v.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==b.object){const t=this._getOrReturnCtx(e);return I(t,{code:k.invalid_type,expected:b.object,received:t.parsedType}),O}const{status:t,ctx:n}=this._processInputParams(e),{shape:s,keys:r}=this._getCached(),a=[];if(!(this._def.catchall instanceof be&&"strip"===this._def.unknownKeys))for(const e in n.data)r.includes(e)||a.push(e);const i=[];for(const e of r){const t=s[e],r=n.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new $(n,r,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof be){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of a)i.push({key:{status:"valid",value:e},value:{status:"valid",value:n.data[e]}});else if("strict"===e)a.length>0&&(I(n,{code:k.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of a){const s=n.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new $(n,s,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of i){const n=await t.key,s=await t.value;e.push({key:n,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>R.mergeObjectSync(t,e)):R.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return A.errToObj,new Se({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,n)=>{const s=this._def.errorMap?.(t,n).message??n.defaultError;return"unrecognized_keys"===t.code?{message:A.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new Se({...this._def,unknownKeys:"strip"})}passthrough(){return new Se({...this._def,unknownKeys:"passthrough"})}extend(e){return new Se({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Se({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Qe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Se({...this._def,catchall:e})}pick(e){const t={};for(const n of v.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new Se({...this._def,shape:()=>t})}omit(e){const t={};for(const n of v.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new Se({...this._def,shape:()=>t})}deepPartial(){return Ee(this)}partial(e){const t={};for(const n of v.objectKeys(this.shape)){const s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new Se({...this._def,shape:()=>t})}required(e){const t={};for(const n of v.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof qe;)e=e._def.innerType;t[n]=e}return new Se({...this._def,shape:()=>t})}keyof(){return $e(v.objectKeys(this.shape))}}Se.create=(e,t)=>new Se({shape:()=>e,unknownKeys:"strip",catchall:be.create(),typeName:Qe.ZodObject,...M(t)}),Se.strictCreate=(e,t)=>new Se({shape:()=>e,unknownKeys:"strict",catchall:be.create(),typeName:Qe.ZodObject,...M(t)}),Se.lazycreate=(e,t)=>new Se({shape:e,unknownKeys:"strip",catchall:be.create(),typeName:Qe.ZodObject,...M(t)});class Te extends G{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const n=e.map(e=>new E(e.ctx.common.issues));return I(t,{code:k.invalid_union,unionErrors:n}),O});{let e;const s=[];for(const r of n){const n={...t,common:{...t.common,issues:[]},parent:null},a=r._parseSync({data:t.data,path:t.path,parent:n});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:n}),n.common.issues.length&&s.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const r=s.map(e=>new E(e));return I(t,{code:k.invalid_union,unionErrors:r}),O}}get options(){return this._def.options}}Te.create=(e,t)=>new Te({options:e,typeName:Qe.ZodUnion,...M(t)});const Ae=e=>e instanceof Ze?Ae(e.schema):e instanceof Ue?Ae(e.innerType()):e instanceof De?[e.value]:e instanceof je?e.options:e instanceof Me?v.objectValues(e.enum):e instanceof ze?Ae(e._def.innerType):e instanceof ye?[void 0]:e instanceof _e?[null]:e instanceof qe?[void 0,...Ae(e.unwrap())]:e instanceof Fe?[null,...Ae(e.unwrap())]:e instanceof Be||e instanceof We?Ae(e.unwrap()):e instanceof Ke?Ae(e._def.innerType):[];class Ie extends G{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==b.object)return I(t,{code:k.invalid_type,expected:b.object,received:t.parsedType}),O;const n=this.discriminator,s=t.data[n],r=this.optionsMap.get(s);return r?t.common.async?r._parseAsync({data:t.data,path:t.path,parent:t}):r._parseSync({data:t.data,path:t.path,parent:t}):(I(t,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),O)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const s=new Map;for(const n of t){const t=Ae(n.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const r of t){if(s.has(r))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(r)}`);s.set(r,n)}}return new Ie({typeName:Qe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...M(n)})}}function Re(e,t){const n=x(e),s=x(t);if(e===t)return{valid:!0,data:e};if(n===b.object&&s===b.object){const n=v.objectKeys(t),s=v.objectKeys(e).filter(e=>-1!==n.indexOf(e)),r={...e,...t};for(const n of s){const s=Re(e[n],t[n]);if(!s.valid)return{valid:!1};r[n]=s.data}return{valid:!0,data:r}}if(n===b.array&&s===b.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let s=0;s<e.length;s++){const r=Re(e[s],t[s]);if(!r.valid)return{valid:!1};n.push(r.data)}return{valid:!0,data:n}}return n===b.date&&s===b.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class Oe extends G{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(e,s)=>{if(P(e)||P(s))return O;const r=Re(e.value,s.value);return r.valid?((L(e)||L(s))&&t.dirty(),{status:t.value,value:r.data}):(I(n,{code:k.invalid_intersection_types}),O)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Oe.create=(e,t,n)=>new Oe({left:e,right:t,typeName:Qe.ZodIntersection,...M(n)});class Ce extends G{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.array)return I(n,{code:k.invalid_type,expected:b.array,received:n.parsedType}),O;if(n.data.length<this._def.items.length)return I(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),O;!this._def.rest&&n.data.length>this._def.items.length&&(I(n,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...n.data].map((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new $(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(s).then(e=>R.mergeArray(t,e)):R.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new Ce({...this._def,rest:e})}}Ce.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ce({items:e,typeName:Qe.ZodTuple,rest:null,...M(t)})};class Ne extends G{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.object)return I(n,{code:k.invalid_type,expected:b.object,received:n.parsedType}),O;const s=[],r=this._def.keyType,a=this._def.valueType;for(const e in n.data)s.push({key:r._parse(new $(n,e,n.path,e)),value:a._parse(new $(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?R.mergeObjectAsync(t,s):R.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return new Ne(t instanceof G?{keyType:e,valueType:t,typeName:Qe.ZodRecord,...M(n)}:{keyType:ue.create(),valueType:e,typeName:Qe.ZodRecord,...M(t)})}}class Pe extends G{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.map)return I(n,{code:k.invalid_type,expected:b.map,received:n.parsedType}),O;const s=this._def.keyType,r=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:s._parse(new $(n,e,n.path,[a,"key"])),value:r._parse(new $(n,t,n.path,[a,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const n of a){const s=await n.key,r=await n.value;if("aborted"===s.status||"aborted"===r.status)return O;"dirty"!==s.status&&"dirty"!==r.status||t.dirty(),e.set(s.value,r.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of a){const s=n.key,r=n.value;if("aborted"===s.status||"aborted"===r.status)return O;"dirty"!==s.status&&"dirty"!==r.status||t.dirty(),e.set(s.value,r.value)}return{status:t.value,value:e}}}}Pe.create=(e,t,n)=>new Pe({valueType:t,keyType:e,typeName:Qe.ZodMap,...M(n)});class Le extends G{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.set)return I(n,{code:k.invalid_type,expected:b.set,received:n.parsedType}),O;const s=this._def;null!==s.minSize&&n.data.size<s.minSize.value&&(I(n,{code:k.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&n.data.size>s.maxSize.value&&(I(n,{code:k.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const r=this._def.valueType;function a(e){const n=new Set;for(const s of e){if("aborted"===s.status)return O;"dirty"===s.status&&t.dirty(),n.add(s.value)}return{status:t.value,value:n}}const i=[...n.data.values()].map((e,t)=>r._parse(new $(n,e,n.path,t)));return n.common.async?Promise.all(i).then(e=>a(e)):a(i)}min(e,t){return new Le({...this._def,minSize:{value:e,message:A.toString(t)}})}max(e,t){return new Le({...this._def,maxSize:{value:e,message:A.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Le.create=(e,t)=>new Le({valueType:e,minSize:null,maxSize:null,typeName:Qe.ZodSet,...M(t)});class Ze extends G{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ze.create=(e,t)=>new Ze({getter:e,typeName:Qe.ZodLazy,...M(t)});class De extends G{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return I(t,{received:t.data,code:k.invalid_literal,expected:this._def.value}),O}return{status:"valid",value:e.data}}get value(){return this._def.value}}function $e(e,t){return new je({values:e,typeName:Qe.ZodEnum,...M(t)})}De.create=(e,t)=>new De({value:e,typeName:Qe.ZodLiteral,...M(t)});class je extends G{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return I(t,{expected:v.joinValues(n),received:t.parsedType,code:k.invalid_type}),O}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return I(t,{received:t.data,code:k.invalid_enum_value,options:n}),O}return N(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return je.create(e,{...this._def,...t})}exclude(e,t=this._def){return je.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}je.create=$e;class Me extends G{_parse(e){const t=v.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==b.string&&n.parsedType!==b.number){const e=v.objectValues(t);return I(n,{expected:v.joinValues(e),received:n.parsedType,code:k.invalid_type}),O}if(this._cache||(this._cache=new Set(v.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=v.objectValues(t);return I(n,{received:n.data,code:k.invalid_enum_value,options:e}),O}return N(e.data)}get enum(){return this._def.values}}Me.create=(e,t)=>new Me({values:e,typeName:Qe.ZodNativeEnum,...M(t)});class Ge extends G{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==b.promise&&!1===t.common.async)return I(t,{code:k.invalid_type,expected:b.promise,received:t.parsedType}),O;const n=t.parsedType===b.promise?t.data:Promise.resolve(t.data);return N(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ge.create=(e,t)=>new Ge({type:e,typeName:Qe.ZodPromise,...M(t)});class Ue extends G{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Qe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,r={addIssue:e=>{I(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(r.addIssue=r.addIssue.bind(r),"preprocess"===s.type){const e=s.transform(n.data,r);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return O;const s=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===s.status?O:"dirty"===s.status||"dirty"===t.value?C(s.value):s});{if("aborted"===t.value)return O;const s=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===s.status?O:"dirty"===s.status||"dirty"===t.value?C(s.value):s}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,r);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===s.status?O:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>"aborted"===n.status?O:("dirty"===n.status&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if("transform"===s.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Z(e))return O;const a=s.transform(e.value,r);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Z(e)?Promise.resolve(s.transform(e.value,r)).then(e=>({status:t.value,value:e})):O)}v.assertNever(s)}}Ue.create=(e,t,n)=>new Ue({schema:e,typeName:Qe.ZodEffects,effect:t,...M(n)}),Ue.createWithPreprocess=(e,t,n)=>new Ue({schema:t,effect:{type:"preprocess",transform:e},typeName:Qe.ZodEffects,...M(n)});class qe extends G{_parse(e){return this._getType(e)===b.undefined?N(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}qe.create=(e,t)=>new qe({innerType:e,typeName:Qe.ZodOptional,...M(t)});class Fe extends G{_parse(e){return this._getType(e)===b.null?N(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Fe.create=(e,t)=>new Fe({innerType:e,typeName:Qe.ZodNullable,...M(t)});class ze extends G{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===b.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ze.create=(e,t)=>new ze({innerType:e,typeName:Qe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...M(t)});class Ke extends G{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return D(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new E(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new E(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Ke.create=(e,t)=>new Ke({innerType:e,typeName:Qe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...M(t)});class Ve extends G{_parse(e){if(this._getType(e)!==b.nan){const t=this._getOrReturnCtx(e);return I(t,{code:k.invalid_type,expected:b.nan,received:t.parsedType}),O}return{status:"valid",value:e.data}}}Ve.create=e=>new Ve({typeName:Qe.ZodNaN,...M(e)}),Symbol("zod_brand");class Be extends G{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class He extends G{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?O:"dirty"===e.status?(t.dirty(),C(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{const e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?O:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new He({in:e,out:t,typeName:Qe.ZodPipeline})}}class We extends G{_parse(e){const t=this._def.innerType._parse(e),n=e=>(Z(e)&&(e.value=Object.freeze(e.value)),e);return D(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var Qe;We.create=(e,t)=>new We({innerType:e,typeName:Qe.ZodReadonly,...M(t)}),Se.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Qe||(Qe={}));const Ye=ue.create,Xe=he.create,Je=(Ve.create,pe.create,ge.create),et=(me.create,fe.create,ye.create,_e.create,ve.create,we.create),tt=(be.create,xe.create,ke.create),nt=Se.create,st=(Se.strictCreate,Te.create),rt=Ie.create,at=(Oe.create,Ce.create,Ne.create),it=(Pe.create,Le.create,Ze.create,De.create),ot=je.create,dt=(Me.create,Ge.create,Ue.create,qe.create),ct=(Fe.create,Ue.createWithPreprocess,He.create,"2.0"),ut=st([Ye(),Xe().int()]),lt=Ye(),ht=nt({progressToken:dt(ut)}).passthrough(),pt=nt({_meta:dt(ht)}).passthrough(),gt=nt({method:Ye(),params:dt(pt)}),mt=nt({_meta:dt(nt({}).passthrough())}).passthrough(),ft=nt({method:Ye(),params:dt(mt)}),yt=nt({_meta:dt(nt({}).passthrough())}).passthrough(),_t=st([Ye(),Xe().int()]),vt=nt({jsonrpc:it(ct),id:_t}).merge(gt).strict(),wt=nt({jsonrpc:it(ct)}).merge(ft).strict(),bt=nt({jsonrpc:it(ct),id:_t,result:yt}).strict();var xt;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(xt||(xt={}));const kt=st([vt,wt,bt,nt({jsonrpc:it(ct),id:_t,error:nt({code:Xe().int(),message:Ye(),data:dt(et())})}).strict()]),Et=yt.strict(),St=ft.extend({method:it("notifications/cancelled"),params:mt.extend({requestId:_t,reason:Ye().optional()})}),Tt=nt({name:Ye(),title:dt(Ye())}).passthrough(),At=Tt.extend({version:Ye()}),It=nt({experimental:dt(nt({}).passthrough()),sampling:dt(nt({}).passthrough()),elicitation:dt(nt({}).passthrough()),roots:dt(nt({listChanged:dt(Je())}).passthrough())}).passthrough(),Rt=gt.extend({method:it("initialize"),params:pt.extend({protocolVersion:Ye(),capabilities:It,clientInfo:At})}),Ot=nt({experimental:dt(nt({}).passthrough()),logging:dt(nt({}).passthrough()),completions:dt(nt({}).passthrough()),prompts:dt(nt({listChanged:dt(Je())}).passthrough()),resources:dt(nt({subscribe:dt(Je()),listChanged:dt(Je())}).passthrough()),tools:dt(nt({listChanged:dt(Je())}).passthrough())}).passthrough(),Ct=yt.extend({protocolVersion:Ye(),capabilities:Ot,serverInfo:At,instructions:dt(Ye())}),Nt=ft.extend({method:it("notifications/initialized")}),Pt=gt.extend({method:it("ping")}),Lt=nt({progress:Xe(),total:dt(Xe()),message:dt(Ye())}).passthrough(),Zt=ft.extend({method:it("notifications/progress"),params:mt.merge(Lt).extend({progressToken:ut})}),Dt=gt.extend({params:pt.extend({cursor:dt(lt)}).optional()}),$t=yt.extend({nextCursor:dt(lt)}),jt=nt({uri:Ye(),mimeType:dt(Ye()),_meta:dt(nt({}).passthrough())}).passthrough(),Mt=jt.extend({text:Ye()}),Gt=Ye().refine(e=>{try{return atob(e),!0}catch(e){return!1}},{message:"Invalid Base64 string"}),Ut=jt.extend({blob:Gt}),qt=Tt.extend({uri:Ye(),description:dt(Ye()),mimeType:dt(Ye()),_meta:dt(nt({}).passthrough())}),Ft=Tt.extend({uriTemplate:Ye(),description:dt(Ye()),mimeType:dt(Ye()),_meta:dt(nt({}).passthrough())}),zt=Dt.extend({method:it("resources/list")}),Kt=$t.extend({resources:tt(qt)}),Vt=Dt.extend({method:it("resources/templates/list")}),Bt=$t.extend({resourceTemplates:tt(Ft)}),Ht=gt.extend({method:it("resources/read"),params:pt.extend({uri:Ye()})}),Wt=yt.extend({contents:tt(st([Mt,Ut]))}),Qt=ft.extend({method:it("notifications/resources/list_changed")}),Yt=gt.extend({method:it("resources/subscribe"),params:pt.extend({uri:Ye()})}),Xt=gt.extend({method:it("resources/unsubscribe"),params:pt.extend({uri:Ye()})}),Jt=ft.extend({method:it("notifications/resources/updated"),params:mt.extend({uri:Ye()})}),en=nt({name:Ye(),description:dt(Ye()),required:dt(Je())}).passthrough(),tn=Tt.extend({description:dt(Ye()),arguments:dt(tt(en)),_meta:dt(nt({}).passthrough())}),nn=Dt.extend({method:it("prompts/list")}),sn=$t.extend({prompts:tt(tn)}),rn=gt.extend({method:it("prompts/get"),params:pt.extend({name:Ye(),arguments:dt(at(Ye()))})}),an=nt({type:it("text"),text:Ye(),_meta:dt(nt({}).passthrough())}).passthrough(),on=nt({type:it("image"),data:Gt,mimeType:Ye(),_meta:dt(nt({}).passthrough())}).passthrough(),dn=nt({type:it("audio"),data:Gt,mimeType:Ye(),_meta:dt(nt({}).passthrough())}).passthrough(),cn=nt({type:it("resource"),resource:st([Mt,Ut]),_meta:dt(nt({}).passthrough())}).passthrough(),un=st([an,on,dn,qt.extend({type:it("resource_link")}),cn]),ln=nt({role:ot(["user","assistant"]),content:un}).passthrough(),hn=yt.extend({description:dt(Ye()),messages:tt(ln)}),pn=ft.extend({method:it("notifications/prompts/list_changed")}),gn=nt({title:dt(Ye()),readOnlyHint:dt(Je()),destructiveHint:dt(Je()),idempotentHint:dt(Je()),openWorldHint:dt(Je())}).passthrough(),mn=Tt.extend({description:dt(Ye()),inputSchema:nt({type:it("object"),properties:dt(nt({}).passthrough()),required:dt(tt(Ye()))}).passthrough(),outputSchema:dt(nt({type:it("object"),properties:dt(nt({}).passthrough()),required:dt(tt(Ye()))}).passthrough()),annotations:dt(gn),_meta:dt(nt({}).passthrough())}),fn=Dt.extend({method:it("tools/list")}),yn=$t.extend({tools:tt(mn)}),_n=yt.extend({content:tt(un).default([]),structuredContent:nt({}).passthrough().optional(),isError:dt(Je())}),vn=(_n.or(yt.extend({toolResult:et()})),gt.extend({method:it("tools/call"),params:pt.extend({name:Ye(),arguments:dt(at(et()))})})),wn=ft.extend({method:it("notifications/tools/list_changed")}),bn=ot(["debug","info","notice","warning","error","critical","alert","emergency"]),xn=gt.extend({method:it("logging/setLevel"),params:pt.extend({level:bn})}),kn=ft.extend({method:it("notifications/message"),params:mt.extend({level:bn,logger:dt(Ye()),data:et()})}),En=nt({name:Ye().optional()}).passthrough(),Sn=nt({hints:dt(tt(En)),costPriority:dt(Xe().min(0).max(1)),speedPriority:dt(Xe().min(0).max(1)),intelligencePriority:dt(Xe().min(0).max(1))}).passthrough(),Tn=nt({role:ot(["user","assistant"]),content:st([an,on,dn])}).passthrough(),An=gt.extend({method:it("sampling/createMessage"),params:pt.extend({messages:tt(Tn),systemPrompt:dt(Ye()),includeContext:dt(ot(["none","thisServer","allServers"])),temperature:dt(Xe()),maxTokens:Xe().int(),stopSequences:dt(tt(Ye())),metadata:dt(nt({}).passthrough()),modelPreferences:dt(Sn)})}),In=yt.extend({model:Ye(),stopReason:dt(ot(["endTurn","stopSequence","maxTokens"]).or(Ye())),role:ot(["user","assistant"]),content:rt("type",[an,on,dn])}),Rn=st([nt({type:it("boolean"),title:dt(Ye()),description:dt(Ye()),default:dt(Je())}).passthrough(),nt({type:it("string"),title:dt(Ye()),description:dt(Ye()),minLength:dt(Xe()),maxLength:dt(Xe()),format:dt(ot(["email","uri","date","date-time"]))}).passthrough(),nt({type:ot(["number","integer"]),title:dt(Ye()),description:dt(Ye()),minimum:dt(Xe()),maximum:dt(Xe())}).passthrough(),nt({type:it("string"),title:dt(Ye()),description:dt(Ye()),enum:tt(Ye()),enumNames:dt(tt(Ye()))}).passthrough()]),On=gt.extend({method:it("elicitation/create"),params:pt.extend({message:Ye(),requestedSchema:nt({type:it("object"),properties:at(Ye(),Rn),required:dt(tt(Ye()))}).passthrough()})}),Cn=yt.extend({action:ot(["accept","decline","cancel"]),content:dt(at(Ye(),et()))}),Nn=nt({type:it("ref/resource"),uri:Ye()}).passthrough(),Pn=nt({type:it("ref/prompt"),name:Ye()}).passthrough(),Ln=gt.extend({method:it("completion/complete"),params:pt.extend({ref:st([Pn,Nn]),argument:nt({name:Ye(),value:Ye()}).passthrough(),context:dt(nt({arguments:dt(at(Ye(),Ye()))}))})}),Zn=yt.extend({completion:nt({values:tt(Ye()).max(100),total:dt(Xe().int()),hasMore:dt(Je())}).passthrough()}),Dn=nt({uri:Ye().startsWith("file://"),name:dt(Ye()),_meta:dt(nt({}).passthrough())}).passthrough(),$n=gt.extend({method:it("roots/list")}),jn=yt.extend({roots:tt(Dn)}),Mn=ft.extend({method:it("notifications/roots/list_changed")});st([Pt,Rt,Ln,xn,rn,nn,zt,Vt,Ht,Yt,Xt,vn,fn]),st([St,Zt,Nt,Mn]),st([Et,In,Cn,jn]),st([Pt,An,On,$n]),st([St,Zt,kn,Jt,Qt,wn,pn]),st([Et,Ct,Zn,hn,sn,Kt,Bt,Wt,_n,yn]),Error;class Gn{sessionId;onmessage;onerror;onclose;_port;_started=!1;_closed=!1;constructor(e,t){if(!e)throw new Error("MessagePort is required");this._port=e,this.sessionId=t||this.generateId(),this._port.onmessage=e=>{try{const t=kt.parse(e.data);this.onmessage?.(t)}catch(e){const t=new Error(`Failed to parse message: ${e}`);this.onerror?.(t)}},this._port.onmessageerror=e=>{const t=new Error(`MessagePort error: ${JSON.stringify(e)}`);this.onerror?.(t)}}static generateSessionId(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).substring(2,10)}`}async start(){if(this._started)throw new Error("BrowserContextTransport already started! If using Client or Server class, note that connect() calls start() automatically.");if(this._closed)throw new Error("Cannot start a closed BrowserContextTransport");this._started=!0,this._port.start()}async send(e){if(this._closed)throw new Error("Cannot send on a closed BrowserContextTransport");return new Promise((t,n)=>{try{this._port.postMessage(e),t()}catch(e){const t=e instanceof Error?e:new Error(String(e));this.onerror?.(t),n(t)}})}async close(){this._closed||(this._closed=!0,this._port.close(),this.onclose?.())}generateId(){return Gn.generateSessionId()}}class Un{async requestClientCreation(e){const{config:t}=e,n={serverId:e.id,serverName:t.name,serverVersion:t.version,description:t.description,transport:t.transport||l.POST_MESSAGE,capabilities:t.capabilities,instanceId:e.instanceId};return"type"in t&&"remote"===t.type&&(n.remote={url:t.url}),new Promise((e,t)=>{const s=new MessageChannel,r=setTimeout(()=>{t(new Error("Client creation request timed out after 15000ms"))},15e3);s.port1.onmessage=t=>{clearTimeout(r),e(t.data)};const a={type:g.SDK_REQUEST_CLIENT_CREATION,payload:n,timestamp:Date.now()};window.postMessage(a,window.location.origin,[s.port2])})}}const qn=c("iframe-utils");let Fn=null;const zn=()=>(Fn&&document.contains(Fn)||(Fn=document.querySelector('iframe[src*="angie/"]')),Fn),Kn=(e,t)=>{qn.log("postMessageToAngieIframe",e,t);const n=zn();if(!n?.contentWindow)return!1;const s=t||(()=>{const e=zn();if(!e)return null;try{return new URL(e.src).origin}catch(e){return qn.error("Error parsing iframe URL:",e),null}})();return s?(n.contentWindow.postMessage(e,s),!0):(qn.error("Could not determine target origin for Angie iframe"),!1)},Vn=c("sidebar");let Bn=!1;const Hn="open",Wn="closed";function Qn(){if("undefined"==typeof window)return 370;try{const e=window.localStorage.getItem("angie_sidebar_width");if(e){const t=parseInt(e,10);if(t>=350&&t<=590)return t}}catch(e){Vn.warn("localStorage not available")}return 370}function Yn(){return"undefined"==typeof window?null:localStorage.getItem("angie_sidebar_state")}function Xn(e){try{localStorage.setItem("angie_sidebar_width",e.toString())}catch(e){Vn.warn("localStorage not available")}}function Jn(e){document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`)}function es(){!function(){const e=new URLSearchParams(window.location.search);return e.has("start-oauth")||e.has("oauth_code")||e.has("oauth_state")||e.has("oauth_error")}()?ts(Yn()||Hn):function(){ts(Wn);try{localStorage.setItem("angie_sidebar_state",Wn)}catch(e){Vn.warn("localStorage not available")}}()}function ts(e){"undefined"!=typeof window&&window.toggleAngieSidebar&&window.toggleAngieSidebar(e===Hn,!0)}function ns(){const e=document.getElementById("angie-sidebar-container");if(!e)return;let t=!1,n=0,s=0;e.addEventListener("mousedown",r=>{const a=e.getBoundingClientRect();("rtl"===document.documentElement.dir?r.clientX<=a.left+4:r.clientX>=a.right-4)&&(t=!0,n=r.clientX,s=a.width,e.classList.add("angie-resizing"),document.body.style.cursor="ew-resize",document.body.style.userSelect="none",r.preventDefault(),r.stopPropagation())}),document.addEventListener("mousemove",e=>{if(!t)return;let r;r="rtl"===document.documentElement.dir?n-e.clientX:e.clientX-n,Jn(Math.max(350,Math.min(590,s+r))),e.preventDefault(),e.stopPropagation()}),document.addEventListener("mouseup",n=>{if(t){t=!1,e.classList.remove("angie-resizing"),document.body.style.cursor="",document.body.style.userSelect="";const r=parseInt(getComputedStyle(document.documentElement).getPropertyValue("--angie-sidebar-width"),10);Xn(r),Kn({type:gs.ANGIE_SIDEBAR_RESIZED,payload:{initialWidth:s,width:r}}),n.preventDefault(),n.stopPropagation()}}),Jn(Qn())}function ss(e){!function(){if("undefined"==typeof document||Bn)return;const e="angie-sidebar-styles";if(document.getElementById(e))return void(Bn=!0);const t=document.createElement("style");t.id=e,t.textContent="/* Angie Sidebar - CSS Variables */\n:root {\n --angie-sidebar-z-index: 1200; /* below MUI popups, elementor popups and media library modal */\n --angie-sidebar-width: 330px;\n --angie-sidebar-transition: margin 0.3s ease-in-out, transform 0.3s ease-in-out;\n /* Direction-aware transform values for sidebar positioning */\n --angie-sidebar-hide-transform: translateX(-100%); /* LTR: hide to the left */\n --angie-sidebar-show-transform: translateX(0);\n}\n\n/* RTL-specific transform values */\n[dir=\"rtl\"] {\n --angie-sidebar-hide-transform: translateX(100%); /* RTL: hide to the right */\n}\n\n/* Respect user's motion preferences */\n@media (prefers-reduced-motion: reduce) {\n :root {\n --angie-sidebar-transition: none;\n }\n}\n\n/* Apply transitions only when user is actively toggling */\nbody.angie-sidebar-transitioning {\n transition: var(--angie-sidebar-transition) !important;\n}\n\nbody.angie-sidebar-transitioning #angie-sidebar-container {\n transition: var(--angie-sidebar-transition) !important;\n}\n\n/* LTR Layout (default) - Push content to the right */\n@media (min-width: 768px) {\n body.angie-sidebar-active {\n padding-inline-start: var(--angie-sidebar-width) !important;\n }\n\n body.angie-sidebar-active #angie-body-top-padding {\n width: 100%;\n height: 8px;\n }\n\n /* Push WordPress Admin Bar - LTR */\n body.angie-sidebar-active #wpadminbar {\n inset-inline-start: var(--angie-sidebar-width) !important;\n inset-inline-end: 8px !important;\n width: calc(100% - 8px - var(--angie-sidebar-width)) !important;\n margin-top: 8px;\n }\n\n /* Sidebar container - LTR */\n #angie-sidebar-container {\n position: fixed;\n top: 0;\n inset-inline-start: 0;\n width: var(--angie-sidebar-width);\n height: 100vh;\n z-index: var(--angie-sidebar-z-index) !important; /* below elementor popups and media library modal */\n background: #FCFCFC;\n transform: var(--angie-sidebar-hide-transform);\n outline: none;\n overflow: hidden;\n /* No default transition - only when transitioning */\n }\n\n /* Resize handle */\n #angie-sidebar-container::after {\n content: '';\n position: absolute;\n top: 0;\n inset-inline-end: 0;\n width: 4px;\n height: 100%;\n cursor: ew-resize;\n background: transparent;\n z-index: 1000001;\n }\n\n /* Pink border during resize */\n #angie-sidebar-container.angie-resizing {\n border-inline-end-color: #ff69b4 !important;\n border-inline-end-width: 2px !important;\n }\n\n /* Disable iframe pointer events during resize */\n #angie-sidebar-container.angie-resizing iframe#angie-iframe {\n pointer-events: none !important;\n }\n}\n\n/* Active states */\nbody.angie-sidebar-active #angie-sidebar-container {\n transform: var(--angie-sidebar-show-transform);\n}\n\n/* Studio mode - sidebar takes full width */\n@media (min-width: 768px) {\n html.angie-studio-active body.angie-sidebar-active #angie-sidebar-container {\n width: 100%;\n }\n}\n\n/* High contrast mode support */\n@media (prefers-contrast: high) {\n #angie-sidebar-container {\n border-color: #000;\n box-shadow: none;\n }\n}\n\n/* Screen reader only class */\n.angie-sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n/* Plugin conflict resolution */\nbody.angie-sidebar-active {\n /* Reset common conflicting styles */\n box-sizing: border-box !important;\n position: relative !important;\n}\n\n#angie-sidebar-toggle {\n z-index: 99999 !important;\n}\n";const n=document.head||document.getElementsByTagName("head")[0];n.insertBefore(t,n.firstChild),Bn=!0}(),"undefined"!=typeof window&&(window.toggleAngieSidebar=function(e){return function(t,n){const s=document.body,r=document.getElementById("angie-sidebar-container");if(!r)return void Vn.warn("Required elements not found!");const a=s.classList.contains("angie-sidebar-active"),i=void 0!==t?t:!a;n||(s.classList.add("angie-sidebar-transitioning"),setTimeout(function(){s.classList.remove("angie-sidebar-transitioning")},300)),i?s.classList.add("angie-sidebar-active"):s.classList.remove("angie-sidebar-active"),i&&setTimeout(function(){Kn({type:"focusInput"})},n?0:300),e&&e(i,r,n),function(e){try{localStorage.setItem("angie_sidebar_state",e)}catch(e){Vn.warn("localStorage not available")}}(i?Hn:Wn);const o=new CustomEvent("angieSidebarToggle",{detail:{isOpen:i,sidebar:r,skipTransition:n}});document.dispatchEvent(o),Kn({type:gs.ANGIE_SIDEBAR_TOGGLED,payload:{state:i?"opened":"closed"}})}}(e),window.addEventListener("message",function(e){if(e.data&&"toggleAngieSidebar"===e.data.type){const{force:t,skipTransition:n}=e.data.payload||{};window.toggleAngieSidebar&&window.toggleAngieSidebar(t,n)}}))}const rs=(e,t)=>{const n=document.getElementById("angie-sidebar-container");n&&n.setAttribute("aria-hidden",t?"false":"true"),t?e.removeAttribute("tabindex"):e.setAttribute("tabindex","-1")},as=(e,t)=>{e.postMessage({status:"success",payload:t})},is=(e,t)=>{e.postMessage({status:"error",payload:t})},os=()=>new Promise(e=>{"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e(null)}),ds=c("sdk");var cs;(cs||(cs={})).POST_MESSAGE="postMessage";const us={open:!1,iframe:null,iframeUrlObject:null},ls=c("oauth");function hs(){const e=new URL(window.location.href);e.searchParams.set("start-oauth","1"),ls.log("Redirecting to wp-admin with OAuth:",e.toString()),window.location.href=e.toString()}const ps=()=>{window.addEventListener("message",e=>{if(e.origin===us.iframeUrlObject?.origin)switch(e.data.type){case"OAUTH_GET_CODE_AND_STATE":(e=>{const t=new URLSearchParams(window.location.search),n=t.get("oauth_code"),s=t.get("oauth_state");if(n&&s)as(e,{code:n,state:s});else{const r=t.get("oauth_error");if(r){is(e,{message:r,code:n||null,state:s||null});const t=new URL(window.location.href);t.searchParams.delete("oauth_error"),history.replaceState({},"",t.toString())}else as(e,{message:"No OAuth error found"})}})(e.ports[0]);break;case"OAUTH_GET_TOP_URL":ls.log("Iframe requested top window URL via MessageChannel"),as(e.ports[0],{topUrl:window.location.href});break;case"OAUTH_REDIRECT_TOP_WINDOW":ls.log("Iframe requested top window redirect to:",e.data.payload.url),window.location.href=e.data.payload.url;break;case"OAUTH_UPDATE_URL":ls.log("Iframe requested URL update to:",e.data.payload.url),function(e,t){if(!history?.replaceState)return ls.warn("history.replaceState not supported in this browser"),void is(t,{message:"URL update not supported in this browser"});try{const n=window.location.href;history.replaceState({},"",e),function(e,t){const n=new URL(t),s=new URL(e),r=n.searchParams,a=s.searchParams,i=["oauth_code","oauth_state","start-oauth"];return i.some(e=>a?.has(e))&&!i.some(e=>r?.has(e))}(n,e)&&function(){ls.log("OAuth parameters cleaned, opening sidebar");try{localStorage.setItem("angie_sidebar_state","open")}catch(e){ls.warn("localStorage not available")}setTimeout(()=>{window.toggleAngieSidebar(!0)},500)}(),as(t,{message:"URL updated successfully"})}catch(e){ls.warn("Failed to update URL via history.replaceState:",e),is(t,{message:"URL update failed: "+(e instanceof Error?e.message:"Unknown error")})}}(e.data.payload.url,e.ports[0]);break;case"ANGIE_REDIRECT_TO_WP_ADMIN_WITH_OAUTH":hs();break;case"ANGIE_REDIRECT_TO_AUTH_ORIGIN_LOGOUT":try{hs()}catch(e){ls.error("Auth origin logout fallback failed:",e),window.location.reload()}}})};var gs;!function(e){e.SDK_ANGIE_ALL_SERVERS_REGISTERED="sdk-angie-all-servers-registered",e.SDK_ANGIE_READY_PING="sdk-angie-ready-ping",e.SDK_REQUEST_CLIENT_CREATION="sdk-request-client-creation",e.SDK_TRIGGER_ANGIE="sdk-trigger-angie",e.SDK_TRIGGER_ANGIE_RESPONSE="sdk-trigger-angie-response",e.ANGIE_SIDEBAR_RESIZED="angie-sidebar-resized",e.ANGIE_SIDEBAR_TOGGLED="angie-sidebar-toggled",e.ANGIE_CHAT_TOGGLE="angie-chat-toggle",e.ANGIE_STUDIO_TOGGLE="angie-studio-toggle",e.ANGIE_NAVIGATE_TO_URL="angie/navigate-to-url",e.ANGIE_PAGE_RELOAD="angie/page-reload"}(gs||(gs={}));const ms=c("iframe"),fs=c("registration-queue");class ys{queue=[];isProcessing=!1;add(e){const t={id:this.generateId(e),config:e,timestamp:Date.now(),status:"pending"};return this.queue.push(t),fs.log(`Added server "${e.name}" to queue`),t}getAll(){return[...this.queue]}getPending(){return this.queue.filter(e=>"pending"===e.status)}updateStatus(e,t,n){const s=this.queue.find(t=>t.id===e);s&&(s.status=t,n?s.error=n:"pending"!==t&&"registered"!==t||delete s.error,fs.log(`Updated server ${e} status to ${t}`))}async processQueue(e){if(this.isProcessing)return void fs.log("Already processing queue");this.isProcessing=!0;const t=this.getPending();fs.log(`Processing ${t.length} pending registrations`);try{for(const n of t)try{await e(n),this.updateStatus(n.id,"registered")}catch(e){const t=e instanceof Error?e.message:String(e);this.updateStatus(n.id,"failed",t),fs.error(`Failed to process registration ${n.id}:`,t)}}finally{this.isProcessing=!1}}clear(){this.queue=[],fs.log("Cleared all registrations")}resetAllToPending(){if(this.isProcessing)return fs.log("Cannot reset to pending - processing in progress"),!1;const e=this.queue.filter(e=>"registered"===e.status).length,t=this.queue.filter(e=>"failed"===e.status).length;return this.queue.forEach(e=>{"pending"!==e.status&&(e.status="pending",delete e.error)}),fs.log(`Reset ${e+t} registrations to pending`),!0}remove(e){const t=this.queue.findIndex(t=>t.id===e);return-1!==t&&(this.queue.splice(t,1),fs.log(`Removed registration ${e}`),!0)}generateId(e){return`reg_${e.name}_${e.version}_${Date.now()}`}}class _s{angieDetector;clientManager;logger;registrationQueue;isInitialized=!1;instanceId;constructor(){this.instanceId=Math.random().toString(36).substring(2,8),this.logger=c({instanceId:this.instanceId}),this.logger.log("Constructor called - initializing SDK"),this.angieDetector=new _,this.registrationQueue=new ys,this.clientManager=new Un,this.logger.log("Setting up event handlers"),this.setupAngieReadyHandler(),this.setupServerInitHandler(),this.setupReRegistrationHandler(),this.logger.log("SDK initialization complete")}async loadSidebar(e){ss(),await(async e=>{if(window.screen.availWidth<=768)return void ms.log("Mobile detected, skipping iframe injection");let t=document.getElementById("angie-sidebar-container");if(!t){const e=performance.now();if(ms.log("⏱️ Waiting for sidebar container..."),await new Promise(e=>{let n=0;const s=setInterval(()=>{t=document.getElementById("angie-sidebar-container"),n++,(t||n>20)&&(clearInterval(s),t&&e())},100);setTimeout(()=>{if(clearInterval(s),t)return void e();const n=new MutationObserver(()=>{t=document.getElementById("angie-sidebar-container"),t&&(n.disconnect(),e())});n.observe(document.body,{childList:!0,subtree:!0}),setTimeout(()=>{n.disconnect(),e()},8e3)},2e3)}),ms.log(`⏱️ Sidebar container detection took: ${(performance.now()-e).toFixed(2)}ms`),!t)return void ms.error("Sidebar container not found")}const{iframe:n,iframeUrlObject:s}=await(async e=>{const t=e.origin,n=new URL(e.path,t),s=n.pathname.slice(1).replace(/\//,"--")+"-"+Math.random().toString(36).substring(7);return new Promise(r=>{const a=new URL(t);a.pathname=n.pathname;const i=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";if(a.searchParams.append("colorScheme",e.uiTheme||i||"light"),a.searchParams.append("sdkVersion",e.sdkVersion),a.searchParams.append("instanceId",s),a.searchParams.append("origin",window.location.origin),e.isRTL&&a.searchParams.append("isRTL",e.isRTL?"true":"false"),"localhost"===window.location.hostname&&window.location.search.includes("debug_error")){const e=new URLSearchParams(window.location.search).get("debug_error");e&&a.searchParams.append("debug_error",e)}n.searchParams.forEach((e,t)=>{a.searchParams.set(t,e)}),a.searchParams.set("ver",(new Date).getTime().toString());const o=e.parent||document,d=o.createElement("iframe"),c={"background-color":"transparent","color-scheme":"normal",...e.css};window.addEventListener("message",async e=>{if(e.origin===a.origin)switch(e.data.type){case f.ANGIE_READY:r({iframe:d,iframeUrlObject:a});break;case f.ANGIE_LOADED:d.contentWindow?.postMessage({type:f.HOST_READY,instanceId:s},a.origin)}}),d.setAttribute("src",a.href),d.id="angie-iframe",d.setAttribute("frameborder","0"),d.setAttribute("scrolling","no"),d.setAttribute("style",Object.entries(c).map(([e,t])=>`${e}: ${t}`).join("; ")),d.setAttribute("allow","clipboard-write; clipboard-read"),e.insertCallback?e.insertCallback(d):o.body.appendChild(d)})})({origin:e.origin||"https://angie.elementor.com",path:"angie/wp-admin",insertCallback:e=>{ms.log("Injecting Angie iframe into sidebar container"),e.setAttribute("title","Angie AI Assistant"),e.setAttribute("role","application"),e.setAttribute("aria-label","Angie AI Assistant Interface");const n=document.getElementById("angie-sidebar-loading");n&&(n.textContent=""),t?.appendChild(e),rs(e,!0),e.addEventListener("load",()=>{e.focus()})},css:{width:"100%",height:"100%",border:"none",outline:"none"},uiTheme:e.uiTheme,isRTL:e.isRTL,sdkVersion:"1.0.5"});us.iframe=n,us.iframeUrlObject=s,window.addEventListener("message",e=>{if(e.origin===us.iframeUrlObject?.origin)switch(e.data.type){case m.SET:window.localStorage.setItem(e.data.key,e.data.value);break;case m.GET:{const t=e.ports[0],n=window.localStorage.getItem(e.data.key);t.postMessage({value:n});break}}}),(e=>{window.addEventListener("message",async t=>{const n=t.origin===window.location.origin,s=t.origin===e.iframeUrlObject?.origin;if(n||s)switch(t?.data?.type){case gs.SDK_ANGIE_ALL_SERVERS_REGISTERED:break;case gs.SDK_ANGIE_READY_PING:{const e=t.ports[0];ds.log("Angie is ready",t),as(e,{message:"Angie is ready"});break}case gs.SDK_REQUEST_CLIENT_CREATION:{const n=t.data.payload;try{const s=t.ports[0],r=new MessageChannel;r.port1.onmessage=e=>{s.postMessage({success:!0,data:e.data})};const a={type:gs.SDK_REQUEST_CLIENT_CREATION,payload:{success:!0,...n,clientId:`dynamic-client-${n.serverName}-${n.serverVersion}-${Date.now()}`,requestId:t.data.payload.requestId},timestamp:Date.now()};if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage(a,e.iframeUrlObject?.origin||"",[r.port2])}catch(e){ds.error(`Failed to create client for SDK server "${n.serverName}":`,e)}break}case gs.SDK_TRIGGER_ANGIE:ds.log("SDK Trigger Angie received",t.data);try{const{requestId:n,prompt:s,context:r}=t.data.payload;if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage({type:gs.SDK_TRIGGER_ANGIE,payload:{requestId:n,prompt:s,context:r}},e.iframeUrlObject?.origin||""),window.postMessage({type:gs.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!0,requestId:n,response:"Angie triggered successfully"}},window.location.origin)}catch(e){ds.error("Failed to trigger Angie:",e),window.postMessage({type:gs.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!1,requestId:t.data.payload?.requestId,error:e instanceof Error?e.message:"Unknown error"}},window.location.origin)}}})})(us),ps(),window.addEventListener("message",async t=>{if([window.location.origin,e.origin||"https://angie.elementor.com"].includes(t.origin))if(t?.data?.type===gs.ANGIE_CHAT_TOGGLE)us.open=t.data.open,us.iframe&&rs(us.iframe,us.open);else if(t?.data?.type===gs.ANGIE_STUDIO_TOGGLE){const e=t.data.isStudioOpen;if(!us.iframe)return;if(e)document.documentElement.classList.add("angie-studio-active");else{const e=Qn();document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`),document.documentElement.classList.remove("angie-studio-active")}}else if(t?.data?.type===gs.ANGIE_NAVIGATE_TO_URL){const{url:e=""}=t.data;if(!((e,t=[])=>{const n=0===t.length&&"undefined"!=typeof window?[window.location.origin]:t;if(!e.startsWith("http"))return!1;try{const t=new URL(e);return n.includes(t.origin)}catch{return!1}})(e))throw new Error("Angie: Invalid URL - navigation blocked for security reasons");window.location.assign(e)}else t?.data?.type===gs.ANGIE_PAGE_RELOAD?(ms.log("Angie requested page reload - database operations completed"),window.location.reload()):t?.data?.type===f.RESET_HASH&&(window.location.hash="",as(t.ports[0],{message:"Hash reset successfully"}))})})({origin:e?.origin||"https://angie.elementor.com",uiTheme:e?.uiTheme||"light",isRTL:e?.isRTL||!1,...e}),this.setupPromptHashDetection()}setupReRegistrationHandler(){window.addEventListener("message",e=>{if(e.data?.type===g.SDK_ANGIE_REFRESH_PING)if(this.logger.log("Angie refresh ping received"),this.registrationQueue.resetAllToPending()){const e=this.registrationQueue.getPending().length;this.logger.log(`Successfully reset ${e} registrations, processing queue`),this.handleAngieReady()}else this.logger.log("Skipping queue reset - processing already in progress")})}setupAngieReadyHandler(){this.angieDetector.waitForReady().then(e=>{e.isReady?this.handleAngieReady():this.logger.warn("Angie not detected - servers will remain queued")}).catch(e=>{this.logger.error("Error waiting for Angie:",e)})}async handleAngieReady(){this.logger.log("Angie is ready, processing queued registrations");try{await this.registrationQueue.processQueue(async e=>{this.logger.log(`processQueue callback called for "${e.config.name}"`),await this.processRegistration(e)}),this.isInitialized=!0,this.logger.log("Initialization complete")}catch(e){this.logger.error("Error processing registration queue:",e)}}async processRegistration(e){this.logger.log(`Processing registration for server "${e.config.name}" (ID: ${e.id})`);try{this.logger.log(`Calling clientManager.requestClientCreation for "${e.config.name}"`);const t={...e,instanceId:this.instanceId};await this.clientManager.requestClientCreation(t),this.logger.log(`Successfully registered server "${e.config.name}"`)}catch(t){throw this.logger.error(`Failed to register server "${e.config.name}":`,t),t}}registerLocalServer(e){return e.type=p.LOCAL,e.transport=l.POST_MESSAGE,this.registerServer(e)}registerRemoteServer(e){return e.type=p.REMOTE,this.registerServer(e)}isLocalServerConfig(e){return e.type===p.LOCAL||!e.type&&"server"in e}isRemoteServerConfig(e){return e.type===p.REMOTE&&"url"in e}async registerServer(e){if(!e.type)return this.logger.warn("For a local server, please use registerLocalServer instead of registerServer"),void this.registerLocalServer(e);if(this.logger.log(`registerServer called for "${e.name}"`),!e.name)throw new Error("Server name is required");if(!e.description)throw new Error("Server description is required");if(this.isLocalServerConfig(e)&&!e.server)throw new Error("Server instance is required for local servers");this.logger.log(`Registering server "${e.name}"`);const t=this.registrationQueue.add(e);if(this.logger.log(`Added registration to queue: ${t.id}`),this.angieDetector.isReady())try{await this.processRegistration(t),this.registrationQueue.updateStatus(t.id,"registered"),this.logger.log(`Server "${e.name}" registered successfully`)}catch(e){const n=e instanceof Error?e.message:String(e);throw this.registrationQueue.updateStatus(t.id,"failed",n),e}else this.logger.log(`Server "${e.name}" queued until Angie is ready`)}getRegistrations(){return this.registrationQueue.getAll()}getPendingRegistrations(){return this.registrationQueue.getPending()}isAngieReady(){return this.angieDetector.isReady()}isReady(){return this.isInitialized}async waitForReady(){if(!(await this.angieDetector.waitForReady()).isReady)throw new Error("Angie is not available");for(;!this.isInitialized;)await new Promise(e=>setTimeout(e,100))}async triggerAngie(e){if(!this.isAngieReady())throw new Error("Angie is not ready. Please wait for Angie to be available before triggering.");const t=this.generateRequestId(),n=e.options?.timeout||3e4;return new Promise((s,r)=>{const a=setTimeout(()=>{r(new Error("Angie trigger request timed out"))},n),i=e=>{e.data?.type===g.SDK_TRIGGER_ANGIE_RESPONSE&&e.data?.payload?.requestId===t&&(clearTimeout(a),window.removeEventListener("message",i),s(e.data.payload))};window.addEventListener("message",i);const o={type:g.SDK_TRIGGER_ANGIE,payload:{requestId:t,prompt:e.prompt,options:e.options,context:{pageUrl:window.location.href,pageTitle:document.title,...e.context}},timestamp:Date.now()};this.logger.log(`Triggering Angie with prompt (Request ID: ${t})`),window.postMessage(o,window.location.origin)})}destroy(){this.registrationQueue.clear(),this.logger.log("SDK destroyed")}setupServerInitHandler(){window.addEventListener("message",e=>{e.data?.type===g.SDK_REQUEST_INIT_SERVER&&(this.logger.log("Server init request received"),this.handleServerInitRequest(e))})}handleServerInitRequest(e){const{clientId:t,serverId:n,instanceId:s}=e.data.payload||{};if(t&&n)if(this.logger.log(`Server init request received - Request instanceId: ${s}, This instanceId: ${this.instanceId}`),s&&s!==this.instanceId)this.logger.log(`Ignoring server init request for different instance. Request instanceId: ${s}, this instanceId: ${this.instanceId}`);else{this.logger.log(`Handling server init request for clientId: ${t}, serverId: ${n}`);try{const t=this.registrationQueue.getAll().find(e=>e.id===n);if(!t)return void this.logger.error(`No registration found for serverId: ${n}`);if("type"in t.config&&"remote"===t.config.type)return void this.logger.log("Remote server registration detected; skipping local connect");const s=e.ports[0];if(!s)return void this.logger.error("No port provided in server init request");const r=t.config.server,a=new Gn(s);r.connect(a),this.logger.log(`Server "${t.config.name}" initialized successfully`)}catch(e){this.logger.error(`Error initializing server for clientId ${t}:`,e)}}else this.logger.error("Invalid server init request - missing clientId or serverId")}generateRequestId(){return`${this.instanceId}-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}async handlePromptHash(){const e=window.location.hash;if(e.startsWith("#angie-prompt="))try{const t=e.replace("#angie-prompt=",""),n=decodeURIComponent(t);if(!n)return void this.logger.warn("Empty prompt detected in hash");this.logger.log("Detected prompt in hash:",n),await this.waitForReady();const s=await this.triggerAngie({prompt:n,context:{source:"hash-parameter",pageUrl:window.location.href,timestamp:(new Date).toISOString()}});this.logger.log("Triggered successfully from hash:",s),window.location.hash=""}catch(e){this.logger.error("Failed to trigger from hash:",e)}}setupPromptHashDetection(){this.handlePromptHash(),window.addEventListener("hashchange",()=>this.handlePromptHash())}}const vs=c("navigation"),ws=(e,t)=>{if(zn()){t.isOpen&&window.toggleAngieSidebar&&window.toggleAngieSidebar(!0);const n=Kn({type:"angie-route-navigation",path:e,payload:t});return n||vs.error("Failed to post navigation message to Angie iframe"),n}return vs.error("Angie iframe not found"),!1};export{Hn as ANGIE_SIDEBAR_STATE_OPEN,_ as AngieDetector,l as AngieLocalServerTransport,u as AngieMCPTransport,_s as AngieMcpSdk,h as AngieRemoteServerTransport,p as AngieServerType,Un as ClientManager,f as HostEventType,m as HostLocalStorageEventType,g as MessageEventType,ys as RegistrationQueue,Jn as applyWidth,zn as getAngieIframe,Yn as getAngieSidebarSavedState,ss as initAngieSidebar,ns as initializeResize,es as loadState,Qn as loadWidth,ws as navigateAngieIframe,Xn as saveWidth,rs as toggleAngieSidebar,os as waitForDocumentReady};
1
+ import{JSONRPCMessageSchema as e}from"@modelcontextprotocol/sdk/types.js";const t={none:0,error:1,warn:2,info:3,debug:4},n={error:"error",warn:"warn",info:"info",log:"info",debug:"debug"},i=(e,n)=>t[e]<=t[n],r=e=>"string"==typeof e?e:JSON.stringify(e),o=(e,t)=>`${r(e)} > ${r(t)}`,a=(e,t)=>{let n=`[${r(e)}]`;return typeof window<"u"?{text:`%c${n}`,style:`color: ${t.color||"#00bcd4"}; font-weight: bold;`}:{text:n}},s=(e,t,r,o)=>(...s)=>{if(!i(n[e],o()))return;if(!t)return void console[e](...s);let{text:d,style:g}=a(t,r);g?console[e](d,g,...s):console[e](d,...s)},d=(e,t)=>{let n=t.logLevel??"debug",i=()=>n;return{log:s("log",e,t,i),info:s("info",e,t,i),warn:s("warn",e,t,i),error:s("error",e,t,i),debug:s("debug",e,t,i),setLogLevel:e=>{n=e},extend:i=>d(e?o(e,i):i,{...t,logLevel:n})}},g=d("angie-sdk",{color:"#00bcd4",logLevel:"debug",color:"#00BCD4",logLevel:"error"}),c=e=>g.extend(e);var l,u,h,p,m,w,f;!function(e){e.POST_MESSAGE="postMessage"}(l||(l={})),function(e){e.POST_MESSAGE="postMessage"}(u||(u={})),function(e){e.STREAMABLE_HTTP="streamableHttp",e.SSE="sse"}(h||(h={})),function(e){e.LOCAL="local",e.REMOTE="remote"}(p||(p={})),function(e){e.SDK_ANGIE_READY_PING="sdk-angie-ready-ping",e.SDK_ANGIE_REFRESH_PING="sdk-angie-refresh-ping",e.SDK_ANGIE_ALL_SERVERS_REGISTERED="sdk-angie-all-servers-registered",e.SDK_REQUEST_CLIENT_CREATION="sdk-request-client-creation",e.SDK_REQUEST_INIT_SERVER="sdk-request-init-server",e.SDK_TRIGGER_ANGIE="sdk-trigger-angie",e.SDK_TRIGGER_ANGIE_RESPONSE="sdk-trigger-angie-response",e.ANGIE_SIDEBAR_RESIZED="angie-sidebar-resized",e.ANGIE_SIDEBAR_TOGGLED="angie-sidebar-toggled",e.ANGIE_CHAT_TOGGLE="angie-chat-toggle",e.ANGIE_STUDIO_TOGGLE="angie-studio-toggle",e.ANGIE_NAVIGATE_TO_URL="angie/navigate-to-url",e.ANGIE_PAGE_RELOAD="angie/page-reload",e.ANGIE_DISABLE_NAVIGATION_PREVENTION="angie/disable-navigation-prevention",e.ANGIE_NAVIGATE_AFTER_RESPONSE="angie/navigate-after-response"}(m||(m={})),function(e){e.SET="ANGIE_SET_LOCALSTORAGE",e.GET="ANGIE_GET_LOCALSTORAGE"}(w||(w={})),function(e){e.RESET_HASH="reset-hash",e.HOST_READY="host/ready",e.ANGIE_LOADED="angie/loaded",e.ANGIE_READY="angie/ready"}(f||(f={}));const E=c("angie-detector");class y{isAngieReady=!1;readyPromise;readyResolve;constructor(){if(this.readyPromise=new Promise(e=>{this.readyResolve=e}),"undefined"==typeof window)return;let e=0;const t=()=>{if(this.isAngieReady||e>=500)return void(!this.isAngieReady&&e>=500&&this.handleDetectionTimeout());const n=new MessageChannel;n.port1.onmessage=e=>{this.handleAngieReady(e.data),n.port1.close(),n.port2.close()};const i={type:m.SDK_ANGIE_READY_PING,timestamp:Date.now()};window.postMessage(i,window.location.origin,[n.port2]),e++,setTimeout(t,500)};t()}handleAngieReady(e){this.isAngieReady=!0;const t={isReady:!0,version:e.version,capabilities:e.capabilities};this.readyResolve&&this.readyResolve(t)}handleDetectionTimeout(){this.readyResolve&&this.readyResolve({isReady:!1}),E.warn("Detection timeout - Angie may not be available")}isReady(){return this.isAngieReady}async waitForReady(){return this.readyPromise}}class b{sessionId;onmessage;onerror;onclose;_port;_started=!1;_closed=!1;constructor(t){if(!t)throw new Error("MessagePort is required");this._port=t,this._port.onmessage=t=>{try{const n=e.parse(t.data);this.onmessage?.(n)}catch(e){const t=new Error(`Failed to parse message: ${e}`);this.onerror?.(t)}},this._port.onmessageerror=e=>{const t=new Error(`MessagePort error: ${JSON.stringify(e)}`);this.onerror?.(t)}}async start(){if(this._started)throw new Error("BrowserContextTransport already started! If using Client or Server class, note that connect() calls start() automatically.");if(this._closed)throw new Error("Cannot start a closed BrowserContextTransport");this._started=!0,this._port.start()}async send(e){if(this._closed)throw new Error("Cannot send on a closed BrowserContextTransport");return new Promise((t,n)=>{try{this._port.postMessage(e),t()}catch(e){const t=e instanceof Error?e:new Error(String(e));this.onerror?.(t),n(t)}})}async close(){this._closed||(this._closed=!0,this._port.close(),this.onclose?.())}}class v{async requestClientCreation(e){const{config:t}=e,n={serverId:e.id,serverName:t.name,serverTitle:t.title,serverVersion:t.version,description:t.description,transport:t.transport||u.POST_MESSAGE,capabilities:t.capabilities,instanceId:e.instanceId};return"type"in t&&"remote"===t.type&&(n.remote={url:t.url}),new Promise((e,t)=>{const i=new MessageChannel,r=setTimeout(()=>{t(new Error("Client creation request timed out after 15000ms"))},15e3);i.port1.onmessage=t=>{clearTimeout(r),e(t.data)};const o={type:m.SDK_REQUEST_CLIENT_CREATION,payload:n,timestamp:Date.now()};window.postMessage(o,window.location.origin,[i.port2])})}}const S={open:!1,iframe:null,iframeUrlObject:null},I=(e,t)=>{const n=document.getElementById("angie-sidebar-container");n&&n.setAttribute("aria-hidden",t?"false":"true"),t?e.removeAttribute("tabindex"):e.setAttribute("tabindex","-1")},A=(e,t)=>{e.postMessage({status:"success",payload:t})},_=(e,t)=>{e.postMessage({status:"error",payload:t})},R=()=>new Promise(e=>{"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e(null)}),T=c("oauth");function L(){const e=new URL(window.location.href);e.searchParams.set("start-oauth","1"),T.log("Redirecting to wp-admin with OAuth:",e.toString()),window.location.href=e.toString()}const G=()=>{window.addEventListener("message",e=>{if(e.origin===S.iframeUrlObject?.origin)switch(e.data.type){case"OAUTH_GET_CODE_AND_STATE":(e=>{const t=new URLSearchParams(window.location.search),n=t.get("oauth_code"),i=t.get("oauth_state");if(n&&i)A(e,{code:n,state:i});else{const r=t.get("oauth_error");if(r){_(e,{message:r,code:n||null,state:i||null});const t=new URL(window.location.href);t.searchParams.delete("oauth_error"),history.replaceState({},"",t.toString())}else A(e,{message:"No OAuth error found"})}})(e.ports[0]);break;case"OAUTH_GET_TOP_URL":T.log("Iframe requested top window URL via MessageChannel"),A(e.ports[0],{topUrl:window.location.href});break;case"OAUTH_REDIRECT_TOP_WINDOW":T.log("Iframe requested top window redirect to:",e.data.payload.url),window.location.href=e.data.payload.url;break;case"OAUTH_UPDATE_URL":T.log("Iframe requested URL update to:",e.data.payload.url),function(e,t){if(!history?.replaceState)return T.warn("history.replaceState not supported in this browser"),void _(t,{message:"URL update not supported in this browser"});try{const n=window.location.href;history.replaceState({},"",e),function(e,t){const n=new URL(t),i=new URL(e),r=n.searchParams,o=i.searchParams,a=["oauth_code","oauth_state","start-oauth"];return a.some(e=>o?.has(e))&&!a.some(e=>r?.has(e))}(n,e)&&function(){T.log("OAuth parameters cleaned, opening sidebar");try{localStorage.setItem("angie_sidebar_state","open")}catch(e){T.warn("localStorage not available")}setTimeout(()=>{window.toggleAngieSidebar(!0)},500)}(),A(t,{message:"URL updated successfully"})}catch(e){T.warn("Failed to update URL via history.replaceState:",e),_(t,{message:"URL update failed: "+(e instanceof Error?e.message:"Unknown error")})}}(e.data.payload.url,e.ports[0]);break;case"ANGIE_REDIRECT_TO_WP_ADMIN_WITH_OAUTH":L();break;case"ANGIE_REDIRECT_TO_AUTH_ORIGIN_LOGOUT":try{L()}catch(e){T.error("Auth origin logout fallback failed:",e),window.location.reload()}}})},D=c("sdk");var N;(N||(N={})).POST_MESSAGE="postMessage";const P=c("iframe-utils");let O=null;const C=()=>(O&&document.contains(O)||(O=document.querySelector('iframe[src*="angie/"]')),O),q=(e,t)=>{P.log("postMessageToAngieIframe",e,t);const n=C();if(!n?.contentWindow)return!1;const i=t||(()=>{const e=C();if(!e)return null;try{return new URL(e.src).origin}catch(e){return P.error("Error parsing iframe URL:",e),null}})();return i?(n.contentWindow.postMessage(e,i),!0):(P.error("Could not determine target origin for Angie iframe"),!1)},U=c("sidebar");let $=!1;const M="open",k="closed";function x(){if("undefined"==typeof window)return 370;try{const e=window.localStorage.getItem("angie_sidebar_width");if(e){const t=parseInt(e,10);if(t>=350&&t<=590)return t}}catch(e){U.warn("localStorage not available")}return 370}function H(){return"undefined"==typeof window?null:localStorage.getItem("angie_sidebar_state")}function K(e){try{localStorage.setItem("angie_sidebar_state",e)}catch(e){U.warn("localStorage not available")}}function z(e){try{localStorage.setItem("angie_sidebar_width",e.toString())}catch(e){U.warn("localStorage not available")}}function B(e){document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`)}function F(){!function(){const e=new URLSearchParams(window.location.search);return e.has("start-oauth")||e.has("oauth_code")||e.has("oauth_state")||e.has("oauth_error")}()?Q(H()||M):function(){Q(k);try{localStorage.setItem("angie_sidebar_state",k)}catch(e){U.warn("localStorage not available")}}()}function Q(e){"undefined"!=typeof window&&window.toggleAngieSidebar&&window.toggleAngieSidebar(e===M,!0)}function V(){const e=document.getElementById("angie-sidebar-container");if(!e)return;let t=!1,n=0,i=0;e.addEventListener("mousedown",r=>{const o=e.getBoundingClientRect();("rtl"===document.documentElement.dir?r.clientX<=o.left+4:r.clientX>=o.right-4)&&(t=!0,n=r.clientX,i=o.width,e.classList.add("angie-resizing"),document.body.style.cursor="ew-resize",document.body.style.userSelect="none",r.preventDefault(),r.stopPropagation())}),document.addEventListener("mousemove",e=>{if(!t)return;let r;r="rtl"===document.documentElement.dir?n-e.clientX:e.clientX-n,B(Math.max(350,Math.min(590,i+r))),e.preventDefault(),e.stopPropagation()}),document.addEventListener("mouseup",n=>{if(t){t=!1,e.classList.remove("angie-resizing"),document.body.style.cursor="",document.body.style.userSelect="";const r=parseInt(getComputedStyle(document.documentElement).getPropertyValue("--angie-sidebar-width"),10);z(r),q({type:m.ANGIE_SIDEBAR_RESIZED,payload:{initialWidth:i,width:r}}),n.preventDefault(),n.stopPropagation()}}),B(x())}function j(e){!function(){if("undefined"==typeof document||$)return;const e="angie-sidebar-styles";if(document.getElementById(e))return void($=!0);const t=document.createElement("style");t.id=e,t.textContent="/* Angie Sidebar - CSS Variables */\n:root {\n --angie-sidebar-z-index: 1200; /* below MUI popups, elementor popups and media library modal */\n --angie-sidebar-width: 330px;\n --angie-sidebar-transition: margin 0.3s ease-in-out, transform 0.3s ease-in-out;\n /* Direction-aware transform values for sidebar positioning */\n --angie-sidebar-hide-transform: translateX(-100%); /* LTR: hide to the left */\n --angie-sidebar-show-transform: translateX(0);\n}\n\n/* RTL-specific transform values */\n[dir=\"rtl\"] {\n --angie-sidebar-hide-transform: translateX(100%); /* RTL: hide to the right */\n}\n\n/* Respect user's motion preferences */\n@media (prefers-reduced-motion: reduce) {\n :root {\n --angie-sidebar-transition: none;\n }\n}\n\n/* Apply transitions only when user is actively toggling */\nbody.angie-sidebar-transitioning {\n transition: var(--angie-sidebar-transition) !important;\n}\n\nbody.angie-sidebar-transitioning #angie-sidebar-container {\n transition: var(--angie-sidebar-transition) !important;\n}\n\n/* Layout (default) - Push content */\n@media (min-width: 768px) {\n body.angie-sidebar-active {\n padding-inline-start: var(--angie-sidebar-width) !important;\n }\n\n #angie-sidebar-container {\n position: fixed;\n top: 0;\n inset-inline-start: 0;\n width: var(--angie-sidebar-width);\n height: 100vh;\n z-index: var(--angie-sidebar-z-index) !important; /* below elementor popups and media library modal */\n background: #FCFCFC;\n transform: var(--angie-sidebar-hide-transform);\n outline: none;\n overflow: hidden;\n /* No default transition - only when transitioning */\n }\n\n /* Resize handle */\n #angie-sidebar-container::after {\n content: '';\n position: absolute;\n top: 0;\n inset-inline-end: 0;\n width: 4px;\n height: 100%;\n cursor: ew-resize;\n background: transparent;\n z-index: 1000001;\n }\n\n /* Pink border during resize */\n #angie-sidebar-container.angie-resizing {\n border-inline-end-color: #ff69b4 !important;\n border-inline-end-width: 2px !important;\n }\n\n /* Disable iframe pointer events during resize */\n #angie-sidebar-container.angie-resizing iframe#angie-iframe {\n pointer-events: none !important;\n }\n}\n\n/* Active states */\nbody.angie-sidebar-active #angie-sidebar-container {\n transform: var(--angie-sidebar-show-transform);\n}\n\n/* Studio mode - sidebar takes full width */\n@media (min-width: 768px) {\n html.angie-studio-active body.angie-sidebar-active #angie-sidebar-container {\n width: 100%;\n }\n}\n\n/* High contrast mode support */\n@media (prefers-contrast: high) {\n #angie-sidebar-container {\n border-color: #000;\n box-shadow: none;\n }\n}\n\n/* Screen reader only class */\n.angie-sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n/* Plugin conflict resolution */\nbody.angie-sidebar-active {\n /* Reset common conflicting styles */\n box-sizing: border-box !important;\n position: relative !important;\n}\n\n#angie-sidebar-toggle {\n z-index: 99999 !important;\n}\n";const n=document.head||document.getElementsByTagName("head")[0];n.insertBefore(t,n.firstChild),$=!0}(),"undefined"!=typeof window&&(window.toggleAngieSidebar=function(e){return function(t,n){const i=document.body,r=document.getElementById("angie-sidebar-container");if(!r)return void U.warn("Required elements not found!");const o=i.classList.contains("angie-sidebar-active"),a=void 0!==t?t:!o;n||(i.classList.add("angie-sidebar-transitioning"),setTimeout(function(){i.classList.remove("angie-sidebar-transitioning")},300)),a?i.classList.add("angie-sidebar-active"):i.classList.remove("angie-sidebar-active"),a&&setTimeout(function(){q({type:"focusInput"})},n?0:300),e&&e(a,r,n),K(a?M:k);const s=new CustomEvent("angieSidebarToggle",{detail:{isOpen:a,sidebar:r,skipTransition:n}});document.dispatchEvent(s),q({type:m.ANGIE_SIDEBAR_TOGGLED,payload:{state:a?"opened":"closed"}})}}(e),window.addEventListener("message",function(e){if(e.data&&"toggleAngieSidebar"===e.data.type){const{force:t,skipTransition:n}=e.data.payload||{};window.toggleAngieSidebar&&window.toggleAngieSidebar(t,n)}}))}const W=c("iframe"),X=async()=>{if(S.iframe?.contentWindow&&S.iframeUrlObject)try{W.log("Disabling navigation prevention in Angie iframe"),S.iframe.contentWindow.postMessage({type:m.ANGIE_DISABLE_NAVIGATION_PREVENTION},S.iframeUrlObject.origin),await new Promise(e=>setTimeout(e,100))}catch(e){throw W.error("Failed to disable navigation prevention:",e),e}else W.warn("Cannot disable navigation prevention: iframe or origin not available")},Y=c("registration-queue");class J{queue=[];isProcessing=!1;add(e){const t={id:this.generateId(e),config:e,timestamp:Date.now(),status:"pending"};return this.queue.push(t),Y.log(`Added server "${e.name}" to queue`),t}getAll(){return[...this.queue]}getPending(){return this.queue.filter(e=>"pending"===e.status)}updateStatus(e,t,n){const i=this.queue.find(t=>t.id===e);i&&(i.status=t,n?i.error=n:"pending"!==t&&"registered"!==t||delete i.error,Y.log(`Updated server ${e} status to ${t}`))}async processQueue(e){if(this.isProcessing)return void Y.log("Already processing queue");this.isProcessing=!0;const t=this.getPending();Y.log(`Processing ${t.length} pending registrations`);try{for(const n of t)try{await e(n),this.updateStatus(n.id,"registered")}catch(e){const t=e instanceof Error?e.message:String(e);this.updateStatus(n.id,"failed",t),Y.error(`Failed to process registration ${n.id}:`,t)}}finally{this.isProcessing=!1}}clear(){this.queue=[],Y.log("Cleared all registrations")}resetAllToPending(){if(this.isProcessing)return Y.log("Cannot reset to pending - processing in progress"),!1;const e=this.queue.filter(e=>"registered"===e.status).length,t=this.queue.filter(e=>"failed"===e.status).length;return this.queue.forEach(e=>{"pending"!==e.status&&(e.status="pending",delete e.error)}),Y.log(`Reset ${e+t} registrations to pending`),!0}remove(e){const t=this.queue.findIndex(t=>t.id===e);return-1!==t&&(this.queue.splice(t,1),Y.log(`Removed registration ${e}`),!0)}generateId(e){return`reg_${e.name}_${e.version}_${Date.now()}`}}class Z{angieDetector;clientManager;logger;registrationQueue;isInitialized=!1;instanceId;constructor(){this.instanceId=Math.random().toString(36).substring(2,8),this.logger=c({instanceId:this.instanceId}),this.logger.log("Constructor called - initializing SDK"),this.angieDetector=new y,this.registrationQueue=new J,this.clientManager=new v,this.logger.log("Setting up event handlers"),this.setupAngieReadyHandler(),this.setupServerInitHandler(),this.setupReRegistrationHandler(),this.logger.log("SDK initialization complete")}async loadSidebar(e){j(),await(async e=>{if(window.screen.availWidth<=768)return void W.log("Mobile detected, skipping iframe injection");let t=document.getElementById("angie-sidebar-container");if(!t){const e=performance.now();if(W.log("⏱️ Waiting for sidebar container..."),await new Promise(e=>{let n=0;const i=setInterval(()=>{t=document.getElementById("angie-sidebar-container"),n++,(t||n>20)&&(clearInterval(i),t&&e())},100);setTimeout(()=>{if(clearInterval(i),t)return void e();const n=new MutationObserver(()=>{t=document.getElementById("angie-sidebar-container"),t&&(n.disconnect(),e())});n.observe(document.body,{childList:!0,subtree:!0}),setTimeout(()=>{n.disconnect(),e()},8e3)},2e3)}),W.log(`⏱️ Sidebar container detection took: ${(performance.now()-e).toFixed(2)}ms`),!t)return void W.error("Sidebar container not found")}const{iframe:n,iframeUrlObject:i}=await(async e=>{const t=e.origin,n=new URL(e.path,t),i=n.pathname.slice(1).replace(/\//,"--")+"-"+Math.random().toString(36).substring(7);return new Promise(r=>{const o=new URL(t);o.pathname=n.pathname;const a=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";if(o.searchParams.append("colorScheme",e.uiTheme||a||"light"),o.searchParams.append("sdkVersion",e.sdkVersion),o.searchParams.append("instanceId",i),o.searchParams.append("origin",window.location.origin),e.isRTL&&o.searchParams.append("isRTL",e.isRTL?"true":"false"),"localhost"===window.location.hostname&&window.location.search.includes("debug_error")){const e=new URLSearchParams(window.location.search).get("debug_error");e&&o.searchParams.append("debug_error",e)}n.searchParams.forEach((e,t)=>{o.searchParams.set(t,e)}),o.searchParams.set("ver",(new Date).getTime().toString());const s=e.parent||document,d=s.createElement("iframe"),g={"background-color":"transparent","color-scheme":"normal",...e.css};window.addEventListener("message",async e=>{if(e.origin===o.origin)switch(e.data.type){case f.ANGIE_READY:r({iframe:d,iframeUrlObject:o});break;case f.ANGIE_LOADED:d.contentWindow?.postMessage({type:f.HOST_READY,instanceId:i},o.origin)}}),d.setAttribute("src",o.href),d.id="angie-iframe",d.setAttribute("frameborder","0"),d.setAttribute("scrolling","no"),d.setAttribute("style",Object.entries(g).map(([e,t])=>`${e}: ${t}`).join("; ")),d.setAttribute("allow","clipboard-write; clipboard-read"),e.insertCallback?e.insertCallback(d):s.body.appendChild(d)})})({origin:e.origin||"https://angie.elementor.com",path:"angie/wp-admin",insertCallback:e=>{W.log("Injecting Angie iframe into sidebar container"),e.setAttribute("title","Angie AI Assistant"),e.setAttribute("role","application"),e.setAttribute("aria-label","Angie AI Assistant Interface");const n=document.getElementById("angie-sidebar-loading");n&&(n.textContent=""),t?.appendChild(e),I(e,!0),e.addEventListener("load",()=>{e.focus()})},css:{width:"100%",height:"100%",border:"none",outline:"none"},uiTheme:e.uiTheme,isRTL:e.isRTL,sdkVersion:"1.0.7"});S.iframe=n,S.iframeUrlObject=i,window.addEventListener("message",e=>{if(e.origin===S.iframeUrlObject?.origin)switch(e.data.type){case w.SET:window.localStorage.setItem(e.data.key,e.data.value);break;case w.GET:{const t=e.ports[0],n=window.localStorage.getItem(e.data.key);t.postMessage({value:n});break}}}),(e=>{window.addEventListener("message",async t=>{const n=t.origin===window.location.origin,i=t.origin===e.iframeUrlObject?.origin;if(n||i)switch(t?.data?.type){case m.SDK_ANGIE_ALL_SERVERS_REGISTERED:break;case m.SDK_ANGIE_READY_PING:{const e=t.ports[0];D.log("Angie is ready",t),A(e,{message:"Angie is ready"});break}case m.SDK_REQUEST_CLIENT_CREATION:{const n=t.data.payload;try{const i=t.ports[0],r=new MessageChannel;r.port1.onmessage=e=>{i.postMessage({success:!0,data:e.data})};const o={type:m.SDK_REQUEST_CLIENT_CREATION,payload:{success:!0,...n,clientId:`dynamic-client-${n.serverName}-${n.serverVersion}-${Date.now()}`,requestId:t.data.payload.requestId},timestamp:Date.now()};if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage(o,e.iframeUrlObject?.origin||"",[r.port2])}catch(e){D.error(`Failed to create client for SDK server "${n.serverName}":`,e)}break}case m.SDK_TRIGGER_ANGIE:D.log("SDK Trigger Angie received",t.data);try{const{requestId:n,prompt:i,context:r}=t.data.payload;if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage({type:m.SDK_TRIGGER_ANGIE,payload:{requestId:n,prompt:i,context:r}},e.iframeUrlObject?.origin||""),window.postMessage({type:m.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!0,requestId:n,response:"Angie triggered successfully"}},window.location.origin)}catch(e){D.error("Failed to trigger Angie:",e),window.postMessage({type:m.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!1,requestId:t.data.payload?.requestId,error:e instanceof Error?e.message:"Unknown error"}},window.location.origin)}}})})(S),G(),window.addEventListener("message",async t=>{if([window.location.origin,e.origin||"https://angie.elementor.com"].includes(t.origin))if(t?.data?.type===m.ANGIE_CHAT_TOGGLE)S.open=t.data.open,S.iframe&&I(S.iframe,S.open);else if(t?.data?.type===m.ANGIE_STUDIO_TOGGLE){const e=t.data.isStudioOpen;if(!S.iframe)return;if(e)document.documentElement.classList.add("angie-studio-active");else{const e=x();document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`),document.documentElement.classList.remove("angie-studio-active")}}else if(t?.data?.type===m.ANGIE_NAVIGATE_TO_URL){const{url:e="",confirmed:n=!1}=t.data.payload||{};if(!n)return void W.log("Navigation requires user confirmation");if(!((e,t=[])=>{const n=0===t.length&&"undefined"!=typeof window?[window.location.origin]:t;if(!e.startsWith("http"))return!1;try{const t=new URL(e);return n.includes(t.origin)}catch{return!1}})(e))return void W.error("Navigation blocked: Invalid or unsafe URL",{url:e});await X(),window.location.assign(e)}else if(t?.data?.type===m.ANGIE_PAGE_RELOAD){const{confirmed:e=!1}=t.data.payload||{};if(!e)return void W.log("Page reload requires user confirmation");W.log("Page reload confirmed - disabling navigation prevention and reloading"),await X(),setTimeout(()=>{window.location.reload()},50)}else t?.data?.type===f.RESET_HASH&&(window.location.hash="",A(t.ports[0],{message:"Hash reset successfully"}))})})({origin:e?.origin||"https://angie.elementor.com",uiTheme:e?.uiTheme||"light",isRTL:e?.isRTL||!1,...e}),this.setupPromptHashDetection()}setupReRegistrationHandler(){window.addEventListener("message",e=>{if(e.data?.type===m.SDK_ANGIE_REFRESH_PING)if(this.logger.log("Angie refresh ping received"),this.registrationQueue.resetAllToPending()){const e=this.registrationQueue.getPending().length;this.logger.log(`Successfully reset ${e} registrations, processing queue`),this.handleAngieReady()}else this.logger.log("Skipping queue reset - processing already in progress")})}setupAngieReadyHandler(){this.angieDetector.waitForReady().then(e=>{e.isReady?this.handleAngieReady():this.logger.warn("Angie not detected - servers will remain queued")}).catch(e=>{this.logger.error("Error waiting for Angie:",e)})}async handleAngieReady(){this.logger.log("Angie is ready, processing queued registrations");try{await this.registrationQueue.processQueue(async e=>{this.logger.log(`processQueue callback called for "${e.config.name}"`),await this.processRegistration(e)}),this.isInitialized=!0,this.logger.log("Initialization complete")}catch(e){this.logger.error("Error processing registration queue:",e)}}async processRegistration(e){this.logger.log(`Processing registration for server "${e.config.name}" (ID: ${e.id})`);try{this.logger.log(`Calling clientManager.requestClientCreation for "${e.config.name}"`);const t={...e,instanceId:this.instanceId};await this.clientManager.requestClientCreation(t),this.logger.log(`Successfully registered server "${e.config.name}"`)}catch(t){throw this.logger.error(`Failed to register server "${e.config.name}":`,t),t}}registerLocalServer(e){return e.type=p.LOCAL,e.transport=u.POST_MESSAGE,this.registerServer(e)}registerRemoteServer(e){return e.type=p.REMOTE,this.registerServer(e)}isLocalServerConfig(e){return e.type===p.LOCAL||!e.type&&"server"in e}isRemoteServerConfig(e){return e.type===p.REMOTE&&"url"in e}async registerServer(e){if(!e.type)return this.logger.warn("For a local server, please use registerLocalServer instead of registerServer"),void this.registerLocalServer(e);if(this.logger.log(`registerServer called for "${e.name}"`),!e.name)throw new Error("Server name is required");if(!e.description)throw new Error("Server description is required");if(this.isLocalServerConfig(e)&&!e.server)throw new Error("Server instance is required for local servers");this.logger.log(`Registering server "${e.name}"`);const t=this.registrationQueue.add(e);if(this.logger.log(`Added registration to queue: ${t.id}`),this.angieDetector.isReady())try{await this.processRegistration(t),this.registrationQueue.updateStatus(t.id,"registered"),this.logger.log(`Server "${e.name}" registered successfully`)}catch(e){const n=e instanceof Error?e.message:String(e);throw this.registrationQueue.updateStatus(t.id,"failed",n),e}else this.logger.log(`Server "${e.name}" queued until Angie is ready`)}getRegistrations(){return this.registrationQueue.getAll()}getPendingRegistrations(){return this.registrationQueue.getPending()}isAngieReady(){return this.angieDetector.isReady()}isReady(){return this.isInitialized}async waitForReady(){if(!(await this.angieDetector.waitForReady()).isReady)throw new Error("Angie is not available");for(;!this.isInitialized;)await new Promise(e=>setTimeout(e,100))}async triggerAngie(e){if(!this.isAngieReady())throw new Error("Angie is not ready. Please wait for Angie to be available before triggering.");const t=this.generateRequestId(),n=e.options?.timeout||3e4;return new Promise((i,r)=>{const o=setTimeout(()=>{r(new Error("Angie trigger request timed out"))},n),a=e=>{e.data?.type===m.SDK_TRIGGER_ANGIE_RESPONSE&&e.data?.payload?.requestId===t&&(clearTimeout(o),window.removeEventListener("message",a),i(e.data.payload))};window.addEventListener("message",a);const s={type:m.SDK_TRIGGER_ANGIE,payload:{requestId:t,prompt:e.prompt,options:e.options,context:{pageUrl:window.location.href,pageTitle:document.title,...e.context}},timestamp:Date.now()};this.logger.log(`Triggering Angie with prompt (Request ID: ${t})`),window.postMessage(s,window.location.origin)})}destroy(){this.registrationQueue.clear(),this.logger.log("SDK destroyed")}setupServerInitHandler(){window.addEventListener("message",e=>{e.data?.type===m.SDK_REQUEST_INIT_SERVER&&(this.logger.log("Server init request received"),this.handleServerInitRequest(e))})}handleServerInitRequest(e){const{clientId:t,serverId:n,instanceId:i}=e.data.payload||{};if(t&&n)if(this.logger.log(`Server init request received - Request instanceId: ${i}, This instanceId: ${this.instanceId}`),i&&i!==this.instanceId)this.logger.log(`Ignoring server init request for different instance. Request instanceId: ${i}, this instanceId: ${this.instanceId}`);else{this.logger.log(`Handling server init request for clientId: ${t}, serverId: ${n}`);try{const t=this.registrationQueue.getAll().find(e=>e.id===n);if(!t)return void this.logger.error(`No registration found for serverId: ${n}`);if("type"in t.config&&"remote"===t.config.type)return void this.logger.log("Remote server registration detected; skipping local connect");const i=e.ports[0];if(!i)return void this.logger.error("No port provided in server init request");const r=t.config.server,o=new b(i);r.connect(o),this.logger.log(`Server "${t.config.name}" initialized successfully`)}catch(e){this.logger.error(`Error initializing server for clientId ${t}:`,e)}}else this.logger.error("Invalid server init request - missing clientId or serverId")}generateRequestId(){return`${this.instanceId}-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}async handlePromptHash(){const e=window.location.hash;if(e.startsWith("#angie-prompt="))try{const t=e.replace("#angie-prompt=",""),n=decodeURIComponent(t);if(!n)return void this.logger.warn("Empty prompt detected in hash");this.logger.log("Detected prompt in hash:",n),await this.waitForReady();const i=await this.triggerAngie({prompt:n,context:{source:"hash-parameter",pageUrl:window.location.href,timestamp:(new Date).toISOString()}});this.logger.log("Triggered successfully from hash:",i),window.location.hash=""}catch(e){this.logger.error("Failed to trigger from hash:",e)}}setupPromptHashDetection(){this.handlePromptHash(),window.addEventListener("hashchange",()=>this.handlePromptHash())}}const ee=c("navigation"),te=(e,t)=>{if(C()){t.isOpen&&window.toggleAngieSidebar&&window.toggleAngieSidebar(!0);const n=q({type:"angie-route-navigation",path:e,payload:t});return n||ee.error("Failed to post navigation message to Angie iframe"),n}return ee.error("Angie iframe not found"),!1};export{M as ANGIE_SIDEBAR_STATE_OPEN,y as AngieDetector,u as AngieLocalServerTransport,l as AngieMCPTransport,Z as AngieMcpSdk,h as AngieRemoteServerTransport,p as AngieServerType,b as BrowserContextTransport,v as ClientManager,f as HostEventType,w as HostLocalStorageEventType,m as MessageEventType,J as RegistrationQueue,B as applyWidth,X as disableNavigationPrevention,C as getAngieIframe,H as getAngieSidebarSavedState,j as initAngieSidebar,V as initializeResize,F as loadState,x as loadWidth,te as navigateAngieIframe,K as saveState,z as saveWidth,I as toggleAngieSidebar,R as waitForDocumentReady};
package/dist/types.d.ts CHANGED
@@ -17,6 +17,7 @@ export declare enum AngieServerType {
17
17
  }
18
18
  export type AngieBaseServerConfig = {
19
19
  name: string;
20
+ title?: string;
20
21
  version: string;
21
22
  description: string;
22
23
  capabilities?: ServerCapabilities;
@@ -54,6 +55,7 @@ export interface AngieMessage<T = unknown> {
54
55
  export interface ClientCreationRequest {
55
56
  serverId: string;
56
57
  serverName: string;
58
+ serverTitle?: string;
57
59
  description: string;
58
60
  serverVersion: string;
59
61
  transport?: AngieLocalServerTransport | AngieRemoteServerTransport;
@@ -86,10 +88,19 @@ export interface AngieTriggerResponse {
86
88
  export declare enum MessageEventType {
87
89
  SDK_ANGIE_READY_PING = "sdk-angie-ready-ping",
88
90
  SDK_ANGIE_REFRESH_PING = "sdk-angie-refresh-ping",
91
+ SDK_ANGIE_ALL_SERVERS_REGISTERED = "sdk-angie-all-servers-registered",
89
92
  SDK_REQUEST_CLIENT_CREATION = "sdk-request-client-creation",
90
93
  SDK_REQUEST_INIT_SERVER = "sdk-request-init-server",
91
94
  SDK_TRIGGER_ANGIE = "sdk-trigger-angie",
92
- SDK_TRIGGER_ANGIE_RESPONSE = "sdk-trigger-angie-response"
95
+ SDK_TRIGGER_ANGIE_RESPONSE = "sdk-trigger-angie-response",
96
+ ANGIE_SIDEBAR_RESIZED = "angie-sidebar-resized",
97
+ ANGIE_SIDEBAR_TOGGLED = "angie-sidebar-toggled",
98
+ ANGIE_CHAT_TOGGLE = "angie-chat-toggle",
99
+ ANGIE_STUDIO_TOGGLE = "angie-studio-toggle",
100
+ ANGIE_NAVIGATE_TO_URL = "angie/navigate-to-url",
101
+ ANGIE_PAGE_RELOAD = "angie/page-reload",
102
+ ANGIE_DISABLE_NAVIGATION_PREVENTION = "angie/disable-navigation-prevention",
103
+ ANGIE_NAVIGATE_AFTER_RESPONSE = "angie/navigate-after-response"
93
104
  }
94
105
  export declare enum HostLocalStorageEventType {
95
106
  SET = "ANGIE_SET_LOCALSTORAGE",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elementor/angie-sdk",
3
- "version": "1.0.5",
3
+ "version": "1.0.7",
4
4
  "description": "TypeScript SDK for Angie AI assistant",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -26,12 +26,14 @@
26
26
  "author": "Elementor",
27
27
  "license": "MIT",
28
28
  "dependencies": {
29
- "@elementor/angie-logger": "^0.3.1",
30
- "@modelcontextprotocol/sdk": "1.17.4",
31
- "zod": "4.1.3"
29
+ "@elementor/angie-logger": "^0.3.1"
30
+ },
31
+ "peerDependencies": {
32
+ "@modelcontextprotocol/sdk": ">=1.17.4"
32
33
  },
33
34
  "devDependencies": {
34
35
  "@eslint/js": "^8.0.0",
36
+ "@modelcontextprotocol/sdk": "1.20.1",
35
37
  "@types/jest": "^29.5.12",
36
38
  "@types/node": "^20.19.0",
37
39
  "@typescript-eslint/eslint-plugin": "^6.19.1",
@@ -54,6 +56,10 @@
54
56
  ],
55
57
  "repository": {
56
58
  "type": "git",
57
- "url": "https://github.com/elementor/angie-sdk.git"
59
+ "url": "git+https://github.com/elementor/angie-sdk.git"
60
+ },
61
+ "homepage": "https://github.com/elementor/angie-sdk",
62
+ "publishConfig": {
63
+ "access": "public"
58
64
  }
59
65
  }