@opentiny/next-sdk 0.4.2 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{SimulatorMask-BHVXyogh-CARX3Rff.js → SimulatorMask-BHVXyogh-CKmEDsYG.js} +1 -1
- package/dist/{index-R_HIbfUX.js → index-CHMa2zG4.js} +1065 -1042
- package/dist/index.js +1 -1
- package/dist/page-tools/a11y/config.d.ts +6 -3
- package/dist/page-tools/a11y/constants.d.ts +20 -0
- package/dist/page-tools/a11y/utils.d.ts +14 -0
- package/dist/page-tools/constants.d.ts +4 -2
- package/dist/page-tools/context.d.ts +2 -0
- package/dist/page-tools/handlers/hover.d.ts +9 -0
- package/dist/page-tools/schema.d.ts +3 -3
- package/dist/page-tools/utils/dom.d.ts +8 -2
- package/dist/runtime.js +19 -172
- package/package.json +6 -1
- package/WebMcpClient.ts +0 -505
- package/WebMcpServer.ts +0 -447
- package/agent/AgentModelProvider.ts +0 -932
- package/agent/type.ts +0 -91
- package/agent/utils/generateReActPrompt.ts +0 -71
- package/agent/utils/getAISDKTools.ts +0 -34
- package/agent/utils/getBuiltinMcpTools.ts +0 -86
- package/agent/utils/parseReActAction.ts +0 -34
- package/core.ts +0 -26
- package/index.ts +0 -91
- package/page-tools/a11y/build.ts +0 -74
- package/page-tools/a11y/config.ts +0 -465
- package/page-tools/a11y/constants.ts +0 -131
- package/page-tools/a11y/search.ts +0 -127
- package/page-tools/a11y/types.ts +0 -105
- package/page-tools/a11y/utils.ts +0 -239
- package/page-tools/a11y/vnode.ts +0 -439
- package/page-tools/a11y-tree.ts +0 -14
- package/page-tools/bridge.ts +0 -722
- package/page-tools/configs/console-cloud.ts +0 -172
- package/page-tools/constants.ts +0 -12
- package/page-tools/context.ts +0 -50
- package/page-tools/effects.ts +0 -345
- package/page-tools/handlers/browserState.ts +0 -12
- package/page-tools/handlers/click.ts +0 -30
- package/page-tools/handlers/executeJavascript.ts +0 -22
- package/page-tools/handlers/fill.ts +0 -65
- package/page-tools/handlers/scroll.ts +0 -66
- package/page-tools/handlers/searchTree.ts +0 -27
- package/page-tools/handlers/select.ts +0 -39
- package/page-tools/initialize-builtin-WebMCP.ts +0 -20
- package/page-tools/page-agent-highlight/index.ts +0 -245
- package/page-tools/page-agent-mask/SimulatorMask.module.css +0 -14
- package/page-tools/page-agent-mask/SimulatorMask.ts +0 -299
- package/page-tools/page-agent-mask/checkDarkMode.ts +0 -181
- package/page-tools/page-agent-mask/cursor-border.svg +0 -3
- package/page-tools/page-agent-mask/cursor-fill.svg +0 -5
- package/page-tools/page-agent-mask/cursor.module.css +0 -70
- package/page-tools/page-agent-mask/hauwei.svg +0 -25
- package/page-tools/page-agent-prompt.md +0 -139
- package/page-tools/page-agent-tool-event.ts +0 -113
- package/page-tools/page-agent-tool.ts +0 -207
- package/page-tools/page-state-cache.ts +0 -78
- package/page-tools/schema.ts +0 -52
- package/page-tools/tool-config.ts +0 -100
- package/page-tools/utils/dom.ts +0 -158
- package/page-tools/utils/scroll.ts +0 -58
- package/remoter/QrCode.ts +0 -54
- package/remoter/createRemoter.ts +0 -957
- package/remoter/svgs/chat.svg +0 -43
- package/remoter/svgs/icon-copy.svg +0 -25
- package/remoter/svgs/link.svg +0 -28
- package/remoter/svgs/logo.svg +0 -45
- package/remoter/svgs/qrcode.svg +0 -35
- package/remoter/svgs/scan.svg +0 -21
- package/remoter/tooltips.ts +0 -260
- package/runtime.html +0 -39
- package/runtime.ts +0 -44
- package/script/utils.ts +0 -26
- package/skills/index.ts +0 -287
- package/test/page-tools/a11y/build.test.ts +0 -638
- package/test/page-tools/a11y/config.test.ts +0 -370
- package/test/page-tools/configs/console-cloud.test.ts +0 -168
- package/test/page-tools/page-agent-highlight.test.ts +0 -110
- package/test/page-tools/page-agent-tool-dispatch.test.ts +0 -208
- package/test/page-tools/page-agent-tool.test.ts +0 -102
- package/test/page-tools/tool-config.test.ts +0 -112
- package/test/page-tools/utils/dom.test.ts +0 -122
- package/tsconfig.json +0 -16
- package/utils/builtinProxy.ts +0 -144
- package/utils/env.ts +0 -13
- package/utils/uuid.ts +0 -10
- package/vite.config.runtime.ts +0 -22
- package/vite.config.ts +0 -63
- package/vitest.config.ts +0 -10
package/dist/runtime.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var WebMCPSDK=(function(exports){"use strict";function deepCompareStrict(t,e){const r=typeof t;if(r!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;const n=t.length;if(n!==e.length)return!1;for(let i=0;i<n;i++)if(!deepCompareStrict(t[i],e[i]))return!1;return!0}if(r==="object"){if(!t||!e)return t===e;const n=Object.keys(t),i=Object.keys(e);if(n.length!==i.length)return!1;for(const s of n)if(!deepCompareStrict(t[s],e[s]))return!1;return!0}return t===e}function encodePointer(t){return encodeURI(escapePointer(t))}function escapePointer(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}const schemaArrayKeyword={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},schemaMapKeyword={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},ignoredKeyword={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};let initialBaseURI=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function dereference(t,e=Object.create(null),r=initialBaseURI,n=""){if(t&&typeof t=="object"&&!Array.isArray(t)){const o=t.$id||t.id;if(o){const s=new URL(o,r.href);s.hash.length>1?e[s.href]=t:(s.hash="",n===""?r=s:dereference(t,e,r))}}else if(t!==!0&&t!==!1)return e;const i=r.href+(n?"#"+n:"");if(e[i]!==void 0)throw new Error(`Duplicate schema URI "${i}".`);if(e[i]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:i}),t.$ref&&t.__absolute_ref__===void 0){const o=new URL(t.$ref,r.href);o.hash=o.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:o.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){const o=new URL(t.$recursiveRef,r.href);o.hash=o.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:o.href})}if(t.$anchor){const o=new URL("#"+t.$anchor,r.href);e[o.href]=t}for(let o in t){if(ignoredKeyword[o])continue;const s=`${n}/${encodePointer(o)}`,a=t[o];if(Array.isArray(a)){if(schemaArrayKeyword[o]){const l=a.length;for(let c=0;c<l;c++)dereference(a[c],e,r,`${s}/${c}`)}}else if(schemaMapKeyword[o])for(let l in a)dereference(a[l],e,r,`${s}/${encodePointer(l)}`);else dereference(a,e,r,s)}return e}const DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31],TIME=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,HOSTNAME=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,URIREF=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,URITEMPLATE=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,URL_=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,UUID=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,JSON_POINTER=/^(?:\/(?:[^~/]|~0|~1)*)*$/,JSON_POINTER_URI_FRAGMENT=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,RELATIVE_JSON_POINTER=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,EMAIL=t=>{if(t[0]==='"')return!1;const[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},IPV4=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,IPV6=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,DURATION=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));function bind(t){return t.test.bind(t)}const format={date,time:time.bind(void 0,!1),"date-time":date_time,duration:DURATION,uri,"uri-reference":bind(URIREF),"uri-template":bind(URITEMPLATE),url:bind(URL_),email:EMAIL,hostname:bind(HOSTNAME),ipv4:bind(IPV4),ipv6:bind(IPV6),regex,uuid:bind(UUID),"json-pointer":bind(JSON_POINTER),"json-pointer-uri-fragment":bind(JSON_POINTER_URI_FRAGMENT),"relative-json-pointer":bind(RELATIVE_JSON_POINTER)};function isLeapYear(t){return t%4===0&&(t%100!==0||t%400===0)}function date(t){const e=t.match(DATE);if(!e)return!1;const r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&isLeapYear(r)?29:DAYS[n])}function time(t,e){const r=e.match(TIME);if(!r)return!1;const n=+r[1],i=+r[2],o=+r[3],s=!!r[5];return(n<=23&&i<=59&&o<=59||n==23&&i==59&&o==60)&&(!t||s)}const DATE_TIME_SEPARATOR=/t|\s/i;function date_time(t){const e=t.split(DATE_TIME_SEPARATOR);return e.length==2&&date(e[0])&&time(!0,e[1])}const NOT_URI_FRAGMENT=/\/|:/,URI_PATTERN=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function uri(t){return NOT_URI_FRAGMENT.test(t)&&URI_PATTERN.test(t)}const Z_ANCHOR=/[^\\]\\Z/;function regex(t){if(Z_ANCHOR.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}function ucs2length(t){let e=0,r=t.length,n=0,i;for(;n<r;)e++,i=t.charCodeAt(n++),i>=55296&&i<=56319&&n<r&&(i=t.charCodeAt(n),(i&64512)==56320&&n++);return e}function validate(t,e,r="2019-09",n=dereference(e),i=!0,o=null,s="#",a="#",l=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};const c=typeof t;let u;switch(c){case"boolean":case"number":case"string":u=c;break;case"object":t===null?u="null":Array.isArray(t)?u="array":u="object";break;default:throw new Error(`Instances of "${c}" type are not supported.`)}const{$ref:h,$recursiveRef:f,$recursiveAnchor:g,type:b,const:P,enum:w,required:p,not:m,anyOf:A,allOf:T,oneOf:k,if:Z,then:R,else:V,format:j,properties:H,patternProperties:B,additionalProperties:G,unevaluatedProperties:ie,minProperties:X,maxProperties:te,propertyNames:oe,dependentRequired:re,dependentSchemas:Q,dependencies:K,prefixItems:ce,items:d,additionalItems:x,unevaluatedItems:U,contains:_,minContains:I,maxContains:z,minItems:C,maxItems:M,uniqueItems:O,minimum:F,maximum:Y,exclusiveMinimum:W,exclusiveMaximum:ee,multipleOf:J,minLength:ae,maxLength:ne,pattern:ue,__absolute_ref__:le,__absolute_recursive_ref__:de}=e,E=[];if(g===!0&&o===null&&(o=e),f==="#"){const D=o===null?n[de]:o,$=`${a}/$recursiveRef`,S=validate(t,o===null?e:o,r,n,i,D,s,$,l);S.valid||E.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:$,error:"A subschema had errors."},...S.errors)}if(h!==void 0){const $=n[le||h];if($===void 0){let y=`Unresolved $ref "${h}".`;throw le&&le!==h&&(y+=` Absolute URI "${le}".`),y+=`
|
|
1
|
+
var WebMCPSDK=(function(exports){"use strict";function deepCompareStrict(t,e){const r=typeof t;if(r!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;const n=t.length;if(n!==e.length)return!1;for(let i=0;i<n;i++)if(!deepCompareStrict(t[i],e[i]))return!1;return!0}if(r==="object"){if(!t||!e)return t===e;const n=Object.keys(t),i=Object.keys(e);if(n.length!==i.length)return!1;for(const s of n)if(!deepCompareStrict(t[s],e[s]))return!1;return!0}return t===e}function encodePointer(t){return encodeURI(escapePointer(t))}function escapePointer(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}const schemaArrayKeyword={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},schemaMapKeyword={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},ignoredKeyword={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};let initialBaseURI=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function dereference(t,e=Object.create(null),r=initialBaseURI,n=""){if(t&&typeof t=="object"&&!Array.isArray(t)){const o=t.$id||t.id;if(o){const s=new URL(o,r.href);s.hash.length>1?e[s.href]=t:(s.hash="",n===""?r=s:dereference(t,e,r))}}else if(t!==!0&&t!==!1)return e;const i=r.href+(n?"#"+n:"");if(e[i]!==void 0)throw new Error(`Duplicate schema URI "${i}".`);if(e[i]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:i}),t.$ref&&t.__absolute_ref__===void 0){const o=new URL(t.$ref,r.href);o.hash=o.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:o.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){const o=new URL(t.$recursiveRef,r.href);o.hash=o.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:o.href})}if(t.$anchor){const o=new URL("#"+t.$anchor,r.href);e[o.href]=t}for(let o in t){if(ignoredKeyword[o])continue;const s=`${n}/${encodePointer(o)}`,a=t[o];if(Array.isArray(a)){if(schemaArrayKeyword[o]){const l=a.length;for(let c=0;c<l;c++)dereference(a[c],e,r,`${s}/${c}`)}}else if(schemaMapKeyword[o])for(let l in a)dereference(a[l],e,r,`${s}/${encodePointer(l)}`);else dereference(a,e,r,s)}return e}const DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31],TIME=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,HOSTNAME=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,URIREF=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,URITEMPLATE=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,URL_=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,UUID=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,JSON_POINTER=/^(?:\/(?:[^~/]|~0|~1)*)*$/,JSON_POINTER_URI_FRAGMENT=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,RELATIVE_JSON_POINTER=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,EMAIL=t=>{if(t[0]==='"')return!1;const[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},IPV4=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,IPV6=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,DURATION=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));function bind(t){return t.test.bind(t)}const format={date,time:time.bind(void 0,!1),"date-time":date_time,duration:DURATION,uri,"uri-reference":bind(URIREF),"uri-template":bind(URITEMPLATE),url:bind(URL_),email:EMAIL,hostname:bind(HOSTNAME),ipv4:bind(IPV4),ipv6:bind(IPV6),regex,uuid:bind(UUID),"json-pointer":bind(JSON_POINTER),"json-pointer-uri-fragment":bind(JSON_POINTER_URI_FRAGMENT),"relative-json-pointer":bind(RELATIVE_JSON_POINTER)};function isLeapYear(t){return t%4===0&&(t%100!==0||t%400===0)}function date(t){const e=t.match(DATE);if(!e)return!1;const r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&isLeapYear(r)?29:DAYS[n])}function time(t,e){const r=e.match(TIME);if(!r)return!1;const n=+r[1],i=+r[2],o=+r[3],s=!!r[5];return(n<=23&&i<=59&&o<=59||n==23&&i==59&&o==60)&&(!t||s)}const DATE_TIME_SEPARATOR=/t|\s/i;function date_time(t){const e=t.split(DATE_TIME_SEPARATOR);return e.length==2&&date(e[0])&&time(!0,e[1])}const NOT_URI_FRAGMENT=/\/|:/,URI_PATTERN=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function uri(t){return NOT_URI_FRAGMENT.test(t)&&URI_PATTERN.test(t)}const Z_ANCHOR=/[^\\]\\Z/;function regex(t){if(Z_ANCHOR.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}function ucs2length(t){let e=0,r=t.length,n=0,i;for(;n<r;)e++,i=t.charCodeAt(n++),i>=55296&&i<=56319&&n<r&&(i=t.charCodeAt(n),(i&64512)==56320&&n++);return e}function validate(t,e,r="2019-09",n=dereference(e),i=!0,o=null,s="#",a="#",l=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};const c=typeof t;let u;switch(c){case"boolean":case"number":case"string":u=c;break;case"object":t===null?u="null":Array.isArray(t)?u="array":u="object";break;default:throw new Error(`Instances of "${c}" type are not supported.`)}const{$ref:f,$recursiveRef:h,$recursiveAnchor:m,type:g,const:A,enum:_,required:p,not:v,anyOf:S,allOf:b,oneOf:C,if:M,then:L,else:z,format:D,properties:V,patternProperties:H,additionalProperties:G,unevaluatedProperties:ie,minProperties:X,maxProperties:te,propertyNames:oe,dependentRequired:re,dependentSchemas:Q,dependencies:K,prefixItems:ce,items:d,additionalItems:x,unevaluatedItems:j,contains:T,minContains:P,maxContains:B,minItems:k,maxItems:F,uniqueItems:O,minimum:U,maximum:Y,exclusiveMinimum:W,exclusiveMaximum:ee,multipleOf:J,minLength:ae,maxLength:ne,pattern:ue,__absolute_ref__:le,__absolute_recursive_ref__:de}=e,E=[];if(m===!0&&o===null&&(o=e),h==="#"){const Z=o===null?n[de]:o,R=`${a}/$recursiveRef`,I=validate(t,o===null?e:o,r,n,i,Z,s,R,l);I.valid||E.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:R,error:"A subschema had errors."},...I.errors)}if(f!==void 0){const R=n[le||f];if(R===void 0){let y=`Unresolved $ref "${f}".`;throw le&&le!==f&&(y+=` Absolute URI "${le}".`),y+=`
|
|
2
2
|
Known schemas:
|
|
3
3
|
- ${Object.keys(n).join(`
|
|
4
|
-
- `)}`,new Error(y)}const S=`${a}/$ref`,v=validate(t,$,r,n,i,o,s,S,l);if(v.valid||E.push({instanceLocation:s,keyword:"$ref",keywordLocation:S,error:"A subschema had errors."},...v.errors),r==="4"||r==="7")return{valid:E.length===0,errors:E}}if(Array.isArray(b)){let D=b.length,$=!1;for(let S=0;S<D;S++)if(u===b[S]||b[S]==="integer"&&u==="number"&&t%1===0&&t===t){$=!0;break}$||E.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${b.join('", "')}".`})}else b==="integer"?(u!=="number"||t%1||t!==t)&&E.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${b}".`}):b!==void 0&&u!==b&&E.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${b}".`});if(P!==void 0&&(u==="object"||u==="array"?deepCompareStrict(t,P)||E.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(P)}.`}):t!==P&&E.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(P)}.`})),w!==void 0&&(u==="object"||u==="array"?w.some(D=>deepCompareStrict(t,D))||E.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(w)}.`}):w.some(D=>t===D)||E.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(w)}.`})),m!==void 0){const D=`${a}/not`;validate(t,m,r,n,i,o,s,D).valid&&E.push({instanceLocation:s,keyword:"not",keywordLocation:D,error:'Instance matched "not" schema.'})}let fe=[];if(A!==void 0){const D=`${a}/anyOf`,$=E.length;let S=!1;for(let v=0;v<A.length;v++){const y=A[v],L=Object.create(l),N=validate(t,y,r,n,i,g===!0?o:null,s,`${D}/${v}`,L);E.push(...N.errors),S=S||N.valid,N.valid&&fe.push(L)}S?E.length=$:E.splice($,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:D,error:"Instance does not match any subschemas."})}if(T!==void 0){const D=`${a}/allOf`,$=E.length;let S=!0;for(let v=0;v<T.length;v++){const y=T[v],L=Object.create(l),N=validate(t,y,r,n,i,g===!0?o:null,s,`${D}/${v}`,L);E.push(...N.errors),S=S&&N.valid,N.valid&&fe.push(L)}S?E.length=$:E.splice($,0,{instanceLocation:s,keyword:"allOf",keywordLocation:D,error:"Instance does not match every subschema."})}if(k!==void 0){const D=`${a}/oneOf`,$=E.length,S=k.filter((v,y)=>{const L=Object.create(l),N=validate(t,v,r,n,i,g===!0?o:null,s,`${D}/${y}`,L);return E.push(...N.errors),N.valid&&fe.push(L),N.valid}).length;S===1?E.length=$:E.splice($,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:D,error:`Instance does not match exactly one subschema (${S} matches).`})}if((u==="object"||u==="array")&&Object.assign(l,...fe),Z!==void 0){const D=`${a}/if`;if(validate(t,Z,r,n,i,o,s,D,l).valid){if(R!==void 0){const S=validate(t,R,r,n,i,o,s,`${a}/then`,l);S.valid||E.push({instanceLocation:s,keyword:"if",keywordLocation:D,error:'Instance does not match "then" schema.'},...S.errors)}}else if(V!==void 0){const S=validate(t,V,r,n,i,o,s,`${a}/else`,l);S.valid||E.push({instanceLocation:s,keyword:"if",keywordLocation:D,error:'Instance does not match "else" schema.'},...S.errors)}}if(u==="object"){if(p!==void 0)for(const v of p)v in t||E.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${v}".`});const D=Object.keys(t);if(X!==void 0&&D.length<X&&E.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${X} properties.`}),te!==void 0&&D.length>te&&E.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${te} properties.`}),oe!==void 0){const v=`${a}/propertyNames`;for(const y in t){const L=`${s}/${encodePointer(y)}`,N=validate(y,oe,r,n,i,o,L,v);N.valid||E.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:v,error:`Property name "${y}" does not match schema.`},...N.errors)}}if(re!==void 0){const v=`${a}/dependantRequired`;for(const y in re)if(y in t){const L=re[y];for(const N of L)N in t||E.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:v,error:`Instance has "${y}" but does not have "${N}".`})}}if(Q!==void 0)for(const v in Q){const y=`${a}/dependentSchemas`;if(v in t){const L=validate(t,Q[v],r,n,i,o,s,`${y}/${encodePointer(v)}`,l);L.valid||E.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:y,error:`Instance has "${v}" but does not match dependant schema.`},...L.errors)}}if(K!==void 0){const v=`${a}/dependencies`;for(const y in K)if(y in t){const L=K[y];if(Array.isArray(L))for(const N of L)N in t||E.push({instanceLocation:s,keyword:"dependencies",keywordLocation:v,error:`Instance has "${y}" but does not have "${N}".`});else{const N=validate(t,L,r,n,i,o,s,`${v}/${encodePointer(y)}`);N.valid||E.push({instanceLocation:s,keyword:"dependencies",keywordLocation:v,error:`Instance has "${y}" but does not match dependant schema.`},...N.errors)}}}const $=Object.create(null);let S=!1;if(H!==void 0){const v=`${a}/properties`;for(const y in H){if(!(y in t))continue;const L=`${s}/${encodePointer(y)}`,N=validate(t[y],H[y],r,n,i,o,L,`${v}/${encodePointer(y)}`);if(N.valid)l[y]=$[y]=!0;else if(S=i,E.push({instanceLocation:s,keyword:"properties",keywordLocation:v,error:`Property "${y}" does not match schema.`},...N.errors),S)break}}if(!S&&B!==void 0){const v=`${a}/patternProperties`;for(const y in B){const L=new RegExp(y,"u"),N=B[y];for(const q in t){if(!L.test(q))continue;const se=`${s}/${encodePointer(q)}`,pe=validate(t[q],N,r,n,i,o,se,`${v}/${encodePointer(y)}`);pe.valid?l[q]=$[q]=!0:(S=i,E.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:v,error:`Property "${q}" matches pattern "${y}" but does not match associated schema.`},...pe.errors))}}}if(!S&&G!==void 0){const v=`${a}/additionalProperties`;for(const y in t){if($[y])continue;const L=`${s}/${encodePointer(y)}`,N=validate(t[y],G,r,n,i,o,L,v);N.valid?l[y]=!0:(S=i,E.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:v,error:`Property "${y}" does not match additional properties schema.`},...N.errors))}}else if(!S&&ie!==void 0){const v=`${a}/unevaluatedProperties`;for(const y in t)if(!l[y]){const L=`${s}/${encodePointer(y)}`,N=validate(t[y],ie,r,n,i,o,L,v);N.valid?l[y]=!0:E.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:v,error:`Property "${y}" does not match unevaluated properties schema.`},...N.errors)}}}else if(u==="array"){M!==void 0&&t.length>M&&E.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${t.length} > ${M}).`}),C!==void 0&&t.length<C&&E.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${t.length} < ${C}).`});const D=t.length;let $=0,S=!1;if(ce!==void 0){const v=`${a}/prefixItems`,y=Math.min(ce.length,D);for(;$<y;$++){const L=validate(t[$],ce[$],r,n,i,o,`${s}/${$}`,`${v}/${$}`);if(l[$]=!0,!L.valid&&(S=i,E.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:v,error:"Items did not match schema."},...L.errors),S))break}}if(d!==void 0){const v=`${a}/items`;if(Array.isArray(d)){const y=Math.min(d.length,D);for(;$<y;$++){const L=validate(t[$],d[$],r,n,i,o,`${s}/${$}`,`${v}/${$}`);if(l[$]=!0,!L.valid&&(S=i,E.push({instanceLocation:s,keyword:"items",keywordLocation:v,error:"Items did not match schema."},...L.errors),S))break}}else for(;$<D;$++){const y=validate(t[$],d,r,n,i,o,`${s}/${$}`,v);if(l[$]=!0,!y.valid&&(S=i,E.push({instanceLocation:s,keyword:"items",keywordLocation:v,error:"Items did not match schema."},...y.errors),S))break}if(!S&&x!==void 0){const y=`${a}/additionalItems`;for(;$<D;$++){const L=validate(t[$],x,r,n,i,o,`${s}/${$}`,y);l[$]=!0,L.valid||(S=i,E.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:y,error:"Items did not match additional items schema."},...L.errors))}}}if(_!==void 0)if(D===0&&I===void 0)E.push({instanceLocation:s,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(I!==void 0&&D<I)E.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${D}) than minContains (${I}).`});else{const v=`${a}/contains`,y=E.length;let L=0;for(let N=0;N<D;N++){const q=validate(t[N],_,r,n,i,o,`${s}/${N}`,v);q.valid?(l[N]=!0,L++):E.push(...q.errors)}L>=(I||0)&&(E.length=y),I===void 0&&z===void 0&&L===0?E.splice(y,0,{instanceLocation:s,keyword:"contains",keywordLocation:v,error:"Array does not contain item matching schema."}):I!==void 0&&L<I?E.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${I} items matching schema. Only ${L} items were found.`}):z!==void 0&&L>z&&E.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${z} items matching schema. ${L} items were found.`})}if(!S&&U!==void 0){const v=`${a}/unevaluatedItems`;for($;$<D;$++){if(l[$])continue;const y=validate(t[$],U,r,n,i,o,`${s}/${$}`,v);l[$]=!0,y.valid||E.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:v,error:"Items did not match unevaluated items schema."},...y.errors)}}if(O)for(let v=0;v<D;v++){const y=t[v],L=typeof y=="object"&&y!==null;for(let N=0;N<D;N++){if(v===N)continue;const q=t[N];(y===q||L&&(typeof q=="object"&&q!==null)&&deepCompareStrict(y,q))&&(E.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${v} and ${N}.`}),v=Number.MAX_SAFE_INTEGER,N=Number.MAX_SAFE_INTEGER)}}}else if(u==="number"){if(r==="4"?(F!==void 0&&(W===!0&&t<=F||t<F)&&E.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${t} is less than ${W?"or equal to ":""} ${F}.`}),Y!==void 0&&(ee===!0&&t>=Y||t>Y)&&E.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${t} is greater than ${ee?"or equal to ":""} ${Y}.`})):(F!==void 0&&t<F&&E.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${t} is less than ${F}.`}),Y!==void 0&&t>Y&&E.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${t} is greater than ${Y}.`}),W!==void 0&&t<=W&&E.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${t} is less than ${W}.`}),ee!==void 0&&t>=ee&&E.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${t} is greater than or equal to ${ee}.`})),J!==void 0){const D=t%J;Math.abs(0-D)>=11920929e-14&&Math.abs(J-D)>=11920929e-14&&E.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${t} is not a multiple of ${J}.`})}}else if(u==="string"){const D=ae===void 0&&ne===void 0?0:ucs2length(t);ae!==void 0&&D<ae&&E.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${D} < ${ae}).`}),ne!==void 0&&D>ne&&E.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${D} > ${ne}).`}),ue!==void 0&&!new RegExp(ue,"u").test(t)&&E.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),j!==void 0&&format[j]&&!format[j](t)&&E.push({instanceLocation:s,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${j}".`})}return{valid:E.length===0,errors:E}}class Validator{schema;draft;shortCircuit;lookup;constructor(e,r="2019-09",n=!0){this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=dereference(e)}validate(e){return validate(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),dereference(e,this.lookup)}}const FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE="Failed to parse input arguments",TOOL_INVOCATION_FAILED_MESSAGE="Tool was executed but the invocation failed. For example, the script function threw an error",TOOL_CANCELLED_MESSAGE="Tool was cancelled",DEFAULT_INPUT_SCHEMA={type:"object",properties:{}},STANDARD_JSON_SCHEMA_TARGETS=["draft-2020-12","draft-07"],POLYFILL_MARKER_PROPERTY="__isWebMCPPolyfill",STANDARD_VALIDATOR_SYMBOL=Symbol("standardValidator"),installState={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1};var StrictWebMCPContext=class extends EventTarget{tools=new Map;testingShim=null;_ontoolchange=null;unregisterToolDeprecationWarned=!1;get ontoolchange(){return this._ontoolchange}set ontoolchange(t){this._ontoolchange=t}registerTool(t,e){const r=e?.signal;if(r?.aborted){console.warn(`[WebMCPPolyfill] registerTool("${t?.name??"<unknown>"}") skipped: options.signal was already aborted.`);return}const n=normalizeToolDescriptor(t,this.tools);this.tools.set(n.name,n),this.notifyToolsChanged(),r&&r.addEventListener("abort",()=>{this.tools.delete(n.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(t){this.warnUnregisterToolDeprecationOnce();const e=getToolNameForUnregister(t);this.tools.delete(e)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(t,e,r){return this.executeToolByName(t.name,e,r,!1)}getTestingShim(){return this.testingShim||(this.testingShim=new PolyfillTestingShim(this)),this.testingShim}getToolInfos(){return[...this.tools.values()].map(t=>{let e;try{e=JSON.stringify(t.inputSchema??{type:"object"})}catch{e='{"type":"object"}'}return{name:t.name,description:t.description,inputSchema:e}})}getRegisteredToolInfos(){return this.getToolInfos().map(t=>{const e=this.tools.get(t.name);return{...t,title:e?.title??"",origin:globalThis.location?.origin??"",window:globalThis.window}})}async executeToolForTesting(t,e,r){return this.executeToolByName(t,e,r,!0)}async executeToolByName(t,e,r,n){if(r?.signal?.aborted)throw createUnknownError(TOOL_CANCELLED_MESSAGE);const i=this.tools.get(t);if(!i)throw createUnknownError(`Tool not found: ${t}`);const o=parseInputArgsJson(e),s=await validateArgsForTool(o,i);if(s)throw createUnknownError(s);let a=!0;const l={requestUserInteraction:async c=>{if(!a)throw new Error(`ModelContextClient for tool "${t}" is no longer active after execute() resolved`);if(typeof c!="function")throw new TypeError("requestUserInteraction(callback) requires a function callback");return c()}};try{const c=i.execute(o,l),u=await withAbortSignal(Promise.resolve(c),r?.signal);if(n)return toSerializedTestingResult(normalizeToolResponse(u));const h=JSON.stringify(u);return h===void 0?null:h}catch(c){throw createUnknownError(c instanceof Error?`${TOOL_INVOCATION_FAILED_MESSAGE}: ${c.message}`:TOOL_INVOCATION_FAILED_MESSAGE)}finally{a=!1}}notifyToolsChanged(){queueMicrotask(()=>{const t=new Event("toolchange");try{this._ontoolchange?.call(this,t)}catch(e){console.warn("[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:",e)}this.dispatchEvent(t),this.testingShim?.dispatchToolChange()})}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) — pass an AbortSignal and abort it to unregister."))}},PolyfillTestingShim=class extends EventTarget{context;_ontoolchange=null;constructor(t){super(),this.context=t}listTools(){return this.context.getToolInfos()}executeTool(t,e,r){return this.context.executeToolForTesting(t,e,r)}getCrossDocumentScriptToolResult(){return Promise.resolve("[]")}get ontoolchange(){return this._ontoolchange}set ontoolchange(t){this._ontoolchange=t}registerToolsChangedCallback(t){if(typeof t!="function")throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");this.addEventListener("toolchange",t)}dispatchToolChange(){const t=new Event("toolchange");try{this._ontoolchange?.call(this,t)}catch(e){console.warn("[WebMCPPolyfill] ontoolchange handler threw:",e)}this.dispatchEvent(t),this.dispatchEvent(new Event("toolschanged"))}};function createUnknownError(t){try{return new DOMException(t,"UnknownError")}catch{const e=new Error(t);return e.name="UnknownError",e}}function parseInputArgsJson(t){let e;try{e=JSON.parse(t)}catch{throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE)}if(!e||typeof e!="object"||Array.isArray(e))throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE);return e}function getToolNameForUnregister(t){if(typeof t=="string")return t;if(isPlainObject(t)&&typeof t.name=="string")return t.name;throw new TypeError("Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.")}function isPlainObject(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function getStandardProps(t){if(!isPlainObject(t))return null;const e=t["~standard"];return isPlainObject(e)?e:null}function isStandardInputValidatorSchema(t){const e=getStandardProps(t);return!!(e&&e.version===1&&typeof e.validate=="function")}function isStandardInputJsonSchema(t){const e=getStandardProps(t);return!e||e.version!==1||!isPlainObject(e.jsonSchema)?!1:typeof e.jsonSchema.input=="function"}function createStandardValidatorFromJsonSchema(t){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(e){if(!isPlainObject(e))return{issues:[{message:"expected object arguments"}]};const r=validateArgsWithSchema(e,t);return r?{issues:[r]}:{value:e}}}}}function convertStandardInputSchema(t){for(const e of STANDARD_JSON_SCHEMA_TARGETS)try{const r=t["~standard"].jsonSchema.input({target:e});return validateInputSchema(r),r}catch(r){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${e}":`,r)}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function normalizeInputSchema(t){if(t===void 0){const r=DEFAULT_INPUT_SCHEMA;return{inputSchema:r,standardValidator:createStandardValidatorFromJsonSchema(r)}}if(isStandardInputJsonSchema(t)){const r=convertStandardInputSchema(t);return{inputSchema:r,standardValidator:createStandardValidatorFromJsonSchema(r)}}if(isStandardInputValidatorSchema(t))return{inputSchema:DEFAULT_INPUT_SCHEMA,standardValidator:t};if(validateInputSchema(t),Object.keys(t).length===0)return{inputSchema:DEFAULT_INPUT_SCHEMA,standardValidator:createStandardValidatorFromJsonSchema(DEFAULT_INPUT_SCHEMA)};const e=t.type===void 0?{type:"object",...t}:t;return{inputSchema:e,standardValidator:createStandardValidatorFromJsonSchema(e)}}function validateInputSchema(t){if(!isPlainObject(t))throw new Error("inputSchema must be a JSON Schema object");validateJsonSchemaNode(t,"$")}function validateJsonSchemaNode(t,e){const r=t.type;if(r!==void 0&&typeof r!="string"&&!(Array.isArray(r)&&r.every(a=>typeof a=="string"&&a.length>0)))throw new Error(`Invalid JSON Schema at ${e}: "type" must be a string or string[]`);const n=t.required;if(n!==void 0&&!(Array.isArray(n)&&n.every(a=>typeof a=="string")))throw new Error(`Invalid JSON Schema at ${e}: "required" must be an array of strings`);const i=t.properties;if(i!==void 0){if(!isPlainObject(i))throw new Error(`Invalid JSON Schema at ${e}: "properties" must be an object`);for(const[a,l]of Object.entries(i)){if(!isPlainObject(l))throw new Error(`Invalid JSON Schema at ${e}.properties.${a}: expected object schema`);validateJsonSchemaNode(l,`${e}.properties.${a}`)}}const o=t.items;if(o!==void 0)if(Array.isArray(o))for(const[a,l]of o.entries()){if(!isPlainObject(l))throw new Error(`Invalid JSON Schema at ${e}.items[${a}]: expected object schema`);validateJsonSchemaNode(l,`${e}.items[${a}]`)}else if(isPlainObject(o))validateJsonSchemaNode(o,`${e}.items`);else throw new Error(`Invalid JSON Schema at ${e}: "items" must be an object or object[]`);for(const a of["allOf","anyOf","oneOf"]){const l=t[a];if(l!==void 0){if(!Array.isArray(l))throw new Error(`Invalid JSON Schema at ${e}: "${a}" must be an array`);for(const[c,u]of l.entries()){if(!isPlainObject(u))throw new Error(`Invalid JSON Schema at ${e}.${a}[${c}]: expected object schema`);validateJsonSchemaNode(u,`${e}.${a}[${c}]`)}}}const s=t.not;if(s!==void 0){if(!isPlainObject(s))throw new Error(`Invalid JSON Schema at ${e}: "not" must be an object schema`);validateJsonSchemaNode(s,`${e}.not`)}try{JSON.stringify(t)}catch{throw new Error(`Invalid JSON Schema at ${e}: schema must be JSON-serializable`)}}function normalizeToolDescriptor(t,e){if(!t||typeof t!="object")throw new TypeError("registerTool(tool) requires a tool object");if(typeof t.name!="string"||t.name.length===0)throw new TypeError('Tool "name" must be a non-empty string');if(typeof t.description!="string"||t.description.length===0)throw new TypeError('Tool "description" must be a non-empty string');if(typeof t.execute!="function")throw new TypeError('Tool "execute" must be a function');if(e.has(t.name))throw new Error(`Tool already registered: ${t.name}`);const r=normalizeInputSchema(t.inputSchema),n=t.annotations,i=n?{...n,...n.readOnlyHint==="true"?{readOnlyHint:!0}:n.readOnlyHint==="false"?{readOnlyHint:!1}:{},...n.destructiveHint==="true"?{destructiveHint:!0}:n.destructiveHint==="false"?{destructiveHint:!1}:{},...n.idempotentHint==="true"?{idempotentHint:!0}:n.idempotentHint==="false"?{idempotentHint:!1}:{},...n.openWorldHint==="true"?{openWorldHint:!0}:n.openWorldHint==="false"?{openWorldHint:!1}:{}}:void 0;return{...t,...i?{annotations:i}:{},inputSchema:r.inputSchema,[STANDARD_VALIDATOR_SYMBOL]:r.standardValidator}}function validateArgsWithSchema(t,e){const r=new Validator(e,"2020-12",!0).validate(t);if(r.valid)return null;const n=r.errors[r.errors.length-1];return n?{message:n.error}:{message:"Input validation failed"}}function formatStandardIssuePath(t){if(!t||t.length===0)return null;const e=t.map(r=>isPlainObject(r)&&"key"in r?r.key:r).map(r=>String(r)).filter(r=>r.length>0);return e.length===0?null:e.join(".")}async function validateArgsWithStandardSchema(t,e){let r;try{r=await Promise.resolve(e["~standard"].validate(t))}catch(o){const s=o instanceof Error?`: ${o.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",o),`Input validation error: schema validation failed${s}`}if(!r.issues||r.issues.length===0)return null;const n=r.issues[0];if(!n)return"Input validation error";const i=formatStandardIssuePath(n?.path);return i?`Input validation error: ${n.message} at ${i}`:`Input validation error: ${n.message}`}async function validateArgsForTool(t,e){return validateArgsWithStandardSchema(t,e[STANDARD_VALIDATOR_SYMBOL])}function isCallToolResult(t){return isPlainObject(t)&&Array.isArray(t.content)}function isJsonPrimitive(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function isJsonValue(t){return isJsonPrimitive(t)?Number.isFinite(t)||typeof t!="number":Array.isArray(t)?t.every(e=>isJsonValue(e)):isPlainObject(t)?Object.values(t).every(e=>isJsonValue(e)):!1}function toStructuredContent(t){if(!(!isPlainObject(t)||!isJsonValue(t)))return t}function serializeTextContent(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function normalizeToolResponse(t){if(isCallToolResult(t))return t;const e=toStructuredContent(t);return{content:[{type:"text",text:serializeTextContent(t)}],...e?{structuredContent:e}:{},isError:!1}}function getFirstTextBlock(t){for(const e of t.content??[])if(e.type==="text"&&"text"in e&&typeof e.text=="string")return e.text;return null}function toSerializedTestingResult(t){if(t.isError)throw createUnknownError(getFirstTextBlock(t)?.replace(/^Error:\s*/i,"").trim()||TOOL_INVOCATION_FAILED_MESSAGE);const e=t.metadata;if(e&&typeof e=="object"&&e.willNavigate)return null;try{return JSON.stringify(t)}catch{throw createUnknownError(TOOL_INVOCATION_FAILED_MESSAGE)}}function withAbortSignal(t,e){return e?e.aborted?Promise.reject(createUnknownError(TOOL_CANCELLED_MESSAGE)):new Promise((r,n)=>{const i=()=>{o(),n(createUnknownError(TOOL_CANCELLED_MESSAGE))},o=()=>{e.removeEventListener("abort",i)};e.addEventListener("abort",i,{once:!0}),t.then(s=>{o(),r(s)},s=>{o(),n(s)})}):t}function getNavigator(){return typeof navigator<"u"?navigator:null}function getDocument(){return typeof document<"u"?document:null}function defineNavigatorProperty(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,writable:!1,value:r})}function defineDocumentModelContextProperty(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:e})}let navigatorModelContextDeprecationWarned=!1;function defineDeprecatedNavigatorModelContext(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,get(){return navigatorModelContextDeprecationWarned||(navigatorModelContextDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document — use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.")),e}})}function initializeWebMCPPolyfill(t){const e=getNavigator(),r=getDocument();if(!e&&!r||r?.modelContext)return;const i=e?.modelContext,o=!!i;if(installState.installed&&cleanupWebMCPPolyfill(),r&&i){installState.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),defineDocumentModelContextProperty(r,i),installState.installedDocumentModelContext=!0,installState.installed=!0;return}if(o)return;const s=new StrictWebMCPContext,a=s;if(a[POLYFILL_MARKER_PROPERTY]=!0,r&&(installState.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),defineDocumentModelContextProperty(r,a),installState.installedDocumentModelContext=!0),e){installState.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(e,"modelContext"),installState.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(e,"modelContextTesting"),navigatorModelContextDeprecationWarned=!1,defineDeprecatedNavigatorModelContext(e,a),installState.installedNavigatorModelContext=!0;const l=t?.installTestingShim??"if-missing",c=!!e.modelContextTesting;(l==="always"||(l===!0||l==="if-missing")&&!c)&&(defineNavigatorProperty(e,"modelContextTesting",s.getTestingShim()),installState.installedNavigatorModelContextTesting=!0)}installState.installed=!0}function cleanupWebMCPPolyfill(){if(!installState.installed)return;const t=(n,i,o)=>{if(o){Object.defineProperty(n,i,o);return}delete n[i]},e=getNavigator(),r=getDocument();r&&installState.installedDocumentModelContext&&t(r,"modelContext",installState.previousDocumentModelContextDescriptor),e&&installState.installedNavigatorModelContext&&t(e,"modelContext",installState.previousNavigatorModelContextDescriptor),e&&installState.installedNavigatorModelContextTesting&&t(e,"modelContextTesting",installState.previousNavigatorModelContextTestingDescriptor),installState.installed=!1,installState.previousDocumentModelContextDescriptor=void 0,installState.previousNavigatorModelContextDescriptor=void 0,installState.previousNavigatorModelContextTestingDescriptor=void 0,installState.installedDocumentModelContext=!1,installState.installedNavigatorModelContext=!1,installState.installedNavigatorModelContextTesting=!1,navigatorModelContextDeprecationWarned=!1}if(typeof window<"u"&&typeof document<"u"){const t=window.__webMCPPolyfillOptions;if(t?.autoInitialize!==!1)try{initializeWebMCPPolyfill(t)}catch(e){console.error("[WebMCPPolyfill] Auto-initialization failed:",e)}}const randomUUID=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)}),isBrowser=()=>typeof window<"u"&&typeof navigator<"u",isDomAvailable=()=>isBrowser()&&typeof document<"u";let overlayElement=null,labelElement=null,styleElement=null,activeCount=0;const BODY_GLOW_CLASS="next-sdk-tool-body-glow";function ensureDomReady(){return isDomAvailable()}function ensureStyleElement(){if(!ensureDomReady()||styleElement)return;const t=document.createElement("style");t.textContent=`
|
|
4
|
+
- `)}`,new Error(y)}const I=`${a}/$ref`,w=validate(t,R,r,n,i,o,s,I,l);if(w.valid||E.push({instanceLocation:s,keyword:"$ref",keywordLocation:I,error:"A subschema had errors."},...w.errors),r==="4"||r==="7")return{valid:E.length===0,errors:E}}if(Array.isArray(g)){let Z=g.length,R=!1;for(let I=0;I<Z;I++)if(u===g[I]||g[I]==="integer"&&u==="number"&&t%1===0&&t===t){R=!0;break}R||E.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${g.join('", "')}".`})}else g==="integer"?(u!=="number"||t%1||t!==t)&&E.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${g}".`}):g!==void 0&&u!==g&&E.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${g}".`});if(A!==void 0&&(u==="object"||u==="array"?deepCompareStrict(t,A)||E.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(A)}.`}):t!==A&&E.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(A)}.`})),_!==void 0&&(u==="object"||u==="array"?_.some(Z=>deepCompareStrict(t,Z))||E.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(_)}.`}):_.some(Z=>t===Z)||E.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(_)}.`})),v!==void 0){const Z=`${a}/not`;validate(t,v,r,n,i,o,s,Z).valid&&E.push({instanceLocation:s,keyword:"not",keywordLocation:Z,error:'Instance matched "not" schema.'})}let fe=[];if(S!==void 0){const Z=`${a}/anyOf`,R=E.length;let I=!1;for(let w=0;w<S.length;w++){const y=S[w],$=Object.create(l),N=validate(t,y,r,n,i,m===!0?o:null,s,`${Z}/${w}`,$);E.push(...N.errors),I=I||N.valid,N.valid&&fe.push($)}I?E.length=R:E.splice(R,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:Z,error:"Instance does not match any subschemas."})}if(b!==void 0){const Z=`${a}/allOf`,R=E.length;let I=!0;for(let w=0;w<b.length;w++){const y=b[w],$=Object.create(l),N=validate(t,y,r,n,i,m===!0?o:null,s,`${Z}/${w}`,$);E.push(...N.errors),I=I&&N.valid,N.valid&&fe.push($)}I?E.length=R:E.splice(R,0,{instanceLocation:s,keyword:"allOf",keywordLocation:Z,error:"Instance does not match every subschema."})}if(C!==void 0){const Z=`${a}/oneOf`,R=E.length,I=C.filter((w,y)=>{const $=Object.create(l),N=validate(t,w,r,n,i,m===!0?o:null,s,`${Z}/${y}`,$);return E.push(...N.errors),N.valid&&fe.push($),N.valid}).length;I===1?E.length=R:E.splice(R,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:Z,error:`Instance does not match exactly one subschema (${I} matches).`})}if((u==="object"||u==="array")&&Object.assign(l,...fe),M!==void 0){const Z=`${a}/if`;if(validate(t,M,r,n,i,o,s,Z,l).valid){if(L!==void 0){const I=validate(t,L,r,n,i,o,s,`${a}/then`,l);I.valid||E.push({instanceLocation:s,keyword:"if",keywordLocation:Z,error:'Instance does not match "then" schema.'},...I.errors)}}else if(z!==void 0){const I=validate(t,z,r,n,i,o,s,`${a}/else`,l);I.valid||E.push({instanceLocation:s,keyword:"if",keywordLocation:Z,error:'Instance does not match "else" schema.'},...I.errors)}}if(u==="object"){if(p!==void 0)for(const w of p)w in t||E.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${w}".`});const Z=Object.keys(t);if(X!==void 0&&Z.length<X&&E.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${X} properties.`}),te!==void 0&&Z.length>te&&E.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${te} properties.`}),oe!==void 0){const w=`${a}/propertyNames`;for(const y in t){const $=`${s}/${encodePointer(y)}`,N=validate(y,oe,r,n,i,o,$,w);N.valid||E.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:w,error:`Property name "${y}" does not match schema.`},...N.errors)}}if(re!==void 0){const w=`${a}/dependantRequired`;for(const y in re)if(y in t){const $=re[y];for(const N of $)N in t||E.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:w,error:`Instance has "${y}" but does not have "${N}".`})}}if(Q!==void 0)for(const w in Q){const y=`${a}/dependentSchemas`;if(w in t){const $=validate(t,Q[w],r,n,i,o,s,`${y}/${encodePointer(w)}`,l);$.valid||E.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:y,error:`Instance has "${w}" but does not match dependant schema.`},...$.errors)}}if(K!==void 0){const w=`${a}/dependencies`;for(const y in K)if(y in t){const $=K[y];if(Array.isArray($))for(const N of $)N in t||E.push({instanceLocation:s,keyword:"dependencies",keywordLocation:w,error:`Instance has "${y}" but does not have "${N}".`});else{const N=validate(t,$,r,n,i,o,s,`${w}/${encodePointer(y)}`);N.valid||E.push({instanceLocation:s,keyword:"dependencies",keywordLocation:w,error:`Instance has "${y}" but does not match dependant schema.`},...N.errors)}}}const R=Object.create(null);let I=!1;if(V!==void 0){const w=`${a}/properties`;for(const y in V){if(!(y in t))continue;const $=`${s}/${encodePointer(y)}`,N=validate(t[y],V[y],r,n,i,o,$,`${w}/${encodePointer(y)}`);if(N.valid)l[y]=R[y]=!0;else if(I=i,E.push({instanceLocation:s,keyword:"properties",keywordLocation:w,error:`Property "${y}" does not match schema.`},...N.errors),I)break}}if(!I&&H!==void 0){const w=`${a}/patternProperties`;for(const y in H){const $=new RegExp(y,"u"),N=H[y];for(const q in t){if(!$.test(q))continue;const se=`${s}/${encodePointer(q)}`,pe=validate(t[q],N,r,n,i,o,se,`${w}/${encodePointer(y)}`);pe.valid?l[q]=R[q]=!0:(I=i,E.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:w,error:`Property "${q}" matches pattern "${y}" but does not match associated schema.`},...pe.errors))}}}if(!I&&G!==void 0){const w=`${a}/additionalProperties`;for(const y in t){if(R[y])continue;const $=`${s}/${encodePointer(y)}`,N=validate(t[y],G,r,n,i,o,$,w);N.valid?l[y]=!0:(I=i,E.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:w,error:`Property "${y}" does not match additional properties schema.`},...N.errors))}}else if(!I&&ie!==void 0){const w=`${a}/unevaluatedProperties`;for(const y in t)if(!l[y]){const $=`${s}/${encodePointer(y)}`,N=validate(t[y],ie,r,n,i,o,$,w);N.valid?l[y]=!0:E.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:w,error:`Property "${y}" does not match unevaluated properties schema.`},...N.errors)}}}else if(u==="array"){F!==void 0&&t.length>F&&E.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${t.length} > ${F}).`}),k!==void 0&&t.length<k&&E.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${t.length} < ${k}).`});const Z=t.length;let R=0,I=!1;if(ce!==void 0){const w=`${a}/prefixItems`,y=Math.min(ce.length,Z);for(;R<y;R++){const $=validate(t[R],ce[R],r,n,i,o,`${s}/${R}`,`${w}/${R}`);if(l[R]=!0,!$.valid&&(I=i,E.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:w,error:"Items did not match schema."},...$.errors),I))break}}if(d!==void 0){const w=`${a}/items`;if(Array.isArray(d)){const y=Math.min(d.length,Z);for(;R<y;R++){const $=validate(t[R],d[R],r,n,i,o,`${s}/${R}`,`${w}/${R}`);if(l[R]=!0,!$.valid&&(I=i,E.push({instanceLocation:s,keyword:"items",keywordLocation:w,error:"Items did not match schema."},...$.errors),I))break}}else for(;R<Z;R++){const y=validate(t[R],d,r,n,i,o,`${s}/${R}`,w);if(l[R]=!0,!y.valid&&(I=i,E.push({instanceLocation:s,keyword:"items",keywordLocation:w,error:"Items did not match schema."},...y.errors),I))break}if(!I&&x!==void 0){const y=`${a}/additionalItems`;for(;R<Z;R++){const $=validate(t[R],x,r,n,i,o,`${s}/${R}`,y);l[R]=!0,$.valid||(I=i,E.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:y,error:"Items did not match additional items schema."},...$.errors))}}}if(T!==void 0)if(Z===0&&P===void 0)E.push({instanceLocation:s,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(P!==void 0&&Z<P)E.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${Z}) than minContains (${P}).`});else{const w=`${a}/contains`,y=E.length;let $=0;for(let N=0;N<Z;N++){const q=validate(t[N],T,r,n,i,o,`${s}/${N}`,w);q.valid?(l[N]=!0,$++):E.push(...q.errors)}$>=(P||0)&&(E.length=y),P===void 0&&B===void 0&&$===0?E.splice(y,0,{instanceLocation:s,keyword:"contains",keywordLocation:w,error:"Array does not contain item matching schema."}):P!==void 0&&$<P?E.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${P} items matching schema. Only ${$} items were found.`}):B!==void 0&&$>B&&E.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${B} items matching schema. ${$} items were found.`})}if(!I&&j!==void 0){const w=`${a}/unevaluatedItems`;for(R;R<Z;R++){if(l[R])continue;const y=validate(t[R],j,r,n,i,o,`${s}/${R}`,w);l[R]=!0,y.valid||E.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:w,error:"Items did not match unevaluated items schema."},...y.errors)}}if(O)for(let w=0;w<Z;w++){const y=t[w],$=typeof y=="object"&&y!==null;for(let N=0;N<Z;N++){if(w===N)continue;const q=t[N];(y===q||$&&(typeof q=="object"&&q!==null)&&deepCompareStrict(y,q))&&(E.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${w} and ${N}.`}),w=Number.MAX_SAFE_INTEGER,N=Number.MAX_SAFE_INTEGER)}}}else if(u==="number"){if(r==="4"?(U!==void 0&&(W===!0&&t<=U||t<U)&&E.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${t} is less than ${W?"or equal to ":""} ${U}.`}),Y!==void 0&&(ee===!0&&t>=Y||t>Y)&&E.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${t} is greater than ${ee?"or equal to ":""} ${Y}.`})):(U!==void 0&&t<U&&E.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${t} is less than ${U}.`}),Y!==void 0&&t>Y&&E.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${t} is greater than ${Y}.`}),W!==void 0&&t<=W&&E.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${t} is less than ${W}.`}),ee!==void 0&&t>=ee&&E.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${t} is greater than or equal to ${ee}.`})),J!==void 0){const Z=t%J;Math.abs(0-Z)>=11920929e-14&&Math.abs(J-Z)>=11920929e-14&&E.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${t} is not a multiple of ${J}.`})}}else if(u==="string"){const Z=ae===void 0&&ne===void 0?0:ucs2length(t);ae!==void 0&&Z<ae&&E.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${Z} < ${ae}).`}),ne!==void 0&&Z>ne&&E.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${Z} > ${ne}).`}),ue!==void 0&&!new RegExp(ue,"u").test(t)&&E.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),D!==void 0&&format[D]&&!format[D](t)&&E.push({instanceLocation:s,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${D}".`})}return{valid:E.length===0,errors:E}}class Validator{schema;draft;shortCircuit;lookup;constructor(e,r="2019-09",n=!0){this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=dereference(e)}validate(e){return validate(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),dereference(e,this.lookup)}}const FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE="Failed to parse input arguments",TOOL_INVOCATION_FAILED_MESSAGE="Tool was executed but the invocation failed. For example, the script function threw an error",TOOL_CANCELLED_MESSAGE="Tool was cancelled",DEFAULT_INPUT_SCHEMA={type:"object",properties:{}},STANDARD_JSON_SCHEMA_TARGETS=["draft-2020-12","draft-07"],POLYFILL_MARKER_PROPERTY="__isWebMCPPolyfill",STANDARD_VALIDATOR_SYMBOL=Symbol("standardValidator"),installState={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1};var StrictWebMCPContext=class extends EventTarget{tools=new Map;testingShim=null;_ontoolchange=null;unregisterToolDeprecationWarned=!1;get ontoolchange(){return this._ontoolchange}set ontoolchange(t){this._ontoolchange=t}registerTool(t,e){const r=e?.signal;if(r?.aborted){console.warn(`[WebMCPPolyfill] registerTool("${t?.name??"<unknown>"}") skipped: options.signal was already aborted.`);return}const n=normalizeToolDescriptor(t,this.tools);this.tools.set(n.name,n),this.notifyToolsChanged(),r&&r.addEventListener("abort",()=>{this.tools.delete(n.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(t){this.warnUnregisterToolDeprecationOnce();const e=getToolNameForUnregister(t);this.tools.delete(e)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(t,e,r){return this.executeToolByName(t.name,e,r,!1)}getTestingShim(){return this.testingShim||(this.testingShim=new PolyfillTestingShim(this)),this.testingShim}getToolInfos(){return[...this.tools.values()].map(t=>{let e;try{e=JSON.stringify(t.inputSchema??{type:"object"})}catch{e='{"type":"object"}'}return{name:t.name,description:t.description,inputSchema:e}})}getRegisteredToolInfos(){return this.getToolInfos().map(t=>{const e=this.tools.get(t.name);return{...t,title:e?.title??"",origin:globalThis.location?.origin??"",window:globalThis.window}})}async executeToolForTesting(t,e,r){return this.executeToolByName(t,e,r,!0)}async executeToolByName(t,e,r,n){if(r?.signal?.aborted)throw createUnknownError(TOOL_CANCELLED_MESSAGE);const i=this.tools.get(t);if(!i)throw createUnknownError(`Tool not found: ${t}`);const o=parseInputArgsJson(e),s=await validateArgsForTool(o,i);if(s)throw createUnknownError(s);let a=!0;const l={requestUserInteraction:async c=>{if(!a)throw new Error(`ModelContextClient for tool "${t}" is no longer active after execute() resolved`);if(typeof c!="function")throw new TypeError("requestUserInteraction(callback) requires a function callback");return c()}};try{const c=i.execute(o,l),u=await withAbortSignal(Promise.resolve(c),r?.signal);if(n)return toSerializedTestingResult(normalizeToolResponse(u));const f=JSON.stringify(u);return f===void 0?null:f}catch(c){throw createUnknownError(c instanceof Error?`${TOOL_INVOCATION_FAILED_MESSAGE}: ${c.message}`:TOOL_INVOCATION_FAILED_MESSAGE)}finally{a=!1}}notifyToolsChanged(){queueMicrotask(()=>{const t=new Event("toolchange");try{this._ontoolchange?.call(this,t)}catch(e){console.warn("[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:",e)}this.dispatchEvent(t),this.testingShim?.dispatchToolChange()})}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) — pass an AbortSignal and abort it to unregister."))}},PolyfillTestingShim=class extends EventTarget{context;_ontoolchange=null;constructor(t){super(),this.context=t}listTools(){return this.context.getToolInfos()}executeTool(t,e,r){return this.context.executeToolForTesting(t,e,r)}getCrossDocumentScriptToolResult(){return Promise.resolve("[]")}get ontoolchange(){return this._ontoolchange}set ontoolchange(t){this._ontoolchange=t}registerToolsChangedCallback(t){if(typeof t!="function")throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");this.addEventListener("toolchange",t)}dispatchToolChange(){const t=new Event("toolchange");try{this._ontoolchange?.call(this,t)}catch(e){console.warn("[WebMCPPolyfill] ontoolchange handler threw:",e)}this.dispatchEvent(t),this.dispatchEvent(new Event("toolschanged"))}};function createUnknownError(t){try{return new DOMException(t,"UnknownError")}catch{const e=new Error(t);return e.name="UnknownError",e}}function parseInputArgsJson(t){let e;try{e=JSON.parse(t)}catch{throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE)}if(!e||typeof e!="object"||Array.isArray(e))throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE);return e}function getToolNameForUnregister(t){if(typeof t=="string")return t;if(isPlainObject(t)&&typeof t.name=="string")return t.name;throw new TypeError("Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.")}function isPlainObject(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function getStandardProps(t){if(!isPlainObject(t))return null;const e=t["~standard"];return isPlainObject(e)?e:null}function isStandardInputValidatorSchema(t){const e=getStandardProps(t);return!!(e&&e.version===1&&typeof e.validate=="function")}function isStandardInputJsonSchema(t){const e=getStandardProps(t);return!e||e.version!==1||!isPlainObject(e.jsonSchema)?!1:typeof e.jsonSchema.input=="function"}function createStandardValidatorFromJsonSchema(t){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(e){if(!isPlainObject(e))return{issues:[{message:"expected object arguments"}]};const r=validateArgsWithSchema(e,t);return r?{issues:[r]}:{value:e}}}}}function convertStandardInputSchema(t){for(const e of STANDARD_JSON_SCHEMA_TARGETS)try{const r=t["~standard"].jsonSchema.input({target:e});return validateInputSchema(r),r}catch(r){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${e}":`,r)}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function normalizeInputSchema(t){if(t===void 0){const r=DEFAULT_INPUT_SCHEMA;return{inputSchema:r,standardValidator:createStandardValidatorFromJsonSchema(r)}}if(isStandardInputJsonSchema(t)){const r=convertStandardInputSchema(t);return{inputSchema:r,standardValidator:createStandardValidatorFromJsonSchema(r)}}if(isStandardInputValidatorSchema(t))return{inputSchema:DEFAULT_INPUT_SCHEMA,standardValidator:t};if(validateInputSchema(t),Object.keys(t).length===0)return{inputSchema:DEFAULT_INPUT_SCHEMA,standardValidator:createStandardValidatorFromJsonSchema(DEFAULT_INPUT_SCHEMA)};const e=t.type===void 0?{type:"object",...t}:t;return{inputSchema:e,standardValidator:createStandardValidatorFromJsonSchema(e)}}function validateInputSchema(t){if(!isPlainObject(t))throw new Error("inputSchema must be a JSON Schema object");validateJsonSchemaNode(t,"$")}function validateJsonSchemaNode(t,e){const r=t.type;if(r!==void 0&&typeof r!="string"&&!(Array.isArray(r)&&r.every(a=>typeof a=="string"&&a.length>0)))throw new Error(`Invalid JSON Schema at ${e}: "type" must be a string or string[]`);const n=t.required;if(n!==void 0&&!(Array.isArray(n)&&n.every(a=>typeof a=="string")))throw new Error(`Invalid JSON Schema at ${e}: "required" must be an array of strings`);const i=t.properties;if(i!==void 0){if(!isPlainObject(i))throw new Error(`Invalid JSON Schema at ${e}: "properties" must be an object`);for(const[a,l]of Object.entries(i)){if(!isPlainObject(l))throw new Error(`Invalid JSON Schema at ${e}.properties.${a}: expected object schema`);validateJsonSchemaNode(l,`${e}.properties.${a}`)}}const o=t.items;if(o!==void 0)if(Array.isArray(o))for(const[a,l]of o.entries()){if(!isPlainObject(l))throw new Error(`Invalid JSON Schema at ${e}.items[${a}]: expected object schema`);validateJsonSchemaNode(l,`${e}.items[${a}]`)}else if(isPlainObject(o))validateJsonSchemaNode(o,`${e}.items`);else throw new Error(`Invalid JSON Schema at ${e}: "items" must be an object or object[]`);for(const a of["allOf","anyOf","oneOf"]){const l=t[a];if(l!==void 0){if(!Array.isArray(l))throw new Error(`Invalid JSON Schema at ${e}: "${a}" must be an array`);for(const[c,u]of l.entries()){if(!isPlainObject(u))throw new Error(`Invalid JSON Schema at ${e}.${a}[${c}]: expected object schema`);validateJsonSchemaNode(u,`${e}.${a}[${c}]`)}}}const s=t.not;if(s!==void 0){if(!isPlainObject(s))throw new Error(`Invalid JSON Schema at ${e}: "not" must be an object schema`);validateJsonSchemaNode(s,`${e}.not`)}try{JSON.stringify(t)}catch{throw new Error(`Invalid JSON Schema at ${e}: schema must be JSON-serializable`)}}function normalizeToolDescriptor(t,e){if(!t||typeof t!="object")throw new TypeError("registerTool(tool) requires a tool object");if(typeof t.name!="string"||t.name.length===0)throw new TypeError('Tool "name" must be a non-empty string');if(typeof t.description!="string"||t.description.length===0)throw new TypeError('Tool "description" must be a non-empty string');if(typeof t.execute!="function")throw new TypeError('Tool "execute" must be a function');if(e.has(t.name))throw new Error(`Tool already registered: ${t.name}`);const r=normalizeInputSchema(t.inputSchema),n=t.annotations,i=n?{...n,...n.readOnlyHint==="true"?{readOnlyHint:!0}:n.readOnlyHint==="false"?{readOnlyHint:!1}:{},...n.destructiveHint==="true"?{destructiveHint:!0}:n.destructiveHint==="false"?{destructiveHint:!1}:{},...n.idempotentHint==="true"?{idempotentHint:!0}:n.idempotentHint==="false"?{idempotentHint:!1}:{},...n.openWorldHint==="true"?{openWorldHint:!0}:n.openWorldHint==="false"?{openWorldHint:!1}:{}}:void 0;return{...t,...i?{annotations:i}:{},inputSchema:r.inputSchema,[STANDARD_VALIDATOR_SYMBOL]:r.standardValidator}}function validateArgsWithSchema(t,e){const r=new Validator(e,"2020-12",!0).validate(t);if(r.valid)return null;const n=r.errors[r.errors.length-1];return n?{message:n.error}:{message:"Input validation failed"}}function formatStandardIssuePath(t){if(!t||t.length===0)return null;const e=t.map(r=>isPlainObject(r)&&"key"in r?r.key:r).map(r=>String(r)).filter(r=>r.length>0);return e.length===0?null:e.join(".")}async function validateArgsWithStandardSchema(t,e){let r;try{r=await Promise.resolve(e["~standard"].validate(t))}catch(o){const s=o instanceof Error?`: ${o.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",o),`Input validation error: schema validation failed${s}`}if(!r.issues||r.issues.length===0)return null;const n=r.issues[0];if(!n)return"Input validation error";const i=formatStandardIssuePath(n?.path);return i?`Input validation error: ${n.message} at ${i}`:`Input validation error: ${n.message}`}async function validateArgsForTool(t,e){return validateArgsWithStandardSchema(t,e[STANDARD_VALIDATOR_SYMBOL])}function isCallToolResult(t){return isPlainObject(t)&&Array.isArray(t.content)}function isJsonPrimitive(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function isJsonValue(t){return isJsonPrimitive(t)?Number.isFinite(t)||typeof t!="number":Array.isArray(t)?t.every(e=>isJsonValue(e)):isPlainObject(t)?Object.values(t).every(e=>isJsonValue(e)):!1}function toStructuredContent(t){if(!(!isPlainObject(t)||!isJsonValue(t)))return t}function serializeTextContent(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function normalizeToolResponse(t){if(isCallToolResult(t))return t;const e=toStructuredContent(t);return{content:[{type:"text",text:serializeTextContent(t)}],...e?{structuredContent:e}:{},isError:!1}}function getFirstTextBlock(t){for(const e of t.content??[])if(e.type==="text"&&"text"in e&&typeof e.text=="string")return e.text;return null}function toSerializedTestingResult(t){if(t.isError)throw createUnknownError(getFirstTextBlock(t)?.replace(/^Error:\s*/i,"").trim()||TOOL_INVOCATION_FAILED_MESSAGE);const e=t.metadata;if(e&&typeof e=="object"&&e.willNavigate)return null;try{return JSON.stringify(t)}catch{throw createUnknownError(TOOL_INVOCATION_FAILED_MESSAGE)}}function withAbortSignal(t,e){return e?e.aborted?Promise.reject(createUnknownError(TOOL_CANCELLED_MESSAGE)):new Promise((r,n)=>{const i=()=>{o(),n(createUnknownError(TOOL_CANCELLED_MESSAGE))},o=()=>{e.removeEventListener("abort",i)};e.addEventListener("abort",i,{once:!0}),t.then(s=>{o(),r(s)},s=>{o(),n(s)})}):t}function getNavigator(){return typeof navigator<"u"?navigator:null}function getDocument(){return typeof document<"u"?document:null}function defineNavigatorProperty(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,writable:!1,value:r})}function defineDocumentModelContextProperty(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:e})}let navigatorModelContextDeprecationWarned=!1;function defineDeprecatedNavigatorModelContext(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,get(){return navigatorModelContextDeprecationWarned||(navigatorModelContextDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document — use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.")),e}})}function initializeWebMCPPolyfill(t){const e=getNavigator(),r=getDocument();if(!e&&!r||r?.modelContext)return;const i=e?.modelContext,o=!!i;if(installState.installed&&cleanupWebMCPPolyfill(),r&&i){installState.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),defineDocumentModelContextProperty(r,i),installState.installedDocumentModelContext=!0,installState.installed=!0;return}if(o)return;const s=new StrictWebMCPContext,a=s;if(a[POLYFILL_MARKER_PROPERTY]=!0,r&&(installState.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),defineDocumentModelContextProperty(r,a),installState.installedDocumentModelContext=!0),e){installState.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(e,"modelContext"),installState.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(e,"modelContextTesting"),navigatorModelContextDeprecationWarned=!1,defineDeprecatedNavigatorModelContext(e,a),installState.installedNavigatorModelContext=!0;const l=t?.installTestingShim??"if-missing",c=!!e.modelContextTesting;(l==="always"||(l===!0||l==="if-missing")&&!c)&&(defineNavigatorProperty(e,"modelContextTesting",s.getTestingShim()),installState.installedNavigatorModelContextTesting=!0)}installState.installed=!0}function cleanupWebMCPPolyfill(){if(!installState.installed)return;const t=(n,i,o)=>{if(o){Object.defineProperty(n,i,o);return}delete n[i]},e=getNavigator(),r=getDocument();r&&installState.installedDocumentModelContext&&t(r,"modelContext",installState.previousDocumentModelContextDescriptor),e&&installState.installedNavigatorModelContext&&t(e,"modelContext",installState.previousNavigatorModelContextDescriptor),e&&installState.installedNavigatorModelContextTesting&&t(e,"modelContextTesting",installState.previousNavigatorModelContextTestingDescriptor),installState.installed=!1,installState.previousDocumentModelContextDescriptor=void 0,installState.previousNavigatorModelContextDescriptor=void 0,installState.previousNavigatorModelContextTestingDescriptor=void 0,installState.installedDocumentModelContext=!1,installState.installedNavigatorModelContext=!1,installState.installedNavigatorModelContextTesting=!1,navigatorModelContextDeprecationWarned=!1}if(typeof window<"u"&&typeof document<"u"){const t=window.__webMCPPolyfillOptions;if(t?.autoInitialize!==!1)try{initializeWebMCPPolyfill(t)}catch(e){console.error("[WebMCPPolyfill] Auto-initialization failed:",e)}}const randomUUID=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)}),isBrowser=()=>typeof window<"u"&&typeof navigator<"u",isDomAvailable=()=>isBrowser()&&typeof document<"u";let overlayElement=null,labelElement=null,styleElement=null,activeCount=0;const BODY_GLOW_CLASS="next-sdk-tool-body-glow";function ensureDomReady(){return isDomAvailable()}function ensureStyleElement(){if(!ensureDomReady()||styleElement)return;const t=document.createElement("style");t.textContent=`
|
|
5
5
|
.${BODY_GLOW_CLASS} {
|
|
6
6
|
position: relative;
|
|
7
7
|
}
|
|
@@ -169,150 +169,11 @@ Known schemas:
|
|
|
169
169
|
transform: scale(1) translateY(0);
|
|
170
170
|
}
|
|
171
171
|
}
|
|
172
|
-
`,document.head.appendChild(t),styleElement=t}function ensureOverlayElement(){if(!ensureDomReady()||overlayElement)return;ensureStyleElement();const t=document.createElement("div");t.className="next-sdk-tool-overlay";const e=document.createElement("div");e.className="next-sdk-tool-overlay__glow-ring";const r=document.createElement("div");r.className="next-sdk-tool-overlay__panel";const n=document.createElement("div");n.className="next-sdk-tool-overlay__indicator";const i=document.createElement("div");i.className="next-sdk-tool-overlay__indicator-orbit";const o=document.createElement("div");o.className="next-sdk-tool-overlay__indicator-core";const s=document.createElement("div");s.className="next-sdk-tool-overlay__content";const a=document.createElement("div");a.className="next-sdk-tool-overlay__title",a.textContent="AI 正在调用页面工具";const l=document.createElement("span");l.className="next-sdk-tool-overlay__title-dot";const c=document.createElement("div");c.className="next-sdk-tool-overlay__label",a.prepend(l),s.appendChild(a),s.appendChild(c),n.appendChild(i),n.appendChild(o),r.appendChild(n),r.appendChild(s),t.appendChild(e),t.appendChild(r),document.body.appendChild(t),overlayElement=t,labelElement=c}function updateOverlay(t){ensureDomReady()&&(ensureOverlayElement(),!(!overlayElement||!labelElement)&&(overlayElement.classList.remove("next-sdk-tool-overlay--exit"),labelElement.textContent=t.label))}function removeOverlayWithAnimation(){if(!overlayElement)return;overlayElement.classList.add("next-sdk-tool-overlay--exit");const t=overlayElement;let e=!1,r;const n=()=>{e||(e=!0,r!==void 0&&(clearTimeout(r),r=void 0),t.parentNode&&t.parentNode.removeChild(t),overlayElement===t&&(overlayElement=null,labelElement=null),t.removeEventListener("animationend",n))};t.addEventListener("animationend",n),r=setTimeout(n,500)}function showToolInvokeEffect(t){ensureDomReady()&&(activeCount+=1,updateOverlay(t))}function hideToolInvokeEffect(){!ensureDomReady()||activeCount<=0||(activeCount-=1,activeCount===0&&removeOverlayWithAnimation())}function resolveRuntimeEffectConfig(t,e,r){if(!r)return;const n=e||t;return typeof r=="boolean"?r?{label:n}:void 0:{label:r.label||n}}const MSG_TOOL_CALL="next-sdk:tool-call",MSG_TOOL_RESPONSE="next-sdk:tool-response",MSG_TOOL_REGISTERED="next-sdk:tool-registered",MSG_TOOL_UNREGISTERED="next-sdk:tool-unregistered",MSG_REMOTER_READY="next-sdk:remoter-ready",activePages=new Map,normalizeRoute=t=>t.replace(/\/+$/,"")||"/",broadcastTargets=new Set;function initBroadcastTargets(){isBrowser()&&broadcastTargets.add({win:window,origin:window.location.origin||"*"})}initBroadcastTargets();function broadcastToolChange(t){if(!isBrowser())return;const e={type:t};broadcastTargets.forEach(({win:r,origin:n})=>{try{r.postMessage(e,n)}catch{}})}function setupIframeRemoterBridge(){isBrowser()&&window.addEventListener("message",t=>{if(t.data?.type!==MSG_REMOTER_READY||!t.source||t.origin!==window.location.origin)return;const e=t.source;broadcastTargets.add({win:e,origin:t.origin||"*"})})}setupIframeRemoterBridge();function isToolReadyOnRoute(t,e){const r=activePages.get(t);return!!r&&r.has(e)}let _navigator=null;function buildPageHandler(t,e,r=3e4,n){return i=>{const o=randomUUID();return new Promise((s,a)=>{let l,c;const u=()=>{clearTimeout(l),window.removeEventListener("message",h),c&&window.removeEventListener("message",c),n&&hideToolInvokeEffect()};l=setTimeout(()=>{u(),a(new Error(`工具 [${t}] 调用超时 (${r}ms),请检查目标页面是否正确调用了 registerPageTool`))},r);const h=w=>{w.source===window&&w.data?.type===MSG_TOOL_RESPONSE&&w.data.callId===o&&(u(),w.data.error?a(new Error(w.data.error)):s(w.data.result))};window.addEventListener("message",h);const f=()=>{window.postMessage({type:MSG_TOOL_CALL,callId:o,toolName:t,route:e,input:i},window.location.origin||"*")};let g=!1;const b=()=>{g||(g=!0,f())};(async()=>{try{if(n&&showToolInvokeEffect(n),isToolReadyOnRoute(e,t)){b();return}c=w=>{w.source!==window||w.data?.type!==MSG_TOOL_REGISTERED||(window.removeEventListener("message",c),b())},window.addEventListener("message",c),isToolReadyOnRoute(e,t)&&(window.removeEventListener("message",c),b())}catch(w){u(),a(w instanceof Error?w:new Error(String(w)))}})()})}}const _registeredTools=new Map;function setupModelContextBridge(){if(typeof document>"u")return;const t=document,e=typeof navigator<"u"?navigator:void 0,r=t.modelContext||e?.modelContext;if(!r||r.__isNextSdkBridgeSetup)return;!t.modelContext&&e?.modelContext&&(t.modelContext=e.modelContext),isBrowser()&&(window.__nextSdkRegisteredTools=()=>Array.from(_registeredTools.values()));const n=r.registerTool?.bind(r),i=r.unregisterTool?.bind(r);typeof n=="function"&&(r.registerTool=(o,s)=>{const a=o.name,l={...o};s?.signal&&s.signal.addEventListener("abort",()=>{_registeredTools.delete(a),broadcastToolChange(MSG_TOOL_UNREGISTERED)});const c=l.routeConfig&&typeof l.routeConfig=="object"&&"route"in l.routeConfig?l.routeConfig:null;if(c){const u=normalizeRoute(c.route),h=resolveRuntimeEffectConfig(a,l.title,c.invokeEffect),f=buildPageHandler(a,u,c.timeout,h);l.execute=f,delete l.routeConfig}_registeredTools.set(a,{name:a,title:o.title,description:o.description,inputSchema:o.inputSchema});try{n(l,s),broadcastToolChange(MSG_TOOL_REGISTERED)}catch{_registeredTools.delete(a)}}),r.unregisterTool=o=>{try{typeof i=="function"&&i(o)}catch{}finally{_registeredTools.delete(o),broadcastToolChange(MSG_TOOL_UNREGISTERED)}},r.__isNextSdkBridgeSetup=!0}let initialized=!1;const initializeBuiltinWebMCP=()=>{if(isBrowser())try{if(initialized)return;initializeWebMCPPolyfill(),setupModelContextBridge(),initialized=!0}catch(t){console.warn("[next-sdk] 自动注入 modelContext polyfill 和桥接同步失败:",t)}},ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use"),defaultOptions={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},getDefaultOptions=t=>({...defaultOptions,...t}),getRefs=t=>{const e=getDefaultOptions(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function addErrorMessage(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function setResponseValueAndErrors(t,e,r,n,i){t[e]=r,addErrorMessage(t,e,n,i)}const getRelativePath=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};var util;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{const o={};for(const s of i)o[s]=s;return o},t.getValidEnumValues=i=>{const o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(const a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const o=[];for(const s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},t.find=(i,o)=>{for(const s of i)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(util||(util={}));var objectUtil;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=t=>{switch(typeof t){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(t)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(t)?ZodParsedType.array:t===null?ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?ZodParsedType.map:typeof Set<"u"&&t instanceof Set?ZodParsedType.set:typeof Date<"u"&&t instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.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 ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(o){return o.message},n={_errors:[]},i=o=>{for(const s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,l=0;for(;l<s.path.length;){const c=s.path[l];l===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(s))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return i(this),n}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const i of this.issues)if(i.path.length>0){const o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}ZodError.create=t=>new ZodError(t);const errorMap=(t,e)=>{let r;switch(t.code){case ZodIssueCode.invalid_type:t.received===ZodParsedType.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case ZodIssueCode.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:r=`Unrecognized key(s) in object: ${util.joinValues(t.keys,", ")}`;break;case ZodIssueCode.invalid_union:r="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${util.joinValues(t.options)}`;break;case ZodIssueCode.invalid_enum_value:r=`Invalid enum value. Expected ${util.joinValues(t.options)}, received '${t.received}'`;break;case ZodIssueCode.invalid_arguments:r="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:r="Invalid function return type";break;case ZodIssueCode.invalid_date:r="Invalid date";break;case ZodIssueCode.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:util.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case ZodIssueCode.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case ZodIssueCode.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case ZodIssueCode.custom:r="Invalid input";break;case ZodIssueCode.invalid_intersection_types:r="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case ZodIssueCode.not_finite:r="Number must be finite";break;default:r=e.defaultError,util.assertNever(t)}return{message:r}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=t=>{const{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)a=c(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}};function addIssueToContext(t,e){const r=getErrorMap(),n=makeIssue({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===errorMap?void 0:errorMap].filter(i=>!!i)});t.common.issues.push(n)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const i of r){if(i.status==="aborted")return INVALID;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const i of r){const o=await i.key,s=await i.value;n.push({key:o,value:s})}return ParseStatus.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const i of r){const{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return INVALID;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=t=>({status:"dirty",value:t}),OK=t=>({status:"valid",value:t}),isAborted=t=>t.status==="aborted",isDirty=t=>t.status==="dirty",isValid=t=>t.status==="valid",isAsync=t=>typeof Promise<"u"&&t instanceof Promise;var errorUtil;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}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 handleResult=(t,e)=>{if(isValid(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new ZodError(t.common.issues);return this._error=r,this._error}}};function processCreateParams(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,a)=>{const{message:l}=t;return s.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:l??r??a.defaultError}},description:i}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(isAsync(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},i=this._parseSync({data:e,path:n.path,parent:n});return handleResult(n,i)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return isValid(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>isValid(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(isAsync(i)?i:Promise.resolve(i));return handleResult(n,o)}refine(e,r){const n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{const s=e(i),a=()=>o.addIssue({code:ZodIssueCode.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.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:r=>this["~validate"](r)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:r,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:r,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[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,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?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)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex$1;const ipv4Regex=/^(?:(?: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])$/,ipv4CidrRegex=/^(?:(?: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])$/,ipv6Regex=/^(([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]))$/,ipv6CidrRegex=/^(([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])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\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])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function timeRegex(t){return new RegExp(`^${timeRegexSource(t)}$`)}function datetimeRegex(t){let e=`${dateRegexSource}T${timeRegexSource(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function isValidIP(t,e){return!!((e==="v4"||!e)&&ipv4Regex.test(t)||(e==="v6"||!e)&&ipv6Regex.test(t))}function isValidJWT(t,e){if(!jwtRegex.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function isValidCidr(t,e){return!!((e==="v4"||!e)&&ipv4CidrRegex.test(t)||(e==="v6"||!e)&&ipv6CidrRegex.test(t))}class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:o.parsedType}),INVALID}const n=new ParseStatus;let i;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")emailRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"email",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")emojiRegex$1||(emojiRegex$1=new RegExp(_emojiRegex,"u")),emojiRegex$1.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"emoji",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")uuidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"uuid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")nanoidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")cuidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cuid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")cuid2Regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")ulidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"ulid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"url",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"regex",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?datetimeRegex(o).test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?dateRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?timeRegex(o).test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?durationRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"duration",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?isValidIP(e.data,o.version)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"ip",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?isValidJWT(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"jwt",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?isValidCidr(e.data,o.version)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cidr",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?base64Regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"base64",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?base64urlRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"base64url",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):util.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(n)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...errorUtil.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(r)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}ZodString.create=t=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:t?.coerce??!1,...processCreateParams(t)});function floatSafeRemainder(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}class ZodNumber extends ZodType{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)!==ZodParsedType.number){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:o.parsedType}),INVALID}let n;const i=new ParseStatus;for(const o of this._def.checks)o.kind==="int"?util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?floatSafeRemainder(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_finite,message:o.message}),i.dirty()):util.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,errorUtil.toString(r))}gt(e,r){return this.setLimit("min",e,!1,errorUtil.toString(r))}lte(e,r){return this.setLimit("max",e,!0,errorUtil.toString(r))}lt(e,r){return this.setLimit("max",e,!1,errorUtil.toString(r))}setLimit(e,r,n,i){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:errorUtil.toString(i)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&util.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}ZodNumber.create=t=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:t?.coerce||!1,...processCreateParams(t)});class ZodBigInt extends ZodType{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)!==ZodParsedType.bigint)return this._getInvalidInput(e);let n;const i=new ParseStatus;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):util.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:r.parsedType}),INVALID}gte(e,r){return this.setLimit("min",e,!0,errorUtil.toString(r))}gt(e,r){return this.setLimit("min",e,!1,errorUtil.toString(r))}lte(e,r){return this.setLimit("max",e,!0,errorUtil.toString(r))}lt(e,r){return this.setLimit("max",e,!1,errorUtil.toString(r))}setLimit(e,r,n,i){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:errorUtil.toString(i)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}ZodBigInt.create=t=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:t?.coerce??!1,...processCreateParams(t)});class ZodBoolean extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:n.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=t=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:t?.coerce||!1,...processCreateParams(t)});class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:o.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_date}),INVALID}const n=new ParseStatus;let i;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):util.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}ZodDate.create=t=>new ZodDate({checks:[],coerce:t?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(t)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:n.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=t=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(t)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:n.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=t=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(t)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:n.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=t=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(t)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=t=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(t)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=t=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(t)});class ZodNever extends ZodType{_parse(e){const r=this._getOrReturnCtx(e);return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:r.parsedType}),INVALID}}ZodNever.create=t=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(t)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:n.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=t=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(t)});class ZodArray extends ZodType{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==ZodParsedType.array)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:r.parsedType}),INVALID;if(i.exactLength!==null){const s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(addIssueToContext(r,{code:s?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new ParseInputLazyPath(r,s,r.path,a)))).then(s=>ParseStatus.mergeArray(n,s));const o=[...r.data].map((s,a)=>i.type._parseSync(new ParseInputLazyPath(r,s,r.path,a)));return ParseStatus.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(r)}})}max(e,r){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(r)}})}length(e,r){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(r)}})}nonempty(e){return this.min(1,e)}}ZodArray.create=(t,e)=>new ZodArray({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(e)});function deepPartialify(t){if(t instanceof ZodObject){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=ZodOptional.create(deepPartialify(n))}return new ZodObject({...t._def,shape:()=>e})}else return t instanceof ZodArray?new ZodArray({...t._def,type:deepPartialify(t.element)}):t instanceof ZodOptional?ZodOptional.create(deepPartialify(t.unwrap())):t instanceof ZodNullable?ZodNullable.create(deepPartialify(t.unwrap())):t instanceof ZodTuple?ZodTuple.create(t.items.map(e=>deepPartialify(e))):t}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=util.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){const c=this._getOrReturnCtx(e);return addIssueToContext(c,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:c.parsedType}),INVALID}const{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const c in i.data)s.includes(c)||a.push(c);const l=[];for(const c of s){const u=o[c],h=i.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new ParseInputLazyPath(i,h,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof ZodNever){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(c==="strict")a.length>0&&(addIssueToContext(i,{code:ZodIssueCode.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of a){const h=i.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new ParseInputLazyPath(i,h,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const h=await u.key,f=await u.value;c.push({key:h,value:f,alwaysSet:u.alwaysSet})}return c}).then(c=>ParseStatus.mergeObjectSync(n,c)):ParseStatus.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const r={};for(const n of util.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>r})}omit(e){const r={};for(const n of util.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>r})}deepPartial(){return deepPartialify(this)}partial(e){const r={};for(const n of util.objectKeys(this.shape)){const i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new ZodObject({...this._def,shape:()=>r})}required(e){const r={};for(const n of util.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ZodOptional;)o=o._def.innerType;r[n]=o}return new ZodObject({...this._def,shape:()=>r})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(t,e)=>new ZodObject({shape:()=>t,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)}),ZodObject.strictCreate=(t,e)=>new ZodObject({shape:()=>t,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)}),ZodObject.lazycreate=(t,e)=>new ZodObject({shape:t,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});class ZodUnion extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function i(o){for(const a of o)if(a.result.status==="valid")return a.result;for(const a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;const s=o.map(a=>new ZodError(a.ctx.common.issues));return addIssueToContext(r,{code:ZodIssueCode.invalid_union,unionErrors:s}),INVALID}if(r.common.async)return Promise.all(n.map(async o=>{const s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o;const s=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;const a=s.map(l=>new ZodError(l));return addIssueToContext(r,{code:ZodIssueCode.invalid_union,unionErrors:a}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(t,e)=>new ZodUnion({options:t,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(e)});function mergeValues(t,e){const r=getParsedType(t),n=getParsedType(e);if(t===e)return{valid:!0,data:t};if(r===ZodParsedType.object&&n===ZodParsedType.object){const i=util.objectKeys(e),o=util.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(const a of o){const l=mergeValues(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(r===ZodParsedType.array&&n===ZodParsedType.array){if(t.length!==e.length)return{valid:!1};const i=[];for(let o=0;o<t.length;o++){const s=t[o],a=e[o],l=mergeValues(s,a);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return r===ZodParsedType.date&&n===ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),i=(o,s)=>{if(isAborted(o)||isAborted(s))return INVALID;const a=mergeValues(o.value,s.value);return a.valid?((isDirty(o)||isDirty(s))&&r.dirty(),{status:r.value,value:a.data}):(addIssueToContext(n,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};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(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}ZodIntersection.create=(t,e,r)=>new ZodIntersection({left:t,right:e,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(r)});class ZodTuple extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.array)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:n.parsedType}),INVALID;if(n.data.length<this._def.items.length)return addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&n.data.length>this._def.items.length&&(addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const o=[...n.data].map((s,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new ParseInputLazyPath(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>ParseStatus.mergeArray(r,s)):ParseStatus.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:t,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(e)})};class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.map)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:n.parsedType}),INVALID;const i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,l],c)=>({key:i._parse(new ParseInputLazyPath(n,a,n.path,[c,"key"])),value:o._parse(new ParseInputLazyPath(n,l,n.path,[c,"value"]))}));if(n.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of s){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return INVALID;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}})}else{const a=new Map;for(const l of s){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return INVALID;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}}}}ZodMap.create=(t,e,r)=>new ZodMap({valueType:e,keyType:t,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(r)});class ZodSet extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.set)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:n.parsedType}),INVALID;const i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());const o=this._def.valueType;function s(l){const c=new Set;for(const u of l){if(u.status==="aborted")return INVALID;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const a=[...n.data.values()].map((l,c)=>o._parse(new ParseInputLazyPath(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>s(l)):s(a)}min(e,r){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(r)}})}max(e,r){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}ZodSet.create=(t,e)=>new ZodSet({valueType:t,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(e)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}ZodLazy.create=(t,e)=>new ZodLazy({getter:t,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(e)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return addIssueToContext(r,{received:r.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}ZodLiteral.create=(t,e)=>new ZodLiteral({value:t,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(e)});function createZodEnum(t,e){return new ZodEnum({values:t,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(e)})}class ZodEnum extends ZodType{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(r,{expected:util.joinValues(n),received:r.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(r,{received:r.data,code:ZodIssueCode.invalid_enum_value,options:n}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return ZodEnum.create(e,{...this._def,...r})}exclude(e,r=this._def){return ZodEnum.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const r=util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ZodParsedType.string&&n.parsedType!==ZodParsedType.number){const i=util.objectValues(r);return addIssueToContext(n,{expected:util.joinValues(i),received:n.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const i=util.objectValues(r);return addIssueToContext(n,{received:n.data,code:ZodIssueCode.invalid_enum_value,options:i}),INVALID}return OK(e.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(t,e)=>new ZodNativeEnum({values:t,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(e)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.promise&&r.common.async===!1)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:r.parsedType}),INVALID;const n=r.parsedType===ZodParsedType.promise?r.data:Promise.resolve(r.data);return OK(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}}ZodPromise.create=(t,e)=>new ZodPromise({type:t,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(e)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{addIssueToContext(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){const s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return INVALID;const l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?INVALID:l.status==="dirty"||r.value==="dirty"?DIRTY(l.value):l});{if(r.value==="aborted")return INVALID;const a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?INVALID:a.status==="dirty"||r.value==="dirty"?DIRTY(a.value):a}}if(i.type==="refinement"){const s=a=>{const l=i.refinement(a,o);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?INVALID:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?INVALID:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!isValid(s))return INVALID;const a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>isValid(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):INVALID);util.assertNever(i)}}ZodEffects.create=(t,e,r)=>new ZodEffects({schema:t,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:e,...processCreateParams(r)}),ZodEffects.createWithPreprocess=(t,e,r)=>new ZodEffects({schema:e,effect:{type:"preprocess",transform:t},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(r)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(t,e)=>new ZodOptional({innerType:t,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(e)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(t,e)=>new ZodNullable({innerType:t,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(e)});class ZodDefault extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}ZodDefault.create=(t,e)=>new ZodDefault({innerType:t,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...processCreateParams(e)});class ZodCatch extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return isAsync(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(t,e)=>new ZodCatch({innerType:t,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...processCreateParams(e)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:n.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=t=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(t)});class ZodBranded extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?INVALID:o.status==="dirty"?(r.dirty(),DIRTY(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?INVALID:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new ZodPipeline({in:e,out:r,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const r=this._def.innerType._parse(e),n=i=>(isValid(i)&&(i.value=Object.freeze(i.value)),i);return isAsync(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}}ZodReadonly.create=(t,e)=>new ZodReadonly({innerType:t,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(e)});var ZodFirstPartyTypeKind;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,booleanType=ZodBoolean.create;ZodNever.create,ZodArray.create;const objectType=ZodObject.create;ZodUnion.create,ZodIntersection.create,ZodTuple.create;const enumType=ZodEnum.create;ZodPromise.create,ZodOptional.create,ZodNullable.create;function parseAnyDef(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?getRelativePath(e,t.currentPath):e.join("/")}}function parseArrayDef(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(r.items=parseDef(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&setResponseValueAndErrors(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&setResponseValueAndErrors(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(setResponseValueAndErrors(r,"minItems",t.exactLength.value,t.exactLength.message,e),setResponseValueAndErrors(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function parseBigintDef(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"minimum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"maximum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors(r,"maximum",n.value,n.message,e));break;case"multipleOf":setResponseValueAndErrors(r,"multipleOf",n.value,n.message,e);break}return r}function parseBooleanDef(){return{type:"boolean"}}function parseBrandedDef(t,e){return parseDef(t.type._def,e)}const parseCatchDef=(t,e)=>parseDef(t.innerType._def,e);function parseDateDef(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,o)=>parseDateDef(t,e,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(t,e)}}const integerDateParser=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":setResponseValueAndErrors(r,"minimum",n.value,n.message,e);break;case"max":setResponseValueAndErrors(r,"maximum",n.value,n.message,e);break}return r};function parseDefaultDef(t,e){return{...parseDef(t.innerType._def,e),default:t.defaultValue()}}function parseEffectsDef(t,e){return e.effectStrategy==="input"?parseDef(t.schema._def,e):parseAnyDef(e)}function parseEnumDef(t){return{type:"string",enum:Array.from(t.values)}}const isJsonSchema7AllOfType=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function parseIntersectionDef(t,e){const r=[parseDef(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),parseDef(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const i=[];return r.forEach(o=>{if(isJsonSchema7AllOfType(o))i.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...l}=o;s=l}else n=void 0;i.push(s)}}),i.length?{allOf:i,...n}:void 0}function parseLiteralDef(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let emojiRegex;const zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(emojiRegex===void 0&&(emojiRegex=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":setResponseValueAndErrors(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":setResponseValueAndErrors(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":addFormat(r,"email",n.message,e);break;case"format:idn-email":addFormat(r,"idn-email",n.message,e);break;case"pattern:zod":addPattern(r,zodPatterns.email,n.message,e);break}break;case"url":addFormat(r,"uri",n.message,e);break;case"uuid":addFormat(r,"uuid",n.message,e);break;case"regex":addPattern(r,n.regex,n.message,e);break;case"cuid":addPattern(r,zodPatterns.cuid,n.message,e);break;case"cuid2":addPattern(r,zodPatterns.cuid2,n.message,e);break;case"startsWith":addPattern(r,RegExp(`^${escapeLiteralCheckValue(n.value,e)}`),n.message,e);break;case"endsWith":addPattern(r,RegExp(`${escapeLiteralCheckValue(n.value,e)}$`),n.message,e);break;case"datetime":addFormat(r,"date-time",n.message,e);break;case"date":addFormat(r,"date",n.message,e);break;case"time":addFormat(r,"time",n.message,e);break;case"duration":addFormat(r,"duration",n.message,e);break;case"length":setResponseValueAndErrors(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),setResponseValueAndErrors(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{addPattern(r,RegExp(escapeLiteralCheckValue(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&addFormat(r,"ipv4",n.message,e),n.version!=="v4"&&addFormat(r,"ipv6",n.message,e);break}case"base64url":addPattern(r,zodPatterns.base64url,n.message,e);break;case"jwt":addPattern(r,zodPatterns.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&addPattern(r,zodPatterns.ipv4Cidr,n.message,e),n.version!=="v4"&&addPattern(r,zodPatterns.ipv6Cidr,n.message,e);break}case"emoji":addPattern(r,zodPatterns.emoji(),n.message,e);break;case"ulid":{addPattern(r,zodPatterns.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{addFormat(r,"binary",n.message,e);break}case"contentEncoding:base64":{setResponseValueAndErrors(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{addPattern(r,zodPatterns.base64,n.message,e);break}}break}case"nanoid":addPattern(r,zodPatterns.nanoid,n.message,e)}return r}function escapeLiteralCheckValue(t,e){return e.patternStrategy==="escape"?escapeNonAlphaNumeric(t):t}const ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(t){let e="";for(let r=0;r<t.length;r++)ALPHA_NUMERIC.has(t[r])||(e+="\\"),e+=t[r];return e}function addFormat(t,e,r,n){t.format||t.anyOf?.some(i=>i.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):setResponseValueAndErrors(t,"format",e,r,n)}function addPattern(t,e,r,n){t.pattern||t.allOf?.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:stringifyRegExpWithFlags(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):setResponseValueAndErrors(t,"pattern",stringifyRegExpWithFlags(e,n),r,n)}function stringifyRegExpWithFlags(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let i="",o=!1,s=!1,a=!1;for(let l=0;l<n.length;l++){if(o){i+=n[l],o=!1;continue}if(r.i){if(s){if(n[l].match(/[a-z]/)){a?(i+=n[l],i+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(i+=n[l],a=!0):i+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){i+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){i+=`(^|(?<=[\r
|
|
172
|
+
`,document.head.appendChild(t),styleElement=t}function ensureOverlayElement(){if(!ensureDomReady()||overlayElement)return;ensureStyleElement();const t=document.createElement("div");t.className="next-sdk-tool-overlay";const e=document.createElement("div");e.className="next-sdk-tool-overlay__glow-ring";const r=document.createElement("div");r.className="next-sdk-tool-overlay__panel";const n=document.createElement("div");n.className="next-sdk-tool-overlay__indicator";const i=document.createElement("div");i.className="next-sdk-tool-overlay__indicator-orbit";const o=document.createElement("div");o.className="next-sdk-tool-overlay__indicator-core";const s=document.createElement("div");s.className="next-sdk-tool-overlay__content";const a=document.createElement("div");a.className="next-sdk-tool-overlay__title",a.textContent="AI 正在调用页面工具";const l=document.createElement("span");l.className="next-sdk-tool-overlay__title-dot";const c=document.createElement("div");c.className="next-sdk-tool-overlay__label",a.prepend(l),s.appendChild(a),s.appendChild(c),n.appendChild(i),n.appendChild(o),r.appendChild(n),r.appendChild(s),t.appendChild(e),t.appendChild(r),document.body.appendChild(t),overlayElement=t,labelElement=c}function updateOverlay(t){ensureDomReady()&&(ensureOverlayElement(),!(!overlayElement||!labelElement)&&(overlayElement.classList.remove("next-sdk-tool-overlay--exit"),labelElement.textContent=t.label))}function removeOverlayWithAnimation(){if(!overlayElement)return;overlayElement.classList.add("next-sdk-tool-overlay--exit");const t=overlayElement;let e=!1,r;const n=()=>{e||(e=!0,r!==void 0&&(clearTimeout(r),r=void 0),t.parentNode&&t.parentNode.removeChild(t),overlayElement===t&&(overlayElement=null,labelElement=null),t.removeEventListener("animationend",n))};t.addEventListener("animationend",n),r=setTimeout(n,500)}function showToolInvokeEffect(t){ensureDomReady()&&(activeCount+=1,updateOverlay(t))}function hideToolInvokeEffect(){!ensureDomReady()||activeCount<=0||(activeCount-=1,activeCount===0&&removeOverlayWithAnimation())}function resolveRuntimeEffectConfig(t,e,r){if(!r)return;const n=e||t;return typeof r=="boolean"?r?{label:n}:void 0:{label:r.label||n}}const MSG_TOOL_CALL="next-sdk:tool-call",MSG_TOOL_RESPONSE="next-sdk:tool-response",MSG_TOOL_REGISTERED="next-sdk:tool-registered",MSG_TOOL_UNREGISTERED="next-sdk:tool-unregistered",MSG_REMOTER_READY="next-sdk:remoter-ready",activePages=new Map,normalizeRoute=t=>t.replace(/\/+$/,"")||"/",broadcastTargets=new Set;function initBroadcastTargets(){isBrowser()&&broadcastTargets.add({win:window,origin:window.location.origin||"*"})}initBroadcastTargets();function broadcastToolChange(t){if(!isBrowser())return;const e={type:t};broadcastTargets.forEach(({win:r,origin:n})=>{try{r.postMessage(e,n)}catch{}})}function setupIframeRemoterBridge(){isBrowser()&&window.addEventListener("message",t=>{if(t.data?.type!==MSG_REMOTER_READY||!t.source||t.origin!==window.location.origin)return;const e=t.source;broadcastTargets.add({win:e,origin:t.origin||"*"})})}setupIframeRemoterBridge();function isToolReadyOnRoute(t,e){const r=activePages.get(t);return!!r&&r.has(e)}let _navigator=null;function buildPageHandler(t,e,r=3e4,n){return i=>{const o=randomUUID();return new Promise((s,a)=>{let l,c;const u=()=>{clearTimeout(l),window.removeEventListener("message",f),c&&window.removeEventListener("message",c),n&&hideToolInvokeEffect()};l=setTimeout(()=>{u(),a(new Error(`工具 [${t}] 调用超时 (${r}ms),请检查目标页面是否正确调用了 registerPageTool`))},r);const f=_=>{_.source===window&&_.data?.type===MSG_TOOL_RESPONSE&&_.data.callId===o&&(u(),_.data.error?a(new Error(_.data.error)):s(_.data.result))};window.addEventListener("message",f);const h=()=>{window.postMessage({type:MSG_TOOL_CALL,callId:o,toolName:t,route:e,input:i},window.location.origin||"*")};let m=!1;const g=()=>{m||(m=!0,h())};(async()=>{try{if(n&&showToolInvokeEffect(n),isToolReadyOnRoute(e,t)){g();return}c=_=>{_.source!==window||_.data?.type!==MSG_TOOL_REGISTERED||(window.removeEventListener("message",c),g())},window.addEventListener("message",c),isToolReadyOnRoute(e,t)&&(window.removeEventListener("message",c),g())}catch(_){u(),a(_ instanceof Error?_:new Error(String(_)))}})()})}}const _registeredTools=new Map;function setupModelContextBridge(){if(typeof document>"u")return;const t=document,e=typeof navigator<"u"?navigator:void 0,r=t.modelContext||e?.modelContext;if(!r||r.__isNextSdkBridgeSetup)return;!t.modelContext&&e?.modelContext&&(t.modelContext=e.modelContext),isBrowser()&&(window.__nextSdkRegisteredTools=()=>Array.from(_registeredTools.values()));const n=r.registerTool?.bind(r),i=r.unregisterTool?.bind(r);typeof n=="function"&&(r.registerTool=(o,s)=>{const a=o.name,l={...o};s?.signal&&s.signal.addEventListener("abort",()=>{_registeredTools.delete(a),broadcastToolChange(MSG_TOOL_UNREGISTERED)});const c=l.routeConfig&&typeof l.routeConfig=="object"&&"route"in l.routeConfig?l.routeConfig:null;if(c){const u=normalizeRoute(c.route),f=resolveRuntimeEffectConfig(a,l.title,c.invokeEffect),h=buildPageHandler(a,u,c.timeout,f);l.execute=h,delete l.routeConfig}_registeredTools.set(a,{name:a,title:o.title,description:o.description,inputSchema:o.inputSchema});try{n(l,s),broadcastToolChange(MSG_TOOL_REGISTERED)}catch{_registeredTools.delete(a)}}),r.unregisterTool=o=>{try{typeof i=="function"&&i(o)}catch{}finally{_registeredTools.delete(o),broadcastToolChange(MSG_TOOL_UNREGISTERED)}},r.__isNextSdkBridgeSetup=!0}let initialized=!1;const initializeBuiltinWebMCP=()=>{if(isBrowser())try{if(initialized)return;initializeWebMCPPolyfill(),setupModelContextBridge(),initialized=!0}catch(t){console.warn("[next-sdk] 自动注入 modelContext polyfill 和桥接同步失败:",t)}},ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use"),defaultOptions={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},getDefaultOptions=t=>({...defaultOptions,...t}),getRefs=t=>{const e=getDefaultOptions(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function addErrorMessage(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function setResponseValueAndErrors(t,e,r,n,i){t[e]=r,addErrorMessage(t,e,n,i)}const getRelativePath=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};var util;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{const o={};for(const s of i)o[s]=s;return o},t.getValidEnumValues=i=>{const o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(const a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const o=[];for(const s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},t.find=(i,o)=>{for(const s of i)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(util||(util={}));var objectUtil;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=t=>{switch(typeof t){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(t)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(t)?ZodParsedType.array:t===null?ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?ZodParsedType.map:typeof Set<"u"&&t instanceof Set?ZodParsedType.set:typeof Date<"u"&&t instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.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 ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(o){return o.message},n={_errors:[]},i=o=>{for(const s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,l=0;for(;l<s.path.length;){const c=s.path[l];l===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(s))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return i(this),n}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const i of this.issues)if(i.path.length>0){const o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}ZodError.create=t=>new ZodError(t);const errorMap=(t,e)=>{let r;switch(t.code){case ZodIssueCode.invalid_type:t.received===ZodParsedType.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case ZodIssueCode.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:r=`Unrecognized key(s) in object: ${util.joinValues(t.keys,", ")}`;break;case ZodIssueCode.invalid_union:r="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${util.joinValues(t.options)}`;break;case ZodIssueCode.invalid_enum_value:r=`Invalid enum value. Expected ${util.joinValues(t.options)}, received '${t.received}'`;break;case ZodIssueCode.invalid_arguments:r="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:r="Invalid function return type";break;case ZodIssueCode.invalid_date:r="Invalid date";break;case ZodIssueCode.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:util.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case ZodIssueCode.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case ZodIssueCode.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case ZodIssueCode.custom:r="Invalid input";break;case ZodIssueCode.invalid_intersection_types:r="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case ZodIssueCode.not_finite:r="Number must be finite";break;default:r=e.defaultError,util.assertNever(t)}return{message:r}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=t=>{const{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)a=c(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}};function addIssueToContext(t,e){const r=getErrorMap(),n=makeIssue({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===errorMap?void 0:errorMap].filter(i=>!!i)});t.common.issues.push(n)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const i of r){if(i.status==="aborted")return INVALID;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const i of r){const o=await i.key,s=await i.value;n.push({key:o,value:s})}return ParseStatus.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const i of r){const{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return INVALID;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=t=>({status:"dirty",value:t}),OK=t=>({status:"valid",value:t}),isAborted=t=>t.status==="aborted",isDirty=t=>t.status==="dirty",isValid=t=>t.status==="valid",isAsync=t=>typeof Promise<"u"&&t instanceof Promise;var errorUtil;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}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 handleResult=(t,e)=>{if(isValid(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new ZodError(t.common.issues);return this._error=r,this._error}}};function processCreateParams(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,a)=>{const{message:l}=t;return s.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:l??r??a.defaultError}},description:i}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(isAsync(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},i=this._parseSync({data:e,path:n.path,parent:n});return handleResult(n,i)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return isValid(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>isValid(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(isAsync(i)?i:Promise.resolve(i));return handleResult(n,o)}refine(e,r){const n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{const s=e(i),a=()=>o.addIssue({code:ZodIssueCode.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.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:r=>this["~validate"](r)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:r,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:r,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[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,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?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)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex$1;const ipv4Regex=/^(?:(?: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])$/,ipv4CidrRegex=/^(?:(?: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])$/,ipv6Regex=/^(([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]))$/,ipv6CidrRegex=/^(([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])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\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])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function timeRegex(t){return new RegExp(`^${timeRegexSource(t)}$`)}function datetimeRegex(t){let e=`${dateRegexSource}T${timeRegexSource(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function isValidIP(t,e){return!!((e==="v4"||!e)&&ipv4Regex.test(t)||(e==="v6"||!e)&&ipv6Regex.test(t))}function isValidJWT(t,e){if(!jwtRegex.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function isValidCidr(t,e){return!!((e==="v4"||!e)&&ipv4CidrRegex.test(t)||(e==="v6"||!e)&&ipv6CidrRegex.test(t))}class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:o.parsedType}),INVALID}const n=new ParseStatus;let i;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")emailRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"email",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")emojiRegex$1||(emojiRegex$1=new RegExp(_emojiRegex,"u")),emojiRegex$1.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"emoji",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")uuidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"uuid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")nanoidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")cuidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cuid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")cuid2Regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")ulidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"ulid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"url",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"regex",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?datetimeRegex(o).test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?dateRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?timeRegex(o).test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?durationRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"duration",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?isValidIP(e.data,o.version)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"ip",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?isValidJWT(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"jwt",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?isValidCidr(e.data,o.version)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cidr",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?base64Regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"base64",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?base64urlRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"base64url",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):util.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(n)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...errorUtil.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(r)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}ZodString.create=t=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:t?.coerce??!1,...processCreateParams(t)});function floatSafeRemainder(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}class ZodNumber extends ZodType{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)!==ZodParsedType.number){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:o.parsedType}),INVALID}let n;const i=new ParseStatus;for(const o of this._def.checks)o.kind==="int"?util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?floatSafeRemainder(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_finite,message:o.message}),i.dirty()):util.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,errorUtil.toString(r))}gt(e,r){return this.setLimit("min",e,!1,errorUtil.toString(r))}lte(e,r){return this.setLimit("max",e,!0,errorUtil.toString(r))}lt(e,r){return this.setLimit("max",e,!1,errorUtil.toString(r))}setLimit(e,r,n,i){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:errorUtil.toString(i)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&util.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}ZodNumber.create=t=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:t?.coerce||!1,...processCreateParams(t)});class ZodBigInt extends ZodType{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)!==ZodParsedType.bigint)return this._getInvalidInput(e);let n;const i=new ParseStatus;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):util.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:r.parsedType}),INVALID}gte(e,r){return this.setLimit("min",e,!0,errorUtil.toString(r))}gt(e,r){return this.setLimit("min",e,!1,errorUtil.toString(r))}lte(e,r){return this.setLimit("max",e,!0,errorUtil.toString(r))}lt(e,r){return this.setLimit("max",e,!1,errorUtil.toString(r))}setLimit(e,r,n,i){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:errorUtil.toString(i)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}ZodBigInt.create=t=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:t?.coerce??!1,...processCreateParams(t)});class ZodBoolean extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:n.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=t=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:t?.coerce||!1,...processCreateParams(t)});class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:o.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_date}),INVALID}const n=new ParseStatus;let i;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):util.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}ZodDate.create=t=>new ZodDate({checks:[],coerce:t?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(t)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:n.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=t=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(t)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:n.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=t=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(t)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:n.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=t=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(t)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=t=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(t)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=t=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(t)});class ZodNever extends ZodType{_parse(e){const r=this._getOrReturnCtx(e);return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:r.parsedType}),INVALID}}ZodNever.create=t=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(t)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:n.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=t=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(t)});class ZodArray extends ZodType{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==ZodParsedType.array)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:r.parsedType}),INVALID;if(i.exactLength!==null){const s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(addIssueToContext(r,{code:s?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new ParseInputLazyPath(r,s,r.path,a)))).then(s=>ParseStatus.mergeArray(n,s));const o=[...r.data].map((s,a)=>i.type._parseSync(new ParseInputLazyPath(r,s,r.path,a)));return ParseStatus.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(r)}})}max(e,r){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(r)}})}length(e,r){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(r)}})}nonempty(e){return this.min(1,e)}}ZodArray.create=(t,e)=>new ZodArray({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(e)});function deepPartialify(t){if(t instanceof ZodObject){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=ZodOptional.create(deepPartialify(n))}return new ZodObject({...t._def,shape:()=>e})}else return t instanceof ZodArray?new ZodArray({...t._def,type:deepPartialify(t.element)}):t instanceof ZodOptional?ZodOptional.create(deepPartialify(t.unwrap())):t instanceof ZodNullable?ZodNullable.create(deepPartialify(t.unwrap())):t instanceof ZodTuple?ZodTuple.create(t.items.map(e=>deepPartialify(e))):t}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=util.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){const c=this._getOrReturnCtx(e);return addIssueToContext(c,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:c.parsedType}),INVALID}const{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const c in i.data)s.includes(c)||a.push(c);const l=[];for(const c of s){const u=o[c],f=i.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new ParseInputLazyPath(i,f,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof ZodNever){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(c==="strict")a.length>0&&(addIssueToContext(i,{code:ZodIssueCode.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of a){const f=i.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new ParseInputLazyPath(i,f,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const f=await u.key,h=await u.value;c.push({key:f,value:h,alwaysSet:u.alwaysSet})}return c}).then(c=>ParseStatus.mergeObjectSync(n,c)):ParseStatus.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const r={};for(const n of util.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>r})}omit(e){const r={};for(const n of util.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>r})}deepPartial(){return deepPartialify(this)}partial(e){const r={};for(const n of util.objectKeys(this.shape)){const i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new ZodObject({...this._def,shape:()=>r})}required(e){const r={};for(const n of util.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ZodOptional;)o=o._def.innerType;r[n]=o}return new ZodObject({...this._def,shape:()=>r})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(t,e)=>new ZodObject({shape:()=>t,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)}),ZodObject.strictCreate=(t,e)=>new ZodObject({shape:()=>t,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)}),ZodObject.lazycreate=(t,e)=>new ZodObject({shape:t,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});class ZodUnion extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function i(o){for(const a of o)if(a.result.status==="valid")return a.result;for(const a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;const s=o.map(a=>new ZodError(a.ctx.common.issues));return addIssueToContext(r,{code:ZodIssueCode.invalid_union,unionErrors:s}),INVALID}if(r.common.async)return Promise.all(n.map(async o=>{const s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o;const s=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;const a=s.map(l=>new ZodError(l));return addIssueToContext(r,{code:ZodIssueCode.invalid_union,unionErrors:a}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(t,e)=>new ZodUnion({options:t,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(e)});function mergeValues(t,e){const r=getParsedType(t),n=getParsedType(e);if(t===e)return{valid:!0,data:t};if(r===ZodParsedType.object&&n===ZodParsedType.object){const i=util.objectKeys(e),o=util.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(const a of o){const l=mergeValues(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(r===ZodParsedType.array&&n===ZodParsedType.array){if(t.length!==e.length)return{valid:!1};const i=[];for(let o=0;o<t.length;o++){const s=t[o],a=e[o],l=mergeValues(s,a);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return r===ZodParsedType.date&&n===ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),i=(o,s)=>{if(isAborted(o)||isAborted(s))return INVALID;const a=mergeValues(o.value,s.value);return a.valid?((isDirty(o)||isDirty(s))&&r.dirty(),{status:r.value,value:a.data}):(addIssueToContext(n,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};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(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}ZodIntersection.create=(t,e,r)=>new ZodIntersection({left:t,right:e,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(r)});class ZodTuple extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.array)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:n.parsedType}),INVALID;if(n.data.length<this._def.items.length)return addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&n.data.length>this._def.items.length&&(addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const o=[...n.data].map((s,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new ParseInputLazyPath(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>ParseStatus.mergeArray(r,s)):ParseStatus.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:t,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(e)})};class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.map)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:n.parsedType}),INVALID;const i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,l],c)=>({key:i._parse(new ParseInputLazyPath(n,a,n.path,[c,"key"])),value:o._parse(new ParseInputLazyPath(n,l,n.path,[c,"value"]))}));if(n.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of s){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return INVALID;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}})}else{const a=new Map;for(const l of s){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return INVALID;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}}}}ZodMap.create=(t,e,r)=>new ZodMap({valueType:e,keyType:t,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(r)});class ZodSet extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.set)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:n.parsedType}),INVALID;const i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());const o=this._def.valueType;function s(l){const c=new Set;for(const u of l){if(u.status==="aborted")return INVALID;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const a=[...n.data.values()].map((l,c)=>o._parse(new ParseInputLazyPath(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>s(l)):s(a)}min(e,r){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(r)}})}max(e,r){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}ZodSet.create=(t,e)=>new ZodSet({valueType:t,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(e)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}ZodLazy.create=(t,e)=>new ZodLazy({getter:t,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(e)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return addIssueToContext(r,{received:r.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}ZodLiteral.create=(t,e)=>new ZodLiteral({value:t,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(e)});function createZodEnum(t,e){return new ZodEnum({values:t,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(e)})}class ZodEnum extends ZodType{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(r,{expected:util.joinValues(n),received:r.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(r,{received:r.data,code:ZodIssueCode.invalid_enum_value,options:n}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return ZodEnum.create(e,{...this._def,...r})}exclude(e,r=this._def){return ZodEnum.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const r=util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ZodParsedType.string&&n.parsedType!==ZodParsedType.number){const i=util.objectValues(r);return addIssueToContext(n,{expected:util.joinValues(i),received:n.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const i=util.objectValues(r);return addIssueToContext(n,{received:n.data,code:ZodIssueCode.invalid_enum_value,options:i}),INVALID}return OK(e.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(t,e)=>new ZodNativeEnum({values:t,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(e)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.promise&&r.common.async===!1)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:r.parsedType}),INVALID;const n=r.parsedType===ZodParsedType.promise?r.data:Promise.resolve(r.data);return OK(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}}ZodPromise.create=(t,e)=>new ZodPromise({type:t,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(e)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{addIssueToContext(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){const s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return INVALID;const l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?INVALID:l.status==="dirty"||r.value==="dirty"?DIRTY(l.value):l});{if(r.value==="aborted")return INVALID;const a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?INVALID:a.status==="dirty"||r.value==="dirty"?DIRTY(a.value):a}}if(i.type==="refinement"){const s=a=>{const l=i.refinement(a,o);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?INVALID:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?INVALID:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!isValid(s))return INVALID;const a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>isValid(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):INVALID);util.assertNever(i)}}ZodEffects.create=(t,e,r)=>new ZodEffects({schema:t,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:e,...processCreateParams(r)}),ZodEffects.createWithPreprocess=(t,e,r)=>new ZodEffects({schema:e,effect:{type:"preprocess",transform:t},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(r)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(t,e)=>new ZodOptional({innerType:t,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(e)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(t,e)=>new ZodNullable({innerType:t,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(e)});class ZodDefault extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}ZodDefault.create=(t,e)=>new ZodDefault({innerType:t,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...processCreateParams(e)});class ZodCatch extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return isAsync(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(t,e)=>new ZodCatch({innerType:t,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...processCreateParams(e)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:n.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=t=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(t)});class ZodBranded extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?INVALID:o.status==="dirty"?(r.dirty(),DIRTY(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?INVALID:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new ZodPipeline({in:e,out:r,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const r=this._def.innerType._parse(e),n=i=>(isValid(i)&&(i.value=Object.freeze(i.value)),i);return isAsync(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}}ZodReadonly.create=(t,e)=>new ZodReadonly({innerType:t,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(e)});var ZodFirstPartyTypeKind;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,booleanType=ZodBoolean.create;ZodNever.create,ZodArray.create;const objectType=ZodObject.create;ZodUnion.create,ZodIntersection.create,ZodTuple.create;const enumType=ZodEnum.create;ZodPromise.create,ZodOptional.create,ZodNullable.create;function parseAnyDef(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?getRelativePath(e,t.currentPath):e.join("/")}}function parseArrayDef(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(r.items=parseDef(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&setResponseValueAndErrors(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&setResponseValueAndErrors(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(setResponseValueAndErrors(r,"minItems",t.exactLength.value,t.exactLength.message,e),setResponseValueAndErrors(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function parseBigintDef(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"minimum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"maximum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors(r,"maximum",n.value,n.message,e));break;case"multipleOf":setResponseValueAndErrors(r,"multipleOf",n.value,n.message,e);break}return r}function parseBooleanDef(){return{type:"boolean"}}function parseBrandedDef(t,e){return parseDef(t.type._def,e)}const parseCatchDef=(t,e)=>parseDef(t.innerType._def,e);function parseDateDef(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,o)=>parseDateDef(t,e,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(t,e)}}const integerDateParser=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":setResponseValueAndErrors(r,"minimum",n.value,n.message,e);break;case"max":setResponseValueAndErrors(r,"maximum",n.value,n.message,e);break}return r};function parseDefaultDef(t,e){return{...parseDef(t.innerType._def,e),default:t.defaultValue()}}function parseEffectsDef(t,e){return e.effectStrategy==="input"?parseDef(t.schema._def,e):parseAnyDef(e)}function parseEnumDef(t){return{type:"string",enum:Array.from(t.values)}}const isJsonSchema7AllOfType=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function parseIntersectionDef(t,e){const r=[parseDef(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),parseDef(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const i=[];return r.forEach(o=>{if(isJsonSchema7AllOfType(o))i.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...l}=o;s=l}else n=void 0;i.push(s)}}),i.length?{allOf:i,...n}:void 0}function parseLiteralDef(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let emojiRegex;const zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(emojiRegex===void 0&&(emojiRegex=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":setResponseValueAndErrors(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":setResponseValueAndErrors(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":addFormat(r,"email",n.message,e);break;case"format:idn-email":addFormat(r,"idn-email",n.message,e);break;case"pattern:zod":addPattern(r,zodPatterns.email,n.message,e);break}break;case"url":addFormat(r,"uri",n.message,e);break;case"uuid":addFormat(r,"uuid",n.message,e);break;case"regex":addPattern(r,n.regex,n.message,e);break;case"cuid":addPattern(r,zodPatterns.cuid,n.message,e);break;case"cuid2":addPattern(r,zodPatterns.cuid2,n.message,e);break;case"startsWith":addPattern(r,RegExp(`^${escapeLiteralCheckValue(n.value,e)}`),n.message,e);break;case"endsWith":addPattern(r,RegExp(`${escapeLiteralCheckValue(n.value,e)}$`),n.message,e);break;case"datetime":addFormat(r,"date-time",n.message,e);break;case"date":addFormat(r,"date",n.message,e);break;case"time":addFormat(r,"time",n.message,e);break;case"duration":addFormat(r,"duration",n.message,e);break;case"length":setResponseValueAndErrors(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),setResponseValueAndErrors(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{addPattern(r,RegExp(escapeLiteralCheckValue(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&addFormat(r,"ipv4",n.message,e),n.version!=="v4"&&addFormat(r,"ipv6",n.message,e);break}case"base64url":addPattern(r,zodPatterns.base64url,n.message,e);break;case"jwt":addPattern(r,zodPatterns.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&addPattern(r,zodPatterns.ipv4Cidr,n.message,e),n.version!=="v4"&&addPattern(r,zodPatterns.ipv6Cidr,n.message,e);break}case"emoji":addPattern(r,zodPatterns.emoji(),n.message,e);break;case"ulid":{addPattern(r,zodPatterns.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{addFormat(r,"binary",n.message,e);break}case"contentEncoding:base64":{setResponseValueAndErrors(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{addPattern(r,zodPatterns.base64,n.message,e);break}}break}case"nanoid":addPattern(r,zodPatterns.nanoid,n.message,e)}return r}function escapeLiteralCheckValue(t,e){return e.patternStrategy==="escape"?escapeNonAlphaNumeric(t):t}const ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(t){let e="";for(let r=0;r<t.length;r++)ALPHA_NUMERIC.has(t[r])||(e+="\\"),e+=t[r];return e}function addFormat(t,e,r,n){t.format||t.anyOf?.some(i=>i.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):setResponseValueAndErrors(t,"format",e,r,n)}function addPattern(t,e,r,n){t.pattern||t.allOf?.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:stringifyRegExpWithFlags(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):setResponseValueAndErrors(t,"pattern",stringifyRegExpWithFlags(e,n),r,n)}function stringifyRegExpWithFlags(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let i="",o=!1,s=!1,a=!1;for(let l=0;l<n.length;l++){if(o){i+=n[l],o=!1;continue}if(r.i){if(s){if(n[l].match(/[a-z]/)){a?(i+=n[l],i+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(i+=n[l],a=!0):i+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){i+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){i+=`(^|(?<=[\r
|
|
173
173
|
]))`;continue}else if(n[l]==="$"){i+=`($|(?=[\r
|
|
174
174
|
]))`;continue}}if(r.s&&n[l]==="."){i+=s?`${n[l]}\r
|
|
175
175
|
`:`[${n[l]}\r
|
|
176
|
-
]`;continue}i+=n[l],n[l]==="\\"?o=!0:s&&n[l]==="]"?s=!1:!s&&n[l]==="["&&(s=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return i}function parseRecordDef(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,i)=>({...n,[i]:parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??parseAnyDef(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){const{type:n,...i}=parseStringDef(t.keyType._def,e);return{...r,propertyNames:i}}else{if(t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...i}=parseBrandedDef(t.keyType._def,e);return{...r,propertyNames:i}}}return r}function parseMapDef(t,e){if(e.mapStrategy==="record")return parseRecordDef(t,e);const r=parseDef(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||parseAnyDef(e),n=parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||parseAnyDef(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function parseNativeEnumDef(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),i=Array.from(new Set(n.map(o=>typeof o)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function parseNeverDef(t){return t.target==="openAi"?void 0:{not:parseAnyDef({...t,currentPath:[...t.currentPath,"not"]})}}function parseNullDef(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(t,e){if(e.target==="openApi3")return asAnyOf(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in primitiveMappings&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((i,o)=>{const s=primitiveMappings[o._def.typeName];return s&&!i.includes(s)?[...i,s]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((i,o)=>{const s=typeof o._def.value;switch(s){case"string":case"number":case"boolean":return[...i,s];case"bigint":return[...i,"integer"];case"object":if(o._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(n.length===r.length){const i=n.filter((o,s,a)=>a.indexOf(o)===s);return{type:i.length>1?i:i[0],enum:r.reduce((o,s)=>o.includes(s._def.value)?o:[...o,s._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(o=>!n.includes(o))],[])};return asAnyOf(t,e)}const asAnyOf=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,i)=>parseDef(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function parseNullableDef(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:primitiveMappings[t.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=parseDef(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=parseDef(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function parseNumberDef(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",addErrorMessage(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"minimum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"maximum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors(r,"maximum",n.value,n.message,e));break;case"multipleOf":setResponseValueAndErrors(r,"multipleOf",n.value,n.message,e);break}return r}function parseObjectDef(t,e){const r=e.target==="openAi",n={type:"object",properties:{}},i=[],o=t.shape();for(const a in o){let l=o[a];if(l===void 0||l._def===void 0)continue;let c=safeIsOptional(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=parseDef(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,c||i.push(a))}i.length&&(n.required=i);const s=decideAdditionalProperties(t,e);return s!==void 0&&(n.additionalProperties=s),n}function decideAdditionalProperties(t,e){if(t.catchall._def.typeName!=="ZodNever")return parseDef(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function safeIsOptional(t){try{return t.isOptional()}catch{return!0}}const parseOptionalDef=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return parseDef(t.innerType._def,e);const r=parseDef(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:parseAnyDef(e)},r]}:parseAnyDef(e)},parsePipelineDef=(t,e)=>{if(e.pipeStrategy==="input")return parseDef(t.in._def,e);if(e.pipeStrategy==="output")return parseDef(t.out._def,e);const r=parseDef(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=parseDef(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function parsePromiseDef(t,e){return parseDef(t.type._def,e)}function parseSetDef(t,e){const n={type:"array",uniqueItems:!0,items:parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&setResponseValueAndErrors(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&setResponseValueAndErrors(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function parseTupleDef(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>parseDef(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:parseDef(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>parseDef(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function parseUndefinedDef(t){return{not:parseAnyDef(t)}}function parseUnknownDef(t){return parseAnyDef(t)}const parseReadonlyDef=(t,e)=>parseDef(t.innerType._def,e),selectParser=(t,e,r)=>{switch(e){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(t,r);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(t,r);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(t,r);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(t,r);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(t,r);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef(r);case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(r);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(t,r);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(t,r);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(t,r);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(t,r);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(t,r);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(t,r);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(t);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(t);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(t,r);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(t,r);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(t,r);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(t,r);case ZodFirstPartyTypeKind.ZodLazy:return()=>t.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(t,r);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef(r);case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(t,r);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef(r);case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef(r);case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(t,r);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(t,r);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(t,r);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(t,r);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(t,r);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:return;default:return(n=>{})()}};function parseDef(t,e,r=!1){const n=e.seen.get(t);if(e.override){const a=e.override?.(t,e,n,r);if(a!==ignoreOverride)return a}if(n&&!r){const a=get$ref(n,e);if(a!==void 0)return a}const i={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,i);const o=selectParser(t,t.typeName,e),s=typeof o=="function"?parseDef(o(),e):o;if(s&&addMeta(t,e,s),e.postProcess){const a=e.postProcess(s,t,e);return i.jsonSchema=s,a}return i.jsonSchema=s,s}const get$ref=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:getRelativePath(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),parseAnyDef(e)):e.$refStrategy==="seen"?parseAnyDef(e):void 0}},addMeta=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),zodToJsonSchema=(t,e)=>{const r=getRefs(e);let n;const i=e?.name,o=parseDef(t._def,r,!1)??parseAnyDef(r);r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const s=i===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:o}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s},pageAgentPrompt=`## 角色
|
|
177
|
-
|
|
178
|
-
你是浏览器页面的操作工具,你拥有识别网页内容,点击,填写,选择下拉框和滚动页面等功能。
|
|
179
|
-
|
|
180
|
-
在执行页面操作之前,你必须先调用\`browserState\`工具一次,根据最新的网页状态,再调用操作动作,比如 'click','fill','select' 等动作。
|
|
181
|
-
|
|
182
|
-
<intro>
|
|
183
|
-
你擅长以下任务:
|
|
184
|
-
1. 导航复杂网站并提取精确信息
|
|
185
|
-
2. 自动化表单提交和交互式网页操作
|
|
186
|
-
3. 收集和保存信息
|
|
187
|
-
4. 在代理循环中有效运行
|
|
188
|
-
5. 高效执行多样化的网页任务
|
|
189
|
-
</intro>
|
|
190
|
-
|
|
191
|
-
<input>
|
|
192
|
-
在每一步,你的输入将包括:
|
|
193
|
-
1. <agent_history>:一个按时间顺序排列的事件流,包括你之前的操作及其结果。
|
|
194
|
-
2. <agent_state>:当前的 <user_request> 和 <step_info>。
|
|
195
|
-
3. <browser_state>:当前 URL、页面标题、可交互元素总数以及语义化 YAML 树。
|
|
196
|
-
</input>
|
|
197
|
-
|
|
198
|
-
<browser_state>
|
|
199
|
-
|
|
200
|
-
浏览器状态包含以下内容:
|
|
201
|
-
|
|
202
|
-
- url: 当前查看页面的 URL。
|
|
203
|
-
- title: 当前查看页面的标题。
|
|
204
|
-
- 可交互元素总数:带有 \`#N\` 标记的元素数量。
|
|
205
|
-
- YAML 树:页面的语义化结构,格式如下:
|
|
206
|
-
|
|
207
|
-
\`\`\`yaml
|
|
208
|
-
- region:
|
|
209
|
-
- main:
|
|
210
|
-
- button #9 [cursor=pointer] "产品文档"
|
|
211
|
-
- button #47 [selected] [cursor=pointer] "40元/月 2核CPU 2GB内存"
|
|
212
|
-
- radio #53 [checked] [cursor=pointer] "自动生成密码"
|
|
213
|
-
- button #74 [cursor=pointer] "立即购买"
|
|
214
|
-
- generic #6 [cf-uba="serviceList..Flexus云服务"] "Flexus云服务"
|
|
215
|
-
\`\`\`
|
|
216
|
-
|
|
217
|
-
节点格式说明:
|
|
218
|
-
- \`- role #N [token1] [token2] "accessible name"\`
|
|
219
|
-
- \`role\`:ARIA 语义角色(如 button/link/radio/heading/listitem/generic 等)
|
|
220
|
-
- \`#N\`:可交互元素的唯一操作索引,**只有带 \`#N\` 的节点才能被操作**,操作时将 N 作为 \`index\` 参数传入
|
|
221
|
-
- \`[token]\`:可选 token,包括状态标记(如 \`[checked]\` \`[selected]\` \`[pressed]\` \`[current]\` \`[expanded]\` \`[disabled]\` \`[readonly]\` \`[required]\` \`[invalid]\` \`[busy]\` \`[error]\` \`[warning]\` \`[cursor=pointer]\`)和定制属性(如 \`[cf-uba="..."]\`)
|
|
222
|
-
- \`"accessible name"\`:元素的语义化名称,**用双引号包裹**(通过 aria-label/aria-labelledby/innerText 等计算得出);无名称的节点此字段省略
|
|
223
|
-
- 缩进表示父子关系
|
|
224
|
-
|
|
225
|
-
</browser_state>
|
|
226
|
-
|
|
227
|
-
<responseMode>
|
|
228
|
-
|
|
229
|
-
\`page-agent-tool\` 支持 \`responseMode\` 参数,用于控制操作后返回的页面状态形式:
|
|
230
|
-
|
|
231
|
-
- **\`diff\`**(默认):仅返回自上一次状态以来的增量 DOM 差异,极大节省 Token。
|
|
232
|
-
- **\`full\`**:返回当前视口中完整的语义化 ARIA YAML 树。
|
|
233
|
-
- **\`both\`**:同时返回全量树和增量差异。
|
|
234
|
-
|
|
235
|
-
执行 \`click\`、\`fill\`、\`select\`、\`scroll\` 操作后,工具默认自动以 \`diff\` 模式返回最新页面状态,无需再次手动调用 \`browserState\`。
|
|
236
|
-
|
|
237
|
-
</responseMode>
|
|
238
|
-
|
|
239
|
-
<browser_state_diff>
|
|
240
|
-
|
|
241
|
-
在交互过程中,为了提高效率和减少上下文占用,工具会生成页面的增量差异(Diff)信息。
|
|
242
|
-
Diff 格式示例如下:
|
|
243
|
-
\`\`\`diff
|
|
244
|
-
- button #9: 产品文档
|
|
245
|
-
+ button #9: 产品文档 (已点击)
|
|
246
|
-
\`\`\`
|
|
247
|
-
或者,当页面结构发生改变时,会展示新增或移除的节点差异。
|
|
248
|
-
|
|
249
|
-
### 页面状态获取四原则(重要,请严格遵守):
|
|
250
|
-
|
|
251
|
-
> 与业界 AI 编辑器(Cursor / Windsurf)按需读取文件而非全量加载的理念完全一致——**先精准搜索,再按需拉取全量**,将发送给大模型的 token 降至最低。
|
|
252
|
-
|
|
253
|
-
1. **按关键词精准搜索(最高优先级)**:当你已知要找什么类型的元素(如按钮、输入框、特定名称的链接)时,**优先使用 \`searchTree\` 动作**,传入 role 名称、元素文本或状态关键词搜索。它只返回命中行和上下文,token 消耗比全量树减少 80%+。
|
|
254
|
-
- 示例:查找所有按钮 → \`{"action": "searchTree", "query": "button"}\`
|
|
255
|
-
- 示例:查找含"提交"文本的节点 → \`{"action": "searchTree", "query": "提交"}\`
|
|
256
|
-
- 示例:查找已勾选的复选框 → \`{"action": "searchTree", "query": "checked"}\`
|
|
257
|
-
- 示例:精确定位某个 ref → \`{"action": "searchTree", "query": "#5"}\`
|
|
258
|
-
2. **首次获取全量**:首次进入页面、页面发生重大刷新、或 \`searchTree\` 无法找到所需信息时,调用 \`browserState\` 并指定 \`responseMode\` 为 \`full\` 或 \`both\` 获取完整 A11y 树。
|
|
259
|
-
3. **增量优先**:执行 \`click\`、\`fill\`、\`select\`、\`scroll\` 操作后,工具默认自动返回 \`diff\` 增量信息。优先阅读这些 Diff,以便快速确认操作是否生效。
|
|
260
|
-
4. **按需拉取全量**:如果增量 Diff 不足以支持下一步操作,或需要寻找不在 Diff 中的 \`#N\` 节点,且 \`searchTree\` 也无法定位时,再显式调用 \`browserState\` 拉取完整树。
|
|
261
|
-
|
|
262
|
-
</browser_state_diff>
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
<browser_rules>
|
|
267
|
-
在使用浏览器和浏览网页时严格遵守以下规则:
|
|
268
|
-
|
|
269
|
-
- 仅与分配有 \`#N\` 索引的元素进行交互,将 N 作为 \`index\` 参数传入。
|
|
270
|
-
- 仅使用明确出现在树中的 \`#N\` 索引,切勿猜测或沿用过期索引。
|
|
271
|
-
- 每次操作后 \`#N\` 索引会重新分配,不要使用旧的索引。
|
|
272
|
-
- 如果页面在执行操作后发生变化(例如输入文本操作),分析是否需要与新元素进行交互,例如从列表中选择正确的选项。
|
|
273
|
-
- 默认情况下,仅列出可见视口中的元素。如果你怀疑需要交互的相关内容在屏幕外,请使用滚动操作。仅在页面下方或上方还有更多像素时才滚动。
|
|
274
|
-
- 你可以使用 num_pages 参数滚动特定页数(例如,0.5 表示半页,2.0 表示两页)。
|
|
275
|
-
- 如果出现验证码,告诉用户你无法解决验证码。完成任务并请用户解决它。
|
|
276
|
-
- 如果缺少预期元素,尝试滚动或导航回退。
|
|
277
|
-
- 除非某些条件发生变化,否则不要重复同一操作超过 3 次。
|
|
278
|
-
- 如果你向输入字段填充文本且操作序列被中断,通常意味着某些内容发生了变化,例如下拉建议弹出。
|
|
279
|
-
- 如果 <user_request> 包含特定的页面信息,如产品类型、评分、价格、位置等,尝试应用过滤器以提高效率。
|
|
280
|
-
- <user_request> 是最终目标。如果用户指定了明确的步骤,它们始终具有最高优先级。
|
|
281
|
-
- 如果你向字段输入文本,可能需要按回车键、点击搜索按钮或从下拉列表中选择以完成操作。
|
|
282
|
-
- **不要通过 executeJavascript 向页面插入 DOM 元素**(如创建 div 显示调试信息)。这会污染页面结构并影响后续操作。如需读取数据,使用 return 语句返回结果即可。
|
|
283
|
-
- 如果操作返回中出现 \`[校验提示]\`,说明页面有表单校验错误未通过,请先根据提示修复错误后再继续操作。
|
|
284
|
-
- 如果操作后页面没有发生预期变化,优先检查是否有 \`[校验提示]\` 或 \`[error]\` token 的错误信息,而非重复操作。
|
|
285
|
-
- 如果不需要,不要登录页面。如果没有凭据,不要登录。
|
|
286
|
-
- 有两种类型的任务,首先思考你正在处理哪种类型的请求:
|
|
287
|
-
|
|
288
|
-
1. 非常具体的逐步说明:
|
|
289
|
-
|
|
290
|
-
- 非常精确地遵循它们,不要跳过步骤。尝试按要求完成所有内容。
|
|
291
|
-
|
|
292
|
-
2. 开放式任务。自己规划,在实现目标时保持创造性。
|
|
293
|
-
|
|
294
|
-
- 如果在开放式任务中陷入困境(例如登录或验证码),可以重新评估任务并尝试替代方法,例如有时即使页面的某些部分可访问或通过 Web 搜索获取一些信息,也会意外弹出登录框。
|
|
295
|
-
</browser_rules>
|
|
296
|
-
|
|
297
|
-
<capability>
|
|
298
|
-
- 你只能处理单页应用。不要跳出当前页面。
|
|
299
|
-
- 如果链接将在新页面中打开(例如,<a target="_blank">),不要点击该链接。
|
|
300
|
-
- 任务失败是可以接受的。
|
|
301
|
-
- 用户可能是错的。如果用户的请求无法实现、不适当,或者你没有足够的信息或工具来实现它。告诉用户提出更好的请求。
|
|
302
|
-
- 网页可能已损坏。所有网页或应用都有 bug。有些 bug 会使你的工作变得困难。鼓励你告诉用户当前页面的问题。你的反馈(包括失败)对用户很有价值。
|
|
303
|
-
- 过于努力可能有害。来回重复某些操作或在知识有限的情况下推动复杂程序可能导致不良结果和有害副作用。用户宁愿你以失败告终完成任务。
|
|
304
|
-
- 如果你对当前网页或任务没有相关知识。你必须要求用户提供具体说明和详细步骤。
|
|
305
|
-
</capability>
|
|
306
|
-
|
|
307
|
-
<task_completion_rules>
|
|
308
|
-
你必须在以下情况时结束任务:
|
|
309
|
-
|
|
310
|
-
- 当你完全完成用户请求时。
|
|
311
|
-
- 当你感到困惑或无法解决用户请求时。或者用户请求不清楚或包含不当内容。
|
|
312
|
-
- 如果绝对不可能继续。
|
|
313
|
-
|
|
314
|
-
</task_completion_rules>
|
|
315
|
-
`;function isHTMLElement(t){return!!t&&t.nodeType===1}function isInputElement(t){return t?.nodeType===1&&t.tagName==="INPUT"}function isTextAreaElement(t){return t?.nodeType===1&&t.tagName==="TEXTAREA"}function isSelectElement(t){return t?.nodeType===1&&t.tagName==="SELECT"}function isAnchorElement(t){return t?.nodeType===1&&t.tagName==="A"}function getIframeOffset(t){const e=t.ownerDocument.defaultView?.frameElement;if(!e)return{x:0,y:0};const r=e.getBoundingClientRect();return{x:r.left,y:r.top}}function getNativeValueSetter(t){return Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t),"value").set}async function waitFor(t){await new Promise(e=>setTimeout(e,t*1e3))}async function movePointerToElement(t,e,r){const n=getIframeOffset(t);window.dispatchEvent(new CustomEvent("PageAgent::MovePointerTo",{detail:{x:e+n.x,y:r+n.y}})),await waitFor(.3)}async function clickPointer(){window.dispatchEvent(new CustomEvent("PageAgent::ClickPointer"))}async function enablePassThrough(){window.dispatchEvent(new CustomEvent("PageAgent::EnablePassThrough"))}async function disablePassThrough(){window.dispatchEvent(new CustomEvent("PageAgent::DisablePassThrough"))}function getElementByIndex(t,e){const r=t.get(e);if(!r)throw new Error(`No interactive element found at index ${e}`);const n=r.ref;if(!n)throw new Error(`Element at index ${e} does not have a reference`);if(!isHTMLElement(n))throw new Error(`Element at index ${e} is not an HTMLElement`);return n}var lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&(lastClickedElement.dispatchEvent(new PointerEvent("pointerout",{bubbles:!0})),lastClickedElement.dispatchEvent(new PointerEvent("pointerleave",{bubbles:!1})),lastClickedElement.dispatchEvent(new MouseEvent("mouseout",{bubbles:!0})),lastClickedElement.dispatchEvent(new MouseEvent("mouseleave",{bubbles:!1})),lastClickedElement.blur(),lastClickedElement=null)}async function clickElement(t){blurLastClickedElement(),lastClickedElement=t,await scrollIntoViewIfNeeded(t);const e=t.ownerDocument.defaultView?.frameElement;e&&await scrollIntoViewIfNeeded(e);const r=t.getBoundingClientRect(),n=r.left+r.width/2,i=r.top+r.height/2;await movePointerToElement(t,n,i),await clickPointer(),await waitFor(.1);const o=t.ownerDocument;await enablePassThrough();const s=o.elementFromPoint(n,i);await disablePassThrough();const a=s instanceof HTMLElement&&t.contains(s)?s:t,l={bubbles:!0,cancelable:!0,clientX:n,clientY:i,pointerType:"mouse"},c={bubbles:!0,cancelable:!0,clientX:n,clientY:i,button:0};a.dispatchEvent(new PointerEvent("pointerover",l)),a.dispatchEvent(new PointerEvent("pointerenter",{...l,bubbles:!1})),a.dispatchEvent(new MouseEvent("mouseover",c)),a.dispatchEvent(new MouseEvent("mouseenter",{...c,bubbles:!1})),a.dispatchEvent(new PointerEvent("pointerdown",l)),a.dispatchEvent(new MouseEvent("mousedown",c)),t.focus({preventScroll:!0}),a.dispatchEvent(new PointerEvent("pointerup",l)),a.dispatchEvent(new MouseEvent("mouseup",c)),a.click(),await waitFor(.2)}async function inputTextElement(t,e){const r=t.isContentEditable;if(!isInputElement(t)&&!isTextAreaElement(t)&&!r)throw new Error("Element is not an input, textarea, or contenteditable");if(await clickElement(t),r){if(t.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"deleteContent"}))&&(t.innerText="",t.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"deleteContent"}))),t.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e}))&&(t.innerText=e,t.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"insertText",data:e}))),t.innerText.trim()!==e.trim()){t.focus();const n=t.ownerDocument,i=(n.defaultView||window).getSelection(),o=n.createRange();o.selectNodeContents(t),i?.removeAllRanges(),i?.addRange(o),n.execCommand("delete",!1),n.execCommand("insertText",!1,e)}t.dispatchEvent(new Event("change",{bubbles:!0})),t.blur()}else getNativeValueSetter(t).call(t,e);r||t.dispatchEvent(new Event("input",{bubbles:!0})),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(t,e){if(!isSelectElement(t))throw new Error("Element is not a select element");const r=Array.from(t.options).find(n=>n.textContent?.trim()===e.trim());if(!r)throw new Error(`Option with text "${e}" not found in select element`);t.value=r.value,t.dispatchEvent(new Event("change",{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(t){const e=t;typeof e.scrollIntoViewIfNeeded=="function"?e.scrollIntoViewIfNeeded():t.scrollIntoView({behavior:"auto",block:"center",inline:"nearest"})}async function scrollVertically(t,e){if(e){const s=e;let a=s,l=!1,c=null,u=0,h=0;const f=t;for(;a&&h<10;){const g=window.getComputedStyle(a),b=/(auto|scroll|overlay)/.test(g.overflowY)||g.scrollbarWidth&&g.scrollbarWidth!=="auto"||g.scrollbarGutter&&g.scrollbarGutter!=="auto",P=a.scrollHeight>a.clientHeight;if(b&&P){const w=a.scrollTop,p=a.scrollHeight-a.clientHeight;let m=f/3;m>0?m=Math.min(m,p-w):m=Math.max(m,-w),a.scrollTop=w+m;const A=a.scrollTop-w;if(Math.abs(A)>.5){l=!0,c=a,u=A;break}}if(a===document.body||a===document.documentElement)break;a=a.parentElement,h++}return l?`Scrolled container (${c?.tagName}) by ${u}px`:`No scrollable container found for element (${s.tagName})`}const r=t,n=s=>s.clientHeight>=window.innerHeight*.5,i=s=>!!(s&&/(auto|scroll|overlay)/.test(getComputedStyle(s).overflowY)&&s.scrollHeight>s.clientHeight&&n(s));let o=document.activeElement;for(;o&&!i(o)&&o!==document.body;)o=o.parentElement;if(o=i(o)?o:Array.from(document.querySelectorAll("*")).find(i)||document.scrollingElement||document.documentElement,o===document.scrollingElement||o===document.documentElement||o===document.body){const s=window.scrollY,a=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,r);const l=window.scrollY,c=l-s;if(Math.abs(c)<1)return r>0?"⚠️ Already at the bottom of the page, cannot scroll down further.":"⚠️ Already at the top of the page, cannot scroll up further.";const u=r>0&&l>=a-1,h=r<0&&l<=1;return u?`✅ Scrolled page by ${c}px. Reached the bottom of the page.`:h?`✅ Scrolled page by ${c}px. Reached the top of the page.`:`✅ Scrolled page by ${c}px.`}else{const s="The document is not scrollable. Falling back to container scroll.";console.log(`[PageController] ${s}`);const a=o.scrollTop,l=o.scrollHeight-o.clientHeight;o.scrollBy({top:r,behavior:"smooth"}),await waitFor(.1);const c=o.scrollTop,u=c-a;if(Math.abs(u)<1)return r>0?`⚠️ ${s} Already at the bottom of container (${o.tagName}), cannot scroll down further.`:`⚠️ ${s} Already at the top of container (${o.tagName}), cannot scroll up further.`;const h=r>0&&c>=l-1,f=r<0&&c<=1;return h?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the bottom.`:f?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the top.`:`✅ ${s} Scrolled container (${o.tagName}) by ${u}px.`}}async function scrollHorizontally(t,e){if(e){const s=e;let a=s,l=!1,c=null,u=0,h=0;const f=t;for(;a&&h<10;){const g=window.getComputedStyle(a),b=/(auto|scroll|overlay)/.test(g.overflowX)||g.scrollbarWidth&&g.scrollbarWidth!=="auto"||g.scrollbarGutter&&g.scrollbarGutter!=="auto",P=a.scrollWidth>a.clientWidth;if(b&&P){const w=a.scrollLeft,p=a.scrollWidth-a.clientWidth;let m=f/3;m>0?m=Math.min(m,p-w):m=Math.max(m,-w),a.scrollLeft=w+m;const A=a.scrollLeft-w;if(Math.abs(A)>.5){l=!0,c=a,u=A;break}}if(a===document.body||a===document.documentElement)break;a=a.parentElement,h++}return l?`Scrolled container (${c?.tagName}) horizontally by ${u}px`:`No horizontally scrollable container found for element (${s.tagName})`}const r=t,n=s=>s.clientWidth>=window.innerWidth*.5,i=s=>!!(s&&/(auto|scroll|overlay)/.test(getComputedStyle(s).overflowX)&&s.scrollWidth>s.clientWidth&&n(s));let o=document.activeElement;for(;o&&!i(o)&&o!==document.body;)o=o.parentElement;if(o=i(o)?o:Array.from(document.querySelectorAll("*")).find(i)||document.scrollingElement||document.documentElement,o===document.scrollingElement||o===document.documentElement||o===document.body){const s=window.scrollX,a=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(r,0);const l=window.scrollX,c=l-s;if(Math.abs(c)<1)return r>0?"⚠️ Already at the right edge of the page, cannot scroll right further.":"⚠️ Already at the left edge of the page, cannot scroll left further.";const u=r>0&&l>=a-1,h=r<0&&l<=1;return u?`✅ Scrolled page by ${c}px. Reached the right edge of the page.`:h?`✅ Scrolled page by ${c}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${c}px.`}else{const s="The document is not scrollable. Falling back to container scroll.";console.log(`[PageController] ${s}`);const a=o.scrollLeft,l=o.scrollWidth-o.clientWidth;o.scrollBy({left:r,behavior:"smooth"}),await waitFor(.1);const c=o.scrollLeft,u=c-a;if(Math.abs(u)<1)return r>0?`⚠️ ${s} Already at the right edge of container (${o.tagName}), cannot scroll right further.`:`⚠️ ${s} Already at the left edge of container (${o.tagName}), cannot scroll left further.`;const h=r>0&&c>=l-1,f=r<0&&c<=1;return h?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the right edge.`:f?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the left edge.`:`✅ ${s} Scrolled container (${o.tagName}) horizontally by ${u}px.`}}var dom_tree_default=(t={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:e,interactiveWhitelist:r,highlightOpacity:n,highlightLabelOpacity:i}=t,{doHighlightElements:o,focusHighlightIndex:s,viewportExpansion:a,debugMode:l}=t;let c=0;const u=new WeakMap;function h(d,x){!d||d.nodeType!==Node.ELEMENT_NODE||u.set(d,{...u.get(d),...x})}const f={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{f.boundingRects=new WeakMap,f.clientRects=new WeakMap,f.computedStyles=new WeakMap}};function g(d){if(!d)return null;if(f.boundingRects.has(d))return f.boundingRects.get(d);const x=d.getBoundingClientRect();return x&&f.boundingRects.set(d,x),x}function b(d){if(!d)return null;if(f.computedStyles.has(d))return f.computedStyles.get(d);const x=window.getComputedStyle(d);return x&&f.computedStyles.set(d,x),x}function P(d){if(!d)return null;if(f.clientRects.has(d))return f.clientRects.get(d);const x=d.getClientRects();return x&&f.clientRects.set(d,x),x}const w={},p={current:0},m="playwright-highlight-container";function A(d,x,U=null){if(!d)return x;const _=[];let I=null,z=20,C=16,M=null;try{let O=document.getElementById(m);O||(O=document.createElement("div"),O.id=m,O.style.position="fixed",O.style.pointerEvents="none",O.style.top="0",O.style.left="0",O.style.width="100%",O.style.height="100%",O.style.zIndex="2147483640",O.style.backgroundColor="transparent",document.body.appendChild(O));const F=d.getClientRects();if(!F||F.length===0)return x;const Y=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];let W=Y[x%Y.length];const ee=W+Math.floor(n*255).toString(16).padStart(2,"0");W=W+Math.floor(i*255).toString(16).padStart(2,"0");let J={x:0,y:0};if(U){const S=U.getBoundingClientRect();J.x=S.left,J.y=S.top}const ae=document.createDocumentFragment();for(const S of F){if(S.width===0||S.height===0)continue;const v=document.createElement("div");v.style.position="fixed",v.style.border=`2px solid ${W}`,v.style.backgroundColor=ee,v.style.pointerEvents="none",v.style.boxSizing="border-box";const y=S.top+J.y,L=S.left+J.x;v.style.top=`${y}px`,v.style.left=`${L}px`,v.style.width=`${S.width}px`,v.style.height=`${S.height}px`,ae.appendChild(v),_.push({element:v,initialRect:S})}const ne=F[0];I=document.createElement("div"),I.className="playwright-highlight-label",I.style.position="fixed",I.style.background=W,I.style.color="white",I.style.padding="1px 4px",I.style.borderRadius="4px",I.style.fontSize=`${Math.min(12,Math.max(8,ne.height/2))}px`,I.textContent=x.toString(),z=I.offsetWidth>0?I.offsetWidth:z,C=I.offsetHeight>0?I.offsetHeight:C;const ue=ne.top+J.y,le=ne.left+J.x;let de=ue+2,E=le+ne.width-z-2;(ne.width<z+4||ne.height<C+4)&&(de=ue-C-2,E=le+ne.width-z,E<J.x&&(E=le)),de=Math.max(0,Math.min(de,window.innerHeight-C)),E=Math.max(0,Math.min(E,window.innerWidth-z)),I.style.top=`${de}px`,I.style.left=`${E}px`,ae.appendChild(I);const $=((S,v)=>{let y=0;return(...L)=>{const N=performance.now();if(!(N-y<v))return y=N,S(...L)}})(()=>{const S=d.getClientRects();let v={x:0,y:0};if(U){const y=U.getBoundingClientRect();v.x=y.left,v.y=y.top}if(_.forEach((y,L)=>{if(L<S.length){const N=S[L],q=N.top+v.y,se=N.left+v.x;y.element.style.top=`${q}px`,y.element.style.left=`${se}px`,y.element.style.width=`${N.width}px`,y.element.style.height=`${N.height}px`,y.element.style.display=N.width===0||N.height===0?"none":"block"}else y.element.style.display="none"}),S.length<_.length)for(let y=S.length;y<_.length;y++)_[y].element.style.display="none";if(I&&S.length>0){const y=S[0],L=y.top+v.y,N=y.left+v.x;let q=L+2,se=N+y.width-z-2;(y.width<z+4||y.height<C+4)&&(q=L-C-2,se=N+y.width-z,se<v.x&&(se=N)),q=Math.max(0,Math.min(q,window.innerHeight-C)),se=Math.max(0,Math.min(se,window.innerWidth-z)),I.style.top=`${q}px`,I.style.left=`${se}px`,I.style.display="block"}else I&&(I.style.display="none")},16);return window.addEventListener("scroll",$,!0),window.addEventListener("resize",$),M=()=>{window.removeEventListener("scroll",$,!0),window.removeEventListener("resize",$),_.forEach(S=>S.element.remove()),I&&I.remove()},O.appendChild(ae),x+1}finally{M&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(M)}}function T(d){if(!d||d.nodeType!==Node.ELEMENT_NODE)return null;const x=b(d);if(!x)return null;const U=x.display;if(U==="inline"||U==="inline-block")return null;const _=x.overflowX,I=x.overflowY,z=x.scrollbarWidth&&x.scrollbarWidth!=="auto"||x.scrollbarGutter&&x.scrollbarGutter!=="auto",C=_==="auto"||_==="scroll",M=I==="auto"||I==="scroll";if(!C&&!M&&!z)return null;const O=d.scrollWidth-d.clientWidth,F=d.scrollHeight-d.clientHeight,Y=4;if(O<Y&&F<Y||!M&&!z&&O<Y||!C&&!z&&F<Y)return null;const W=d.scrollTop,ee=d.scrollLeft,J={top:W,right:d.scrollWidth-d.clientWidth-d.scrollLeft,bottom:d.scrollHeight-d.clientHeight-d.scrollTop,left:ee};return h(d,{scrollable:!0,scrollData:J}),J}function k(d){try{if(a===-1){const C=d.parentElement;if(!C)return!1;try{return C.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const O=window.getComputedStyle(C);return O.display!=="none"&&O.visibility!=="hidden"&&O.opacity!=="0"}}const x=document.createRange();x.selectNodeContents(d);const U=x.getClientRects();if(!U||U.length===0)return!1;let _=!1,I=!1;for(const C of U)if(C.width>0&&C.height>0&&(_=!0,!(C.bottom<-a||C.top>window.innerHeight+a||C.right<-a||C.left>window.innerWidth+a))){I=!0;break}if(!_||!I)return!1;const z=d.parentElement;if(!z)return!1;try{return z.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const M=window.getComputedStyle(z);return M.display!=="none"&&M.visibility!=="hidden"&&M.opacity!=="0"}}catch(x){return console.warn("Error checking text node visibility:",x),!1}}function Z(d){if(!d||!d.tagName)return!1;const x=new Set(["body","div","main","article","section","nav","header","footer"]),U=d.tagName.toLowerCase();return x.has(U)?!0:!new Set(["svg","script","style","link","meta","noscript","template"]).has(U)}function R(d){const x=b(d);return d.offsetWidth>0&&d.offsetHeight>0&&x?.visibility!=="hidden"&&x?.display!=="none"}function V(d){if(!d||d.nodeType!==Node.ELEMENT_NODE||e.includes(d))return!1;if(r.includes(d))return!0;const x=d.tagName.toLowerCase(),U=b(d),_=new Set(["pointer","move","text","grab","grabbing","cell","copy","alias","all-scroll","col-resize","context-menu","crosshair","e-resize","ew-resize","help","n-resize","ne-resize","nesw-resize","ns-resize","nw-resize","nwse-resize","row-resize","s-resize","se-resize","sw-resize","vertical-text","w-resize","zoom-in","zoom-out"]),I=new Set(["not-allowed","no-drop","wait","progress","initial","inherit"]);function z(W){return W.tagName.toLowerCase()==="html"?!1:!!(U?.cursor&&_.has(U.cursor))}if(z(d))return!0;const C=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),M=new Set(["disabled","readonly"]);if(C.has(x)){if(U?.cursor&&I.has(U.cursor))return!1;for(const W of M)if(d.hasAttribute(W)||d.getAttribute(W)==="true"||d.getAttribute(W)==="")return!1;return!(d.disabled||d.readOnly||d.inert)}const O=d.getAttribute("role"),F=d.getAttribute("aria-role");if(d.getAttribute("contenteditable")==="true"||d.isContentEditable||d.classList&&(d.classList.contains("button")||d.classList.contains("dropdown-toggle")||d.getAttribute("data-index")||d.getAttribute("data-toggle")==="dropdown"||d.getAttribute("aria-haspopup")==="true"))return!0;const Y=new Set(["button","menu","menubar","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);if(C.has(x)||O&&Y.has(O)||F&&Y.has(F))return!0;try{if(typeof getEventListeners=="function"){const ee=getEventListeners(d);for(const J of["click","mousedown","mouseup","dblclick"])if(ee[J]&&ee[J].length>0)return!0}const W=d?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof W=="function"){const ee=W(d);for(const J of["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"])for(const ae of ee)if(ae.type===J)return!0}for(const ee of["onclick","onmousedown","onmouseup","ondblclick"])if(d.hasAttribute(ee)||typeof d[ee]=="function")return!0}catch{}return!!T(d)}function j(d){if(a===-1)return!0;const x=P(d);if(!x||x.length===0)return!1;let U=!1;for(const C of x)if(C.width>0&&C.height>0&&!(C.bottom<-a||C.top>window.innerHeight+a||C.right<-a||C.left>window.innerWidth+a)){U=!0;break}if(!U)return!1;if(d.ownerDocument!==window.document)return!0;let _=Array.from(x).find(C=>C.width>0&&C.height>0);if(!_)return!1;const I=d.getRootNode();if(I instanceof ShadowRoot){const C=_.left+_.width/2,M=_.top+_.height/2;try{const O=I.elementFromPoint(C,M);if(!O)return!1;let F=O;for(;F&&F!==I;){if(F===d)return!0;F=F.parentElement}return!1}catch{return!0}}const z=5;return[{x:_.left+_.width/2,y:_.top+_.height/2},{x:_.left+z,y:_.top+z},{x:_.right-z,y:_.bottom-z}].some(({x:C,y:M})=>{try{const O=document.elementFromPoint(C,M);if(!O)return!1;let F=O;for(;F&&F!==document.documentElement;){if(F===d)return!0;F=F.parentElement}return!1}catch{return!0}})}function H(d,x){if(x===-1)return!0;const U=d.getClientRects();if(!U||U.length===0){const _=g(d);return!_||_.width===0||_.height===0?!1:!(_.bottom<-x||_.top>window.innerHeight+x||_.right<-x||_.left>window.innerWidth+x)}for(const _ of U)if(!(_.width===0||_.height===0)&&!(_.bottom<-x||_.top>window.innerHeight+x||_.right<-x||_.left>window.innerWidth+x))return!0;return!1}const B=["aria-expanded","aria-checked","aria-selected","aria-pressed","aria-haspopup","aria-controls","aria-owns","aria-activedescendant","aria-valuenow","aria-valuetext","aria-valuemax","aria-valuemin","aria-autocomplete"];function G(d){for(let x=0;x<B.length;x++)if(d.hasAttribute(B[x]))return!0;return!1}function ie(d){if(!d||d.nodeType!==Node.ELEMENT_NODE)return!1;const x=d.tagName.toLowerCase();return new Set(["a","button","input","select","textarea","details","summary","label"]).has(x)?!0:d.hasAttribute("onclick")||d.hasAttribute("role")||d.hasAttribute("tabindex")||G(d)||d.hasAttribute("data-action")||d.getAttribute("contenteditable")==="true"}const X=new Set(["a","button","input","select","textarea","summary","details","label","option","li"]),te=new Set(["button","link","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","listitem","treeitem","row","option","scrollbar"]);function oe(d){if(!d||d.nodeType!==Node.ELEMENT_NODE||!R(d))return!1;const x=d.hasAttribute("role")||d.hasAttribute("tabindex")||d.hasAttribute("onclick")||typeof d.onclick=="function",U=/\b(btn|clickable|menu|item|entry|link)\b/i.test(d.className||""),_=!!d.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar'),I=[...d.children].some(R),z=d.parentElement&&d.parentElement.isSameNode(document.body);return(V(d)||x||U)&&I&&_&&!z}function re(d){if(!d||d.nodeType!==Node.ELEMENT_NODE)return!1;const x=d.tagName.toLowerCase(),U=d.getAttribute("role");if(x==="iframe"||X.has(x)||U&&te.has(U)||d.isContentEditable||d.getAttribute("contenteditable")==="true"||d.hasAttribute("data-testid")||d.hasAttribute("data-cy")||d.hasAttribute("data-test")||d.hasAttribute("onclick")||typeof d.onclick=="function"||G(d))return!0;try{const _=d?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof _=="function"){const I=_(d);for(const z of["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"])for(const C of I)if(C.type===z)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(I=>d.hasAttribute(I)))return!0}catch{}return!!(oe(d)||u.get(d)?.scrollable)}function Q(d,x,U,_){if(!d.isInteractive)return!1;let I=!1;return _?re(x)?I=!0:I=!1:I=!0,I&&(d.isInViewport=H(x,a),(d.isInViewport||a===-1)&&(d.highlightIndex=c++,o))?(s>=0?s===d.highlightIndex&&A(x,d.highlightIndex,U):A(x,d.highlightIndex,U),!0):!1}function K(d,x=null,U=!1){if(!d||d.id===m||d.nodeType!==Node.ELEMENT_NODE&&d.nodeType!==Node.TEXT_NODE||!d||d.id===m||d.dataset?.browserUseIgnore==="true"||d.dataset?.pageAgentIgnore==="true"||d.getAttribute&&d.getAttribute("aria-hidden")==="true")return null;if(d===document.body){const C={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const O of d.childNodes){const F=K(O,x,!1);F&&C.children.push(F)}const M=`${p.current++}`;return w[M]=C,M}if(d.nodeType!==Node.ELEMENT_NODE&&d.nodeType!==Node.TEXT_NODE)return null;if(d.nodeType===Node.TEXT_NODE){const C=d.textContent?.trim();if(!C)return null;const M=d.parentElement;if(!M||M.tagName.toLowerCase()==="script")return null;const O=`${p.current++}`;return w[O]={type:"TEXT_NODE",text:C,isVisible:k(d)},O}if(d.nodeType===Node.ELEMENT_NODE&&!Z(d))return null;if(a!==-1&&!d.shadowRoot){const C=g(d),M=b(d),O=M&&(M.position==="fixed"||M.position==="sticky"),F=d.offsetWidth>0||d.offsetHeight>0;if(!C||!O&&!F&&(C.bottom<-a||C.top>window.innerHeight+a||C.right<-a||C.left>window.innerWidth+a))return null}const _={tagName:d.tagName.toLowerCase(),attributes:{},children:[]};if(ie(d)||d.tagName.toLowerCase()==="iframe"||d.tagName.toLowerCase()==="body"){const C=d.getAttributeNames?.()||[];for(const M of C){const O=d.getAttribute(M);_.attributes[M]=O}d.tagName.toLowerCase()==="input"&&(d.type==="checkbox"||d.type==="radio")&&(_.attributes.checked=d.checked?"true":"false")}let I=!1;if(d.nodeType===Node.ELEMENT_NODE&&(_.isVisible=R(d),_.isVisible)){_.isTopElement=j(d);const C=d.getAttribute("role"),M=C==="menu"||C==="menubar"||C==="listbox";if((_.isTopElement||M)&&(_.isInteractive=V(d),I=Q(_,d,x,U),_.ref=d,_.isInteractive&&Object.keys(_.attributes).length===0)){const O=d.getAttributeNames?.()||[];for(const F of O){const Y=d.getAttribute(F);_.attributes[F]=Y}}}if(d.tagName){const C=d.tagName.toLowerCase();if(C==="iframe")try{const M=d.contentDocument||d.contentWindow?.document;if(M)for(const O of M.childNodes){const F=K(O,d,!1);F&&_.children.push(F)}}catch(M){console.warn("Unable to access iframe:",M)}else if(d.isContentEditable||d.getAttribute("contenteditable")==="true"||d.id==="tinymce"||d.classList.contains("mce-content-body")||C==="body"&&d.getAttribute("data-id")?.startsWith("mce_"))for(const M of d.childNodes){const O=K(M,x,I);O&&_.children.push(O)}else{if(d.shadowRoot){_.shadowRoot=!0;for(const M of d.shadowRoot.childNodes){const O=K(M,x,I);O&&_.children.push(O)}}for(const M of d.childNodes){const O=K(M,x,I||U);O&&_.children.push(O)}}}if(_.tagName==="a"&&_.children.length===0&&!_.attributes.href){const C=g(d);if(!(C&&C.width>0&&C.height>0||d.offsetWidth>0||d.offsetHeight>0))return null}_.extra=u.get(d)||null;const z=`${p.current++}`;return w[z]=_,z}const ce=K(document.body);return f.clearCache(),{rootId:ce,map:w}},DEFAULT_VIEWPORT_EXPANSION=-1;function resolveViewportExpansion(t){return t??DEFAULT_VIEWPORT_EXPANSION}var SEMANTIC_TAGS=new Set(["nav","menu","header","footer","aside","dialog"]),newElementsCache=new WeakMap;function getFlatTree(t){const e=resolveViewportExpansion(t.viewportExpansion),r=[];for(const s of t.interactiveBlacklist||[])typeof s=="function"?r.push(s()):r.push(s);const n=[];for(const s of t.interactiveWhitelist||[])typeof s=="function"?n.push(s()):n.push(s);const i=dom_tree_default({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:e,interactiveBlacklist:r,interactiveWhitelist:n,highlightOpacity:t.highlightOpacity??0,highlightLabelOpacity:t.highlightLabelOpacity??.1}),o=window.location.href;for(const s in i.map){const a=i.map[s];if(a.isInteractive&&a.ref){const l=a.ref;newElementsCache.has(l)||(newElementsCache.set(l,o),a.isNew=!0)}}return i}var globRegexCache=new Map;function globToRegex(t){let e=globRegexCache.get(t);if(!e){const r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");e=new RegExp(`^${r.replace(/\*/g,".*")}$`),globRegexCache.set(t,e)}return e}function matchAttributes(t,e){const r={};for(const n of e)if(n.includes("*")){const i=globToRegex(n);for(const o of Object.keys(t))i.test(o)&&t[o].trim()&&(r[o]=t[o].trim())}else{const i=t[n];i&&i.trim()&&(r[n]=i.trim())}return r}function flatTreeToString(t,e=[],r=!1){const n=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","id","for","target","aria-haspopup","aria-controls","aria-owns","contenteditable"],i=[...e,...n],o=(f,g)=>f.length>g?f.substring(0,g)+"...":f,s=f=>{const g=t.map[f];if(!g)return null;if(g.type==="TEXT_NODE"){const b=g;return{type:"text",text:b.text,isVisible:b.isVisible,parent:null,children:[]}}else{const b=g,P=[];if(b.children)for(const w of b.children){const p=s(w);p&&(p.parent=null,P.push(p))}return{type:"element",tagName:b.tagName,attributes:b.attributes??{},isVisible:b.isVisible??!1,isInteractive:b.isInteractive??!1,isTopElement:b.isTopElement??!1,isNew:b.isNew??!1,highlightIndex:b.highlightIndex,parent:null,children:P,extra:b.extra??{}}}},a=(f,g=null)=>{f.parent=g;for(const b of f.children)a(b,f)},l=s(t.rootId);if(!l)return"";a(l);const c=f=>{let g=f.parent;for(;g;){if(g.type==="element"&&g.highlightIndex!==void 0)return!0;g=g.parent}return!1},u=(f,g,b)=>{let P=g;const w=" ".repeat(g);if(f.type==="element"){const p=r&&f.tagName&&SEMANTIC_TAGS.has(f.tagName);if(f.highlightIndex!==void 0){P+=1;const T=getAllTextTillNextClickableElement(f);let k="";if(i.length>0&&f.attributes){const R=matchAttributes(f.attributes,i),V=Object.keys(R);if(V.length>1){const j=new Set,H={};for(const B of V){const G=R[B];G.length>5&&(G in H?j.add(B):H[G]=B)}for(const B of j)delete R[B]}R.role===f.tagName&&delete R.role;for(const j of["aria-label","placeholder","title"])R[j]&&R[j].toLowerCase().trim()===T.toLowerCase().trim()&&delete R[j];Object.keys(R).length>0&&(k=Object.entries(R).map(([j,H])=>`${j}=${o(H,20)}`).join(" "))}let Z=`${w}${f.isNew?`*[${f.highlightIndex}]`:`[${f.highlightIndex}]`}<${f.tagName??""}`;if(k&&(Z+=` ${k}`),f.extra&&f.extra.scrollable){let R="";f.extra.scrollData?.left&&(R+=`left=${f.extra.scrollData.left}, `),f.extra.scrollData?.top&&(R+=`top=${f.extra.scrollData.top}, `),f.extra.scrollData?.right&&(R+=`right=${f.extra.scrollData.right}, `),f.extra.scrollData?.bottom&&(R+=`bottom=${f.extra.scrollData.bottom}`),Z+=` data-scrollable="${R}"`}if(T){const R=T.trim();k||(Z+=" "),Z+=`>${R}`}else k||(Z+=" ");Z+=" />",b.push(Z)}const m=p&&f.highlightIndex===void 0,A=m?b.length:-1;m&&(b.push(`${w}<${f.tagName}>`),P+=1);for(const T of f.children)u(T,P,b);m&&(b.length===A+1?b.pop():b.push(`${w}</${f.tagName}>`))}else if(f.type==="text"){if(c(f))return;f.parent&&f.parent.type==="element"&&f.parent.isVisible&&f.parent.isTopElement&&b.push(`${w}${f.text??""}`)}},h=[];return u(l,0,h),h.join(`
|
|
176
|
+
]`;continue}i+=n[l],n[l]==="\\"?o=!0:s&&n[l]==="]"?s=!1:!s&&n[l]==="["&&(s=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return i}function parseRecordDef(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,i)=>({...n,[i]:parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??parseAnyDef(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){const{type:n,...i}=parseStringDef(t.keyType._def,e);return{...r,propertyNames:i}}else{if(t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...i}=parseBrandedDef(t.keyType._def,e);return{...r,propertyNames:i}}}return r}function parseMapDef(t,e){if(e.mapStrategy==="record")return parseRecordDef(t,e);const r=parseDef(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||parseAnyDef(e),n=parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||parseAnyDef(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function parseNativeEnumDef(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),i=Array.from(new Set(n.map(o=>typeof o)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function parseNeverDef(t){return t.target==="openAi"?void 0:{not:parseAnyDef({...t,currentPath:[...t.currentPath,"not"]})}}function parseNullDef(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(t,e){if(e.target==="openApi3")return asAnyOf(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in primitiveMappings&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((i,o)=>{const s=primitiveMappings[o._def.typeName];return s&&!i.includes(s)?[...i,s]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((i,o)=>{const s=typeof o._def.value;switch(s){case"string":case"number":case"boolean":return[...i,s];case"bigint":return[...i,"integer"];case"object":if(o._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(n.length===r.length){const i=n.filter((o,s,a)=>a.indexOf(o)===s);return{type:i.length>1?i:i[0],enum:r.reduce((o,s)=>o.includes(s._def.value)?o:[...o,s._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(o=>!n.includes(o))],[])};return asAnyOf(t,e)}const asAnyOf=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,i)=>parseDef(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function parseNullableDef(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:primitiveMappings[t.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=parseDef(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=parseDef(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function parseNumberDef(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",addErrorMessage(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"minimum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"maximum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors(r,"maximum",n.value,n.message,e));break;case"multipleOf":setResponseValueAndErrors(r,"multipleOf",n.value,n.message,e);break}return r}function parseObjectDef(t,e){const r=e.target==="openAi",n={type:"object",properties:{}},i=[],o=t.shape();for(const a in o){let l=o[a];if(l===void 0||l._def===void 0)continue;let c=safeIsOptional(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=parseDef(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,c||i.push(a))}i.length&&(n.required=i);const s=decideAdditionalProperties(t,e);return s!==void 0&&(n.additionalProperties=s),n}function decideAdditionalProperties(t,e){if(t.catchall._def.typeName!=="ZodNever")return parseDef(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function safeIsOptional(t){try{return t.isOptional()}catch{return!0}}const parseOptionalDef=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return parseDef(t.innerType._def,e);const r=parseDef(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:parseAnyDef(e)},r]}:parseAnyDef(e)},parsePipelineDef=(t,e)=>{if(e.pipeStrategy==="input")return parseDef(t.in._def,e);if(e.pipeStrategy==="output")return parseDef(t.out._def,e);const r=parseDef(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=parseDef(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function parsePromiseDef(t,e){return parseDef(t.type._def,e)}function parseSetDef(t,e){const n={type:"array",uniqueItems:!0,items:parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&setResponseValueAndErrors(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&setResponseValueAndErrors(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function parseTupleDef(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>parseDef(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:parseDef(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>parseDef(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function parseUndefinedDef(t){return{not:parseAnyDef(t)}}function parseUnknownDef(t){return parseAnyDef(t)}const parseReadonlyDef=(t,e)=>parseDef(t.innerType._def,e),selectParser=(t,e,r)=>{switch(e){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(t,r);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(t,r);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(t,r);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(t,r);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(t,r);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef(r);case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(r);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(t,r);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(t,r);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(t,r);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(t,r);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(t,r);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(t,r);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(t);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(t);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(t,r);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(t,r);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(t,r);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(t,r);case ZodFirstPartyTypeKind.ZodLazy:return()=>t.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(t,r);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef(r);case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(t,r);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef(r);case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef(r);case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(t,r);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(t,r);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(t,r);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(t,r);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(t,r);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:return;default:return(n=>{})()}};function parseDef(t,e,r=!1){const n=e.seen.get(t);if(e.override){const a=e.override?.(t,e,n,r);if(a!==ignoreOverride)return a}if(n&&!r){const a=get$ref(n,e);if(a!==void 0)return a}const i={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,i);const o=selectParser(t,t.typeName,e),s=typeof o=="function"?parseDef(o(),e):o;if(s&&addMeta(t,e,s),e.postProcess){const a=e.postProcess(s,t,e);return i.jsonSchema=s,a}return i.jsonSchema=s,s}const get$ref=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:getRelativePath(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),parseAnyDef(e)):e.$refStrategy==="seen"?parseAnyDef(e):void 0}},addMeta=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),zodToJsonSchema=(t,e)=>{const r=getRefs(e);let n;const i=e?.name,o=parseDef(t._def,r,!1)??parseAnyDef(r);r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const s=i===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:o}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s},pageAgentPrompt='## 角色\n\n你是浏览器页面的操作工具,你拥有识别网页内容,点击,填写,选择下拉框、悬浮(hover)和滚动页面等功能。\n\n在执行页面操作之前,你必须先调用`browserState`工具一次,根据最新的网页状态,再调用操作动作,比如 \'click\',\'fill\',\'select\',\'hover\' 等动作。\n\n<intro>\n你擅长以下任务:\n1. 导航复杂网站并提取精确信息\n2. 自动化表单提交和交互式网页操作\n3. 收集和保存信息\n4. 在代理循环中有效运行\n5. 高效执行多样化的网页任务\n</intro>\n\n<input>\n在每一步,你的输入将包括:\n1. <agent_history>:一个按时间顺序排列的事件流,包括你之前的操作及其结果。\n2. <agent_state>:当前的 <user_request> 和 <step_info>。\n3. <browser_state>:当前 URL、页面标题、可交互元素总数以及语义化 YAML 树。\n</input>\n\n<browser_state>\n\n浏览器状态包含以下内容:\n\n- url: 当前查看页面的 URL。\n- title: 当前查看页面的标题。\n- content: 语义化 YAML 树(或增量 Diff,取决于 responseMode)。\n- dialogs(可选): 当前可见的模态弹窗列表,每项含 `text` 与 `buttons`;若存在请优先处理。\n- validationErrors(可选): 当前可见的表单校验错误文案列表;若存在请先修复。\n- tooltips(可选): 当前可见的 tooltip / 浮层提示文案列表(常见于 hover 后)。\n- 可交互元素总数:带有 `#N` 标记的元素数量。\n- YAML 树:页面的语义化结构,格式如下:\n\n```yaml\n- region:\n - main:\n - button #9 [cursor=pointer] "产品文档"\n - button #47 [selected] [cursor=pointer] "40元/月 2核CPU 2GB内存"\n - radio #53 [checked] [cursor=pointer] "自动生成密码"\n - button #74 [cursor=pointer] "立即购买"\n - generic #6 [cf-uba="serviceList..Flexus云服务"] "Flexus云服务"\n```\n\n节点格式说明:\n- `- role #N [token1] [token2] "accessible name"`\n- `role`:ARIA 语义角色(如 button/link/radio/heading/listitem/generic 等)\n- `#N`:可交互元素的唯一操作索引,**只有带 `#N` 的节点才能被操作**,操作时将 N 作为 `index` 参数传入\n- `[token]`:可选 token,包括状态标记(如 `[checked]` `[selected]` `[pressed]` `[current]` `[expanded]` `[hasPopup]` `[disabled]` `[readonly]` `[required]` `[invalid]` `[busy]` `[error]` `[warning]` `[cursor=pointer]` `[tooltip="帮助文本"]`)和定制属性(如 `[cf-uba="..."]`)\n- `"accessible name"`:元素的语义化名称,**用双引号包裹**(通过 aria-label/aria-labelledby/innerText 等计算得出);无名称的节点此字段省略\n- 缩进表示父子关系\n\n</browser_state>\n\n<responseMode>\n\n`page-agent-tool` 支持 `responseMode` 参数,用于控制操作后返回的页面状态形式:\n\n- **`diff`**(默认):仅返回自上一次状态以来的增量 DOM 差异,极大节省 Token。\n- **`full`**:返回当前视口中完整的语义化 ARIA YAML 树。\n- **`both`**:同时返回全量树和增量差异。\n\n执行 `click`、`fill`、`select`、`scroll` 操作后,工具默认自动以 `diff` 模式返回最新页面状态,无需再次手动调用 `browserState`。`hover` 动作返回重建后的页面状态(含 `tooltips` 等结构化字段)。\n\n</responseMode>\n\n<browser_state_diff>\n\n在交互过程中,为了提高效率和减少上下文占用,工具会生成页面的增量差异(Diff)信息。\nDiff 格式示例如下:\n```diff\n- button #9: 产品文档\n+ button #9: 产品文档 (已点击)\n```\n或者,当页面结构发生改变时,会展示新增或移除的节点差异。\n\n### 页面状态获取四原则(重要,请严格遵守):\n\n> 与业界 AI 编辑器(Cursor / Windsurf)按需读取文件而非全量加载的理念完全一致——**先精准搜索,再按需拉取全量**,将发送给大模型的 token 降至最低。\n\n1. **按关键词精准搜索(最高优先级)**:当你已知要找什么类型的元素(如按钮、输入框、特定名称的链接)时,**优先使用 `searchTree` 动作**,传入 role 名称、元素文本或状态关键词搜索。它只返回命中行和上下文,token 消耗比全量树减少 80%+。\n - 示例:查找所有按钮 → `{"action": "searchTree", "query": "button"}`\n - 示例:查找含"提交"文本的节点 → `{"action": "searchTree", "query": "提交"}`\n - 示例:查找已勾选的复选框 → `{"action": "searchTree", "query": "checked"}`\n - 示例:精确定位某个 ref → `{"action": "searchTree", "query": "#5"}`\n2. **首次获取全量**:首次进入页面、页面发生重大刷新、或 `searchTree` 无法找到所需信息时,调用 `browserState` 并指定 `responseMode` 为 `full` 或 `both` 获取完整 A11y 树。\n3. **增量优先**:执行 `click`、`fill`、`select`、`scroll` 操作后,工具默认自动返回 `diff` 增量信息。优先阅读这些 Diff,以便快速确认操作是否生效。\n4. **按需拉取全量**:如果增量 Diff 不足以支持下一步操作,或需要寻找不在 Diff 中的 `#N` 节点,且 `searchTree` 也无法定位时,再显式调用 `browserState` 拉取完整树。\n\n</browser_state_diff>\n\n\n\n<browser_rules>\n在使用浏览器和浏览网页时严格遵守以下规则:\n\n- 仅与分配有 `#N` 索引的元素进行交互,将 N 作为 `index` 参数传入。\n- 仅使用明确出现在树中的 `#N` 索引,切勿猜测或沿用过期索引。\n- 每次操作后 `#N` 索引会重新分配,不要使用旧的索引。\n- 如果页面在执行操作后发生变化(例如输入文本操作),分析是否需要与新元素进行交互,例如从列表中选择正确的选项。\n- 默认情况下,仅列出可见视口中的元素。如果你怀疑需要交互的相关内容在屏幕外,请使用滚动操作。仅在页面下方或上方还有更多像素时才滚动。\n- 你可以使用 num_pages 参数滚动特定页数(例如,0.5 表示半页,2.0 表示两页)。\n- 如果出现验证码,告诉用户你无法解决验证码。完成任务并请用户解决它。\n- 如果缺少预期元素,尝试滚动或导航回退。\n- 除非某些条件发生变化,否则不要重复同一操作超过 3 次。\n- 如果你向输入字段填充文本且操作序列被中断,通常意味着某些内容发生了变化,例如下拉建议弹出。\n- 如果 <user_request> 包含特定的页面信息,如产品类型、评分、价格、位置等,尝试应用过滤器以提高效率。\n- <user_request> 是最终目标。如果用户指定了明确的步骤,它们始终具有最高优先级。\n- 如果你向字段输入文本,可能需要按回车键、点击搜索按钮或从下拉列表中选择以完成操作。\n- 对于带有 `[tooltip="..."]` token 的元素,可以直接阅读提示文本。对于标记为 `tooltip [hasPopup]` 的元素(如帮助提示图标),tooltip 文本需 hover 才会动态出现——**使用 `hover` 动作并传入元素索引即可触发并获取 tooltip 内容**。hover 返回浮层提示文本 + 重建后的完整页面状态,`#N` 索引会更新,可继续操作新出现的交互元素。\n- **对 tooltip 触发元素优先使用 `hover` 而非 `click`**:click 可能触发标签页切换或 DOM 重建导致 ref 索引失效,而 hover 只触发 pointer/mouse 事件,安全且返回 tooltip 内容。\n- **不要通过 executeJavascript 向页面插入 DOM 元素**(如创建 div 显示调试信息)。这会污染页面结构并影响后续操作。如需读取数据,使用 return 语句返回结果即可。\n- 如果操作返回中出现 `[校验提示]`,说明页面有表单校验错误未通过,请先根据提示修复错误后再继续操作。\n- 如果操作后页面没有发生预期变化,优先检查是否有 `[校验提示]` 或 `[error]` token 的错误信息,而非重复操作。\n- 如果不需要,不要登录页面。如果没有凭据,不要登录。\n- 有两种类型的任务,首先思考你正在处理哪种类型的请求:\n\n1. 非常具体的逐步说明:\n\n- 非常精确地遵循它们,不要跳过步骤。尝试按要求完成所有内容。\n\n2. 开放式任务。自己规划,在实现目标时保持创造性。\n\n- 如果在开放式任务中陷入困境(例如登录或验证码),可以重新评估任务并尝试替代方法,例如有时即使页面的某些部分可访问或通过 Web 搜索获取一些信息,也会意外弹出登录框。\n </browser_rules>\n\n<capability>\n- 你只能处理单页应用。不要跳出当前页面。\n- 如果链接将在新页面中打开(例如,<a target="_blank">),不要点击该链接。\n- 任务失败是可以接受的。\n - 用户可能是错的。如果用户的请求无法实现、不适当,或者你没有足够的信息或工具来实现它。告诉用户提出更好的请求。\n - 网页可能已损坏。所有网页或应用都有 bug。有些 bug 会使你的工作变得困难。鼓励你告诉用户当前页面的问题。你的反馈(包括失败)对用户很有价值。\n - 过于努力可能有害。来回重复某些操作或在知识有限的情况下推动复杂程序可能导致不良结果和有害副作用。用户宁愿你以失败告终完成任务。\n- 如果你对当前网页或任务没有相关知识。你必须要求用户提供具体说明和详细步骤。\n</capability>\n\n<task_completion_rules>\n你必须在以下情况时结束任务:\n\n- 当你完全完成用户请求时。\n- 当你感到困惑或无法解决用户请求时。或者用户请求不清楚或包含不当内容。\n- 如果绝对不可能继续。\n\n</task_completion_rules>\n';function isHTMLElement(t){return!!t&&t.nodeType===1}function isInputElement(t){return t?.nodeType===1&&t.tagName==="INPUT"}function isTextAreaElement(t){return t?.nodeType===1&&t.tagName==="TEXTAREA"}function isSelectElement(t){return t?.nodeType===1&&t.tagName==="SELECT"}function isAnchorElement(t){return t?.nodeType===1&&t.tagName==="A"}function getIframeOffset(t){const e=t.ownerDocument.defaultView?.frameElement;if(!e)return{x:0,y:0};const r=e.getBoundingClientRect();return{x:r.left,y:r.top}}function getNativeValueSetter(t){return Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t),"value").set}async function waitFor(t){await new Promise(e=>setTimeout(e,t*1e3))}async function movePointerToElement(t,e,r){const n=getIframeOffset(t);window.dispatchEvent(new CustomEvent("PageAgent::MovePointerTo",{detail:{x:e+n.x,y:r+n.y}})),await waitFor(.3)}async function clickPointer(){window.dispatchEvent(new CustomEvent("PageAgent::ClickPointer"))}async function enablePassThrough(){window.dispatchEvent(new CustomEvent("PageAgent::EnablePassThrough"))}async function disablePassThrough(){window.dispatchEvent(new CustomEvent("PageAgent::DisablePassThrough"))}function getElementByIndex(t,e){const r=t.get(e);if(!r)throw new Error(`No interactive element found at index ${e}`);const n=r.ref;if(!n)throw new Error(`Element at index ${e} does not have a reference`);if(!isHTMLElement(n))throw new Error(`Element at index ${e} is not an HTMLElement`);return n}var lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&(lastClickedElement.dispatchEvent(new PointerEvent("pointerout",{bubbles:!0})),lastClickedElement.dispatchEvent(new PointerEvent("pointerleave",{bubbles:!1})),lastClickedElement.dispatchEvent(new MouseEvent("mouseout",{bubbles:!0})),lastClickedElement.dispatchEvent(new MouseEvent("mouseleave",{bubbles:!1})),lastClickedElement.blur(),lastClickedElement=null)}async function clickElement(t){blurLastClickedElement(),lastClickedElement=t,await scrollIntoViewIfNeeded(t);const e=t.ownerDocument.defaultView?.frameElement;e&&await scrollIntoViewIfNeeded(e);const r=t.getBoundingClientRect(),n=r.left+r.width/2,i=r.top+r.height/2;await movePointerToElement(t,n,i),await clickPointer(),await waitFor(.1);const o=t.ownerDocument;await enablePassThrough();const s=o.elementFromPoint(n,i);await disablePassThrough();const a=s instanceof HTMLElement&&t.contains(s)?s:t,l={bubbles:!0,cancelable:!0,clientX:n,clientY:i,pointerType:"mouse"},c={bubbles:!0,cancelable:!0,clientX:n,clientY:i,button:0};a.dispatchEvent(new PointerEvent("pointerover",l)),a.dispatchEvent(new PointerEvent("pointerenter",{...l,bubbles:!1})),a.dispatchEvent(new MouseEvent("mouseover",c)),a.dispatchEvent(new MouseEvent("mouseenter",{...c,bubbles:!1})),a.dispatchEvent(new PointerEvent("pointerdown",l)),a.dispatchEvent(new MouseEvent("mousedown",c)),t.focus({preventScroll:!0}),a.dispatchEvent(new PointerEvent("pointerup",l)),a.dispatchEvent(new MouseEvent("mouseup",c)),a.click(),await waitFor(.2)}async function inputTextElement(t,e){const r=t.isContentEditable;if(!isInputElement(t)&&!isTextAreaElement(t)&&!r)throw new Error("Element is not an input, textarea, or contenteditable");if(await clickElement(t),r){if(t.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"deleteContent"}))&&(t.innerText="",t.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"deleteContent"}))),t.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e}))&&(t.innerText=e,t.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"insertText",data:e}))),t.innerText.trim()!==e.trim()){t.focus();const n=t.ownerDocument,i=(n.defaultView||window).getSelection(),o=n.createRange();o.selectNodeContents(t),i?.removeAllRanges(),i?.addRange(o),n.execCommand("delete",!1),n.execCommand("insertText",!1,e)}t.dispatchEvent(new Event("change",{bubbles:!0})),t.blur()}else getNativeValueSetter(t).call(t,e);r||t.dispatchEvent(new Event("input",{bubbles:!0})),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(t,e){if(!isSelectElement(t))throw new Error("Element is not a select element");const r=Array.from(t.options).find(n=>n.textContent?.trim()===e.trim());if(!r)throw new Error(`Option with text "${e}" not found in select element`);t.value=r.value,t.dispatchEvent(new Event("change",{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(t){const e=t;typeof e.scrollIntoViewIfNeeded=="function"?e.scrollIntoViewIfNeeded():t.scrollIntoView({behavior:"auto",block:"center",inline:"nearest"})}async function scrollVertically(t,e){if(e){const s=e;let a=s,l=!1,c=null,u=0,f=0;const h=t;for(;a&&f<10;){const m=window.getComputedStyle(a),g=/(auto|scroll|overlay)/.test(m.overflowY)||m.scrollbarWidth&&m.scrollbarWidth!=="auto"||m.scrollbarGutter&&m.scrollbarGutter!=="auto",A=a.scrollHeight>a.clientHeight;if(g&&A){const _=a.scrollTop,p=a.scrollHeight-a.clientHeight;let v=h/3;v>0?v=Math.min(v,p-_):v=Math.max(v,-_),a.scrollTop=_+v;const S=a.scrollTop-_;if(Math.abs(S)>.5){l=!0,c=a,u=S;break}}if(a===document.body||a===document.documentElement)break;a=a.parentElement,f++}return l?`Scrolled container (${c?.tagName}) by ${u}px`:`No scrollable container found for element (${s.tagName})`}const r=t,n=s=>s.clientHeight>=window.innerHeight*.5,i=s=>!!(s&&/(auto|scroll|overlay)/.test(getComputedStyle(s).overflowY)&&s.scrollHeight>s.clientHeight&&n(s));let o=document.activeElement;for(;o&&!i(o)&&o!==document.body;)o=o.parentElement;if(o=i(o)?o:Array.from(document.querySelectorAll("*")).find(i)||document.scrollingElement||document.documentElement,o===document.scrollingElement||o===document.documentElement||o===document.body){const s=window.scrollY,a=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,r);const l=window.scrollY,c=l-s;if(Math.abs(c)<1)return r>0?"⚠️ Already at the bottom of the page, cannot scroll down further.":"⚠️ Already at the top of the page, cannot scroll up further.";const u=r>0&&l>=a-1,f=r<0&&l<=1;return u?`✅ Scrolled page by ${c}px. Reached the bottom of the page.`:f?`✅ Scrolled page by ${c}px. Reached the top of the page.`:`✅ Scrolled page by ${c}px.`}else{const s="The document is not scrollable. Falling back to container scroll.";console.log(`[PageController] ${s}`);const a=o.scrollTop,l=o.scrollHeight-o.clientHeight;o.scrollBy({top:r,behavior:"smooth"}),await waitFor(.1);const c=o.scrollTop,u=c-a;if(Math.abs(u)<1)return r>0?`⚠️ ${s} Already at the bottom of container (${o.tagName}), cannot scroll down further.`:`⚠️ ${s} Already at the top of container (${o.tagName}), cannot scroll up further.`;const f=r>0&&c>=l-1,h=r<0&&c<=1;return f?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the bottom.`:h?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the top.`:`✅ ${s} Scrolled container (${o.tagName}) by ${u}px.`}}async function scrollHorizontally(t,e){if(e){const s=e;let a=s,l=!1,c=null,u=0,f=0;const h=t;for(;a&&f<10;){const m=window.getComputedStyle(a),g=/(auto|scroll|overlay)/.test(m.overflowX)||m.scrollbarWidth&&m.scrollbarWidth!=="auto"||m.scrollbarGutter&&m.scrollbarGutter!=="auto",A=a.scrollWidth>a.clientWidth;if(g&&A){const _=a.scrollLeft,p=a.scrollWidth-a.clientWidth;let v=h/3;v>0?v=Math.min(v,p-_):v=Math.max(v,-_),a.scrollLeft=_+v;const S=a.scrollLeft-_;if(Math.abs(S)>.5){l=!0,c=a,u=S;break}}if(a===document.body||a===document.documentElement)break;a=a.parentElement,f++}return l?`Scrolled container (${c?.tagName}) horizontally by ${u}px`:`No horizontally scrollable container found for element (${s.tagName})`}const r=t,n=s=>s.clientWidth>=window.innerWidth*.5,i=s=>!!(s&&/(auto|scroll|overlay)/.test(getComputedStyle(s).overflowX)&&s.scrollWidth>s.clientWidth&&n(s));let o=document.activeElement;for(;o&&!i(o)&&o!==document.body;)o=o.parentElement;if(o=i(o)?o:Array.from(document.querySelectorAll("*")).find(i)||document.scrollingElement||document.documentElement,o===document.scrollingElement||o===document.documentElement||o===document.body){const s=window.scrollX,a=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(r,0);const l=window.scrollX,c=l-s;if(Math.abs(c)<1)return r>0?"⚠️ Already at the right edge of the page, cannot scroll right further.":"⚠️ Already at the left edge of the page, cannot scroll left further.";const u=r>0&&l>=a-1,f=r<0&&l<=1;return u?`✅ Scrolled page by ${c}px. Reached the right edge of the page.`:f?`✅ Scrolled page by ${c}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${c}px.`}else{const s="The document is not scrollable. Falling back to container scroll.";console.log(`[PageController] ${s}`);const a=o.scrollLeft,l=o.scrollWidth-o.clientWidth;o.scrollBy({left:r,behavior:"smooth"}),await waitFor(.1);const c=o.scrollLeft,u=c-a;if(Math.abs(u)<1)return r>0?`⚠️ ${s} Already at the right edge of container (${o.tagName}), cannot scroll right further.`:`⚠️ ${s} Already at the left edge of container (${o.tagName}), cannot scroll left further.`;const f=r>0&&c>=l-1,h=r<0&&c<=1;return f?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the right edge.`:h?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the left edge.`:`✅ ${s} Scrolled container (${o.tagName}) horizontally by ${u}px.`}}var dom_tree_default=(t={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:e,interactiveWhitelist:r,highlightOpacity:n,highlightLabelOpacity:i}=t,{doHighlightElements:o,focusHighlightIndex:s,viewportExpansion:a,debugMode:l}=t;let c=0;const u=new WeakMap;function f(d,x){!d||d.nodeType!==Node.ELEMENT_NODE||u.set(d,{...u.get(d),...x})}const h={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{h.boundingRects=new WeakMap,h.clientRects=new WeakMap,h.computedStyles=new WeakMap}};function m(d){if(!d)return null;if(h.boundingRects.has(d))return h.boundingRects.get(d);const x=d.getBoundingClientRect();return x&&h.boundingRects.set(d,x),x}function g(d){if(!d)return null;if(h.computedStyles.has(d))return h.computedStyles.get(d);const x=window.getComputedStyle(d);return x&&h.computedStyles.set(d,x),x}function A(d){if(!d)return null;if(h.clientRects.has(d))return h.clientRects.get(d);const x=d.getClientRects();return x&&h.clientRects.set(d,x),x}const _={},p={current:0},v="playwright-highlight-container";function S(d,x,j=null){if(!d)return x;const T=[];let P=null,B=20,k=16,F=null;try{let O=document.getElementById(v);O||(O=document.createElement("div"),O.id=v,O.style.position="fixed",O.style.pointerEvents="none",O.style.top="0",O.style.left="0",O.style.width="100%",O.style.height="100%",O.style.zIndex="2147483640",O.style.backgroundColor="transparent",document.body.appendChild(O));const U=d.getClientRects();if(!U||U.length===0)return x;const Y=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];let W=Y[x%Y.length];const ee=W+Math.floor(n*255).toString(16).padStart(2,"0");W=W+Math.floor(i*255).toString(16).padStart(2,"0");let J={x:0,y:0};if(j){const I=j.getBoundingClientRect();J.x=I.left,J.y=I.top}const ae=document.createDocumentFragment();for(const I of U){if(I.width===0||I.height===0)continue;const w=document.createElement("div");w.style.position="fixed",w.style.border=`2px solid ${W}`,w.style.backgroundColor=ee,w.style.pointerEvents="none",w.style.boxSizing="border-box";const y=I.top+J.y,$=I.left+J.x;w.style.top=`${y}px`,w.style.left=`${$}px`,w.style.width=`${I.width}px`,w.style.height=`${I.height}px`,ae.appendChild(w),T.push({element:w,initialRect:I})}const ne=U[0];P=document.createElement("div"),P.className="playwright-highlight-label",P.style.position="fixed",P.style.background=W,P.style.color="white",P.style.padding="1px 4px",P.style.borderRadius="4px",P.style.fontSize=`${Math.min(12,Math.max(8,ne.height/2))}px`,P.textContent=x.toString(),B=P.offsetWidth>0?P.offsetWidth:B,k=P.offsetHeight>0?P.offsetHeight:k;const ue=ne.top+J.y,le=ne.left+J.x;let de=ue+2,E=le+ne.width-B-2;(ne.width<B+4||ne.height<k+4)&&(de=ue-k-2,E=le+ne.width-B,E<J.x&&(E=le)),de=Math.max(0,Math.min(de,window.innerHeight-k)),E=Math.max(0,Math.min(E,window.innerWidth-B)),P.style.top=`${de}px`,P.style.left=`${E}px`,ae.appendChild(P);const R=((I,w)=>{let y=0;return(...$)=>{const N=performance.now();if(!(N-y<w))return y=N,I(...$)}})(()=>{const I=d.getClientRects();let w={x:0,y:0};if(j){const y=j.getBoundingClientRect();w.x=y.left,w.y=y.top}if(T.forEach((y,$)=>{if($<I.length){const N=I[$],q=N.top+w.y,se=N.left+w.x;y.element.style.top=`${q}px`,y.element.style.left=`${se}px`,y.element.style.width=`${N.width}px`,y.element.style.height=`${N.height}px`,y.element.style.display=N.width===0||N.height===0?"none":"block"}else y.element.style.display="none"}),I.length<T.length)for(let y=I.length;y<T.length;y++)T[y].element.style.display="none";if(P&&I.length>0){const y=I[0],$=y.top+w.y,N=y.left+w.x;let q=$+2,se=N+y.width-B-2;(y.width<B+4||y.height<k+4)&&(q=$-k-2,se=N+y.width-B,se<w.x&&(se=N)),q=Math.max(0,Math.min(q,window.innerHeight-k)),se=Math.max(0,Math.min(se,window.innerWidth-B)),P.style.top=`${q}px`,P.style.left=`${se}px`,P.style.display="block"}else P&&(P.style.display="none")},16);return window.addEventListener("scroll",R,!0),window.addEventListener("resize",R),F=()=>{window.removeEventListener("scroll",R,!0),window.removeEventListener("resize",R),T.forEach(I=>I.element.remove()),P&&P.remove()},O.appendChild(ae),x+1}finally{F&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(F)}}function b(d){if(!d||d.nodeType!==Node.ELEMENT_NODE)return null;const x=g(d);if(!x)return null;const j=x.display;if(j==="inline"||j==="inline-block")return null;const T=x.overflowX,P=x.overflowY,B=x.scrollbarWidth&&x.scrollbarWidth!=="auto"||x.scrollbarGutter&&x.scrollbarGutter!=="auto",k=T==="auto"||T==="scroll",F=P==="auto"||P==="scroll";if(!k&&!F&&!B)return null;const O=d.scrollWidth-d.clientWidth,U=d.scrollHeight-d.clientHeight,Y=4;if(O<Y&&U<Y||!F&&!B&&O<Y||!k&&!B&&U<Y)return null;const W=d.scrollTop,ee=d.scrollLeft,J={top:W,right:d.scrollWidth-d.clientWidth-d.scrollLeft,bottom:d.scrollHeight-d.clientHeight-d.scrollTop,left:ee};return f(d,{scrollable:!0,scrollData:J}),J}function C(d){try{if(a===-1){const k=d.parentElement;if(!k)return!1;try{return k.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const O=window.getComputedStyle(k);return O.display!=="none"&&O.visibility!=="hidden"&&O.opacity!=="0"}}const x=document.createRange();x.selectNodeContents(d);const j=x.getClientRects();if(!j||j.length===0)return!1;let T=!1,P=!1;for(const k of j)if(k.width>0&&k.height>0&&(T=!0,!(k.bottom<-a||k.top>window.innerHeight+a||k.right<-a||k.left>window.innerWidth+a))){P=!0;break}if(!T||!P)return!1;const B=d.parentElement;if(!B)return!1;try{return B.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const F=window.getComputedStyle(B);return F.display!=="none"&&F.visibility!=="hidden"&&F.opacity!=="0"}}catch(x){return console.warn("Error checking text node visibility:",x),!1}}function M(d){if(!d||!d.tagName)return!1;const x=new Set(["body","div","main","article","section","nav","header","footer"]),j=d.tagName.toLowerCase();return x.has(j)?!0:!new Set(["svg","script","style","link","meta","noscript","template"]).has(j)}function L(d){const x=g(d);return d.offsetWidth>0&&d.offsetHeight>0&&x?.visibility!=="hidden"&&x?.display!=="none"}function z(d){if(!d||d.nodeType!==Node.ELEMENT_NODE||e.includes(d))return!1;if(r.includes(d))return!0;const x=d.tagName.toLowerCase(),j=g(d),T=new Set(["pointer","move","text","grab","grabbing","cell","copy","alias","all-scroll","col-resize","context-menu","crosshair","e-resize","ew-resize","help","n-resize","ne-resize","nesw-resize","ns-resize","nw-resize","nwse-resize","row-resize","s-resize","se-resize","sw-resize","vertical-text","w-resize","zoom-in","zoom-out"]),P=new Set(["not-allowed","no-drop","wait","progress","initial","inherit"]);function B(W){return W.tagName.toLowerCase()==="html"?!1:!!(j?.cursor&&T.has(j.cursor))}if(B(d))return!0;const k=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),F=new Set(["disabled","readonly"]);if(k.has(x)){if(j?.cursor&&P.has(j.cursor))return!1;for(const W of F)if(d.hasAttribute(W)||d.getAttribute(W)==="true"||d.getAttribute(W)==="")return!1;return!(d.disabled||d.readOnly||d.inert)}const O=d.getAttribute("role"),U=d.getAttribute("aria-role");if(d.getAttribute("contenteditable")==="true"||d.isContentEditable||d.classList&&(d.classList.contains("button")||d.classList.contains("dropdown-toggle")||d.getAttribute("data-index")||d.getAttribute("data-toggle")==="dropdown"||d.getAttribute("aria-haspopup")==="true"))return!0;const Y=new Set(["button","menu","menubar","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);if(k.has(x)||O&&Y.has(O)||U&&Y.has(U))return!0;try{if(typeof getEventListeners=="function"){const ee=getEventListeners(d);for(const J of["click","mousedown","mouseup","dblclick"])if(ee[J]&&ee[J].length>0)return!0}const W=d?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof W=="function"){const ee=W(d);for(const J of["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"])for(const ae of ee)if(ae.type===J)return!0}for(const ee of["onclick","onmousedown","onmouseup","ondblclick"])if(d.hasAttribute(ee)||typeof d[ee]=="function")return!0}catch{}return!!b(d)}function D(d){if(a===-1)return!0;const x=A(d);if(!x||x.length===0)return!1;let j=!1;for(const k of x)if(k.width>0&&k.height>0&&!(k.bottom<-a||k.top>window.innerHeight+a||k.right<-a||k.left>window.innerWidth+a)){j=!0;break}if(!j)return!1;if(d.ownerDocument!==window.document)return!0;let T=Array.from(x).find(k=>k.width>0&&k.height>0);if(!T)return!1;const P=d.getRootNode();if(P instanceof ShadowRoot){const k=T.left+T.width/2,F=T.top+T.height/2;try{const O=P.elementFromPoint(k,F);if(!O)return!1;let U=O;for(;U&&U!==P;){if(U===d)return!0;U=U.parentElement}return!1}catch{return!0}}const B=5;return[{x:T.left+T.width/2,y:T.top+T.height/2},{x:T.left+B,y:T.top+B},{x:T.right-B,y:T.bottom-B}].some(({x:k,y:F})=>{try{const O=document.elementFromPoint(k,F);if(!O)return!1;let U=O;for(;U&&U!==document.documentElement;){if(U===d)return!0;U=U.parentElement}return!1}catch{return!0}})}function V(d,x){if(x===-1)return!0;const j=d.getClientRects();if(!j||j.length===0){const T=m(d);return!T||T.width===0||T.height===0?!1:!(T.bottom<-x||T.top>window.innerHeight+x||T.right<-x||T.left>window.innerWidth+x)}for(const T of j)if(!(T.width===0||T.height===0)&&!(T.bottom<-x||T.top>window.innerHeight+x||T.right<-x||T.left>window.innerWidth+x))return!0;return!1}const H=["aria-expanded","aria-checked","aria-selected","aria-pressed","aria-haspopup","aria-controls","aria-owns","aria-activedescendant","aria-valuenow","aria-valuetext","aria-valuemax","aria-valuemin","aria-autocomplete"];function G(d){for(let x=0;x<H.length;x++)if(d.hasAttribute(H[x]))return!0;return!1}function ie(d){if(!d||d.nodeType!==Node.ELEMENT_NODE)return!1;const x=d.tagName.toLowerCase();return new Set(["a","button","input","select","textarea","details","summary","label"]).has(x)?!0:d.hasAttribute("onclick")||d.hasAttribute("role")||d.hasAttribute("tabindex")||G(d)||d.hasAttribute("data-action")||d.getAttribute("contenteditable")==="true"}const X=new Set(["a","button","input","select","textarea","summary","details","label","option","li"]),te=new Set(["button","link","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","listitem","treeitem","row","option","scrollbar"]);function oe(d){if(!d||d.nodeType!==Node.ELEMENT_NODE||!L(d))return!1;const x=d.hasAttribute("role")||d.hasAttribute("tabindex")||d.hasAttribute("onclick")||typeof d.onclick=="function",j=/\b(btn|clickable|menu|item|entry|link)\b/i.test(d.className||""),T=!!d.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar'),P=[...d.children].some(L),B=d.parentElement&&d.parentElement.isSameNode(document.body);return(z(d)||x||j)&&P&&T&&!B}function re(d){if(!d||d.nodeType!==Node.ELEMENT_NODE)return!1;const x=d.tagName.toLowerCase(),j=d.getAttribute("role");if(x==="iframe"||X.has(x)||j&&te.has(j)||d.isContentEditable||d.getAttribute("contenteditable")==="true"||d.hasAttribute("data-testid")||d.hasAttribute("data-cy")||d.hasAttribute("data-test")||d.hasAttribute("onclick")||typeof d.onclick=="function"||G(d))return!0;try{const T=d?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof T=="function"){const P=T(d);for(const B of["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"])for(const k of P)if(k.type===B)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(P=>d.hasAttribute(P)))return!0}catch{}return!!(oe(d)||u.get(d)?.scrollable)}function Q(d,x,j,T){if(!d.isInteractive)return!1;let P=!1;return T?re(x)?P=!0:P=!1:P=!0,P&&(d.isInViewport=V(x,a),(d.isInViewport||a===-1)&&(d.highlightIndex=c++,o))?(s>=0?s===d.highlightIndex&&S(x,d.highlightIndex,j):S(x,d.highlightIndex,j),!0):!1}function K(d,x=null,j=!1){if(!d||d.id===v||d.nodeType!==Node.ELEMENT_NODE&&d.nodeType!==Node.TEXT_NODE||!d||d.id===v||d.dataset?.browserUseIgnore==="true"||d.dataset?.pageAgentIgnore==="true"||d.getAttribute&&d.getAttribute("aria-hidden")==="true")return null;if(d===document.body){const k={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const O of d.childNodes){const U=K(O,x,!1);U&&k.children.push(U)}const F=`${p.current++}`;return _[F]=k,F}if(d.nodeType!==Node.ELEMENT_NODE&&d.nodeType!==Node.TEXT_NODE)return null;if(d.nodeType===Node.TEXT_NODE){const k=d.textContent?.trim();if(!k)return null;const F=d.parentElement;if(!F||F.tagName.toLowerCase()==="script")return null;const O=`${p.current++}`;return _[O]={type:"TEXT_NODE",text:k,isVisible:C(d)},O}if(d.nodeType===Node.ELEMENT_NODE&&!M(d))return null;if(a!==-1&&!d.shadowRoot){const k=m(d),F=g(d),O=F&&(F.position==="fixed"||F.position==="sticky"),U=d.offsetWidth>0||d.offsetHeight>0;if(!k||!O&&!U&&(k.bottom<-a||k.top>window.innerHeight+a||k.right<-a||k.left>window.innerWidth+a))return null}const T={tagName:d.tagName.toLowerCase(),attributes:{},children:[]};if(ie(d)||d.tagName.toLowerCase()==="iframe"||d.tagName.toLowerCase()==="body"){const k=d.getAttributeNames?.()||[];for(const F of k){const O=d.getAttribute(F);T.attributes[F]=O}d.tagName.toLowerCase()==="input"&&(d.type==="checkbox"||d.type==="radio")&&(T.attributes.checked=d.checked?"true":"false")}let P=!1;if(d.nodeType===Node.ELEMENT_NODE&&(T.isVisible=L(d),T.isVisible)){T.isTopElement=D(d);const k=d.getAttribute("role"),F=k==="menu"||k==="menubar"||k==="listbox";if((T.isTopElement||F)&&(T.isInteractive=z(d),P=Q(T,d,x,j),T.ref=d,T.isInteractive&&Object.keys(T.attributes).length===0)){const O=d.getAttributeNames?.()||[];for(const U of O){const Y=d.getAttribute(U);T.attributes[U]=Y}}}if(d.tagName){const k=d.tagName.toLowerCase();if(k==="iframe")try{const F=d.contentDocument||d.contentWindow?.document;if(F)for(const O of F.childNodes){const U=K(O,d,!1);U&&T.children.push(U)}}catch(F){console.warn("Unable to access iframe:",F)}else if(d.isContentEditable||d.getAttribute("contenteditable")==="true"||d.id==="tinymce"||d.classList.contains("mce-content-body")||k==="body"&&d.getAttribute("data-id")?.startsWith("mce_"))for(const F of d.childNodes){const O=K(F,x,P);O&&T.children.push(O)}else{if(d.shadowRoot){T.shadowRoot=!0;for(const F of d.shadowRoot.childNodes){const O=K(F,x,P);O&&T.children.push(O)}}for(const F of d.childNodes){const O=K(F,x,P||j);O&&T.children.push(O)}}}if(T.tagName==="a"&&T.children.length===0&&!T.attributes.href){const k=m(d);if(!(k&&k.width>0&&k.height>0||d.offsetWidth>0||d.offsetHeight>0))return null}T.extra=u.get(d)||null;const B=`${p.current++}`;return _[B]=T,B}const ce=K(document.body);return h.clearCache(),{rootId:ce,map:_}},DEFAULT_VIEWPORT_EXPANSION=-1;function resolveViewportExpansion(t){return t??DEFAULT_VIEWPORT_EXPANSION}var SEMANTIC_TAGS=new Set(["nav","menu","header","footer","aside","dialog"]),newElementsCache=new WeakMap;function getFlatTree(t){const e=resolveViewportExpansion(t.viewportExpansion),r=[];for(const s of t.interactiveBlacklist||[])typeof s=="function"?r.push(s()):r.push(s);const n=[];for(const s of t.interactiveWhitelist||[])typeof s=="function"?n.push(s()):n.push(s);const i=dom_tree_default({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:e,interactiveBlacklist:r,interactiveWhitelist:n,highlightOpacity:t.highlightOpacity??0,highlightLabelOpacity:t.highlightLabelOpacity??.1}),o=window.location.href;for(const s in i.map){const a=i.map[s];if(a.isInteractive&&a.ref){const l=a.ref;newElementsCache.has(l)||(newElementsCache.set(l,o),a.isNew=!0)}}return i}var globRegexCache=new Map;function globToRegex(t){let e=globRegexCache.get(t);if(!e){const r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");e=new RegExp(`^${r.replace(/\*/g,".*")}$`),globRegexCache.set(t,e)}return e}function matchAttributes(t,e){const r={};for(const n of e)if(n.includes("*")){const i=globToRegex(n);for(const o of Object.keys(t))i.test(o)&&t[o].trim()&&(r[o]=t[o].trim())}else{const i=t[n];i&&i.trim()&&(r[n]=i.trim())}return r}function flatTreeToString(t,e=[],r=!1){const n=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","id","for","target","aria-haspopup","aria-controls","aria-owns","contenteditable"],i=[...e,...n],o=(h,m)=>h.length>m?h.substring(0,m)+"...":h,s=h=>{const m=t.map[h];if(!m)return null;if(m.type==="TEXT_NODE"){const g=m;return{type:"text",text:g.text,isVisible:g.isVisible,parent:null,children:[]}}else{const g=m,A=[];if(g.children)for(const _ of g.children){const p=s(_);p&&(p.parent=null,A.push(p))}return{type:"element",tagName:g.tagName,attributes:g.attributes??{},isVisible:g.isVisible??!1,isInteractive:g.isInteractive??!1,isTopElement:g.isTopElement??!1,isNew:g.isNew??!1,highlightIndex:g.highlightIndex,parent:null,children:A,extra:g.extra??{}}}},a=(h,m=null)=>{h.parent=m;for(const g of h.children)a(g,h)},l=s(t.rootId);if(!l)return"";a(l);const c=h=>{let m=h.parent;for(;m;){if(m.type==="element"&&m.highlightIndex!==void 0)return!0;m=m.parent}return!1},u=(h,m,g)=>{let A=m;const _=" ".repeat(m);if(h.type==="element"){const p=r&&h.tagName&&SEMANTIC_TAGS.has(h.tagName);if(h.highlightIndex!==void 0){A+=1;const b=getAllTextTillNextClickableElement(h);let C="";if(i.length>0&&h.attributes){const L=matchAttributes(h.attributes,i),z=Object.keys(L);if(z.length>1){const D=new Set,V={};for(const H of z){const G=L[H];G.length>5&&(G in V?D.add(H):V[G]=H)}for(const H of D)delete L[H]}L.role===h.tagName&&delete L.role;for(const D of["aria-label","placeholder","title"])L[D]&&L[D].toLowerCase().trim()===b.toLowerCase().trim()&&delete L[D];Object.keys(L).length>0&&(C=Object.entries(L).map(([D,V])=>`${D}=${o(V,20)}`).join(" "))}let M=`${_}${h.isNew?`*[${h.highlightIndex}]`:`[${h.highlightIndex}]`}<${h.tagName??""}`;if(C&&(M+=` ${C}`),h.extra&&h.extra.scrollable){let L="";h.extra.scrollData?.left&&(L+=`left=${h.extra.scrollData.left}, `),h.extra.scrollData?.top&&(L+=`top=${h.extra.scrollData.top}, `),h.extra.scrollData?.right&&(L+=`right=${h.extra.scrollData.right}, `),h.extra.scrollData?.bottom&&(L+=`bottom=${h.extra.scrollData.bottom}`),M+=` data-scrollable="${L}"`}if(b){const L=b.trim();C||(M+=" "),M+=`>${L}`}else C||(M+=" ");M+=" />",g.push(M)}const v=p&&h.highlightIndex===void 0,S=v?g.length:-1;v&&(g.push(`${_}<${h.tagName}>`),A+=1);for(const b of h.children)u(b,A,g);v&&(g.length===S+1?g.pop():g.push(`${_}</${h.tagName}>`))}else if(h.type==="text"){if(c(h))return;h.parent&&h.parent.type==="element"&&h.parent.isVisible&&h.parent.isTopElement&&g.push(`${_}${h.text??""}`)}},f=[];return u(l,0,f),f.join(`
|
|
316
177
|
`)}var getAllTextTillNextClickableElement=(t,e=-1)=>{const r=[],n=(i,o)=>{if(!(e!==-1&&o>e)&&!(i.type==="element"&&i!==t&&i.highlightIndex!==void 0)){if(i.type==="text"&&i.text)r.push(i.text);else if(i.type==="element")for(const s of i.children)n(s,o+1)}};return n(t,0),r.join(`
|
|
317
178
|
`).trim()};function getSelectorMap(t){const e=new Map,r=Object.keys(t.map);for(const n of r){const i=t.map[n];i.isInteractive&&typeof i.highlightIndex=="number"&&e.set(i.highlightIndex,i)}return e}function getElementTextMap(t){const e=t.split(`
|
|
318
179
|
`).map(n=>n.trim()).filter(n=>n.length>0),r=new Map;for(const n of e){const i=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(n);if(i){const o=parseInt(i[1],10);r.set(o,n)}}return r}function cleanUpHighlights(){const t=window._highlightCleanupFunctions||[];for(const e of t)typeof e=="function"&&e();window._highlightCleanupFunctions=[]}window.addEventListener("popstate",()=>{cleanUpHighlights()}),window.addEventListener("hashchange",()=>{cleanUpHighlights()}),window.addEventListener("beforeunload",()=>{cleanUpHighlights()});var navigation=window.navigation;if(navigation&&typeof navigation.addEventListener=="function")navigation.addEventListener("navigate",()=>{cleanUpHighlights()});else{let t=window.location.href;setInterval(()=>{window.location.href!==t&&(t=window.location.href,cleanUpHighlights())},500)}function getPageInfo(){const t=window.innerWidth,e=window.innerHeight,r=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),n=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),i=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,o=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,s=Math.max(0,n-(window.innerHeight+o)),a=Math.max(0,r-(window.innerWidth+i));return{viewport_width:t,viewport_height:e,page_width:r,page_height:n,scroll_x:i,scroll_y:o,pixels_above:o,pixels_below:s,pages_above:e>0?o/e:0,pages_below:e>0?s/e:0,total_pages:e>0?n/e:0,current_page_position:o/Math.max(1,n-e),pixels_left:i,pixels_right:a}}function patchReact(t){const e=document.querySelectorAll('[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root');for(const r of e)r.setAttribute("data-page-agent-not-interactive","true")}var PageController=class extends EventTarget{config;flatTree=null;selectorMap=new Map;elementTextMap=new Map;simplifiedHTML="<EMPTY>";lastTimeUpdate=0;isIndexed=!1;mask=null;maskReady=null;constructor(t={}){super(),this.config=t,patchReact(),t.enableMask&&this.initMask()}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{const{SimulatorMask:t}=await Promise.resolve().then(()=>SimulatorMaskBHVXyogh);this.mask=new t})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){const t=window.location.href,e=document.title,r=getPageInfo(),n=resolveViewportExpansion(this.config.viewportExpansion);await this.updateTree();const i=this.simplifiedHTML;return{url:t,title:e,header:`${`Current Page: [${e}](${t})`}
|
|
@@ -320,15 +181,7 @@ ${`Page info: ${r.viewport_width}x${r.viewport_height}px viewport, ${r.page_widt
|
|
|
320
181
|
|
|
321
182
|
${n===-1?"Interactive elements from top layer of the current page (full page):":"Interactive elements from top layer of the current page inside the viewport:"}
|
|
322
183
|
|
|
323
|
-
${r.pixels_above>4&&n!==-1?`... ${r.pixels_above} pixels above (${r.pages_above.toFixed(1)} pages) - scroll to see more ...`:"[Start of page]"}`,content:i,footer:r.pixels_below>4&&n!==-1?`... ${r.pixels_below} pixels below (${r.pages_below.toFixed(1)} pages) - scroll to see more ...`:"[End of page]"}}async updateTree(){this.dispatchEvent(new Event("beforeUpdate")),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents="none"),cleanUpHighlights();const t=[...this.config.interactiveBlacklist||[],...Array.from(document.querySelectorAll("[data-page-agent-not-interactive]"))];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:t}),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.includeAttributes,this.config.keepSemanticTags),this.selectorMap.clear(),this.selectorMap=getSelectorMap(this.flatTree),this.elementTextMap.clear(),this.elementTextMap=getElementTextMap(this.simplifiedHTML),this.isIndexed=!0,this.mask&&(this.mask.wrapper.style.pointerEvents="auto"),this.dispatchEvent(new Event("afterUpdate")),this.simplifiedHTML}async cleanUpHighlights(){console.log("[PageController] cleanUpHighlights"),cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw new Error("DOM tree not indexed yet. Can not perform actions on elements.")}async clickElement(t){try{this.assertIndexed();const e=getElementByIndex(this.selectorMap,t),r=this.elementTextMap.get(t);return await clickElement(e),isAnchorElement(e)&&e.target==="_blank"?{success:!0,message:`✅ Clicked element (${r??t}). ⚠️ Link opened in a new tab.`}:{success:!0,message:`✅ Clicked element (${r??t}).`}}catch(e){return{success:!1,message:`❌ Failed to click element: ${e}`}}}async inputText(t,e){try{this.assertIndexed();const r=getElementByIndex(this.selectorMap,t),n=this.elementTextMap.get(t);return await inputTextElement(r,e),{success:!0,message:`✅ Input text (${e}) into element (${n??t}).`}}catch(r){return{success:!1,message:`❌ Failed to input text: ${r}`}}}async selectOption(t,e){try{this.assertIndexed();const r=getElementByIndex(this.selectorMap,t),n=this.elementTextMap.get(t);return await selectOptionElement(r,e),{success:!0,message:`✅ Selected option (${e}) in element (${n??t}).`}}catch(r){return{success:!1,message:`❌ Failed to select option: ${r}`}}}async scroll(t){try{const{down:e,numPages:r,pixels:n,index:i}=t;return this.assertIndexed(),{success:!0,message:await scrollVertically((n??r*window.innerHeight)*(e?1:-1),i!==void 0?getElementByIndex(this.selectorMap,i):null)}}catch(e){return{success:!1,message:`❌ Failed to scroll: ${e}`}}}async scrollHorizontally(t){try{const{right:e,pixels:r,index:n}=t;return this.assertIndexed(),{success:!0,message:await scrollHorizontally(r*(e?1:-1),n!==void 0?getElementByIndex(this.selectorMap,n):null)}}catch(e){return{success:!1,message:`❌ Failed to scroll horizontally: ${e}`}}}async executeJavascript(script,signal){try{const asyncFunction=eval(`(async (signal) => { ${script} })`),result=await asyncFunction(signal);return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(t){return{success:!1,message:`❌ Error executing JavaScript: ${t}`}}}async showMask(){await this.maskReady,this.mask?.show()}async hideMask(){await this.maskReady,this.mask?.hide()}dispose(){cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML="<EMPTY>",this.isIndexed=!1,this.mask?.dispose(),this.mask=null}};const DEFAULT_ERROR_SELECTORS=['[role="alert"]','[aria-invalid="true"]',".ti3-unifyvalid-error",".ti3-error",".ti-error",".lego-text-error",".lego-error",".el-form-item__error",".ant-form-item-explain-error",".is-invalid",".invalid-feedback",".ng-invalid",".error-msg",".error-message",".error-text",".field-error",".form-error",".is-error",".has-error",".validate-error",".valid-error"],DEFAULT_WARNING_SELECTORS=[".ti3-warning",".ti-warning",".lego-text-warning",".warning-msg",".warning-text",".is-warning",".has-warning"],DEFAULT_DIALOG_SELECTORS=['[role="dialog"]','[role="alertdialog"]','[class*="ti3-modal"]','[class*="ti3-message-box"]','[class*="el-dialog"]','[class*="el-message-box"]','[class*="ant-modal"]','[class*="modal-content"]','[class*="v-dialog"]','[class*="n-modal"]'],TAG_ROLE_MAP={a:"link",article:"article",aside:"complementary",button:"button",caption:"caption",cell:"cell",checkbox:"checkbox",code:"code",columnheader:"columnheader",combobox:"combobox",datalist:"listbox",dd:"definition",details:"group",dialog:"dialog",dt:"term",em:"emphasis",fieldset:"group",figure:"figure",footer:"contentinfo",form:"form",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",header:"banner",hr:"separator",img:"img",input:"textbox",li:"listitem",link:"link",main:"main",mark:"mark",math:"math",menu:"list",menuitem:"menuitem",meter:"meter",nav:"navigation",ol:"list",option:"option",output:"status",p:"paragraph",progress:"progressbar",rowheader:"rowheader",search:"search",section:"region",select:"listbox",strong:"strong",summary:"button",table:"table",tbody:"rowgroup",td:"cell",textarea:"textbox",tfoot:"rowgroup",th:"columnheader",thead:"rowgroup",time:"time",tr:"row",ul:"list"},INPUT_TYPE_ROLE={button:"button",checkbox:"checkbox",color:"textbox",email:"textbox",file:"textbox",image:"button",number:"spinbutton",radio:"radio",range:"slider",reset:"button",search:"searchbox",submit:"button",tel:"textbox",text:"textbox",url:"textbox"},RESOLVED_A11Y_BRAND=Symbol.for("@opentiny/next-sdk:ResolvedA11yConfig");function markResolved(t){return Object.assign(t,{[RESOLVED_A11Y_BRAND]:!0})}function isResolvedA11yConfig(t){return!!t&&t[RESOLVED_A11Y_BRAND]===!0}const STANDARD_STATE_NAMES=["checked","selected","pressed","current","expanded","hasPopup","disabled","readonly","required","invalid","busy","error","warning"],DEFAULT_SELECTED_CLASS_RE=/\b(is-active|isActive|is-selected|isSelected|is-current|isCurrent|active-item|activeItem|tab-active|tabActive|active|selected|current)\b/;function defaultSelectedMatch(t){const e=typeof t.className=="string"?t.className:"";if(!e||!DEFAULT_SELECTED_CLASS_RE.test(e))return!1;const r=t.getAttribute("role")||t.tagName.toLowerCase();return["button","option","a","li","generic"].includes(r)||r.startsWith("tab")}const DEFAULT_A11Y_CONFIG=markResolved({roles:[],states:{selected:[{match:defaultSelectedMatch},{selector:".ti3-btn-item-container.ti3-active"}],error:[{selector:DEFAULT_ERROR_SELECTORS}],warning:[{selector:DEFAULT_WARNING_SELECTORS}]},whitelist:[],blacklist:[],exposedAttributes:[],dialogSelectors:DEFAULT_DIALOG_SELECTORS});function normalizeSelector(t){return t&&(Array.isArray(t)?t.filter(Boolean).join(", "):t)||void 0}function matchesRule(t,e){if(e.match)try{return!!e.match(t)}catch{return!1}const r=normalizeSelector(e.selector);if(r)try{return!!t.closest(r)}catch{return!1}return!1}function matchesRoleRule(t,e){if(e.match)try{return!!e.match(t)}catch{return!1}const r=normalizeSelector(e.selector);if(r)try{return!!t.matches(r)}catch{return!1}return!1}function matchesAnyRule(t,e){return e?(Array.isArray(e)?e:[e]).some(n=>matchesRule(t,n)):!1}function extractSelectors(t){return t?(Array.isArray(t)?t:[t]).flatMap(r=>Array.isArray(r.selector)?r.selector.filter(Boolean):r.selector?[r.selector]:[]):[]}function concatArr(t,e){return[...t??[],...e??[]]}function normalizeMatcherList(t){return t?Array.isArray(t)?t:[t]:[]}function mergeStates(t,e){const r={},n=new Set([...Object.keys(t??{}),...Object.keys(e??{})]);for(const i of n)r[i]=[...normalizeMatcherList(t?.[i]),...normalizeMatcherList(e?.[i])];return r}function mergeA11yConfigs(t,e){return markResolved({roles:concatArr(t.roles,e.roles),states:mergeStates(t.states,e.states),whitelist:concatArr(t.whitelist,e.whitelist),blacklist:concatArr(t.blacklist,e.blacklist),exposedAttributes:concatArr(t.exposedAttributes,e.exposedAttributes),dialogSelectors:concatArr(t.dialogSelectors,e.dialogSelectors)})}function mergeA11yConfig(t){return isResolvedA11yConfig(t)?t:mergeA11yConfigs(DEFAULT_A11Y_CONFIG,t??{})}function ensureResolvedA11yConfig(t){return isResolvedA11yConfig(t)?t:mergeA11yConfig(t)}function defineA11yConfig(t){return t}function computeRole(t,e){const r=t.getAttribute("role"),n=!!r&&r!=="presentation"&&r!=="none";for(const o of e.roles)if(!(n&&!o.force)&&matchesRoleRule(t,o))return o.role;if(n)return r;const i=t.tagName.toLowerCase();if(i==="input"){const o=t.type?.toLowerCase()??"text";return INPUT_TYPE_ROLE[o]??"textbox"}return TAG_ROLE_MAP[i]??"generic"}function computeStates(t,e){const r=[],n=m=>t.getAttribute(m),i=e.states,o=m=>matchesAnyRule(t,i[m]),s=n("aria-checked");if(s==="true")r.push("checked");else if(s==="mixed")r.push("checked=mixed");else if(s==="false")r.push("unchecked");else{const m=t.tagName.toLowerCase();let A;if(m==="input"&&(t.type==="checkbox"||t.type==="radio"))A=t.checked;else if(m==="label"&&t.hasAttribute("for")){const T=document.getElementById(t.getAttribute("for"));T instanceof HTMLInputElement&&(T.type==="checkbox"||T.type==="radio")&&(A=T.checked)}A!==void 0?r.push(A?"checked":"unchecked"):o("checked")&&r.push("checked")}(n("aria-selected")==="true"||o("selected"))&&r.push("selected");const a=n("aria-pressed");a==="true"?r.push("pressed"):a==="mixed"?r.push("pressed=mixed"):a!=="false"&&o("pressed")&&r.push("pressed");const l=n("aria-current");l&&l!=="false"?r.push(l==="true"?"current":`current=${l}`):o("current")&&r.push("current"),(n("aria-disabled")==="true"||t.disabled||o("disabled"))&&r.push("disabled");const c=n("aria-haspopup");(c&&c!=="false"||o("hasPopup"))&&r.push("hasPopup"),(n("aria-expanded")==="true"||o("expanded"))&&r.push("expanded");const u=n("aria-invalid");u&&u!=="false"?r.push(u==="true"?"invalid":`invalid=${u}`):o("invalid")&&r.push("invalid"),(n("aria-readonly")==="true"||t.readOnly||o("readonly"))&&r.push("readonly"),(n("aria-required")==="true"||t.required||o("required"))&&r.push("required"),(n("aria-busy")==="true"||o("busy"))&&r.push("busy");const h=n("aria-orientation");h&&r.push(`orientation=${h}`);const f=n("aria-sort");f&&f!=="none"&&r.push(`sort=${f}`),n("aria-multiselectable")==="true"&&r.push("multiselectable");const g=t.tagName.match(/^H([1-6])$/);g&&r.push(`level=${g[1]}`);const b=n("aria-level");b&&!g&&r.push(`level=${b}`);try{window.getComputedStyle(t).cursor==="pointer"&&r.push("cursor=pointer")}catch{}const P=t.tagName.toLowerCase();if(P==="input"||P==="textarea"||P==="select"){const m=t.value;m!==void 0&&m!==""&&r.push(`value="${m}"`)}const w=n("aria-valuenow");w&&r.push(`valuenow="${w}"`);const p=n("aria-valuetext");if(p&&r.push(`valuetext="${p}"`),P==="a"){const m=n("target");m&&r.push(`target=${m}`)}o("error")?r.push("error"):o("warning")&&r.push("warning");for(const m of Object.keys(i))STANDARD_STATE_NAMES.includes(m)||matchesAnyRule(t,i[m])&&r.push(m);for(const m of e.exposedAttributes){const A=t.getAttribute(m);A!==null&&r.push(`${m}="${A}"`)}return Array.from(new Set(r))}function resolveA11yRole(t,e){return computeRole(t,ensureResolvedA11yConfig(e))}function resolveA11yInfo(t,e){const r=ensureResolvedA11yConfig(e);return{role:computeRole(t,r),tokens:computeStates(t,r)}}var candidateSelectors=["input:not([inert]):not([inert] *)","select:not([inert]):not([inert] *)","textarea:not([inert]):not([inert] *)","a[href]:not([inert]):not([inert] *)","area[href]:not([inert]):not([inert] *)","button:not([inert]):not([inert] *)","[tabindex]:not(slot):not([inert]):not([inert] *)","audio[controls]:not([inert]):not([inert] *)","video[controls]:not([inert]):not([inert] *)",'[contenteditable]:not([contenteditable="false"]):not([inert]):not([inert] *)',"details>summary:first-of-type:not([inert]):not([inert] *)","details:not([inert]):not([inert] *)"],candidateSelector=candidateSelectors.join(","),NoElement=typeof Element>"u",matches=NoElement?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,getRootNode=!NoElement&&Element.prototype.getRootNode?function(t){var e;return t==null||(e=t.getRootNode)===null||e===void 0?void 0:e.call(t)}:function(t){return t?.ownerDocument},isContentEditable=function t(e){var r,n=e==null||(r=e.getAttribute)===null||r===void 0?void 0:r.call(e,"contenteditable");return n===""||n==="true"},hasTabIndex=function t(e){return!isNaN(parseInt(e.getAttribute("tabindex"),10))},getTabIndex=function t(e){if(!e)throw new Error("No node provided");return e.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(e.tagName)||isContentEditable(e))&&!hasTabIndex(e)?0:e.tabIndex},isInput=function t(e){return e.tagName==="INPUT"},isHiddenInput=function t(e){return isInput(e)&&e.type==="hidden"},isDetailsWithSummary=function t(e){var r=e.tagName==="DETAILS"&&Array.prototype.slice.apply(e.children).some(function(n){return n.tagName==="SUMMARY"});return r},getCheckedRadio=function t(e,r){for(var n=0;n<e.length;n++)if(e[n].checked&&e[n].form===r)return e[n]},isTabbableRadio=function t(e){if(!e.name)return!0;var r=e.form||getRootNode(e),n=function(a){return r.querySelectorAll('input[type="radio"][name="'+a+'"]')},i;if(typeof window<"u"&&typeof window.CSS<"u"&&typeof window.CSS.escape=="function")i=n(window.CSS.escape(e.name));else try{i=n(e.name)}catch(s){return console.error("Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s",s.message),!1}var o=getCheckedRadio(i,e.form);return!o||o===e},isRadio=function t(e){return isInput(e)&&e.type==="radio"},isNonTabbableRadio=function t(e){return isRadio(e)&&!isTabbableRadio(e)},isNodeAttached=function t(e){var r,n=e&&getRootNode(e),i=(r=n)===null||r===void 0?void 0:r.host,o=!1;if(n&&n!==e){var s,a,l;for(o=!!((s=i)!==null&&s!==void 0&&(a=s.ownerDocument)!==null&&a!==void 0&&a.contains(i)||e!=null&&(l=e.ownerDocument)!==null&&l!==void 0&&l.contains(e));!o&&i;){var c,u,h;n=getRootNode(i),i=(c=n)===null||c===void 0?void 0:c.host,o=!!((u=i)!==null&&u!==void 0&&(h=u.ownerDocument)!==null&&h!==void 0&&h.contains(i))}}return o},isZeroArea=function t(e){var r=e.getBoundingClientRect(),n=r.width,i=r.height;return n===0&&i===0},isHidden$2=function t(e,r){var n=r.displayCheck,i=r.getShadowRoot;if(n==="full-native"&&"checkVisibility"in e){var o=e.checkVisibility({checkOpacity:!1,opacityProperty:!1,contentVisibilityAuto:!0,visibilityProperty:!0,checkVisibilityCSS:!0});return!o}var s=getComputedStyle(e),a=s.visibility;if(a==="hidden"||a==="collapse")return!0;var l=matches.call(e,"details>summary:first-of-type"),c=l?e.parentElement:e;if(matches.call(c,"details:not([open]) *"))return!0;if(!n||n==="full"||n==="full-native"||n==="legacy-full"){if(typeof i=="function"){for(var u=e;e;){var h=e.parentElement,f=getRootNode(e);if(h&&!h.shadowRoot&&i(h)===!0)return isZeroArea(e);e.assignedSlot?e=e.assignedSlot:!h&&f!==e.ownerDocument?e=f.host:e=h}e=u}if(isNodeAttached(e))return!e.getClientRects().length;if(n!=="legacy-full")return!0}else if(n==="non-zero-area")return isZeroArea(e);return!1},isDisabledFromFieldset=function t(e){if(/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(e.tagName))for(var r=e.parentElement;r;){if(r.tagName==="FIELDSET"&&r.disabled){for(var n=0;n<r.children.length;n++){var i=r.children.item(n);if(i.tagName==="LEGEND")return matches.call(r,"fieldset[disabled] *")?!0:!i.contains(e)}return!0}r=r.parentElement}return!1},isNodeMatchingSelectorFocusable=function t(e,r){return!(r.disabled||isHiddenInput(r)||isHidden$2(r,e)||isDetailsWithSummary(r)||isDisabledFromFieldset(r))},isNodeMatchingSelectorTabbable=function t(e,r){return!(isNonTabbableRadio(r)||getTabIndex(r)<0||!isNodeMatchingSelectorFocusable(e,r))},isTabbable=function t(e,r){if(r=r||{},!e)throw new Error("No node provided");return matches.call(e,candidateSelector)===!1?!1:isNodeMatchingSelectorTabbable(r,e)};const DEFAULT_PAGE_AGENT_TOOL_CONFIG={enableHighlight:!1,removeMaskAfterToolCall:!0,a11yConfig:DEFAULT_A11Y_CONFIG};function getPageAgentToolConfig(){return typeof window<"u"&&window.__webmcpcli_toolConfig?window.__webmcpcli_toolConfig:{enableHighlight:DEFAULT_PAGE_AGENT_TOOL_CONFIG.enableHighlight,removeMaskAfterToolCall:DEFAULT_PAGE_AGENT_TOOL_CONFIG.removeMaskAfterToolCall,a11yConfig:mergeA11yConfig()}}function resolvePatch(t,e){return{enableHighlight:t.enableHighlight??e.enableHighlight,removeMaskAfterToolCall:t.removeMaskAfterToolCall??e.removeMaskAfterToolCall,a11yConfig:mergeA11yConfigs(e.a11yConfig,t.a11yConfig??{})}}function setPageAgentToolConfig(t,e){const r=e?.mode??"merge",n=getPageAgentToolConfig(),i=typeof t=="function"?resolvePatch(t(n),DEFAULT_PAGE_AGENT_TOOL_CONFIG):resolvePatch(t,r==="replace"?DEFAULT_PAGE_AGENT_TOOL_CONFIG:n);return typeof window<"u"&&(window.__webmcpcli_toolConfig=i),i}function isInShadowDom(t){return t.getRootNode()instanceof ShadowRoot}function dispatchComposedEvents(t,...e){for(const r of e)t.dispatchEvent(new Event(r,{bubbles:!0,composed:!0}))}function deepQuerySelectorAll(t,e=document){const r=Array.from(e.querySelectorAll(t)),n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null);let i=n.currentNode;for(;i;)i.shadowRoot&&r.push(...deepQuerySelectorAll(t,i.shadowRoot)),i=n.nextNode();return r}function waitForDomSettled(t=600,e=150){return new Promise(r=>{let n=!1,i;const o=()=>{n||(n=!0,s.disconnect(),i&&clearTimeout(i),r())},s=new MutationObserver(()=>{i&&clearTimeout(i),i=setTimeout(o,e)});i=setTimeout(o,e),setTimeout(o,t),s.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","style","hidden"]})})}function detectPageDialog(){const t=new Set,e=[],r=getPageAgentToolConfig().a11yConfig.dialogSelectors;for(const n of r)try{for(const i of deepQuerySelectorAll(n)){if(t.has(i)||i.id?.includes("page-agent-runtime")||i.closest("#page-agent-runtime_simulator-mask"))continue;const o=i.getBoundingClientRect();if(o.width<50||o.height<50)continue;const s=window.getComputedStyle(i);if(s.display==="none"||s.visibility==="hidden")continue;const a=s.position==="fixed"||s.position==="absolute",l=parseInt(s.zIndex||"0",10);if(!a||l<100)continue;const c=window.innerWidth,u=window.innerHeight;if(!(o.left<c*.6&&o.right>c*.4&&o.top<u*.6&&o.bottom>u*.4))continue;t.add(i);const f=(i.textContent||"").trim().replace(/\s+/g," ");if(f.length>5){const g=i.querySelectorAll('button, [role="button"], a'),b=Array.from(g).map(w=>(w.textContent||"").trim()).filter(w=>w.length>0&&w.length<20).slice(0,5),P=b.length?` [可操作按钮: ${b.join(" / ")}]`:"";e.push(`${f.substring(0,300)}${P}`)}}}catch{}return e.length===0?"":`
|
|
324
|
-
[页面弹窗检测] 检测到 ${e.length} 个模态弹窗,请优先处理:
|
|
325
|
-
${e.map((n,i)=>`${i+1}. ${n}`).join(`
|
|
326
|
-
`)}
|
|
327
|
-
`}function detectValidationErrors(){const t=new Set,e=[],r=extractSelectors(getPageAgentToolConfig().a11yConfig.states.error);for(const n of r)try{for(const i of deepQuerySelectorAll(n)){if(t.has(i)||Array.from(t).some(l=>l.contains(i)))continue;const o=i.getBoundingClientRect();if(o.width<1||o.height<1)continue;const s=window.getComputedStyle(i);if(s.display==="none"||s.visibility==="hidden")continue;const a=(i.textContent||"").trim().replace(/\s+/g," ");a.length>2&&a.length<200&&(t.add(i),e.push(a))}}catch{}return e.length===0?"":`
|
|
328
|
-
[校验提示] 检测到 ${e.length} 个表单校验错误,请先修复后再继续:
|
|
329
|
-
${e.map((n,i)=>`${i+1}. ${n}`).join(`
|
|
330
|
-
`)}
|
|
331
|
-
`}const NON_CONTENT_TAGS=new Set(["script","style","noscript","template","link","meta","head","title"]);function isNonContentElement(t){return NON_CONTENT_TAGS.has(t.tagName.toLowerCase())}function hasOwnPointerCursor(t){try{if(window.getComputedStyle(t).cursor!=="pointer")return!1;const e=t.parentElement;return e?window.getComputedStyle(e).cursor!=="pointer":!0}catch{return!1}}const INTERACTION_PSEUDO_RE=/:(hover|focus|focus-visible|focus-within|active)\b/gi;function collectInteractivePointerSelectors(t,e){for(const r of Array.from(t)){const n=r,i=r;if(!n.selectorText&&i.cssRules){collectInteractivePointerSelectors(i.cssRules,e);continue}const o=n.selectorText;if(!(!o||!n.style||n.style.cursor!=="pointer")&&/:(hover|focus|focus-visible|focus-within|active)\b/i.test(o))for(const s of o.split(",")){const a=s.replace(INTERACTION_PSEUDO_RE,"").trim();a&&a!=="*"&&e.add(a)}}}function collectHoverPointerElements(t){const e=new Set,r=new Set;try{for(const i of Array.from(document.styleSheets)){let o=null;try{o=i.cssRules}catch{continue}o&&collectInteractivePointerSelectors(o,r)}}catch{return e}if(r.size===0)return e;const n=Array.from(r);try{for(const i of deepQuerySelectorAll(n.join(", "),t))e.add(i);return e}catch{for(const i of n)try{for(const o of deepQuerySelectorAll(i,t))e.add(o)}catch{}}return e}function isHidden$1(t){if(isNonContentElement(t)||t.getAttribute("aria-hidden")==="true"||t.hidden)return!0;try{const e=window.getComputedStyle(t);if(e.display==="none"||e.visibility==="hidden"||e.opacity==="0")return!0;const r=e.overflowX!=="visible",n=e.overflowY!=="visible";if(parseFloat(e.width)===0&&r||parseFloat(e.height)===0&&n)return!0}catch{}return!1}function collectTitleLabel(t){const e=t.getAttribute("title")?.trim();if(e)return e;const n=t.querySelector("[title]")?.getAttribute("title")?.trim();return n||""}function collectDescendantText(t,e){let r="";const n=i=>{if(i.nodeType===Node.TEXT_NODE)r+=(i.textContent??"")+" ";else if(i.nodeType===Node.ELEMENT_NODE){const o=i;if(o!==t&&isNonContentElement(o)||isHidden$1(o)&&o!==t||o===t&&isNonContentElement(o))return;if(o!==t){const s=o.tagName.toLowerCase(),a=resolveA11yRole(o,e),l=["button","a","input","select","textarea","li","option"].includes(s),c=["button","link","checkbox","radio","textbox","listitem","option","combobox","listbox"].includes(a),u=isTabbable(o),h=hasOwnPointerCursor(o);if(u&&!(a==="generic"&&!h)||l||c)return}for(const s of Array.from(o.childNodes))n(s)}};return n(t),r.trim().replace(/\s+/g," ")}function getComposedChildren(t){const e=t.shadowRoot?t.shadowRoot.children:t.children,r=[];for(const n of Array.from(e))if(n instanceof HTMLSlotElement){const i=n.assignedElements({flatten:!0});r.push(...i.length>0?i:Array.from(n.children))}else r.push(n);return r}var toStr=Object.prototype.toString;function isCallable(t){return typeof t=="function"||toStr.call(t)==="[object Function]"}function toInteger(t){var e=Number(t);return isNaN(e)?0:e===0||!isFinite(e)?e:(e>0?1:-1)*Math.floor(Math.abs(e))}var maxSafeInteger=Math.pow(2,53)-1;function toLength(t){var e=toInteger(t);return Math.min(Math.max(e,0),maxSafeInteger)}function arrayFrom(t,e){var r=Array,n=Object(t);if(t==null)throw new TypeError("Array.from requires an array-like object - not null or undefined");for(var i=toLength(n.length),o=isCallable(r)?Object(new r(i)):new Array(i),s=0,a;s<i;)a=n[s],o[s]=a,s+=1;return o.length=i,o}function _typeof$1(t){"@babel/helpers - typeof";return _typeof$1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$1(t)}function _classCallCheck(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function _defineProperties(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,_toPropertyKey(n.key),n)}}function _createClass(t,e,r){return e&&_defineProperties(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function _defineProperty(t,e,r){return e=_toPropertyKey(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function _toPropertyKey(t){var e=_toPrimitive(t,"string");return _typeof$1(e)==="symbol"?e:String(e)}function _toPrimitive(t,e){if(_typeof$1(t)!=="object"||t===null)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(_typeof$1(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var SetLike=(function(){function t(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];_classCallCheck(this,t),_defineProperty(this,"items",void 0),this.items=e}return _createClass(t,[{key:"add",value:function(r){return this.has(r)===!1&&this.items.push(r),this}},{key:"clear",value:function(){this.items=[]}},{key:"delete",value:function(r){var n=this.items.length;return this.items=this.items.filter(function(i){return i!==r}),n!==this.items.length}},{key:"forEach",value:function(r){var n=this;this.items.forEach(function(i){r(i,i,n)})}},{key:"has",value:function(r){return this.items.indexOf(r)!==-1}},{key:"size",get:function(){return this.items.length}}]),t})();const SetLike$1=typeof Set>"u"?Set:SetLike;function getLocalName(t){var e;return(e=t.localName)!==null&&e!==void 0?e:t.tagName.toLowerCase()}var localNameToRoleMappings={article:"article",aside:"complementary",button:"button",datalist:"listbox",dd:"definition",details:"group",dialog:"dialog",dt:"term",fieldset:"group",figure:"figure",form:"form",footer:"contentinfo",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",header:"banner",hr:"separator",html:"document",legend:"legend",li:"listitem",math:"math",main:"main",menu:"list",nav:"navigation",ol:"list",optgroup:"group",option:"option",output:"status",progress:"progressbar",section:"region",summary:"button",table:"table",tbody:"rowgroup",textarea:"textbox",tfoot:"rowgroup",td:"cell",th:"columnheader",thead:"rowgroup",tr:"row",ul:"list"},prohibitedAttributes={caption:new Set(["aria-label","aria-labelledby"]),code:new Set(["aria-label","aria-labelledby"]),deletion:new Set(["aria-label","aria-labelledby"]),emphasis:new Set(["aria-label","aria-labelledby"]),generic:new Set(["aria-label","aria-labelledby","aria-roledescription"]),insertion:new Set(["aria-label","aria-labelledby"]),none:new Set(["aria-label","aria-labelledby"]),paragraph:new Set(["aria-label","aria-labelledby"]),presentation:new Set(["aria-label","aria-labelledby"]),strong:new Set(["aria-label","aria-labelledby"]),subscript:new Set(["aria-label","aria-labelledby"]),superscript:new Set(["aria-label","aria-labelledby"])};function hasGlobalAriaAttributes(t,e){return["aria-atomic","aria-busy","aria-controls","aria-current","aria-description","aria-describedby","aria-details","aria-dropeffect","aria-flowto","aria-grabbed","aria-hidden","aria-keyshortcuts","aria-label","aria-labelledby","aria-live","aria-owns","aria-relevant","aria-roledescription"].some(function(r){var n;return t.hasAttribute(r)&&!((n=prohibitedAttributes[e])!==null&&n!==void 0&&n.has(r))})}function ignorePresentationalRole(t,e){return hasGlobalAriaAttributes(t,e)}function getRole(t){var e=getExplicitRole(t);if(e===null||presentationRoles.indexOf(e)!==-1){var r=getImplicitRole(t);if(presentationRoles.indexOf(e||"")===-1||ignorePresentationalRole(t,r||""))return r}return e}function getImplicitRole(t){var e=localNameToRoleMappings[getLocalName(t)];if(e!==void 0)return e;switch(getLocalName(t)){case"a":case"area":case"link":if(t.hasAttribute("href"))return"link";break;case"img":return t.getAttribute("alt")===""&&!ignorePresentationalRole(t,"img")?"presentation":"img";case"input":{var r=t,n=r.type;switch(n){case"button":case"image":case"reset":case"submit":return"button";case"checkbox":case"radio":return n;case"range":return"slider";case"email":case"tel":case"text":case"url":return t.hasAttribute("list")?"combobox":"textbox";case"search":return t.hasAttribute("list")?"combobox":"searchbox";case"number":return"spinbutton";default:return null}}case"select":return t.hasAttribute("multiple")||t.size>1?"listbox":"combobox"}return null}function getExplicitRole(t){var e=t.getAttribute("role");if(e!==null){var r=e.trim().split(" ")[0];if(r.length>0)return r}return null}var presentationRoles=["presentation","none"];function isElement(t){return t!==null&&t.nodeType===t.ELEMENT_NODE}function isHTMLTableCaptionElement(t){return isElement(t)&&getLocalName(t)==="caption"}function isHTMLInputElement(t){return isElement(t)&&getLocalName(t)==="input"}function isHTMLOptGroupElement(t){return isElement(t)&&getLocalName(t)==="optgroup"}function isHTMLSelectElement(t){return isElement(t)&&getLocalName(t)==="select"}function isHTMLTableElement(t){return isElement(t)&&getLocalName(t)==="table"}function isHTMLTextAreaElement(t){return isElement(t)&&getLocalName(t)==="textarea"}function safeWindow(t){var e=t.ownerDocument===null?t:t.ownerDocument,r=e.defaultView;if(r===null)throw new TypeError("no window available");return r}function isHTMLFieldSetElement(t){return isElement(t)&&getLocalName(t)==="fieldset"}function isHTMLLegendElement(t){return isElement(t)&&getLocalName(t)==="legend"}function isHTMLSlotElement(t){return isElement(t)&&getLocalName(t)==="slot"}function isSVGElement(t){return isElement(t)&&t.ownerSVGElement!==void 0}function isSVGSVGElement(t){return isElement(t)&&getLocalName(t)==="svg"}function isSVGTitleElement(t){return isSVGElement(t)&&getLocalName(t)==="title"}function queryIdRefs(t,e){if(isElement(t)&&t.hasAttribute(e)){var r=t.getAttribute(e).split(" "),n=t.getRootNode?t.getRootNode():t.ownerDocument;return r.map(function(i){return n.getElementById(i)}).filter(function(i){return i!==null})}return[]}function hasAnyConcreteRoles(t,e){return isElement(t)?e.indexOf(getRole(t))!==-1:!1}function asFlatString(t){return t.trim().replace(/\s\s+/g," ")}function isHidden(t,e){if(!isElement(t))return!1;if(t.hasAttribute("hidden")||t.getAttribute("aria-hidden")==="true")return!0;var r=e(t);return r.getPropertyValue("display")==="none"||r.getPropertyValue("visibility")==="hidden"}function isControl(t){return hasAnyConcreteRoles(t,["button","combobox","listbox","textbox"])||hasAbstractRole(t,"range")}function hasAbstractRole(t,e){if(!isElement(t))return!1;switch(e){case"range":return hasAnyConcreteRoles(t,["meter","progressbar","scrollbar","slider","spinbutton"]);default:throw new TypeError("No knowledge about abstract role '".concat(e,"'. This is likely a bug :("))}}function querySelectorAllSubtree(t,e){var r=arrayFrom(t.querySelectorAll(e));return queryIdRefs(t,"aria-owns").forEach(function(n){r.push.apply(r,arrayFrom(n.querySelectorAll(e)))}),r}function querySelectedOptions(t){return isHTMLSelectElement(t)?t.selectedOptions||querySelectorAllSubtree(t,"[selected]"):querySelectorAllSubtree(t,'[aria-selected="true"]')}function isMarkedPresentational(t){return hasAnyConcreteRoles(t,presentationRoles)}function isNativeHostLanguageTextAlternativeElement(t){return isHTMLTableCaptionElement(t)}function allowsNameFromContent(t){return hasAnyConcreteRoles(t,["button","cell","checkbox","columnheader","gridcell","heading","label","legend","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","row","rowheader","switch","tab","tooltip","treeitem"])}function isDescendantOfNativeHostLanguageTextAlternativeElement(t){return!1}function getValueOfTextbox(t){return isHTMLInputElement(t)||isHTMLTextAreaElement(t)?t.value:t.textContent||""}function getTextualContent(t){var e=t.getPropertyValue("content");return/^["'].*["']$/.test(e)?e.slice(1,-1):""}function isLabelableElement(t){var e=getLocalName(t);return e==="button"||e==="input"&&t.getAttribute("type")!=="hidden"||e==="meter"||e==="output"||e==="progress"||e==="select"||e==="textarea"}function findLabelableElement(t){if(isLabelableElement(t))return t;var e=null;return t.childNodes.forEach(function(r){if(e===null&&isElement(r)){var n=findLabelableElement(r);n!==null&&(e=n)}}),e}function getControlOfLabel(t){if(t.control!==void 0)return t.control;var e=t.getAttribute("for");return e!==null?t.ownerDocument.getElementById(e):findLabelableElement(t)}function getLabels(t){var e=t.labels;if(e===null)return e;if(e!==void 0)return arrayFrom(e);if(!isLabelableElement(t))return null;var r=t.ownerDocument;return arrayFrom(r.querySelectorAll("label")).filter(function(n){return getControlOfLabel(n)===t})}function getSlotContents(t){var e=t.assignedNodes();return e.length===0?arrayFrom(t.childNodes):e}function computeTextAlternative(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=new SetLike$1,n=safeWindow(t),i=e.compute,o=i===void 0?"name":i,s=e.computedStyleSupportsPseudoElements,a=s===void 0?e.getComputedStyle!==void 0:s,l=e.getComputedStyle,c=l===void 0?n.getComputedStyle.bind(n):l,u=e.hidden,h=u===void 0?!1:u;function f(p,m){var A="";if(isElement(p)&&a){var T=c(p,"::before"),k=getTextualContent(T);A="".concat(k," ").concat(A)}var Z=isHTMLSlotElement(p)?getSlotContents(p):arrayFrom(p.childNodes).concat(queryIdRefs(p,"aria-owns"));if(Z.forEach(function(j){var H=w(j,{isEmbeddedInLabel:m.isEmbeddedInLabel,isReferenced:!1,recursion:!0}),B=isElement(j)?c(j).getPropertyValue("display"):"inline",G=B!=="inline"?" ":"";A+="".concat(G).concat(H).concat(G)}),isElement(p)&&a){var R=c(p,"::after"),V=getTextualContent(R);A="".concat(A," ").concat(V)}return A.trim()}function g(p,m){var A=p.getAttributeNode(m);return A!==null&&!r.has(A)&&A.value.trim()!==""?(r.add(A),A.value):null}function b(p){return isElement(p)?g(p,"title"):null}function P(p){if(!isElement(p))return null;if(isHTMLFieldSetElement(p)){r.add(p);for(var m=arrayFrom(p.childNodes),A=0;A<m.length;A+=1){var T=m[A];if(isHTMLLegendElement(T))return w(T,{isEmbeddedInLabel:!1,isReferenced:!1,recursion:!1})}}else if(isHTMLTableElement(p)){r.add(p);for(var k=arrayFrom(p.childNodes),Z=0;Z<k.length;Z+=1){var R=k[Z];if(isHTMLTableCaptionElement(R))return w(R,{isEmbeddedInLabel:!1,isReferenced:!1,recursion:!1})}}else if(isSVGSVGElement(p)){r.add(p);for(var V=arrayFrom(p.childNodes),j=0;j<V.length;j+=1){var H=V[j];if(isSVGTitleElement(H))return H.textContent}return null}else if(getLocalName(p)==="img"||getLocalName(p)==="area"){var B=g(p,"alt");if(B!==null)return B}else if(isHTMLOptGroupElement(p)){var G=g(p,"label");if(G!==null)return G}if(isHTMLInputElement(p)&&(p.type==="button"||p.type==="submit"||p.type==="reset")){var ie=g(p,"value");if(ie!==null)return ie;if(p.type==="submit")return"Submit";if(p.type==="reset")return"Reset"}var X=getLabels(p);if(X!==null&&X.length!==0)return r.add(p),arrayFrom(X).map(function(Q){return w(Q,{isEmbeddedInLabel:!0,isReferenced:!1,recursion:!0})}).filter(function(Q){return Q.length>0}).join(" ");if(isHTMLInputElement(p)&&p.type==="image"){var te=g(p,"alt");if(te!==null)return te;var oe=g(p,"title");return oe!==null?oe:"Submit Query"}if(hasAnyConcreteRoles(p,["button"])){var re=f(p,{isEmbeddedInLabel:!1});if(re!=="")return re}return null}function w(p,m){if(r.has(p))return"";if(!h&&isHidden(p,c)&&!m.isReferenced)return r.add(p),"";var A=isElement(p)?p.getAttributeNode("aria-labelledby"):null,T=A!==null&&!r.has(A)?queryIdRefs(p,"aria-labelledby"):[];if(o==="name"&&!m.isReferenced&&T.length>0)return r.add(A),T.map(function(B){return w(B,{isEmbeddedInLabel:m.isEmbeddedInLabel,isReferenced:!0,recursion:!1})}).join(" ");var k=m.recursion&&isControl(p)&&o==="name";if(!k){var Z=(isElement(p)&&p.getAttribute("aria-label")||"").trim();if(Z!==""&&o==="name")return r.add(p),Z;if(!isMarkedPresentational(p)){var R=P(p);if(R!==null)return r.add(p),R}}if(hasAnyConcreteRoles(p,["menu"]))return r.add(p),"";if(k||m.isEmbeddedInLabel||m.isReferenced){if(hasAnyConcreteRoles(p,["combobox","listbox"])){r.add(p);var V=querySelectedOptions(p);return V.length===0?isHTMLInputElement(p)?p.value:"":arrayFrom(V).map(function(B){return w(B,{isEmbeddedInLabel:m.isEmbeddedInLabel,isReferenced:!1,recursion:!0})}).join(" ")}if(hasAbstractRole(p,"range"))return r.add(p),p.hasAttribute("aria-valuetext")?p.getAttribute("aria-valuetext"):p.hasAttribute("aria-valuenow")?p.getAttribute("aria-valuenow"):p.getAttribute("value")||"";if(hasAnyConcreteRoles(p,["textbox"]))return r.add(p),getValueOfTextbox(p)}if(allowsNameFromContent(p)||isElement(p)&&m.isReferenced||isNativeHostLanguageTextAlternativeElement(p)||isDescendantOfNativeHostLanguageTextAlternativeElement()){var j=f(p,{isEmbeddedInLabel:m.isEmbeddedInLabel});if(j!=="")return r.add(p),j}if(p.nodeType===p.TEXT_NODE)return r.add(p),p.textContent||"";if(m.recursion)return r.add(p),f(p,{isEmbeddedInLabel:m.isEmbeddedInLabel});var H=b(p);return H!==null?(r.add(p),H):(r.add(p),"")}return asFlatString(w(t,{isEmbeddedInLabel:!1,isReferenced:o==="description",recursion:!1}))}function prohibitsNaming(t){return hasAnyConcreteRoles(t,["caption","code","deletion","emphasis","generic","insertion","none","paragraph","presentation","strong","subscript","superscript"])}function computeAccessibleName(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return prohibitsNaming(t)?"":computeTextAlternative(t,e)}const INTERACTIVE_ROLES=new Set(["button","link","textbox","searchbox","combobox","listbox","checkbox","radio","switch","slider","spinbutton","menuitem","menuitemcheckbox","menuitemradio","tab","treeitem"]);function buildVNode(t,e,r,n,i,o,s=new Set){if(isNonContentElement(t)||isHidden$1(t)||n.has(t))return null;const{role:a,tokens:l}=resolveA11yInfo(t,o);let c=computeAccessibleName(t);const u=isTabbable(t),h=l.includes("cursor=pointer"),f=hasOwnPointerCursor(t)||s.has(t),g=i.has(t),b=t.tagName.toLowerCase()==="label"&&t.hasAttribute("for");if(!c.trim()){const R=t.tagName.toLowerCase();if(!(R==="select"||a==="combobox"||a==="listbox")){const j=["button","a","input","textarea","li","label"].includes(R);(u||g||h||f||j||a==="listitem"||a==="option")&&(c=collectDescendantText(t,o))}}if(!c.trim()&&(u||g||h||f||a==="button")&&(c=collectTitleLabel(t)),!c.trim()&&["tab","menuitem","option","treeitem","button"].includes(a)&&(c=collectVisiblePlainText(t)),!c.trim()&&!(getComposedChildren(t).length>0)){const V=collectDescendantText(t,o);V&&(c=V)}const P=t.tagName.toLowerCase(),w=P==="a"&&t.hasAttribute("href")||["button","input","select","textarea"].includes(P)&&!t.hasAttribute("disabled"),p=u&&!(a==="generic"&&!f),m=l.includes("disabled"),A=!m&&p||g||b||w||!m&&INTERACTIVE_ROLES.has(a)||!m&&f;let T;A&&(T=e.value,r.set(T,t),e.value++);const k=[];for(const R of getComposedChildren(t)){const V=buildVNode(R,e,r,n,i,o,s);V&&k.push(V)}const Z={role:a,name:c,tokens:l,ref:T,el:t,children:k};return hasInteractiveDescendant(Z)&&(Z.name=getOwnDeclaredName(t)),Z}function getOwnDeclaredName(t){return t.hasAttribute("aria-label")||t.hasAttribute("aria-labelledby")?computeAccessibleName(t).trim():""}function isStaticBranch(t){return t.ref===void 0&&!hasInteractiveDescendant(t)}function collectVisiblePlainText(t){return collectDescendantText(t).replace(/\s+/g," ").trim()}function getStaticDisplayText(t){const e=t.children.length>0?t.children.map(getStaticDisplayText).filter(Boolean).join(" ").replace(/\s+/g," ").trim():"",r=t.children.length===0?collectVisiblePlainText(t.el):"",n=t.name.trim(),i=[];if(n&&!isNoiseAccessibleName(n)&&i.push(n),e&&!isNoiseAccessibleName(e)){const o=n.replace(/\s+/g," ").trim(),s=e.replace(/\s+/g," ").trim();(!o||s!==o&&!o.includes(s))&&i.push(e)}return i.length===0&&r&&!isNoiseAccessibleName(r)&&i.push(r),i.join(" ").replace(/\s+/g," ").trim()}function isNoiseAccessibleName(t){const e=t.trim();return e?!!(/@font-face\b/i.test(e)||/data:(?:font|application|image)\//i.test(e)||/base64,[A-Za-z0-9+/=]{80,}/.test(e)):!1}function canOmitStaticChild(t,e,r){const n=getStaticDisplayText(t);if(!n||!e.trim())return!1;const i=e.replace(/\s+/g," ").trim(),o=n.replace(/\s+/g," ").trim();return r?o===i:i.includes(o)}function hasValue(t){return t.ref!==void 0||t.name.trim()!==""?!0:t.children.some(hasValue)}function hasInteractiveDescendant(t){return t.children.some(e=>e.ref!==void 0||hasInteractiveDescendant(e))}function findSingleRefDescendant(t){const e=[],r=n=>{n.ref!==void 0&&e.push(n),!(e.length>1)&&n.children.forEach(r)};return t.children.forEach(r),e.length===1?e[0]:null}function shouldPassThrough(t,e){return!(!e.pruneUnnamed||e.preserveRoles.includes(t.role)||t.ref!==void 0||t.name.trim()!=="")}function formatNameAttr(t){const e=t.replace(/[\r\n]+/g," ").replace(/"/g,'\\"').trim();return e?` "${e}"`:""}function serializeVNode(t,e,r){const n=hasInteractiveDescendant(t),i=r.preserveRoles.includes(t.role),o=" ".repeat(e),s=t.ref!==void 0?` #${t.ref}`:"",a=t.tokens.map(m=>m.replace(/[\r\n]+/g," ").replace(/"/g,'\\"')),l=a.length>0?` [${a.join(" ")}]`:"";if(!n&&!i){if(shouldPassThrough(t,r))return t.children.filter(A=>hasValue(A)).flatMap(A=>serializeVNode(A,e,r));let m=t.name.trim();return!m&&t.children.length>0&&(m=collectVisiblePlainText(t.el)),isNoiseAccessibleName(m)&&(m=""),[`${o}- ${t.role}${s}${l}${formatNameAttr(m)}`]}if(!n&&i){const m=getOwnDeclaredName(t.el),A=`${o}- ${t.role}${s}${l}${formatNameAttr(m)}`,T=t.children.flatMap(k=>serializeVNode(k,e+1,r));return[A,...T]}const c=getOwnDeclaredName(t.el),u=c!=="",h=t.children.filter(isStaticBranch),f=h.map(getStaticDisplayText).filter(Boolean).join(" ").replace(/\s+/g," ").trim();let g=u?c:f;if(isNoiseAccessibleName(g)&&(g=""),!u&&isNoiseAccessibleName(t.name)&&(g=f&&!isNoiseAccessibleName(f)?f:""),!(t.ref!==void 0||g!==""||i||!r.pruneUnnamed))return t.children.filter(m=>hasValue(m)).flatMap(m=>serializeVNode(m,e,r));if(t.ref!==void 0){const m=findSingleRefDescendant(t);if(m&&m.role==="generic"&&!hasInteractiveDescendant(m)&&h.length===0){const A=g.trim()||m.name.trim(),T=m.ref!==void 0?` #${m.ref}`:s;return[`${o}- ${t.role}${T}${l}${formatNameAttr(A)}`]}}const P=t.children.filter(m=>isStaticBranch(m)?!canOmitStaticChild(m,g,u):!0),w=`${o}- ${t.role}${s}${l}${formatNameAttr(g)}`,p=P.flatMap(m=>serializeVNode(m,e+1,r));return[w,...p]}const HIGHLIGHT_CONTAINER_ID="webmcpcli-highlight-container",HIGHLIGHT_CONTAINER_STYLE_ID="webmcpcli-highlight-container-style",colors=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"],opacity=Math.floor(.3*255).toString(16).padStart(2,"0"),injectStyles$1=`
|
|
184
|
+
${r.pixels_above>4&&n!==-1?`... ${r.pixels_above} pixels above (${r.pages_above.toFixed(1)} pages) - scroll to see more ...`:"[Start of page]"}`,content:i,footer:r.pixels_below>4&&n!==-1?`... ${r.pixels_below} pixels below (${r.pages_below.toFixed(1)} pages) - scroll to see more ...`:"[End of page]"}}async updateTree(){this.dispatchEvent(new Event("beforeUpdate")),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents="none"),cleanUpHighlights();const t=[...this.config.interactiveBlacklist||[],...Array.from(document.querySelectorAll("[data-page-agent-not-interactive]"))];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:t}),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.includeAttributes,this.config.keepSemanticTags),this.selectorMap.clear(),this.selectorMap=getSelectorMap(this.flatTree),this.elementTextMap.clear(),this.elementTextMap=getElementTextMap(this.simplifiedHTML),this.isIndexed=!0,this.mask&&(this.mask.wrapper.style.pointerEvents="auto"),this.dispatchEvent(new Event("afterUpdate")),this.simplifiedHTML}async cleanUpHighlights(){console.log("[PageController] cleanUpHighlights"),cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw new Error("DOM tree not indexed yet. Can not perform actions on elements.")}async clickElement(t){try{this.assertIndexed();const e=getElementByIndex(this.selectorMap,t),r=this.elementTextMap.get(t);return await clickElement(e),isAnchorElement(e)&&e.target==="_blank"?{success:!0,message:`✅ Clicked element (${r??t}). ⚠️ Link opened in a new tab.`}:{success:!0,message:`✅ Clicked element (${r??t}).`}}catch(e){return{success:!1,message:`❌ Failed to click element: ${e}`}}}async inputText(t,e){try{this.assertIndexed();const r=getElementByIndex(this.selectorMap,t),n=this.elementTextMap.get(t);return await inputTextElement(r,e),{success:!0,message:`✅ Input text (${e}) into element (${n??t}).`}}catch(r){return{success:!1,message:`❌ Failed to input text: ${r}`}}}async selectOption(t,e){try{this.assertIndexed();const r=getElementByIndex(this.selectorMap,t),n=this.elementTextMap.get(t);return await selectOptionElement(r,e),{success:!0,message:`✅ Selected option (${e}) in element (${n??t}).`}}catch(r){return{success:!1,message:`❌ Failed to select option: ${r}`}}}async scroll(t){try{const{down:e,numPages:r,pixels:n,index:i}=t;return this.assertIndexed(),{success:!0,message:await scrollVertically((n??r*window.innerHeight)*(e?1:-1),i!==void 0?getElementByIndex(this.selectorMap,i):null)}}catch(e){return{success:!1,message:`❌ Failed to scroll: ${e}`}}}async scrollHorizontally(t){try{const{right:e,pixels:r,index:n}=t;return this.assertIndexed(),{success:!0,message:await scrollHorizontally(r*(e?1:-1),n!==void 0?getElementByIndex(this.selectorMap,n):null)}}catch(e){return{success:!1,message:`❌ Failed to scroll horizontally: ${e}`}}}async executeJavascript(script,signal){try{const asyncFunction=eval(`(async (signal) => { ${script} })`),result=await asyncFunction(signal);return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(t){return{success:!1,message:`❌ Error executing JavaScript: ${t}`}}}async showMask(){await this.maskReady,this.mask?.show()}async hideMask(){await this.maskReady,this.mask?.hide()}dispose(){cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML="<EMPTY>",this.isIndexed=!1,this.mask?.dispose(),this.mask=null}};const DEFAULT_ERROR_SELECTORS=['[role="alert"]','[aria-invalid="true"]',".el-form-item__error",".ant-form-item-explain-error",".is-invalid",".invalid-feedback",".ng-invalid",".error-msg",".error-message",".error-text",".field-error",".form-error",".is-error",".has-error",".validate-error",".valid-error"],DEFAULT_WARNING_SELECTORS=[".warning-msg",".warning-text",".is-warning",".has-warning"],DEFAULT_DIALOG_SELECTORS=['[role="dialog"]','[role="alertdialog"]','[class*="el-dialog"]','[class*="el-message-box"]','[class*="ant-modal"]','[class*="modal-content"]','[class*="v-dialog"]','[class*="n-modal"]'],DEFAULT_TOOLTIP_SELECTORS=['[role="tooltip"]','[class*="el-tooltip-popper"]','[class*="el-popper"]','[class*="ant-tooltip"]','[class*="ant-popover"]','[class*="n-tooltip"]','[class*="n-popover"]','[class*="v-tooltip"]','[class*="v-menu"]'],TAG_ROLE_MAP={a:"link",article:"article",aside:"complementary",button:"button",caption:"caption",cell:"cell",checkbox:"checkbox",code:"code",columnheader:"columnheader",combobox:"combobox",datalist:"listbox",dd:"definition",details:"group",dialog:"dialog",dt:"term",em:"emphasis",fieldset:"group",figure:"figure",footer:"contentinfo",form:"form",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",header:"banner",hr:"separator",img:"img",input:"textbox",li:"listitem",link:"link",main:"main",mark:"mark",math:"math",menu:"list",menuitem:"menuitem",meter:"meter",nav:"navigation",ol:"list",option:"option",output:"status",p:"paragraph",progress:"progressbar",rowheader:"rowheader",search:"search",section:"region",select:"listbox",strong:"strong",summary:"button",table:"table",tbody:"rowgroup",td:"cell",textarea:"textbox",tfoot:"rowgroup",th:"columnheader",thead:"rowgroup",time:"time",tr:"row",ul:"list"},DEFAULT_ROLE_OVERRIDES=[],INPUT_TYPE_ROLE={button:"button",checkbox:"checkbox",color:"textbox",email:"textbox",file:"textbox",image:"button",number:"spinbutton",radio:"radio",range:"slider",reset:"button",search:"searchbox",submit:"button",tel:"textbox",text:"textbox",url:"textbox"},RESOLVED_A11Y_BRAND=Symbol.for("@opentiny/next-sdk:ResolvedA11yConfig");function markResolved(t){return Object.assign(t,{[RESOLVED_A11Y_BRAND]:!0})}function isResolvedA11yConfig(t){return!!t&&t[RESOLVED_A11Y_BRAND]===!0}const STANDARD_STATE_NAMES=["checked","selected","pressed","current","expanded","hasPopup","disabled","readonly","required","invalid","busy","error","warning"],DEFAULT_SELECTED_CLASS_RE=/\b(is-active|isActive|is-selected|isSelected|is-current|isCurrent|active-item|activeItem|tab-active|tabActive|active|selected|current)\b/;function defaultSelectedMatch(t){const e=typeof t.className=="string"?t.className:"";if(!e||!DEFAULT_SELECTED_CLASS_RE.test(e))return!1;const r=t.getAttribute("role")||t.tagName.toLowerCase();return["button","option","a","li","generic"].includes(r)||r.startsWith("tab")}const DEFAULT_A11Y_CONFIG=markResolved({roles:[...DEFAULT_ROLE_OVERRIDES,...DEFAULT_DIALOG_SELECTORS.map(t=>({selector:t,role:"dialog"})),...DEFAULT_TOOLTIP_SELECTORS.map(t=>({selector:t,role:"tooltip"}))],states:{selected:[{match:defaultSelectedMatch},{selector:".ti3-btn-item-container.ti3-active"}],error:[{selector:DEFAULT_ERROR_SELECTORS}],warning:[{selector:DEFAULT_WARNING_SELECTORS}]},whitelist:[],blacklist:[],exposedAttributes:[]});function normalizeSelector(t){return t&&(Array.isArray(t)?t.filter(Boolean).join(", "):t)||void 0}function getSelectorsForRole(t,e){const r=[];for(const n of t)n.role!==e||!n.selector||(Array.isArray(n.selector)?r.push(...n.selector.filter(Boolean)):r.push(n.selector));return r}function matchesRule(t,e){if(e.match)try{return!!e.match(t)}catch{return!1}const r=normalizeSelector(e.selector);if(r)try{return!!t.closest(r)}catch{return!1}return!1}function matchesRoleRule(t,e){if(e.match)try{return!!e.match(t)}catch{return!1}const r=normalizeSelector(e.selector);if(r)try{return!!t.matches(r)}catch{return!1}return!1}function matchesAnyRule(t,e){return e?(Array.isArray(e)?e:[e]).some(n=>matchesRule(t,n)):!1}function extractSelectors(t){return t?(Array.isArray(t)?t:[t]).flatMap(r=>Array.isArray(r.selector)?r.selector.filter(Boolean):r.selector?[r.selector]:[]):[]}function concatArr(t,e){return[...t??[],...e??[]]}function normalizeMatcherList(t){return t?Array.isArray(t)?t:[t]:[]}function mergeStates(t,e){const r={},n=new Set([...Object.keys(t??{}),...Object.keys(e??{})]);for(const i of n)r[i]=[...normalizeMatcherList(t?.[i]),...normalizeMatcherList(e?.[i])];return r}function mergeA11yConfigs(t,e){return markResolved({roles:concatArr(t.roles,e.roles),states:mergeStates(t.states,e.states),whitelist:concatArr(t.whitelist,e.whitelist),blacklist:concatArr(t.blacklist,e.blacklist),exposedAttributes:concatArr(t.exposedAttributes,e.exposedAttributes)})}function mergeA11yConfig(t){return isResolvedA11yConfig(t)?t:mergeA11yConfigs(DEFAULT_A11Y_CONFIG,t??{})}function ensureResolvedA11yConfig(t){return isResolvedA11yConfig(t)?t:mergeA11yConfig(t)}function defineA11yConfig(t){return t}function computeRole(t,e){const r=t.getAttribute("role"),n=!!r&&r!=="presentation"&&r!=="none";for(const o of e.roles)if(!(n&&!o.force)&&matchesRoleRule(t,o))return o.role;if(n)return r;const i=t.tagName.toLowerCase();if(i==="input"){const o=t.type?.toLowerCase()??"text";return INPUT_TYPE_ROLE[o]??"textbox"}return TAG_ROLE_MAP[i]??"generic"}function computeStates(t,e){const r=[],n=v=>t.getAttribute(v),i=e.states,o=v=>matchesAnyRule(t,i[v]),s=n("aria-checked");if(s==="true")r.push("checked");else if(s==="mixed")r.push("checked=mixed");else if(s==="false")r.push("unchecked");else{const v=t.tagName.toLowerCase();let S;if(v==="input"&&(t.type==="checkbox"||t.type==="radio"))S=t.checked;else if(v==="label"&&t.hasAttribute("for")){const b=document.getElementById(t.getAttribute("for"));b instanceof HTMLInputElement&&(b.type==="checkbox"||b.type==="radio")&&(S=b.checked)}S!==void 0?r.push(S?"checked":"unchecked"):o("checked")&&r.push("checked")}(n("aria-selected")==="true"||o("selected"))&&r.push("selected");const a=n("aria-pressed");a==="true"?r.push("pressed"):a==="mixed"?r.push("pressed=mixed"):a!=="false"&&o("pressed")&&r.push("pressed");const l=n("aria-current");l&&l!=="false"?r.push(l==="true"?"current":`current=${l}`):o("current")&&r.push("current"),(n("aria-disabled")==="true"||t.disabled||o("disabled"))&&r.push("disabled");const c=n("aria-haspopup");(c&&c!=="false"||o("hasPopup"))&&r.push("hasPopup"),(n("aria-expanded")==="true"||o("expanded"))&&r.push("expanded");const u=n("aria-invalid");u&&u!=="false"?r.push(u==="true"?"invalid":`invalid=${u}`):o("invalid")&&r.push("invalid"),(n("aria-readonly")==="true"||t.readOnly||o("readonly"))&&r.push("readonly"),(n("aria-required")==="true"||t.required||o("required"))&&r.push("required"),(n("aria-busy")==="true"||o("busy"))&&r.push("busy");const f=n("aria-orientation");f&&r.push(`orientation=${f}`);const h=n("aria-sort");h&&h!=="none"&&r.push(`sort=${h}`),n("aria-multiselectable")==="true"&&r.push("multiselectable");const m=t.tagName.match(/^H([1-6])$/);m&&r.push(`level=${m[1]}`);const g=n("aria-level");g&&!m&&r.push(`level=${g}`);try{window.getComputedStyle(t).cursor==="pointer"&&r.push("cursor=pointer")}catch{}const A=t.tagName.toLowerCase();if(A==="input"||A==="textarea"||A==="select"){const v=t.value;v!==void 0&&v!==""&&r.push(`value="${v}"`)}const _=n("aria-valuenow");_&&r.push(`valuenow="${_}"`);const p=n("aria-valuetext");if(p&&r.push(`valuetext="${p}"`),A==="a"){const v=n("target");v&&r.push(`target=${v}`)}o("error")?r.push("error"):o("warning")&&r.push("warning");for(const v of Object.keys(i))STANDARD_STATE_NAMES.includes(v)||matchesAnyRule(t,i[v])&&r.push(v);for(const v of e.exposedAttributes){const S=t.getAttribute(v);S!==null&&r.push(`${v}="${S}"`)}return Array.from(new Set(r))}function resolveA11yRole(t,e){return computeRole(t,ensureResolvedA11yConfig(e))}function resolveA11yInfo(t,e){const r=ensureResolvedA11yConfig(e);return{role:computeRole(t,r),tokens:computeStates(t,r)}}var candidateSelectors=["input:not([inert]):not([inert] *)","select:not([inert]):not([inert] *)","textarea:not([inert]):not([inert] *)","a[href]:not([inert]):not([inert] *)","area[href]:not([inert]):not([inert] *)","button:not([inert]):not([inert] *)","[tabindex]:not(slot):not([inert]):not([inert] *)","audio[controls]:not([inert]):not([inert] *)","video[controls]:not([inert]):not([inert] *)",'[contenteditable]:not([contenteditable="false"]):not([inert]):not([inert] *)',"details>summary:first-of-type:not([inert]):not([inert] *)","details:not([inert]):not([inert] *)"],candidateSelector=candidateSelectors.join(","),NoElement=typeof Element>"u",matches=NoElement?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,getRootNode=!NoElement&&Element.prototype.getRootNode?function(t){var e;return t==null||(e=t.getRootNode)===null||e===void 0?void 0:e.call(t)}:function(t){return t?.ownerDocument},isContentEditable=function t(e){var r,n=e==null||(r=e.getAttribute)===null||r===void 0?void 0:r.call(e,"contenteditable");return n===""||n==="true"},hasTabIndex=function t(e){return!isNaN(parseInt(e.getAttribute("tabindex"),10))},getTabIndex=function t(e){if(!e)throw new Error("No node provided");return e.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(e.tagName)||isContentEditable(e))&&!hasTabIndex(e)?0:e.tabIndex},isInput=function t(e){return e.tagName==="INPUT"},isHiddenInput=function t(e){return isInput(e)&&e.type==="hidden"},isDetailsWithSummary=function t(e){var r=e.tagName==="DETAILS"&&Array.prototype.slice.apply(e.children).some(function(n){return n.tagName==="SUMMARY"});return r},getCheckedRadio=function t(e,r){for(var n=0;n<e.length;n++)if(e[n].checked&&e[n].form===r)return e[n]},isTabbableRadio=function t(e){if(!e.name)return!0;var r=e.form||getRootNode(e),n=function(a){return r.querySelectorAll('input[type="radio"][name="'+a+'"]')},i;if(typeof window<"u"&&typeof window.CSS<"u"&&typeof window.CSS.escape=="function")i=n(window.CSS.escape(e.name));else try{i=n(e.name)}catch(s){return console.error("Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s",s.message),!1}var o=getCheckedRadio(i,e.form);return!o||o===e},isRadio=function t(e){return isInput(e)&&e.type==="radio"},isNonTabbableRadio=function t(e){return isRadio(e)&&!isTabbableRadio(e)},isNodeAttached=function t(e){var r,n=e&&getRootNode(e),i=(r=n)===null||r===void 0?void 0:r.host,o=!1;if(n&&n!==e){var s,a,l;for(o=!!((s=i)!==null&&s!==void 0&&(a=s.ownerDocument)!==null&&a!==void 0&&a.contains(i)||e!=null&&(l=e.ownerDocument)!==null&&l!==void 0&&l.contains(e));!o&&i;){var c,u,f;n=getRootNode(i),i=(c=n)===null||c===void 0?void 0:c.host,o=!!((u=i)!==null&&u!==void 0&&(f=u.ownerDocument)!==null&&f!==void 0&&f.contains(i))}}return o},isZeroArea=function t(e){var r=e.getBoundingClientRect(),n=r.width,i=r.height;return n===0&&i===0},isHidden$2=function t(e,r){var n=r.displayCheck,i=r.getShadowRoot;if(n==="full-native"&&"checkVisibility"in e){var o=e.checkVisibility({checkOpacity:!1,opacityProperty:!1,contentVisibilityAuto:!0,visibilityProperty:!0,checkVisibilityCSS:!0});return!o}var s=getComputedStyle(e),a=s.visibility;if(a==="hidden"||a==="collapse")return!0;var l=matches.call(e,"details>summary:first-of-type"),c=l?e.parentElement:e;if(matches.call(c,"details:not([open]) *"))return!0;if(!n||n==="full"||n==="full-native"||n==="legacy-full"){if(typeof i=="function"){for(var u=e;e;){var f=e.parentElement,h=getRootNode(e);if(f&&!f.shadowRoot&&i(f)===!0)return isZeroArea(e);e.assignedSlot?e=e.assignedSlot:!f&&h!==e.ownerDocument?e=h.host:e=f}e=u}if(isNodeAttached(e))return!e.getClientRects().length;if(n!=="legacy-full")return!0}else if(n==="non-zero-area")return isZeroArea(e);return!1},isDisabledFromFieldset=function t(e){if(/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(e.tagName))for(var r=e.parentElement;r;){if(r.tagName==="FIELDSET"&&r.disabled){for(var n=0;n<r.children.length;n++){var i=r.children.item(n);if(i.tagName==="LEGEND")return matches.call(r,"fieldset[disabled] *")?!0:!i.contains(e)}return!0}r=r.parentElement}return!1},isNodeMatchingSelectorFocusable=function t(e,r){return!(r.disabled||isHiddenInput(r)||isHidden$2(r,e)||isDetailsWithSummary(r)||isDisabledFromFieldset(r))},isNodeMatchingSelectorTabbable=function t(e,r){return!(isNonTabbableRadio(r)||getTabIndex(r)<0||!isNodeMatchingSelectorFocusable(e,r))},isTabbable=function t(e,r){if(r=r||{},!e)throw new Error("No node provided");return matches.call(e,candidateSelector)===!1?!1:isNodeMatchingSelectorTabbable(r,e)};const DEFAULT_PAGE_AGENT_TOOL_CONFIG={enableHighlight:!1,removeMaskAfterToolCall:!0,a11yConfig:DEFAULT_A11Y_CONFIG};function getPageAgentToolConfig(){return typeof window<"u"&&window.__webmcpcli_toolConfig?window.__webmcpcli_toolConfig:{enableHighlight:DEFAULT_PAGE_AGENT_TOOL_CONFIG.enableHighlight,removeMaskAfterToolCall:DEFAULT_PAGE_AGENT_TOOL_CONFIG.removeMaskAfterToolCall,a11yConfig:mergeA11yConfig()}}function resolvePatch(t,e){return{enableHighlight:t.enableHighlight??e.enableHighlight,removeMaskAfterToolCall:t.removeMaskAfterToolCall??e.removeMaskAfterToolCall,a11yConfig:mergeA11yConfigs(e.a11yConfig,t.a11yConfig??{})}}function setPageAgentToolConfig(t,e){const r=e?.mode??"merge",n=getPageAgentToolConfig(),i=typeof t=="function"?resolvePatch(t(n),DEFAULT_PAGE_AGENT_TOOL_CONFIG):resolvePatch(t,r==="replace"?DEFAULT_PAGE_AGENT_TOOL_CONFIG:n);return typeof window<"u"&&(window.__webmcpcli_toolConfig=i),i}function isInShadowDom(t){return t.getRootNode()instanceof ShadowRoot}function dispatchComposedEvents(t,...e){for(const r of e)t.dispatchEvent(new Event(r,{bubbles:!0,composed:!0}))}function deepQuerySelectorAll(t,e=document){const r=Array.from(e.querySelectorAll(t)),n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null);let i=n.currentNode;for(;i;)i.shadowRoot&&r.push(...deepQuerySelectorAll(t,i.shadowRoot)),i=n.nextNode();return r}function waitForDomSettled(t=600,e=150){return new Promise(r=>{let n=!1,i;const o=()=>{n||(n=!0,s.disconnect(),i&&clearTimeout(i),r())},s=new MutationObserver(()=>{i&&clearTimeout(i),i=setTimeout(o,e)});i=setTimeout(o,e),setTimeout(o,t),s.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","style","hidden"]})})}function detectPageDialog(){const t=new Set,e=[],r=getSelectorsForRole(getPageAgentToolConfig().a11yConfig.roles,"dialog");for(const n of r)try{for(const i of deepQuerySelectorAll(n)){if(t.has(i)||i.id?.includes("page-agent-runtime")||i.closest("#page-agent-runtime_simulator-mask"))continue;const o=i.getBoundingClientRect();if(o.width<50||o.height<50)continue;const s=window.getComputedStyle(i);if(s.display==="none"||s.visibility==="hidden")continue;const a=s.position==="fixed"||s.position==="absolute",l=parseInt(s.zIndex||"0",10);if(!a||l<100)continue;const c=window.innerWidth,u=window.innerHeight;if(!(o.left<c*.6&&o.right>c*.4&&o.top<u*.6&&o.bottom>u*.4))continue;t.add(i);const h=(i.textContent||"").trim().replace(/\s+/g," ");if(h.length>5){const m=i.querySelectorAll('button, [role="button"], a'),g=Array.from(m).map(A=>(A.textContent||"").trim()).filter(A=>A.length>0&&A.length<20).slice(0,5);e.push({text:h.substring(0,300),buttons:g})}}}catch{}return e}function detectValidationErrors(){const t=new Set,e=[],r=extractSelectors(getPageAgentToolConfig().a11yConfig.states.error);for(const n of r)try{for(const i of deepQuerySelectorAll(n)){if(t.has(i)||Array.from(t).some(l=>l.contains(i)))continue;const o=i.getBoundingClientRect();if(o.width<1||o.height<1)continue;const s=window.getComputedStyle(i);if(s.display==="none"||s.visibility==="hidden")continue;const a=(i.textContent||"").trim().replace(/\s+/g," ");a.length>2&&a.length<200&&(t.add(i),e.push(a))}}catch{}return e}function getVisibleTooltipElements(){const t=new Set,e=[],r=getSelectorsForRole(getPageAgentToolConfig().a11yConfig.roles,"tooltip");for(const n of r)try{for(const i of deepQuerySelectorAll(n)){if(t.has(i)||Array.from(t).some(l=>l.contains(i)))continue;const o=i.getBoundingClientRect();if(o.width<1||o.height<1)continue;const s=window.getComputedStyle(i);if(s.display==="none"||s.visibility==="hidden"||s.opacity==="0")continue;const a=(i.textContent||"").trim().replace(/\s+/g," ");if(a.length>1){if(i.querySelector?.('[name="cloudx-action-help"]'))continue;t.add(i),e.push({el:i,text:a})}}}catch{}return e}function detectVisibleTooltips(){return getVisibleTooltipElements().map(t=>t.text)}const NON_CONTENT_TAGS=new Set(["script","style","noscript","template","link","meta","head","title"]);function isNonContentElement(t){return NON_CONTENT_TAGS.has(t.tagName.toLowerCase())}function hasOwnPointerCursor(t){try{if(window.getComputedStyle(t).cursor!=="pointer")return!1;const e=t.parentElement;return e?window.getComputedStyle(e).cursor!=="pointer":!0}catch{return!1}}const INTERACTION_PSEUDO_RE=/:(hover|focus|focus-visible|focus-within|active)\b/gi;function collectInteractivePointerSelectors(t,e){for(const r of Array.from(t)){const n=r,i=r;if(!n.selectorText&&i.cssRules){collectInteractivePointerSelectors(i.cssRules,e);continue}const o=n.selectorText;if(!(!o||!n.style||n.style.cursor!=="pointer")&&/:(hover|focus|focus-visible|focus-within|active)\b/i.test(o))for(const s of o.split(",")){const a=s.replace(INTERACTION_PSEUDO_RE,"").trim();a&&a!=="*"&&e.add(a)}}}function collectHoverPointerElements(t){const e=new Set,r=new Set;try{for(const i of Array.from(document.styleSheets)){let o=null;try{o=i.cssRules}catch{continue}o&&collectInteractivePointerSelectors(o,r)}}catch{return e}if(r.size===0)return e;const n=Array.from(r);try{for(const i of deepQuerySelectorAll(n.join(", "),t))e.add(i);return e}catch{for(const i of n)try{for(const o of deepQuerySelectorAll(i,t))e.add(o)}catch{}}return e}function isHidden$1(t){if(isNonContentElement(t)||t.getAttribute("aria-hidden")==="true"||t.hidden)return!0;try{const e=window.getComputedStyle(t);if(e.display==="none"||e.visibility==="hidden"||e.opacity==="0")return!0;const r=e.overflowX!=="visible",n=e.overflowY!=="visible";if(parseFloat(e.width)===0&&r||parseFloat(e.height)===0&&n)return!0}catch{}return!1}function collectTitleLabel(t){const e=t.getAttribute("title")?.trim();if(e)return e;const n=t.querySelector("[title]")?.getAttribute("title")?.trim();return n||""}function collectDescendantText(t,e){let r="";const n=i=>{if(i.nodeType===Node.TEXT_NODE)r+=(i.textContent??"")+" ";else if(i.nodeType===Node.ELEMENT_NODE){const o=i;if(o!==t&&isNonContentElement(o)||isHidden$1(o)&&o!==t||o===t&&isNonContentElement(o))return;if(o!==t){const s=o.tagName.toLowerCase(),a=resolveA11yRole(o,e),l=["button","a","input","select","textarea","li","option"].includes(s),c=["button","link","checkbox","radio","textbox","listitem","option","combobox","listbox"].includes(a),u=isTabbable(o),f=hasOwnPointerCursor(o);if(u&&!(a==="generic"&&!f)||l||c)return}for(const s of Array.from(o.childNodes))n(s)}};return n(t),r.trim().replace(/\s+/g," ")}function getComposedChildren(t){const e=t.shadowRoot?t.shadowRoot.children:t.children,r=[];for(const n of Array.from(e))if(n instanceof HTMLSlotElement){const i=n.assignedElements({flatten:!0});r.push(...i.length>0?i:Array.from(n.children))}else r.push(n);return r}function extractTooltipText(t){const e=t.getAttribute("title");if(e&&e.trim())return e.trim().replace(/"/g,'\\"').substring(0,200);const r=t.getAttribute("aria-describedby");if(r)for(const o of r.split(/\s+/)){const s=document.getElementById(o);if(s){const a=(s.textContent||"").trim().replace(/\s+/g," ");if(a)return a.replace(/"/g,'\\"').substring(0,200)}}for(const o of["data-tooltip","data-tips","data-tip"]){const s=t.getAttribute(o);if(s&&s.trim())return s.trim().replace(/"/g,'\\"').substring(0,200)}const n=t.tagName.toLowerCase();if(n==="tp-helptip"||t.closest("tp-helptip")){const s=(n==="tp-helptip"?t:t.closest("tp-helptip")).querySelector('.tp-helptip-label, [class*="tp-helptip-label"]');if(s){const a=(s.textContent||"").trim();if(a)return a.replace(/"/g,'\\"').substring(0,200)}}const i=t.getAttribute("mattooltip")||t.getAttribute("matTooltip");return i&&i.trim()?i.trim().replace(/"/g,'\\"').substring(0,200):""}var toStr=Object.prototype.toString;function isCallable(t){return typeof t=="function"||toStr.call(t)==="[object Function]"}function toInteger(t){var e=Number(t);return isNaN(e)?0:e===0||!isFinite(e)?e:(e>0?1:-1)*Math.floor(Math.abs(e))}var maxSafeInteger=Math.pow(2,53)-1;function toLength(t){var e=toInteger(t);return Math.min(Math.max(e,0),maxSafeInteger)}function arrayFrom(t,e){var r=Array,n=Object(t);if(t==null)throw new TypeError("Array.from requires an array-like object - not null or undefined");for(var i=toLength(n.length),o=isCallable(r)?Object(new r(i)):new Array(i),s=0,a;s<i;)a=n[s],o[s]=a,s+=1;return o.length=i,o}function _typeof$1(t){"@babel/helpers - typeof";return _typeof$1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$1(t)}function _classCallCheck(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function _defineProperties(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,_toPropertyKey(n.key),n)}}function _createClass(t,e,r){return e&&_defineProperties(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function _defineProperty(t,e,r){return e=_toPropertyKey(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function _toPropertyKey(t){var e=_toPrimitive(t,"string");return _typeof$1(e)==="symbol"?e:String(e)}function _toPrimitive(t,e){if(_typeof$1(t)!=="object"||t===null)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(_typeof$1(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var SetLike=(function(){function t(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];_classCallCheck(this,t),_defineProperty(this,"items",void 0),this.items=e}return _createClass(t,[{key:"add",value:function(r){return this.has(r)===!1&&this.items.push(r),this}},{key:"clear",value:function(){this.items=[]}},{key:"delete",value:function(r){var n=this.items.length;return this.items=this.items.filter(function(i){return i!==r}),n!==this.items.length}},{key:"forEach",value:function(r){var n=this;this.items.forEach(function(i){r(i,i,n)})}},{key:"has",value:function(r){return this.items.indexOf(r)!==-1}},{key:"size",get:function(){return this.items.length}}]),t})();const SetLike$1=typeof Set>"u"?Set:SetLike;function getLocalName(t){var e;return(e=t.localName)!==null&&e!==void 0?e:t.tagName.toLowerCase()}var localNameToRoleMappings={article:"article",aside:"complementary",button:"button",datalist:"listbox",dd:"definition",details:"group",dialog:"dialog",dt:"term",fieldset:"group",figure:"figure",form:"form",footer:"contentinfo",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",header:"banner",hr:"separator",html:"document",legend:"legend",li:"listitem",math:"math",main:"main",menu:"list",nav:"navigation",ol:"list",optgroup:"group",option:"option",output:"status",progress:"progressbar",section:"region",summary:"button",table:"table",tbody:"rowgroup",textarea:"textbox",tfoot:"rowgroup",td:"cell",th:"columnheader",thead:"rowgroup",tr:"row",ul:"list"},prohibitedAttributes={caption:new Set(["aria-label","aria-labelledby"]),code:new Set(["aria-label","aria-labelledby"]),deletion:new Set(["aria-label","aria-labelledby"]),emphasis:new Set(["aria-label","aria-labelledby"]),generic:new Set(["aria-label","aria-labelledby","aria-roledescription"]),insertion:new Set(["aria-label","aria-labelledby"]),none:new Set(["aria-label","aria-labelledby"]),paragraph:new Set(["aria-label","aria-labelledby"]),presentation:new Set(["aria-label","aria-labelledby"]),strong:new Set(["aria-label","aria-labelledby"]),subscript:new Set(["aria-label","aria-labelledby"]),superscript:new Set(["aria-label","aria-labelledby"])};function hasGlobalAriaAttributes(t,e){return["aria-atomic","aria-busy","aria-controls","aria-current","aria-description","aria-describedby","aria-details","aria-dropeffect","aria-flowto","aria-grabbed","aria-hidden","aria-keyshortcuts","aria-label","aria-labelledby","aria-live","aria-owns","aria-relevant","aria-roledescription"].some(function(r){var n;return t.hasAttribute(r)&&!((n=prohibitedAttributes[e])!==null&&n!==void 0&&n.has(r))})}function ignorePresentationalRole(t,e){return hasGlobalAriaAttributes(t,e)}function getRole(t){var e=getExplicitRole(t);if(e===null||presentationRoles.indexOf(e)!==-1){var r=getImplicitRole(t);if(presentationRoles.indexOf(e||"")===-1||ignorePresentationalRole(t,r||""))return r}return e}function getImplicitRole(t){var e=localNameToRoleMappings[getLocalName(t)];if(e!==void 0)return e;switch(getLocalName(t)){case"a":case"area":case"link":if(t.hasAttribute("href"))return"link";break;case"img":return t.getAttribute("alt")===""&&!ignorePresentationalRole(t,"img")?"presentation":"img";case"input":{var r=t,n=r.type;switch(n){case"button":case"image":case"reset":case"submit":return"button";case"checkbox":case"radio":return n;case"range":return"slider";case"email":case"tel":case"text":case"url":return t.hasAttribute("list")?"combobox":"textbox";case"search":return t.hasAttribute("list")?"combobox":"searchbox";case"number":return"spinbutton";default:return null}}case"select":return t.hasAttribute("multiple")||t.size>1?"listbox":"combobox"}return null}function getExplicitRole(t){var e=t.getAttribute("role");if(e!==null){var r=e.trim().split(" ")[0];if(r.length>0)return r}return null}var presentationRoles=["presentation","none"];function isElement(t){return t!==null&&t.nodeType===t.ELEMENT_NODE}function isHTMLTableCaptionElement(t){return isElement(t)&&getLocalName(t)==="caption"}function isHTMLInputElement(t){return isElement(t)&&getLocalName(t)==="input"}function isHTMLOptGroupElement(t){return isElement(t)&&getLocalName(t)==="optgroup"}function isHTMLSelectElement(t){return isElement(t)&&getLocalName(t)==="select"}function isHTMLTableElement(t){return isElement(t)&&getLocalName(t)==="table"}function isHTMLTextAreaElement(t){return isElement(t)&&getLocalName(t)==="textarea"}function safeWindow(t){var e=t.ownerDocument===null?t:t.ownerDocument,r=e.defaultView;if(r===null)throw new TypeError("no window available");return r}function isHTMLFieldSetElement(t){return isElement(t)&&getLocalName(t)==="fieldset"}function isHTMLLegendElement(t){return isElement(t)&&getLocalName(t)==="legend"}function isHTMLSlotElement(t){return isElement(t)&&getLocalName(t)==="slot"}function isSVGElement(t){return isElement(t)&&t.ownerSVGElement!==void 0}function isSVGSVGElement(t){return isElement(t)&&getLocalName(t)==="svg"}function isSVGTitleElement(t){return isSVGElement(t)&&getLocalName(t)==="title"}function queryIdRefs(t,e){if(isElement(t)&&t.hasAttribute(e)){var r=t.getAttribute(e).split(" "),n=t.getRootNode?t.getRootNode():t.ownerDocument;return r.map(function(i){return n.getElementById(i)}).filter(function(i){return i!==null})}return[]}function hasAnyConcreteRoles(t,e){return isElement(t)?e.indexOf(getRole(t))!==-1:!1}function asFlatString(t){return t.trim().replace(/\s\s+/g," ")}function isHidden(t,e){if(!isElement(t))return!1;if(t.hasAttribute("hidden")||t.getAttribute("aria-hidden")==="true")return!0;var r=e(t);return r.getPropertyValue("display")==="none"||r.getPropertyValue("visibility")==="hidden"}function isControl(t){return hasAnyConcreteRoles(t,["button","combobox","listbox","textbox"])||hasAbstractRole(t,"range")}function hasAbstractRole(t,e){if(!isElement(t))return!1;switch(e){case"range":return hasAnyConcreteRoles(t,["meter","progressbar","scrollbar","slider","spinbutton"]);default:throw new TypeError("No knowledge about abstract role '".concat(e,"'. This is likely a bug :("))}}function querySelectorAllSubtree(t,e){var r=arrayFrom(t.querySelectorAll(e));return queryIdRefs(t,"aria-owns").forEach(function(n){r.push.apply(r,arrayFrom(n.querySelectorAll(e)))}),r}function querySelectedOptions(t){return isHTMLSelectElement(t)?t.selectedOptions||querySelectorAllSubtree(t,"[selected]"):querySelectorAllSubtree(t,'[aria-selected="true"]')}function isMarkedPresentational(t){return hasAnyConcreteRoles(t,presentationRoles)}function isNativeHostLanguageTextAlternativeElement(t){return isHTMLTableCaptionElement(t)}function allowsNameFromContent(t){return hasAnyConcreteRoles(t,["button","cell","checkbox","columnheader","gridcell","heading","label","legend","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","row","rowheader","switch","tab","tooltip","treeitem"])}function isDescendantOfNativeHostLanguageTextAlternativeElement(t){return!1}function getValueOfTextbox(t){return isHTMLInputElement(t)||isHTMLTextAreaElement(t)?t.value:t.textContent||""}function getTextualContent(t){var e=t.getPropertyValue("content");return/^["'].*["']$/.test(e)?e.slice(1,-1):""}function isLabelableElement(t){var e=getLocalName(t);return e==="button"||e==="input"&&t.getAttribute("type")!=="hidden"||e==="meter"||e==="output"||e==="progress"||e==="select"||e==="textarea"}function findLabelableElement(t){if(isLabelableElement(t))return t;var e=null;return t.childNodes.forEach(function(r){if(e===null&&isElement(r)){var n=findLabelableElement(r);n!==null&&(e=n)}}),e}function getControlOfLabel(t){if(t.control!==void 0)return t.control;var e=t.getAttribute("for");return e!==null?t.ownerDocument.getElementById(e):findLabelableElement(t)}function getLabels(t){var e=t.labels;if(e===null)return e;if(e!==void 0)return arrayFrom(e);if(!isLabelableElement(t))return null;var r=t.ownerDocument;return arrayFrom(r.querySelectorAll("label")).filter(function(n){return getControlOfLabel(n)===t})}function getSlotContents(t){var e=t.assignedNodes();return e.length===0?arrayFrom(t.childNodes):e}function computeTextAlternative(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=new SetLike$1,n=safeWindow(t),i=e.compute,o=i===void 0?"name":i,s=e.computedStyleSupportsPseudoElements,a=s===void 0?e.getComputedStyle!==void 0:s,l=e.getComputedStyle,c=l===void 0?n.getComputedStyle.bind(n):l,u=e.hidden,f=u===void 0?!1:u;function h(p,v){var S="";if(isElement(p)&&a){var b=c(p,"::before"),C=getTextualContent(b);S="".concat(C," ").concat(S)}var M=isHTMLSlotElement(p)?getSlotContents(p):arrayFrom(p.childNodes).concat(queryIdRefs(p,"aria-owns"));if(M.forEach(function(D){var V=_(D,{isEmbeddedInLabel:v.isEmbeddedInLabel,isReferenced:!1,recursion:!0}),H=isElement(D)?c(D).getPropertyValue("display"):"inline",G=H!=="inline"?" ":"";S+="".concat(G).concat(V).concat(G)}),isElement(p)&&a){var L=c(p,"::after"),z=getTextualContent(L);S="".concat(S," ").concat(z)}return S.trim()}function m(p,v){var S=p.getAttributeNode(v);return S!==null&&!r.has(S)&&S.value.trim()!==""?(r.add(S),S.value):null}function g(p){return isElement(p)?m(p,"title"):null}function A(p){if(!isElement(p))return null;if(isHTMLFieldSetElement(p)){r.add(p);for(var v=arrayFrom(p.childNodes),S=0;S<v.length;S+=1){var b=v[S];if(isHTMLLegendElement(b))return _(b,{isEmbeddedInLabel:!1,isReferenced:!1,recursion:!1})}}else if(isHTMLTableElement(p)){r.add(p);for(var C=arrayFrom(p.childNodes),M=0;M<C.length;M+=1){var L=C[M];if(isHTMLTableCaptionElement(L))return _(L,{isEmbeddedInLabel:!1,isReferenced:!1,recursion:!1})}}else if(isSVGSVGElement(p)){r.add(p);for(var z=arrayFrom(p.childNodes),D=0;D<z.length;D+=1){var V=z[D];if(isSVGTitleElement(V))return V.textContent}return null}else if(getLocalName(p)==="img"||getLocalName(p)==="area"){var H=m(p,"alt");if(H!==null)return H}else if(isHTMLOptGroupElement(p)){var G=m(p,"label");if(G!==null)return G}if(isHTMLInputElement(p)&&(p.type==="button"||p.type==="submit"||p.type==="reset")){var ie=m(p,"value");if(ie!==null)return ie;if(p.type==="submit")return"Submit";if(p.type==="reset")return"Reset"}var X=getLabels(p);if(X!==null&&X.length!==0)return r.add(p),arrayFrom(X).map(function(Q){return _(Q,{isEmbeddedInLabel:!0,isReferenced:!1,recursion:!0})}).filter(function(Q){return Q.length>0}).join(" ");if(isHTMLInputElement(p)&&p.type==="image"){var te=m(p,"alt");if(te!==null)return te;var oe=m(p,"title");return oe!==null?oe:"Submit Query"}if(hasAnyConcreteRoles(p,["button"])){var re=h(p,{isEmbeddedInLabel:!1});if(re!=="")return re}return null}function _(p,v){if(r.has(p))return"";if(!f&&isHidden(p,c)&&!v.isReferenced)return r.add(p),"";var S=isElement(p)?p.getAttributeNode("aria-labelledby"):null,b=S!==null&&!r.has(S)?queryIdRefs(p,"aria-labelledby"):[];if(o==="name"&&!v.isReferenced&&b.length>0)return r.add(S),b.map(function(H){return _(H,{isEmbeddedInLabel:v.isEmbeddedInLabel,isReferenced:!0,recursion:!1})}).join(" ");var C=v.recursion&&isControl(p)&&o==="name";if(!C){var M=(isElement(p)&&p.getAttribute("aria-label")||"").trim();if(M!==""&&o==="name")return r.add(p),M;if(!isMarkedPresentational(p)){var L=A(p);if(L!==null)return r.add(p),L}}if(hasAnyConcreteRoles(p,["menu"]))return r.add(p),"";if(C||v.isEmbeddedInLabel||v.isReferenced){if(hasAnyConcreteRoles(p,["combobox","listbox"])){r.add(p);var z=querySelectedOptions(p);return z.length===0?isHTMLInputElement(p)?p.value:"":arrayFrom(z).map(function(H){return _(H,{isEmbeddedInLabel:v.isEmbeddedInLabel,isReferenced:!1,recursion:!0})}).join(" ")}if(hasAbstractRole(p,"range"))return r.add(p),p.hasAttribute("aria-valuetext")?p.getAttribute("aria-valuetext"):p.hasAttribute("aria-valuenow")?p.getAttribute("aria-valuenow"):p.getAttribute("value")||"";if(hasAnyConcreteRoles(p,["textbox"]))return r.add(p),getValueOfTextbox(p)}if(allowsNameFromContent(p)||isElement(p)&&v.isReferenced||isNativeHostLanguageTextAlternativeElement(p)||isDescendantOfNativeHostLanguageTextAlternativeElement()){var D=h(p,{isEmbeddedInLabel:v.isEmbeddedInLabel});if(D!=="")return r.add(p),D}if(p.nodeType===p.TEXT_NODE)return r.add(p),p.textContent||"";if(v.recursion)return r.add(p),h(p,{isEmbeddedInLabel:v.isEmbeddedInLabel});var V=g(p);return V!==null?(r.add(p),V):(r.add(p),"")}return asFlatString(_(t,{isEmbeddedInLabel:!1,isReferenced:o==="description",recursion:!1}))}function prohibitsNaming(t){return hasAnyConcreteRoles(t,["caption","code","deletion","emphasis","generic","insertion","none","paragraph","presentation","strong","subscript","superscript"])}function computeAccessibleName(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return prohibitsNaming(t)?"":computeTextAlternative(t,e)}const INTERACTIVE_ROLES=new Set(["button","link","textbox","searchbox","combobox","listbox","checkbox","radio","switch","slider","spinbutton","menuitem","menuitemcheckbox","menuitemradio","tab","treeitem"]);function buildVNode(t,e,r,n,i,o,s=new Set){if(isNonContentElement(t)||isHidden$1(t)||n.has(t))return null;const{role:a,tokens:l}=resolveA11yInfo(t,o),c=extractTooltipText(t);c&&l.push(`tooltip="${c}"`);const u=l.some(D=>D.startsWith("tooltip="));let f=computeAccessibleName(t);const h=isTabbable(t),m=l.includes("cursor=pointer"),g=hasOwnPointerCursor(t)||s.has(t),A=i.has(t),_=t.tagName.toLowerCase()==="label"&&t.hasAttribute("for");if(!f.trim()){const D=t.tagName.toLowerCase();if(!(D==="select"||a==="combobox"||a==="listbox")){const H=["button","a","input","textarea","li","label"].includes(D);(h||A||m||g||H||a==="listitem"||a==="option"||a==="button")&&(f=collectDescendantText(t,o))}}if(!f.trim()&&(h||A||m||g||a==="button")&&(f=collectTitleLabel(t)),!f.trim()&&a==="button"){const D=t.getAttribute("name")||"";(D.includes("help")||D.includes("tip")||D.includes("info"))&&(f="帮助")}if(!f.trim()&&u){const D=l.find(V=>V.startsWith("tooltip="));D&&(f=D.replace(/^tooltip="/,"").replace(/"$/,""))}if(!f.trim()&&["tab","menuitem","option","treeitem","button"].includes(a)&&(f=collectVisiblePlainText(t)),!f.trim()&&!(getComposedChildren(t).length>0)){const V=collectDescendantText(t,o);V&&(f=V)}const p=t.tagName.toLowerCase(),v=p==="a"&&t.hasAttribute("href")||["button","input","select","textarea"].includes(p)&&!t.hasAttribute("disabled")||a==="button"&&m&&!["button","a","input","select","textarea"].includes(p),S=h&&!(a==="generic"&&!g),b=l.includes("disabled"),C=!b&&S||A||_||v||!b&&INTERACTIVE_ROLES.has(a)||!b&&g||u;let M;C&&(M=e.value,r.set(M,t),e.value++);const L=[];for(const D of getComposedChildren(t)){const V=buildVNode(D,e,r,n,i,o,s);V&&L.push(V)}const z={role:a,name:f,tokens:l,ref:M,el:t,children:L};return hasInteractiveDescendant(z)&&(z.name=getOwnDeclaredName(t)),z}function getOwnDeclaredName(t){return t.hasAttribute("aria-label")||t.hasAttribute("aria-labelledby")?computeAccessibleName(t).trim():""}function isStaticBranch(t){return t.ref===void 0&&!hasInteractiveDescendant(t)}function collectVisiblePlainText(t){return collectDescendantText(t).replace(/\s+/g," ").trim()}function collectDirectTextNodes(t){let e="";for(const r of Array.from(t.childNodes))r.nodeType===Node.TEXT_NODE&&(e+=(r.textContent??"")+" ");return e.replace(/\s+/g," ").trim()}function getStaticDisplayText(t){const e=t.children.length>0?t.children.map(getStaticDisplayText).filter(Boolean).join(" ").replace(/\s+/g," ").trim():"",r=t.children.length===0?collectVisiblePlainText(t.el):"",n=t.name.trim(),i=[];if(n&&!isNoiseAccessibleName(n)&&i.push(n),e&&!isNoiseAccessibleName(e)){const o=n.replace(/\s+/g," ").trim(),s=e.replace(/\s+/g," ").trim();(!o||s!==o&&!o.includes(s))&&i.push(e)}return i.length===0&&r&&!isNoiseAccessibleName(r)&&i.push(r),i.join(" ").replace(/\s+/g," ").trim()}function isNoiseAccessibleName(t){const e=t.trim();return e?!!(/@font-face\b/i.test(e)||/data:(?:font|application|image)\//i.test(e)||/base64,[A-Za-z0-9+/=]{80,}/.test(e)):!1}function canOmitStaticChild(t,e,r){const n=getStaticDisplayText(t);if(!n||!e.trim())return!1;const i=e.replace(/\s+/g," ").trim(),o=n.replace(/\s+/g," ").trim();return r?o===i:i.includes(o)}function hasValue(t){return t.ref!==void 0||t.name.trim()!==""?!0:t.children.some(hasValue)}function hasInteractiveDescendant(t){return t.children.some(e=>e.ref!==void 0||hasInteractiveDescendant(e))}function findSingleRefDescendant(t){const e=[],r=n=>{n.ref!==void 0&&e.push(n),!(e.length>1)&&n.children.forEach(r)};return t.children.forEach(r),e.length===1?e[0]:null}function shouldPassThrough(t,e){return!(!e.pruneUnnamed||e.preserveRoles.includes(t.role)||t.ref!==void 0||t.name.trim()!=="")}function formatNameAttr(t){const e=t.replace(/[\r\n]+/g," ").replace(/"/g,'\\"').trim();return e?` "${e}"`:""}function serializeVNode(t,e,r){const n=hasInteractiveDescendant(t),i=r.preserveRoles.includes(t.role),o=" ".repeat(e),s=t.ref!==void 0?` #${t.ref}`:"",a=t.tokens.map(b=>b.replace(/[\r\n]+/g," ").replace(/"/g,'\\"')),l=a.length>0?` [${a.join(" ")}]`:"";if(!n&&!i){if(shouldPassThrough(t,r))return t.children.filter(C=>hasValue(C)).flatMap(C=>serializeVNode(C,e,r));let b=t.name.trim();return!b&&t.children.length>0&&(b=collectVisiblePlainText(t.el)),isNoiseAccessibleName(b)&&(b=""),[`${o}- ${t.role}${s}${l}${formatNameAttr(b)}`]}if(!n&&i){const b=getOwnDeclaredName(t.el),C=`${o}- ${t.role}${s}${l}${formatNameAttr(b)}`,M=t.children.flatMap(L=>serializeVNode(L,e+1,r));return[C,...M]}const c=getOwnDeclaredName(t.el),u=c!=="",f=t.children.filter(isStaticBranch),h=f.map(getStaticDisplayText).filter(Boolean).join(" ").replace(/\s+/g," ").trim(),m=collectDirectTextNodes(t.el),g=[h,m].filter(Boolean).join(" ").replace(/\s+/g," ").trim();let A=u?c:g;if(isNoiseAccessibleName(A)&&(A=""),!u&&isNoiseAccessibleName(t.name)&&(A=g&&!isNoiseAccessibleName(g)?g:""),!(t.ref!==void 0||A!==""||i||!r.pruneUnnamed))return t.children.filter(b=>hasValue(b)).flatMap(b=>serializeVNode(b,e,r));if(t.ref!==void 0){const b=findSingleRefDescendant(t);if(b&&b.role==="generic"&&!hasInteractiveDescendant(b)&&f.length===0){const C=A.trim()||b.name.trim(),M=b.ref!==void 0?` #${b.ref}`:s;return[`${o}- ${t.role}${M}${l}${formatNameAttr(C)}`]}}const p=t.children.filter(b=>isStaticBranch(b)?!canOmitStaticChild(b,A,u):!0),v=`${o}- ${t.role}${s}${l}${formatNameAttr(A)}`,S=p.flatMap(b=>serializeVNode(b,e+1,r));return[v,...S]}const HIGHLIGHT_CONTAINER_ID="webmcpcli-highlight-container",HIGHLIGHT_CONTAINER_STYLE_ID="webmcpcli-highlight-container-style",colors=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"],opacity=Math.floor(.3*255).toString(16).padStart(2,"0"),injectStyles$1=`
|
|
332
185
|
#${HIGHLIGHT_CONTAINER_ID} {
|
|
333
186
|
position: fixed;
|
|
334
187
|
pointer-events: none;
|
|
@@ -355,16 +208,16 @@ ${e.map((n,i)=>`${i+1}. ${n}`).join(`
|
|
|
355
208
|
padding: 0 2px;
|
|
356
209
|
border-radius: 4px;
|
|
357
210
|
}
|
|
358
|
-
`,MAX_ICON_FALLBACK_SIZE=48;function resolveHighlightRect(t){const e=t.getBoundingClientRect();if(e.width>0&&e.height>0)return{top:e.top,left:e.left,width:e.width,height:e.height};let r=t.parentElement;for(let n=0;n<3&&r;n++){const i=r.getBoundingClientRect();if(i.width>0&&i.height>0&&i.width<=MAX_ICON_FALLBACK_SIZE&&i.height<=MAX_ICON_FALLBACK_SIZE)return{top:i.top,left:i.left,width:i.width,height:i.height};r=r.parentElement}if(e.width>0||e.height>0)try{const n=parseFloat(getComputedStyle(t).fontSize)||16,i=e.width>0?e.width:n,o=e.height>0?e.height:n;return{top:e.height>0?e.top:e.top-(o-e.height)/2,left:e.width>0?e.left:e.left-(i-e.width)/2,width:i,height:o}}catch{}return null}function isRectInViewport(t){const e=window.innerHeight||document.documentElement.clientHeight,r=window.innerWidth||document.documentElement.clientWidth;return t.top<e&&t.top+t.height>0&&t.left<r&&t.left+t.width>0}const doHighlight=(t,e=null)=>{if(!document.head.querySelector(`#${HIGHLIGHT_CONTAINER_STYLE_ID}`)){const o=document.head.appendChild(document.createElement("style"));o.id=HIGHLIGHT_CONTAINER_STYLE_ID,o.textContent=injectStyles$1,document.head.appendChild(o)}let r=document.getElementById(HIGHLIGHT_CONTAINER_ID);r?r.innerHTML="":(r=document.createElement("div"),r.id=HIGHLIGHT_CONTAINER_ID,document.body.appendChild(r));let n={x:0,y:0};if(e){const o=e.getBoundingClientRect();n.x=o.left,n.y=o.top}const i=document.createDocumentFragment();for(const[o,s]of t.entries()){const a=resolveHighlightRect(s);if(!a)continue;const l=a.top+n.y,c=a.left+n.x,u={top:l,left:c,width:a.width,height:a.height};if(!isRectInViewport(u))continue;const
|
|
359
|
-
`)+"\n```",refMap:l,interactiveCount:l.size,lines:
|
|
360
|
-
`),matches:
|
|
211
|
+
`,MAX_ICON_FALLBACK_SIZE=48;function resolveHighlightRect(t){const e=t.getBoundingClientRect();if(e.width>0&&e.height>0)return{top:e.top,left:e.left,width:e.width,height:e.height};let r=t.parentElement;for(let n=0;n<3&&r;n++){const i=r.getBoundingClientRect();if(i.width>0&&i.height>0&&i.width<=MAX_ICON_FALLBACK_SIZE&&i.height<=MAX_ICON_FALLBACK_SIZE)return{top:i.top,left:i.left,width:i.width,height:i.height};r=r.parentElement}if(e.width>0||e.height>0)try{const n=parseFloat(getComputedStyle(t).fontSize)||16,i=e.width>0?e.width:n,o=e.height>0?e.height:n;return{top:e.height>0?e.top:e.top-(o-e.height)/2,left:e.width>0?e.left:e.left-(i-e.width)/2,width:i,height:o}}catch{}return null}function isRectInViewport(t){const e=window.innerHeight||document.documentElement.clientHeight,r=window.innerWidth||document.documentElement.clientWidth;return t.top<e&&t.top+t.height>0&&t.left<r&&t.left+t.width>0}const doHighlight=(t,e=null)=>{if(!document.head.querySelector(`#${HIGHLIGHT_CONTAINER_STYLE_ID}`)){const o=document.head.appendChild(document.createElement("style"));o.id=HIGHLIGHT_CONTAINER_STYLE_ID,o.textContent=injectStyles$1,document.head.appendChild(o)}let r=document.getElementById(HIGHLIGHT_CONTAINER_ID);r?r.innerHTML="":(r=document.createElement("div"),r.id=HIGHLIGHT_CONTAINER_ID,document.body.appendChild(r));let n={x:0,y:0};if(e){const o=e.getBoundingClientRect();n.x=o.left,n.y=o.top}const i=document.createDocumentFragment();for(const[o,s]of t.entries()){const a=resolveHighlightRect(s);if(!a)continue;const l=a.top+n.y,c=a.left+n.x,u={top:l,left:c,width:a.width,height:a.height};if(!isRectInViewport(u))continue;const h=colors[o%colors.length]+opacity,m=document.createElement("div");m.style.border=`2px solid ${h}`,m.dataset.refIndex=String(o),m.style.top=`${l}px`,m.style.left=`${c}px`,m.style.width=`${a.width}px`,m.style.height=`${a.height}px`;const g=document.createElement("span");g.style.backgroundColor=h,g.style.height=`${Math.max(a.height-4,0)}px`,g.style.lineHeight=`${Math.max(a.height-4,0)}px`,g.textContent=o.toString(),m.appendChild(g),i.appendChild(m)}r.appendChild(i)},highlight=(t,e=null)=>{doHighlight(t,e);const i=((a,l)=>{let c=0;return(...u)=>{const f=performance.now();if(!(f-c<l))return c=f,a(...u)}})(()=>doHighlight(t,e),16);window.addEventListener("scroll",i,!0),window.addEventListener("resize",i);const o=()=>{window.removeEventListener("scroll",i,!0),window.removeEventListener("resize",i)},s=window;(s._highlightCleanupFunctions=s._highlightCleanupFunctions||[]).push(o)},unhighlight=()=>{document.getElementById(HIGHLIGHT_CONTAINER_ID)?.remove();const t=window._highlightCleanupFunctions||[];for(const e of t)typeof e=="function"&&e();window._highlightCleanupFunctions=[]},globalRemoveListener=()=>{if(window.__registerGlobalRemoveListener)return;window.__registerGlobalRemoveListener=!0,window.addEventListener("popstate",()=>{unhighlight()}),window.addEventListener("hashchange",()=>{unhighlight()}),window.addEventListener("beforeunload",()=>{unhighlight()});const t=window.navigation;if(t&&typeof t.addEventListener=="function")t.addEventListener("navigate",()=>{unhighlight()});else{let e=window.location.href;setInterval(()=>{window.location.href!==e&&(e=window.location.href,unhighlight())},500)}};function resolveElementList(t,e){const r=new Set;for(const n of t)if(typeof n=="string")try{for(const i of deepQuerySelectorAll(n,e))r.add(i)}catch{}else n&&r.add(n);return r}function buildA11yTree(t=document.body,e){const{pruneUnnamed:r=!0,preserveRoles:n=[],...i}=e??{},o=ensureResolvedA11yConfig(i),s={pruneUnnamed:r,preserveRoles:n},a={value:0},l=new Map,c=resolveElementList(o.blacklist,t),u=resolveElementList(o.whitelist,t),f=[],h=document.getElementById(HIGHLIGHT_CONTAINER_ID);h&&c.add(h);const m=collectHoverPointerElements(t);for(const A of getComposedChildren(t)){const _=buildVNode(A,a,l,c,u,o,m);_&&f.push(...serializeVNode(_,0,s))}return{yaml:"```yaml\n"+f.join(`
|
|
212
|
+
`)+"\n```",refMap:l,interactiveCount:l.size,lines:f}}function searchA11yTree(t,e=document.body,r){const{contextLines:n=2,caseInsensitive:i=!0,maxMatches:o=20,...s}=r??{},a=Math.max(0,n),l=Math.max(1,o),{lines:c,refMap:u,yaml:f}=buildA11yTree(e,s),h=i?t.toLowerCase():t,m=c.length,A=/^#\d+$/.test(t)?new RegExp(`\\s${t}(?:\\s|[\\[]|$)`):null,_=[];for(let C=0;C<c.length;C++){let M=!1;A?M=A.test(c[C]):M=(i?c[C].toLowerCase():c[C]).includes(h),M&&_.push(C)}const p=[];let v=!1;for(const C of _){const M=Math.max(0,C-a),L=Math.min(m-1,C+a),z=p[p.length-1];if(z&&M<=z.end+1)z.end=Math.max(z.end,L),z.hits.push(C);else{if(p.length>=l){v=!0;break}p.push({start:M,end:L,hits:[C]})}}const S=p.map(C=>({lineNumber:C.hits[0]+1,line:c[C.hits[0]],context:Array.from({length:C.end-C.start+1},(M,L)=>({lineNumber:C.start+L+1,line:c[C.start+L]}))})),b=[`无障碍树搜索结果 — 关键词: "${t}" | 总行数: ${m} | 命中: ${_.length} 行 | 返回分组: ${S.length}`,""];return S.length===0?b.push("(未找到匹配项)"):(S.forEach((C,M)=>{const L=p[M];b.push(`── 分组 ${M+1}(第 ${L.start+1}–${L.end+1} 行)──`),C.context.forEach(({lineNumber:z,line:D})=>{const V=L.hits.includes(z-1),H=String(z).padStart(4);b.push(V?`>>>${H} | ${D}`:` ${H} | ${D}`)}),b.push("")}),v&&b.push(`⚠️ 命中过多,已截断至前 ${l} 个分组,建议缩小搜索范围`),b.push("提示:如需操作命中元素,使用其 #N 索引;如需查看完整树,请使用 browserState。")),{text:b.join(`
|
|
213
|
+
`),matches:S,totalLines:m,matchCount:_.length,refMap:u,yaml:f}}function Diff(){}Diff.prototype={diff:function t(e,r){var n,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o=i.callback;typeof i=="function"&&(o=i,i={});var s=this;function a(b){return b=s.postProcess(b,i),o?(setTimeout(function(){o(b)},0),!0):b}e=this.castInput(e,i),r=this.castInput(r,i),e=this.removeEmpty(this.tokenize(e,i)),r=this.removeEmpty(this.tokenize(r,i));var l=r.length,c=e.length,u=1,f=l+c;i.maxEditLength!=null&&(f=Math.min(f,i.maxEditLength));var h=(n=i.timeout)!==null&&n!==void 0?n:1/0,m=Date.now()+h,g=[{oldPos:-1,lastComponent:void 0}],A=this.extractCommon(g[0],r,e,0,i);if(g[0].oldPos+1>=c&&A+1>=l)return a(buildValues(s,g[0].lastComponent,r,e,s.useLongestToken));var _=-1/0,p=1/0;function v(){for(var b=Math.max(_,-u);b<=Math.min(p,u);b+=2){var C=void 0,M=g[b-1],L=g[b+1];M&&(g[b-1]=void 0);var z=!1;if(L){var D=L.oldPos-b;z=L&&0<=D&&D<l}var V=M&&M.oldPos+1<c;if(!z&&!V){g[b]=void 0;continue}if(!V||z&&M.oldPos<L.oldPos?C=s.addToPath(L,!0,!1,0,i):C=s.addToPath(M,!1,!0,1,i),A=s.extractCommon(C,r,e,b,i),C.oldPos+1>=c&&A+1>=l)return a(buildValues(s,C.lastComponent,r,e,s.useLongestToken));g[b]=C,C.oldPos+1>=c&&(p=Math.min(p,b-1)),A+1>=l&&(_=Math.max(_,b+1))}u++}if(o)(function b(){setTimeout(function(){if(u>f||Date.now()>m)return o();v()||b()},0)})();else for(;u<=f&&Date.now()<=m;){var S=v();if(S)return S}},addToPath:function t(e,r,n,i,o){var s=e.lastComponent;return s&&!o.oneChangePerToken&&s.added===r&&s.removed===n?{oldPos:e.oldPos+i,lastComponent:{count:s.count+1,added:r,removed:n,previousComponent:s.previousComponent}}:{oldPos:e.oldPos+i,lastComponent:{count:1,added:r,removed:n,previousComponent:s}}},extractCommon:function t(e,r,n,i,o){for(var s=r.length,a=n.length,l=e.oldPos,c=l-i,u=0;c+1<s&&l+1<a&&this.equals(n[l+1],r[c+1],o);)c++,l++,u++,o.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return u&&!o.oneChangePerToken&&(e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=l,c},equals:function t(e,r,n){return n.comparator?n.comparator(e,r):e===r||n.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function t(e){for(var r=[],n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r},castInput:function t(e){return e},tokenize:function t(e){return Array.from(e)},join:function t(e){return e.join("")},postProcess:function t(e){return e}};function buildValues(t,e,r,n,i){for(var o=[],s;e;)o.push(e),s=e.previousComponent,delete e.previousComponent,e=s;o.reverse();for(var a=0,l=o.length,c=0,u=0;a<l;a++){var f=o[a];if(f.removed)f.value=t.join(n.slice(u,u+f.count)),u+=f.count;else{if(!f.added&&i){var h=r.slice(c,c+f.count);h=h.map(function(m,g){var A=n[u+g];return A.length>m.length?A:m}),f.value=t.join(h)}else f.value=t.join(r.slice(c,c+f.count));c+=f.count,f.added||(u+=f.count)}}return o}function longestCommonPrefix(t,e){var r;for(r=0;r<t.length&&r<e.length;r++)if(t[r]!=e[r])return t.slice(0,r);return t.slice(0,r)}function longestCommonSuffix(t,e){var r;if(!t||!e||t[t.length-1]!=e[e.length-1])return"";for(r=0;r<t.length&&r<e.length;r++)if(t[t.length-(r+1)]!=e[e.length-(r+1)])return t.slice(-r);return t.slice(-r)}function replacePrefix(t,e,r){if(t.slice(0,e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't start with prefix ").concat(JSON.stringify(e),"; this is a bug"));return r+t.slice(e.length)}function replaceSuffix(t,e,r){if(!e)return t+r;if(t.slice(-e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't end with suffix ").concat(JSON.stringify(e),"; this is a bug"));return t.slice(0,-e.length)+r}function removePrefix(t,e){return replacePrefix(t,e,"")}function removeSuffix(t,e){return replaceSuffix(t,e,"")}function maximumOverlap(t,e){return e.slice(0,overlapCount(t,e))}function overlapCount(t,e){var r=0;t.length>e.length&&(r=t.length-e.length);var n=e.length;t.length<e.length&&(n=t.length);var i=Array(n),o=0;i[0]=0;for(var s=1;s<n;s++){for(e[s]==e[o]?i[s]=i[o]:i[s]=o;o>0&&e[s]!=e[o];)o=i[o];e[s]==e[o]&&o++}o=0;for(var a=r;a<t.length;a++){for(;o>0&&t[a]!=e[o];)o=i[o];t[a]==e[o]&&o++}return o}var extendedWordChars="a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}",tokenizeIncludingWhitespace=new RegExp("[".concat(extendedWordChars,"]+|\\s+|[^").concat(extendedWordChars,"]"),"ug"),wordDiff=new Diff;wordDiff.equals=function(t,e,r){return r.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t.trim()===e.trim()},wordDiff.tokenize=function(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r;if(e.intlSegmenter){if(e.intlSegmenter.resolvedOptions().granularity!="word")throw new Error('The segmenter passed must have a granularity of "word"');r=Array.from(e.intlSegmenter.segment(t),function(o){return o.segment})}else r=t.match(tokenizeIncludingWhitespace)||[];var n=[],i=null;return r.forEach(function(o){/\s/.test(o)?i==null?n.push(o):n.push(n.pop()+o):/\s/.test(i)?n[n.length-1]==i?n.push(n.pop()+o):n.push(i+o):n.push(o),i=o}),n},wordDiff.join=function(t){return t.map(function(e,r){return r==0?e:e.replace(/^\s+/,"")}).join("")},wordDiff.postProcess=function(t,e){if(!t||e.oneChangePerToken)return t;var r=null,n=null,i=null;return t.forEach(function(o){o.added?n=o:o.removed?i=o:((n||i)&&dedupeWhitespaceInChangeObjects(r,i,n,o),r=o,n=null,i=null)}),(n||i)&&dedupeWhitespaceInChangeObjects(r,i,n,null),t};function dedupeWhitespaceInChangeObjects(t,e,r,n){if(e&&r){var i=e.value.match(/^\s*/)[0],o=e.value.match(/\s*$/)[0],s=r.value.match(/^\s*/)[0],a=r.value.match(/\s*$/)[0];if(t){var l=longestCommonPrefix(i,s);t.value=replaceSuffix(t.value,s,l),e.value=removePrefix(e.value,l),r.value=removePrefix(r.value,l)}if(n){var c=longestCommonSuffix(o,a);n.value=replacePrefix(n.value,a,c),e.value=removeSuffix(e.value,c),r.value=removeSuffix(r.value,c)}}else if(r)t&&(r.value=r.value.replace(/^\s*/,"")),n&&(n.value=n.value.replace(/^\s*/,""));else if(t&&n){var u=n.value.match(/^\s*/)[0],f=e.value.match(/^\s*/)[0],h=e.value.match(/\s*$/)[0],m=longestCommonPrefix(u,f);e.value=removePrefix(e.value,m);var g=longestCommonSuffix(removePrefix(u,m),h);e.value=removeSuffix(e.value,g),n.value=replacePrefix(n.value,u,g),t.value=replaceSuffix(t.value,u,u.slice(0,u.length-g.length))}else if(n){var A=n.value.match(/^\s*/)[0],_=e.value.match(/\s*$/)[0],p=maximumOverlap(_,A);e.value=removeSuffix(e.value,p)}else if(t){var v=t.value.match(/\s*$/)[0],S=e.value.match(/^\s*/)[0],b=maximumOverlap(v,S);e.value=removePrefix(e.value,b)}}var wordWithSpaceDiff=new Diff;wordWithSpaceDiff.tokenize=function(t){var e=new RegExp("(\\r?\\n)|[".concat(extendedWordChars,"]+|[^\\S\\n\\r]+|[^").concat(extendedWordChars,"]"),"ug");return t.match(e)||[]};var lineDiff=new Diff;lineDiff.tokenize=function(t,e){e.stripTrailingCr&&(t=t.replace(/\r\n/g,`
|
|
361
214
|
`));var r=[],n=t.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var i=0;i<n.length;i++){var o=n[i];i%2&&!e.newlineIsToken?r[r.length-1]+=o:r.push(o)}return r},lineDiff.equals=function(t,e,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
362
215
|
`))&&(t=t.trim()),(!r.newlineIsToken||!e.includes(`
|
|
363
216
|
`))&&(e=e.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
|
|
364
217
|
`)&&(t=t.slice(0,-1)),e.endsWith(`
|
|
365
|
-
`)&&(e=e.slice(0,-1))),Diff.prototype.equals.call(this,t,e,r)};function diffLines(t,e,r){return lineDiff.diff(t,e,r)}var sentenceDiff=new Diff;sentenceDiff.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var cssDiff=new Diff;cssDiff.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function _typeof(t){"@babel/helpers - typeof";return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(t)}var jsonDiff=new Diff;jsonDiff.useLongestToken=!0,jsonDiff.tokenize=lineDiff.tokenize,jsonDiff.castInput=function(t,e){var r=e.undefinedReplacement,n=e.stringifyReplacer,i=n===void 0?function(o,s){return typeof s>"u"?r:s}:n;return typeof t=="string"?t:JSON.stringify(canonicalize(t,null,null,i),i," ")},jsonDiff.equals=function(t,e,r){return Diff.prototype.equals.call(jsonDiff,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),r)};function canonicalize(t,e,r,n,i){e=e||[],r=r||[],n&&(t=n(i,t));var o;for(o=0;o<e.length;o+=1)if(e[o]===t)return r[o];var s;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),s=new Array(t.length),r.push(s),o=0;o<t.length;o+=1)s[o]=canonicalize(t[o],e,r,n,i);return e.pop(),r.pop(),s}if(t&&t.toJSON&&(t=t.toJSON()),_typeof(t)==="object"&&t!==null){e.push(t),s={},r.push(s);var a=[],l;for(l in t)Object.prototype.hasOwnProperty.call(t,l)&&a.push(l);for(a.sort(),o=0;o<a.length;o+=1)l=a[o],s[l]=canonicalize(t[l],e,r,n,l);e.pop(),r.pop()}else s=t;return s}var arrayDiff=new Diff;arrayDiff.tokenize=function(t){return t.slice()},arrayDiff.join=arrayDiff.removeEmpty=function(t){return t};class PageStateCache{constructor(){this.prev=null}isFullRefresh(e){return!this.prev||this.prev.url!==e}update(e,r){const n=this.isFullRefresh(e),i=this.prev?.url??"";let o=0,s=0,a="";if(!n&&this.prev){const l=diffLines(this.prev.yaml,r),c=[];l.forEach(u=>{if(!u.added&&!u.removed)return;const
|
|
366
|
-
`).filter(Boolean);u.added?(o+=
|
|
367
|
-
`)}return this.prev={url:e,yaml:r},{isFullRefresh:n,prevUrl:i,addedLines:o,removedLines:s,diffText:a}}invalidate(){this.prev=null}}function computeBorderGeometry(t,e,r,n){const i=Math.max(1,Math.min(t,e)),o=Math.min(r,20),a=Math.min(o+n,i),l=Math.min(a,Math.floor(t/2)),c=Math.min(a,Math.floor(e/2)),u=x=>x/t*2-1,
|
|
218
|
+
`)&&(e=e.slice(0,-1))),Diff.prototype.equals.call(this,t,e,r)};function diffLines(t,e,r){return lineDiff.diff(t,e,r)}var sentenceDiff=new Diff;sentenceDiff.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var cssDiff=new Diff;cssDiff.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function _typeof(t){"@babel/helpers - typeof";return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(t)}var jsonDiff=new Diff;jsonDiff.useLongestToken=!0,jsonDiff.tokenize=lineDiff.tokenize,jsonDiff.castInput=function(t,e){var r=e.undefinedReplacement,n=e.stringifyReplacer,i=n===void 0?function(o,s){return typeof s>"u"?r:s}:n;return typeof t=="string"?t:JSON.stringify(canonicalize(t,null,null,i),i," ")},jsonDiff.equals=function(t,e,r){return Diff.prototype.equals.call(jsonDiff,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),r)};function canonicalize(t,e,r,n,i){e=e||[],r=r||[],n&&(t=n(i,t));var o;for(o=0;o<e.length;o+=1)if(e[o]===t)return r[o];var s;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),s=new Array(t.length),r.push(s),o=0;o<t.length;o+=1)s[o]=canonicalize(t[o],e,r,n,i);return e.pop(),r.pop(),s}if(t&&t.toJSON&&(t=t.toJSON()),_typeof(t)==="object"&&t!==null){e.push(t),s={},r.push(s);var a=[],l;for(l in t)Object.prototype.hasOwnProperty.call(t,l)&&a.push(l);for(a.sort(),o=0;o<a.length;o+=1)l=a[o],s[l]=canonicalize(t[l],e,r,n,l);e.pop(),r.pop()}else s=t;return s}var arrayDiff=new Diff;arrayDiff.tokenize=function(t){return t.slice()},arrayDiff.join=arrayDiff.removeEmpty=function(t){return t};class PageStateCache{constructor(){this.prev=null}isFullRefresh(e){return!this.prev||this.prev.url!==e}update(e,r){const n=this.isFullRefresh(e),i=this.prev?.url??"";let o=0,s=0,a="";if(!n&&this.prev){const l=diffLines(this.prev.yaml,r),c=[];l.forEach(u=>{if(!u.added&&!u.removed)return;const f=u.value.split(`
|
|
219
|
+
`).filter(Boolean);u.added?(o+=f.length,f.forEach(h=>c.push(`+ ${h}`))):(s+=f.length,f.forEach(h=>c.push(`- ${h}`)))}),a=c.join(`
|
|
220
|
+
`)}return this.prev={url:e,yaml:r},{isFullRefresh:n,prevUrl:i,addedLines:o,removedLines:s,diffText:a}}invalidate(){this.prev=null}}function computeBorderGeometry(t,e,r,n){const i=Math.max(1,Math.min(t,e)),o=Math.min(r,20),a=Math.min(o+n,i),l=Math.min(a,Math.floor(t/2)),c=Math.min(a,Math.floor(e/2)),u=x=>x/t*2-1,f=x=>x/e*2-1,h=0,m=t,g=0,A=e,_=l,p=t-l,v=c,S=e-c,b=u(h),C=u(m),M=f(g),L=f(A),z=u(_),D=u(p),V=f(v),H=f(S),G=0,ie=0,X=1,te=1,oe=l/t,re=1-l/t,Q=c/e,K=1-c/e,ce=new Float32Array([b,M,C,M,b,V,b,V,C,M,C,V,b,H,C,H,b,L,b,L,C,H,C,L,b,V,z,V,b,H,b,H,z,V,z,H,D,V,C,V,D,H,D,H,C,V,C,H]),d=new Float32Array([G,ie,X,ie,G,Q,G,Q,X,ie,X,Q,G,K,X,K,G,te,G,te,X,K,X,te,G,Q,oe,Q,G,K,G,K,oe,Q,oe,K,re,Q,X,Q,re,K,re,K,X,Q,X,K]);return{positions:ce,uvs:d}}function compileShader(t,e,r){const n=t.createShader(e);if(!n)throw new Error("Failed to create shader");if(t.shaderSource(n,r),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(n)||"Unknown shader error";throw t.deleteShader(n),new Error(i)}return n}function createProgram(t,e,r){const n=compileShader(t,t.VERTEX_SHADER,e),i=compileShader(t,t.FRAGMENT_SHADER,r),o=t.createProgram();if(!o)throw new Error("Failed to create program");if(t.attachShader(o,n),t.attachShader(o,i),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS)){const s=t.getProgramInfoLog(o)||"Unknown link error";throw t.deleteProgram(o),t.deleteShader(n),t.deleteShader(i),new Error(s)}return t.deleteShader(n),t.deleteShader(i),o}const fragmentShaderSource=`#version 300 es
|
|
368
221
|
precision lowp float;
|
|
369
222
|
in vec2 vUV;
|
|
370
223
|
out vec4 outColor;
|
|
@@ -474,7 +327,7 @@ out vec2 vUV;
|
|
|
474
327
|
void main() {
|
|
475
328
|
vUV = aUV;
|
|
476
329
|
gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
477
|
-
}`;const DEFAULT_COLORS=["rgb(57, 182, 255)","rgb(189, 69, 251)","rgb(255, 87, 51)","rgb(255, 214, 0)"];function parseColor(t){const e=t.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!e)throw new Error(`Invalid color format: ${t}`);const[,r,n,i]=e;return[parseInt(r)/255,parseInt(n)/255,parseInt(i)/255]}class Motion{element;canvas;options;running=!1;disposed=!1;startTime=0;lastTime=0;rafId=null;glr;observer;constructor(e={}){this.options={width:e.width??600,height:e.height??600,ratio:e.ratio??window.devicePixelRatio??1,borderWidth:e.borderWidth??8,glowWidth:e.glowWidth??200,borderRadius:e.borderRadius??8,mode:e.mode??"light",...e},this.canvas=document.createElement("canvas"),this.options.classNames&&(this.canvas.className=this.options.classNames),this.options.styles&&Object.assign(this.canvas.style,this.options.styles),this.canvas.style.display="block",this.canvas.style.transformOrigin="center",this.canvas.style.pointerEvents="none",this.element=this.canvas,this.setupGL(),this.options.skipGreeting||this.greet()}start(){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.running)return;if(!this.glr){console.error("WebGL resources are not initialized.");return}this.running=!0,this.startTime=performance.now(),this.resize(this.options.width??600,this.options.height??600,this.options.ratio),this.glr.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.glr.gl.useProgram(this.glr.program),this.glr.gl.uniform2f(this.glr.uResolution,this.canvas.width,this.canvas.height),this.checkGLError(this.glr.gl,"start: after initial setup");const e=()=>{if(!this.running||!this.glr)return;this.rafId=requestAnimationFrame(e);const r=performance.now();if(r-this.lastTime<1e3/32)return;this.lastTime=r;const i=(r-this.startTime)*.001;this.render(i)};this.rafId=requestAnimationFrame(e)}pause(){if(this.disposed)throw new Error("Motion instance has been disposed.");this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId)}dispose(){if(this.disposed)return;this.disposed=!0,this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId);const{gl:e,vao:r,positionBuffer:n,uvBuffer:i,program:o}=this.glr;r&&e.deleteVertexArray(r),n&&e.deleteBuffer(n),i&&e.deleteBuffer(i),e.deleteProgram(o),this.observer&&this.observer.disconnect(),this.canvas.remove()}resize(e,r,n){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.options.width=e,this.options.height=r,n&&(this.options.ratio=n),!this.running)return;const{gl:i,program:o,vao:s,positionBuffer:a,uvBuffer:l,uResolution:c}=this.glr,u=n??this.options.ratio??window.devicePixelRatio??1,h=Math.max(1,Math.floor(e*u)),f=Math.max(1,Math.floor(r*u));this.canvas.style.width=`${e}px`,this.canvas.style.height=`${r}px`,(this.canvas.width!==h||this.canvas.height!==f)&&(this.canvas.width=h,this.canvas.height=f),i.viewport(0,0,this.canvas.width,this.canvas.height),this.checkGLError(i,"resize: after viewport setup");const{positions:g,uvs:b}=computeBorderGeometry(this.canvas.width,this.canvas.height,this.options.borderWidth*u,this.options.glowWidth*u);i.bindVertexArray(s),i.bindBuffer(i.ARRAY_BUFFER,a),i.bufferData(i.ARRAY_BUFFER,g,i.STATIC_DRAW);const P=i.getAttribLocation(o,"aPosition");i.enableVertexAttribArray(P),i.vertexAttribPointer(P,2,i.FLOAT,!1,0,0),this.checkGLError(i,"resize: after position buffer update"),i.bindBuffer(i.ARRAY_BUFFER,l),i.bufferData(i.ARRAY_BUFFER,b,i.STATIC_DRAW);const w=i.getAttribLocation(o,"aUV");i.enableVertexAttribArray(w),i.vertexAttribPointer(w,2,i.FLOAT,!1,0,0),this.checkGLError(i,"resize: after UV buffer update"),i.useProgram(o),i.uniform2f(c,this.canvas.width,this.canvas.height),i.uniform1f(this.glr.uBorderWidth,this.options.borderWidth*u),i.uniform1f(this.glr.uGlowWidth,this.options.glowWidth*u),i.uniform1f(this.glr.uBorderRadius,this.options.borderRadius*u),this.checkGLError(i,"resize: after uniform updates");const p=performance.now();this.lastTime=p;const m=(p-this.startTime)*.001;this.render(m)}autoResize(e){this.observer&&this.observer.disconnect(),this.observer=new ResizeObserver(()=>{const r=e.getBoundingClientRect();this.resize(r.width,r.height)}),this.observer.observe(e)}fadeIn(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((e,r)=>{const n=this.canvas.animate([{opacity:0,transform:"scale(1.2)"},{opacity:1,transform:"scale(1)"}],{duration:300,easing:"ease-out",fill:"forwards"});n.onfinish=()=>e(),n.oncancel=()=>r("canceled")})}fadeOut(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((e,r)=>{const n=this.canvas.animate([{opacity:1,transform:"scale(1)"},{opacity:0,transform:"scale(1.2)"}],{duration:300,easing:"ease-in",fill:"forwards"});n.onfinish=()=>e(),n.oncancel=()=>r("canceled")})}checkGLError(e,r){let n=e.getError();if(n!==e.NO_ERROR){for(console.group(`🔴 WebGL Error in ${r}`);n!==e.NO_ERROR;){const i=this.getGLErrorName(e,n);console.error(`${i} (0x${n.toString(16)})`),n=e.getError()}console.groupEnd()}}getGLErrorName(e,r){switch(r){case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"UNKNOWN_ERROR"}}setupGL(){const e=this.canvas.getContext("webgl2",{antialias:!1,alpha:!0});if(!e)throw new Error("WebGL2 is required but not available.");const r=createProgram(e,vertexShaderSource,fragmentShaderSource);this.checkGLError(e,"setupGL: after createProgram");const n=e.createVertexArray();e.bindVertexArray(n),this.checkGLError(e,"setupGL: after VAO creation");const i=this.canvas.width||2,o=this.canvas.height||2,{positions:s,uvs:a}=computeBorderGeometry(i,o,this.options.borderWidth,this.options.glowWidth),l=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,l),e.bufferData(e.ARRAY_BUFFER,s,e.STATIC_DRAW);const c=e.getAttribLocation(r,"aPosition");e.enableVertexAttribArray(c),e.vertexAttribPointer(c,2,e.FLOAT,!1,0,0),this.checkGLError(e,"setupGL: after position buffer setup");const u=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,u),e.bufferData(e.ARRAY_BUFFER,a,e.STATIC_DRAW);const h=e.getAttribLocation(r,"aUV");e.enableVertexAttribArray(h),e.vertexAttribPointer(h,2,e.FLOAT,!1,0,0),this.checkGLError(e,"setupGL: after UV buffer setup");const f=e.getUniformLocation(r,"uResolution"),g=e.getUniformLocation(r,"uTime"),b=e.getUniformLocation(r,"uBorderWidth"),P=e.getUniformLocation(r,"uGlowWidth"),w=e.getUniformLocation(r,"uBorderRadius"),p=e.getUniformLocation(r,"uColors"),m=e.getUniformLocation(r,"uGlowExponent"),A=e.getUniformLocation(r,"uGlowFactor");e.useProgram(r),e.uniform1f(b,this.options.borderWidth),e.uniform1f(P,this.options.glowWidth),e.uniform1f(w,this.options.borderRadius),this.options.mode==="dark"?(e.uniform1f(m,2),e.uniform1f(A,1.8)):(e.uniform1f(m,1),e.uniform1f(A,1));const T=(this.options.colors||DEFAULT_COLORS).map(parseColor);for(let k=0;k<T.length;k++)e.uniform3f(e.getUniformLocation(r,`uColors[${k}]`),...T[k]);this.checkGLError(e,"setupGL: after uniform setup"),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),this.glr={gl:e,program:r,vao:n,positionBuffer:l,uvBuffer:u,uResolution:f,uTime:g,uBorderWidth:b,uGlowWidth:P,uBorderRadius:w,uColors:p}}render(e){if(!this.glr)return;const{gl:r,program:n,vao:i,uTime:o}=this.glr;r.useProgram(n),r.bindVertexArray(i),r.uniform1f(o,e),r.disable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.disable(r.BLEND),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLES,0,24),this.checkGLError(r,"render: after draw call"),r.bindVertexArray(null)}greet(){console.log("%c🌈 ai-motion 0.4.8 🌈","background: linear-gradient(90deg, #39b6ff, #bd45fb, #ff5733, #ffd600); color: white; text-shadow: 0 0 2px rgba(0, 0, 0, 0.2); font-weight: bold; font-size: 1em; padding: 2px 12px; border-radius: 6px;")}}function isPageDark$1(){try{return!!(hasDarkModeClass$1()||hasDarkModeDataAttribute$1()||isColorSchemeDark$1()||isBackgroundDark$1()||isMainContentBackgroundDark$1()||isTextColorLight$1())}catch(t){return console.warn("Error determining if page is dark:",t),!1}}function hasDarkModeClass$1(){const t=["dark","dark-mode","theme-dark","night","night-mode"],e=document.documentElement,r=document.body||document.documentElement;for(const n of t)if(e.classList.contains(n)||r?.classList.contains(n))return!0;return!1}function hasDarkModeDataAttribute$1(){const t=document.documentElement,e=document.body||document.documentElement,r=["data-theme","data-color-mode","data-bs-theme","data-mui-color-scheme"];for(const n of r){const i=e?.getAttribute(n),o=t.getAttribute(n);if(i?.toLowerCase()==="dark"||o?.toLowerCase()==="dark")return!0}return!1}function isColorSchemeDark$1(){const e=document.querySelector('meta[name="color-scheme"]')?.content.toLowerCase();if(e==="dark"||e==="only dark")return!0;const n=window.getComputedStyle(document.documentElement).getPropertyValue("color-scheme").trim().toLowerCase();return n==="dark"||n==="only dark"}function isBackgroundDark$1(){const t=window.getComputedStyle(document.documentElement),e=window.getComputedStyle(document.body||document.documentElement),r=t.backgroundColor,n=e.backgroundColor;return isColorDark$1(n)?!0:n==="transparent"||n.startsWith("rgba(0, 0, 0, 0)")?isColorDark$1(r):!1}function isTextColorLight$1(){const e=window.getComputedStyle(document.body||document.documentElement),r=getLuminance$1(e.color);return r!==null&&r>200}function isMainContentBackgroundDark$1(){const{innerWidth:t,innerHeight:e}=window,r=t*e*.5,n=["#app","#root","#__next"];for(const i of n){const o=document.querySelector(i);if(!o)continue;const s=o.getBoundingClientRect();if(!(s.width*s.height<r)&&isColorDark$1(window.getComputedStyle(o).backgroundColor))return!0}return!1}function parseRgbColor$1(t){const e=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(t);return e?{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3])}:null}function getLuminance$1(t){if(!t||t==="transparent"||t.startsWith("rgba(0, 0, 0, 0)"))return null;const e=parseRgbColor$1(t);return e?.299*e.r+.587*e.g+.114*e.b:null}function isColorDark$1(t,e=128){const r=getLuminance$1(t);return r!==null&&r<e}const injectStyles=`
|
|
330
|
+
}`;const DEFAULT_COLORS=["rgb(57, 182, 255)","rgb(189, 69, 251)","rgb(255, 87, 51)","rgb(255, 214, 0)"];function parseColor(t){const e=t.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!e)throw new Error(`Invalid color format: ${t}`);const[,r,n,i]=e;return[parseInt(r)/255,parseInt(n)/255,parseInt(i)/255]}class Motion{element;canvas;options;running=!1;disposed=!1;startTime=0;lastTime=0;rafId=null;glr;observer;constructor(e={}){this.options={width:e.width??600,height:e.height??600,ratio:e.ratio??window.devicePixelRatio??1,borderWidth:e.borderWidth??8,glowWidth:e.glowWidth??200,borderRadius:e.borderRadius??8,mode:e.mode??"light",...e},this.canvas=document.createElement("canvas"),this.options.classNames&&(this.canvas.className=this.options.classNames),this.options.styles&&Object.assign(this.canvas.style,this.options.styles),this.canvas.style.display="block",this.canvas.style.transformOrigin="center",this.canvas.style.pointerEvents="none",this.element=this.canvas,this.setupGL(),this.options.skipGreeting||this.greet()}start(){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.running)return;if(!this.glr){console.error("WebGL resources are not initialized.");return}this.running=!0,this.startTime=performance.now(),this.resize(this.options.width??600,this.options.height??600,this.options.ratio),this.glr.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.glr.gl.useProgram(this.glr.program),this.glr.gl.uniform2f(this.glr.uResolution,this.canvas.width,this.canvas.height),this.checkGLError(this.glr.gl,"start: after initial setup");const e=()=>{if(!this.running||!this.glr)return;this.rafId=requestAnimationFrame(e);const r=performance.now();if(r-this.lastTime<1e3/32)return;this.lastTime=r;const i=(r-this.startTime)*.001;this.render(i)};this.rafId=requestAnimationFrame(e)}pause(){if(this.disposed)throw new Error("Motion instance has been disposed.");this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId)}dispose(){if(this.disposed)return;this.disposed=!0,this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId);const{gl:e,vao:r,positionBuffer:n,uvBuffer:i,program:o}=this.glr;r&&e.deleteVertexArray(r),n&&e.deleteBuffer(n),i&&e.deleteBuffer(i),e.deleteProgram(o),this.observer&&this.observer.disconnect(),this.canvas.remove()}resize(e,r,n){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.options.width=e,this.options.height=r,n&&(this.options.ratio=n),!this.running)return;const{gl:i,program:o,vao:s,positionBuffer:a,uvBuffer:l,uResolution:c}=this.glr,u=n??this.options.ratio??window.devicePixelRatio??1,f=Math.max(1,Math.floor(e*u)),h=Math.max(1,Math.floor(r*u));this.canvas.style.width=`${e}px`,this.canvas.style.height=`${r}px`,(this.canvas.width!==f||this.canvas.height!==h)&&(this.canvas.width=f,this.canvas.height=h),i.viewport(0,0,this.canvas.width,this.canvas.height),this.checkGLError(i,"resize: after viewport setup");const{positions:m,uvs:g}=computeBorderGeometry(this.canvas.width,this.canvas.height,this.options.borderWidth*u,this.options.glowWidth*u);i.bindVertexArray(s),i.bindBuffer(i.ARRAY_BUFFER,a),i.bufferData(i.ARRAY_BUFFER,m,i.STATIC_DRAW);const A=i.getAttribLocation(o,"aPosition");i.enableVertexAttribArray(A),i.vertexAttribPointer(A,2,i.FLOAT,!1,0,0),this.checkGLError(i,"resize: after position buffer update"),i.bindBuffer(i.ARRAY_BUFFER,l),i.bufferData(i.ARRAY_BUFFER,g,i.STATIC_DRAW);const _=i.getAttribLocation(o,"aUV");i.enableVertexAttribArray(_),i.vertexAttribPointer(_,2,i.FLOAT,!1,0,0),this.checkGLError(i,"resize: after UV buffer update"),i.useProgram(o),i.uniform2f(c,this.canvas.width,this.canvas.height),i.uniform1f(this.glr.uBorderWidth,this.options.borderWidth*u),i.uniform1f(this.glr.uGlowWidth,this.options.glowWidth*u),i.uniform1f(this.glr.uBorderRadius,this.options.borderRadius*u),this.checkGLError(i,"resize: after uniform updates");const p=performance.now();this.lastTime=p;const v=(p-this.startTime)*.001;this.render(v)}autoResize(e){this.observer&&this.observer.disconnect(),this.observer=new ResizeObserver(()=>{const r=e.getBoundingClientRect();this.resize(r.width,r.height)}),this.observer.observe(e)}fadeIn(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((e,r)=>{const n=this.canvas.animate([{opacity:0,transform:"scale(1.2)"},{opacity:1,transform:"scale(1)"}],{duration:300,easing:"ease-out",fill:"forwards"});n.onfinish=()=>e(),n.oncancel=()=>r("canceled")})}fadeOut(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((e,r)=>{const n=this.canvas.animate([{opacity:1,transform:"scale(1)"},{opacity:0,transform:"scale(1.2)"}],{duration:300,easing:"ease-in",fill:"forwards"});n.onfinish=()=>e(),n.oncancel=()=>r("canceled")})}checkGLError(e,r){let n=e.getError();if(n!==e.NO_ERROR){for(console.group(`🔴 WebGL Error in ${r}`);n!==e.NO_ERROR;){const i=this.getGLErrorName(e,n);console.error(`${i} (0x${n.toString(16)})`),n=e.getError()}console.groupEnd()}}getGLErrorName(e,r){switch(r){case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"UNKNOWN_ERROR"}}setupGL(){const e=this.canvas.getContext("webgl2",{antialias:!1,alpha:!0});if(!e)throw new Error("WebGL2 is required but not available.");const r=createProgram(e,vertexShaderSource,fragmentShaderSource);this.checkGLError(e,"setupGL: after createProgram");const n=e.createVertexArray();e.bindVertexArray(n),this.checkGLError(e,"setupGL: after VAO creation");const i=this.canvas.width||2,o=this.canvas.height||2,{positions:s,uvs:a}=computeBorderGeometry(i,o,this.options.borderWidth,this.options.glowWidth),l=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,l),e.bufferData(e.ARRAY_BUFFER,s,e.STATIC_DRAW);const c=e.getAttribLocation(r,"aPosition");e.enableVertexAttribArray(c),e.vertexAttribPointer(c,2,e.FLOAT,!1,0,0),this.checkGLError(e,"setupGL: after position buffer setup");const u=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,u),e.bufferData(e.ARRAY_BUFFER,a,e.STATIC_DRAW);const f=e.getAttribLocation(r,"aUV");e.enableVertexAttribArray(f),e.vertexAttribPointer(f,2,e.FLOAT,!1,0,0),this.checkGLError(e,"setupGL: after UV buffer setup");const h=e.getUniformLocation(r,"uResolution"),m=e.getUniformLocation(r,"uTime"),g=e.getUniformLocation(r,"uBorderWidth"),A=e.getUniformLocation(r,"uGlowWidth"),_=e.getUniformLocation(r,"uBorderRadius"),p=e.getUniformLocation(r,"uColors"),v=e.getUniformLocation(r,"uGlowExponent"),S=e.getUniformLocation(r,"uGlowFactor");e.useProgram(r),e.uniform1f(g,this.options.borderWidth),e.uniform1f(A,this.options.glowWidth),e.uniform1f(_,this.options.borderRadius),this.options.mode==="dark"?(e.uniform1f(v,2),e.uniform1f(S,1.8)):(e.uniform1f(v,1),e.uniform1f(S,1));const b=(this.options.colors||DEFAULT_COLORS).map(parseColor);for(let C=0;C<b.length;C++)e.uniform3f(e.getUniformLocation(r,`uColors[${C}]`),...b[C]);this.checkGLError(e,"setupGL: after uniform setup"),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),this.glr={gl:e,program:r,vao:n,positionBuffer:l,uvBuffer:u,uResolution:h,uTime:m,uBorderWidth:g,uGlowWidth:A,uBorderRadius:_,uColors:p}}render(e){if(!this.glr)return;const{gl:r,program:n,vao:i,uTime:o}=this.glr;r.useProgram(n),r.bindVertexArray(i),r.uniform1f(o,e),r.disable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.disable(r.BLEND),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLES,0,24),this.checkGLError(r,"render: after draw call"),r.bindVertexArray(null)}greet(){console.log("%c🌈 ai-motion 0.4.8 🌈","background: linear-gradient(90deg, #39b6ff, #bd45fb, #ff5733, #ffd600); color: white; text-shadow: 0 0 2px rgba(0, 0, 0, 0.2); font-weight: bold; font-size: 1em; padding: 2px 12px; border-radius: 6px;")}}function isPageDark$1(){try{return!!(hasDarkModeClass$1()||hasDarkModeDataAttribute$1()||isColorSchemeDark$1()||isBackgroundDark$1()||isMainContentBackgroundDark$1()||isTextColorLight$1())}catch(t){return console.warn("Error determining if page is dark:",t),!1}}function hasDarkModeClass$1(){const t=["dark","dark-mode","theme-dark","night","night-mode"],e=document.documentElement,r=document.body||document.documentElement;for(const n of t)if(e.classList.contains(n)||r?.classList.contains(n))return!0;return!1}function hasDarkModeDataAttribute$1(){const t=document.documentElement,e=document.body||document.documentElement,r=["data-theme","data-color-mode","data-bs-theme","data-mui-color-scheme"];for(const n of r){const i=e?.getAttribute(n),o=t.getAttribute(n);if(i?.toLowerCase()==="dark"||o?.toLowerCase()==="dark")return!0}return!1}function isColorSchemeDark$1(){const e=document.querySelector('meta[name="color-scheme"]')?.content.toLowerCase();if(e==="dark"||e==="only dark")return!0;const n=window.getComputedStyle(document.documentElement).getPropertyValue("color-scheme").trim().toLowerCase();return n==="dark"||n==="only dark"}function isBackgroundDark$1(){const t=window.getComputedStyle(document.documentElement),e=window.getComputedStyle(document.body||document.documentElement),r=t.backgroundColor,n=e.backgroundColor;return isColorDark$1(n)?!0:n==="transparent"||n.startsWith("rgba(0, 0, 0, 0)")?isColorDark$1(r):!1}function isTextColorLight$1(){const e=window.getComputedStyle(document.body||document.documentElement),r=getLuminance$1(e.color);return r!==null&&r>200}function isMainContentBackgroundDark$1(){const{innerWidth:t,innerHeight:e}=window,r=t*e*.5,n=["#app","#root","#__next"];for(const i of n){const o=document.querySelector(i);if(!o)continue;const s=o.getBoundingClientRect();if(!(s.width*s.height<r)&&isColorDark$1(window.getComputedStyle(o).backgroundColor))return!0}return!1}function parseRgbColor$1(t){const e=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(t);return e?{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3])}:null}function getLuminance$1(t){if(!t||t==="transparent"||t.startsWith("rgba(0, 0, 0, 0)"))return null;const e=parseRgbColor$1(t);return e?.299*e.r+.587*e.g+.114*e.b:null}function isColorDark$1(t,e=128){const r=getLuminance$1(t);return r!==null&&r<e}const injectStyles=`
|
|
478
331
|
.webmcp-page-agent-cursor {
|
|
479
332
|
position: absolute;
|
|
480
333
|
width: var(--cursor-size, 75px);
|
|
@@ -544,7 +397,7 @@ gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
|
544
397
|
.webmcp-page-agent-wrapper.visible {
|
|
545
398
|
display: block;
|
|
546
399
|
}
|
|
547
|
-
`;let SimulatorMask$1=class extends EventTarget{constructor(){super(),this.shown=!1,this.wrapper=document.createElement("div"),this.motion=null,this.#n=!1,this.#e=document.createElement("div"),this.#t=0,this.#r=0,this.#i=0,this.#o=0,document.head.appendChild(document.createElement("style")).textContent=injectStyles,this.wrapper.id="page-agent-runtime_simulator-mask",this.wrapper.className="webmcp-page-agent-wrapper",this.wrapper.setAttribute("data-browser-use-ignore","true"),this.wrapper.setAttribute("data-page-agent-ignore","true");try{const s=new Motion({mode:isPageDark$1()?"dark":"light",styles:{position:"absolute",inset:"0"},glowWidth:80,borderWidth:8,colors:["rgb(121, 216, 247)","rgb(171, 219, 110)","rgb(252, 188, 114)","rgb(235, 117, 231)"]});this.motion=s,this.wrapper.appendChild(s.element),s.autoResize(this.wrapper)}catch(s){console.warn("[SimulatorMask] Motion overlay unavailable:",s)}const e=s=>{s.stopPropagation(),s.preventDefault()};["click","mousedown","mouseup","mousemove","wheel","keydown","keyup"].forEach(s=>this.wrapper.addEventListener(s,e)),this.#a(),document.body.appendChild(this.wrapper),this.#s();const r=s=>{const{x:a,y:l}=s.detail;this.setCursorPosition(a,l)},n=()=>{this.triggerClickAnimation()},i=()=>{this.wrapper.style.pointerEvents="none"},o=()=>{this.wrapper.style.pointerEvents="auto"};window.addEventListener("PageAgent::MovePointerTo",r),window.addEventListener("PageAgent::ClickPointer",n),window.addEventListener("PageAgent::EnablePassThrough",i),window.addEventListener("PageAgent::DisablePassThrough",o),this.addEventListener("dispose",()=>{window.removeEventListener("PageAgent::MovePointerTo",r),window.removeEventListener("PageAgent::ClickPointer",n),window.removeEventListener("PageAgent::EnablePassThrough",i),window.removeEventListener("PageAgent::DisablePassThrough",o)})}#n;#e;#t;#r;#i;#o;#a(){this.#e.className="webmcp-page-agent-cursor";const e=document.createElement("div");e.className="webmcp-page-agent-cursorRipple",this.#e.appendChild(e);const r=document.createElement("div");r.className="webmcp-page-agent-cursorFilling",this.#e.appendChild(r),this.wrapper.appendChild(this.#e)}#s(){if(this.#n)return;const e=this.#t+(this.#i-this.#t)*.2,r=this.#r+(this.#o-this.#r)*.2,n=Math.abs(e-this.#i);n>0&&(n<2?this.#t=this.#i:this.#t=e,this.#e.style.left=`${this.#t}px`);const i=Math.abs(r-this.#o);i>0&&(i<2?this.#r=this.#o:this.#r=r,this.#e.style.top=`${this.#r}px`),requestAnimationFrame(()=>this.#s())}setCursorPosition(e,r){this.#n||(this.#i=e,this.#o=r)}triggerClickAnimation(){this.#n||(this.#e.classList.remove("clicking"),this.#e.offsetHeight,this.#e.classList.add("clicking"))}show(){this.shown||this.#n||(this.shown=!0,this.motion?.start(),this.motion?.fadeIn(),this.wrapper.classList.add("visible"),this.#t=window.innerWidth/2,this.#r=window.innerHeight/2,this.#i=this.#t,this.#o=this.#r,this.#e.style.left=`${this.#t}px`,this.#e.style.top=`${this.#r}px`)}hide(){!this.shown||this.#n||(this.shown=!1,this.motion?.fadeOut(),this.motion?.pause(),this.#e.classList.remove("clicking"),setTimeout(()=>{this.wrapper.classList.remove("visible")},800))}dispose(){this.#n=!0,this.motion?.dispose(),this.wrapper.remove(),this.dispatchEvent(new Event("dispose"))}borderElement(e){if(!e)return;this.wrapper.querySelector(".webmcp-page-agent-border")?.remove();const r=e.getBoundingClientRect(),n=2,i=2,o=n+i,s=document.createElement("div");s.className="webmcp-page-agent-border",s.style.position="absolute",s.style.left=`${r.left-o}px`,s.style.top=`${r.top-o}px`,s.style.width=`${r.width+o*2}px`,s.style.height=`${r.height+o*2}px`,s.style.boxSizing="border-box",s.style.pointerEvents="none",s.style.zIndex="10000",s.style.border=`${i}px solid transparent`,s.style.borderImageSource="linear-gradient(to bottom right, #79D8F7, #ABDB6E, #FCBC72, #FA8682, #EB75E7)",s.style.borderImageSlice="1",s.style.borderImageWidth=`${i}px`,this.wrapper.appendChild(s)}removeBorderElement(){this.wrapper.querySelector(".webmcp-page-agent-border")?.remove()}};const inputSchema=objectType({action:enumType(["browserState","click","fill","select","scroll","executeJavascript","searchTree"]).describe(`执行的动作名称, 每一次执行 'click', 'fill', 'select'动作之前,**必须**要先调用 'browserState' 去获取页面的最新状态。
|
|
400
|
+
`;let SimulatorMask$1=class extends EventTarget{constructor(){super(),this.shown=!1,this.wrapper=document.createElement("div"),this.motion=null,this.#n=!1,this.#e=document.createElement("div"),this.#t=0,this.#r=0,this.#i=0,this.#o=0,document.head.appendChild(document.createElement("style")).textContent=injectStyles,this.wrapper.id="page-agent-runtime_simulator-mask",this.wrapper.className="webmcp-page-agent-wrapper",this.wrapper.setAttribute("data-browser-use-ignore","true"),this.wrapper.setAttribute("data-page-agent-ignore","true");try{const s=new Motion({mode:isPageDark$1()?"dark":"light",styles:{position:"absolute",inset:"0"},glowWidth:80,borderWidth:8,colors:["rgb(121, 216, 247)","rgb(171, 219, 110)","rgb(252, 188, 114)","rgb(235, 117, 231)"]});this.motion=s,this.wrapper.appendChild(s.element),s.autoResize(this.wrapper)}catch(s){console.warn("[SimulatorMask] Motion overlay unavailable:",s)}const e=s=>{s.stopPropagation(),s.preventDefault()};["click","mousedown","mouseup","mousemove","wheel","keydown","keyup"].forEach(s=>this.wrapper.addEventListener(s,e)),this.#a(),document.body.appendChild(this.wrapper),this.#s();const r=s=>{const{x:a,y:l}=s.detail;this.setCursorPosition(a,l)},n=()=>{this.triggerClickAnimation()},i=()=>{this.wrapper.style.pointerEvents="none"},o=()=>{this.wrapper.style.pointerEvents="auto"};window.addEventListener("PageAgent::MovePointerTo",r),window.addEventListener("PageAgent::ClickPointer",n),window.addEventListener("PageAgent::EnablePassThrough",i),window.addEventListener("PageAgent::DisablePassThrough",o),this.addEventListener("dispose",()=>{window.removeEventListener("PageAgent::MovePointerTo",r),window.removeEventListener("PageAgent::ClickPointer",n),window.removeEventListener("PageAgent::EnablePassThrough",i),window.removeEventListener("PageAgent::DisablePassThrough",o)})}#n;#e;#t;#r;#i;#o;#a(){this.#e.className="webmcp-page-agent-cursor";const e=document.createElement("div");e.className="webmcp-page-agent-cursorRipple",this.#e.appendChild(e);const r=document.createElement("div");r.className="webmcp-page-agent-cursorFilling",this.#e.appendChild(r),this.wrapper.appendChild(this.#e)}#s(){if(this.#n)return;const e=this.#t+(this.#i-this.#t)*.2,r=this.#r+(this.#o-this.#r)*.2,n=Math.abs(e-this.#i);n>0&&(n<2?this.#t=this.#i:this.#t=e,this.#e.style.left=`${this.#t}px`);const i=Math.abs(r-this.#o);i>0&&(i<2?this.#r=this.#o:this.#r=r,this.#e.style.top=`${this.#r}px`),requestAnimationFrame(()=>this.#s())}setCursorPosition(e,r){this.#n||(this.#i=e,this.#o=r)}triggerClickAnimation(){this.#n||(this.#e.classList.remove("clicking"),this.#e.offsetHeight,this.#e.classList.add("clicking"))}show(){this.shown||this.#n||(this.shown=!0,this.motion?.start(),this.motion?.fadeIn(),this.wrapper.classList.add("visible"),this.#t=window.innerWidth/2,this.#r=window.innerHeight/2,this.#i=this.#t,this.#o=this.#r,this.#e.style.left=`${this.#t}px`,this.#e.style.top=`${this.#r}px`)}hide(){!this.shown||this.#n||(this.shown=!1,this.motion?.fadeOut(),this.motion?.pause(),this.#e.classList.remove("clicking"),setTimeout(()=>{this.wrapper.classList.remove("visible")},800))}dispose(){this.#n=!0,this.motion?.dispose(),this.wrapper.remove(),this.dispatchEvent(new Event("dispose"))}borderElement(e){if(!e)return;this.wrapper.querySelector(".webmcp-page-agent-border")?.remove();const r=e.getBoundingClientRect(),n=2,i=2,o=n+i,s=document.createElement("div");s.className="webmcp-page-agent-border",s.style.position="absolute",s.style.left=`${r.left-o}px`,s.style.top=`${r.top-o}px`,s.style.width=`${r.width+o*2}px`,s.style.height=`${r.height+o*2}px`,s.style.boxSizing="border-box",s.style.pointerEvents="none",s.style.zIndex="10000",s.style.border=`${i}px solid transparent`,s.style.borderImageSource="linear-gradient(to bottom right, #79D8F7, #ABDB6E, #FCBC72, #FA8682, #EB75E7)",s.style.borderImageSlice="1",s.style.borderImageWidth=`${i}px`,this.wrapper.appendChild(s)}removeBorderElement(){this.wrapper.querySelector(".webmcp-page-agent-border")?.remove()}};const inputSchema=objectType({action:enumType(["browserState","click","fill","select","scroll","executeJavascript","searchTree","hover"]).describe(`执行的动作名称, 每一次执行 'click', 'fill', 'select', 'hover'动作之前,**必须**要先调用 'browserState' 去获取页面的最新状态。
|
|
548
401
|
browserState: '查询整个页面的浏览器状态;返回页面的标题、URL、YAML格式的语义化页面树',
|
|
549
402
|
click: '根据元素索引点击;',
|
|
550
403
|
fill: '根据元素索引填写文本;';
|
|
@@ -552,20 +405,14 @@ gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
|
552
405
|
scroll: '滚动页面的动作,可以指定水平滚动还是上下滚动; 不带元素索引时:滚动整个文档。带元素索引时:滚动该索引处的容器(或其最近的可滚动祖先元素)'
|
|
553
406
|
executeJavascript: '执行javascript代码'
|
|
554
407
|
searchTree: '按关键词搜索无障碍树,返回带行号的匹配节点及上下文,无需获取全量树。适合快速定位特定元素(如所有按钮、特定名称的链接等),显著减少上下文消耗。必须提供 query 参数。'
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
${r.content[0].text}`}
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
${u}`,f=await e.buildBrowserStateResponse(r);return f.content[0].text=`${h}
|
|
561
|
-
|
|
562
|
-
${f.content[0].text}`,f}async function handleExecuteJavascript(t,e){if(!t.script)return e.errContent("脚本执行异常: 缺少javascript代码");let r=await new Function(`return (async () => { ${t.script} })()`)();if(r===void 0)try{r=await new Function(`return (async () => (${t.script}))()`)()}catch{}return await e.pageController.hideMask(),{content:[{type:"text",text:`脚本执行结果: ${JSON.stringify(r)}`}]}}async function handleSearchTree(t,e){if(!t.query)return e.errContent("搜索失败: 缺少 query 参数");const r=searchA11yTree(t.query,document.body,{...getPageAgentToolConfig().a11yConfig,contextLines:t.contextLines,maxMatches:t.maxMatches});e.setRefMap(r.refMap),e.stateCache.update(window.location.href,r.yaml),await e.pageController.hideMask();const n=detectPageDialog(),i=detectValidationErrors(),o=`${n}${i}`;return{content:[{type:"text",text:o?`${o}
|
|
563
|
-
${r.text}`:r.text}]}}function registerPageAgentTool(t={}){initializeBuiltinWebMCP(),setPageAgentToolConfig(t,{mode:"replace"}),window.__webmcpcli_beforeGetBrowserState=window.__webmcpcli_beforeGetBrowserState||null;const e=new PageController({enableMask:!1});e.maskReady=(async()=>{e.mask=new SimulatorMask$1})();const r=new PageStateCache;let n=new Map;async function i(u){return{content:[{type:"text",text:u}]}}async function o(u){const h=await createActionErrorResult(u,a);return t.removeMaskAfterToolCall&&await e.hideMask(),h}async function s(u,h){const f=await a("full");return{content:[{type:"text",text:`⚠️ ${u}失败: ref 索引 ${h} 已失效(页面可能已刷新),已自动重新加载页面状态,请使用新的 ref 索引重试。
|
|
564
|
-
`+f.content[0].text}]}}async function a(u="diff"){const h=window.location.href,f=document.title,{yaml:g,refMap:b}=buildA11yTree(document.body,getPageAgentToolConfig().a11yConfig);n=b,getPageAgentToolConfig().enableHighlight&&(highlight(b),globalRemoveListener());const P=r.update(h,g),w=detectPageDialog(),p=detectValidationErrors();let m="";return u==="full"?m=g:u==="diff"?m=P.isFullRefresh?g:P.diffText:u==="both"&&(m=`【全量页面树】:
|
|
565
|
-
${g}
|
|
408
|
+
hover: '根据元素索引悬浮(hover)目标元素; 触发 mouseover/mouseenter 等事件,用于显示 tooltip、展开悬浮菜单等交互; 操作后自动返回最新页面状态。'
|
|
409
|
+
`),index:numberType().min(0).optional().describe("执行动作 of the element index, 动作为 click,fill,select,hover时,必须提供元素索引"),text:stringType().optional().describe("执行动作的文本内容, 动作为 fill,select 时,必须提供文本内容"),down:booleanType().optional().describe("执行上下滚动时,必须提供down参数"),right:booleanType().optional().describe("执行水平滚动方向, 必须提供right参数"),numPages:numberType().optional().describe("执行动作的滚动页数, 动作为 scroll时,可以提供滚动页数,建议每次滚动0.1页,该值不要大于5."),pixels:numberType().int().min(0).optional().describe("执行动作的滚动像素数,动作为 scroll时,可以提供滚动像素数"),script:stringType().optional().describe("执行的javascript代码,动作为 executeJavascript时,必须提供script参数"),query:stringType().optional().describe("搜索关键词,动作为 searchTree 时必须提供。支持按 role(如 button、link)、节点名称、状态(如 checked)或 ref 索引(如 #3)搜索"),contextLines:numberType().int().min(0).max(10).default(2).describe("searchTree 时每个命中行前后保留的上下文行数,默认 2"),maxMatches:numberType().int().min(1).max(50).default(20).describe("searchTree 时最大返回分组数,默认 20"),responseMode:enumType(["full","diff","both"]).optional().default("diff").describe("返回浏览器状态的模式。full: 仅返回当前全量 A11y 树;diff: 仅返回与上一次状态的增量差异;both: 同时返回全量 A11y 树与增量差异。默认值为 diff。")}),PAGE_AGENT_TOOL_CALL_EVENT="page-agent-tool-call",PAGE_AGENT_TOOL_RESULT_EVENT="page-agent-tool-result",PAGE_AGENT_CHAT_END_EVENT="page-agent-chat-end";function isPageAgentToolErrorResult(t){return typeof t=="object"&&t!==null&&"isError"in t&&t.isError===!0&&"error"in t&&typeof t.error=="string"}function dispatchPageAgentToolResult(t){window.dispatchEvent(new CustomEvent(PAGE_AGENT_TOOL_RESULT_EVENT,{detail:t}))}function setupPageAgentToolEventBridge(t,e){window.__nextSdkPageAgentToolEventCleanup?.();const r=async i=>{const o=i.detail,s=o?.requestId;if(!s){dispatchPageAgentToolResult({requestId:"",data:{success:!1,error:"缺少 requestId"}});return}try{const a=inputSchema.parse(o.data),l=await t(a);if(isPageAgentToolErrorResult(l)){dispatchPageAgentToolResult({requestId:s,data:{success:!1,error:l.error,result:l}});return}dispatchPageAgentToolResult({requestId:s,data:{success:!0,result:l}})}catch(a){dispatchPageAgentToolResult({requestId:s,data:{success:!1,error:a instanceof Error?a.message:String(a)}})}},n=async()=>{try{await e.hideMask()}catch{}};window.addEventListener(PAGE_AGENT_TOOL_CALL_EVENT,r),window.addEventListener(PAGE_AGENT_CHAT_END_EVENT,n),window.__nextSdkPageAgentToolEventCleanup=()=>{window.removeEventListener(PAGE_AGENT_TOOL_CALL_EVENT,r),window.removeEventListener(PAGE_AGENT_CHAT_END_EVENT,n),window.__nextSdkPageAgentToolEventCleanup=void 0}}function withStateFields(t,e){try{const r=JSON.parse(t);return JSON.stringify({...r,...e})}catch{return JSON.stringify({...e,raw:t})}}async function createActionErrorResult(t,e){try{const r=await e("full");return{isError:!0,error:t,content:[{type:"text",text:withStateFields(r.content[0].text,{error:t})}]}}catch(r){return{isError:!0,error:t,content:[{type:"text",text:JSON.stringify({error:t,stateError:r instanceof Error?r.message:String(r)})}]}}}async function handleBrowserState(t,e){if(window.__webmcpcli_beforeGetBrowserState)try{window.__webmcpcli_beforeGetBrowserState()}catch(r){console.warn("__webmcpcli_beforeGetBrowserState error:",r)}return e.buildBrowserStateResponse(t.responseMode??"diff")}async function handleClick(t,e){const r=t.responseMode??"diff";if(t.index===void 0)return e.actionError("点击结果: 缺少元素索引");const n=e.getRefMap().get(t.index);if(!n)return e.actionError(`点击失败: ref 索引 ${t.index} 已失效(页面可能已刷新),已自动重新加载页面状态,请使用新的 ref 索引重试。`);let i=n;if(n.shadowRoot&&!(n instanceof HTMLButtonElement)&&!(n instanceof HTMLAnchorElement)){const o=n.shadowRoot.querySelector('button, a, [role="button"], [role="link"]');o&&(i=o)}return await clickElement(i),await waitForDomSettled(),e.buildBrowserStateResponse(r)}async function handleFill(t,e){const r=t.responseMode??"diff";if(t.index===void 0||typeof t.text!="string")return e.actionError("填写结果: 缺少元素索引或文本内容");const n=e.getRefMap().get(t.index);if(!n)return e.actionError(`填写失败: ref 索引 ${t.index} 已失效(页面可能已刷新),已自动重新加载页面状态,请使用新的 ref 索引重试。`);let i=n;if(!(i instanceof HTMLInputElement)&&!(i instanceof HTMLTextAreaElement)){const o=n.querySelector("input, textarea")??n.shadowRoot?.querySelector("input, textarea");o&&(i=o)}if(i instanceof HTMLInputElement&&i.readOnly)i.value=t.text,dispatchComposedEvents(i,"input","change","blur");else{let o=!1;try{await inputTextElement(i,t.text),o=!0}catch{const a=Object.getOwnPropertyDescriptor((i instanceof HTMLTextAreaElement?HTMLTextAreaElement:HTMLInputElement).prototype,"value")?.set;a&&(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement)&&(a.call(i,t.text),i.dispatchEvent(new Event("focus",{bubbles:!0,composed:!0})),i.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),i.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),i.dispatchEvent(new Event("blur",{bubbles:!0,composed:!0})),o=!0)}if(!o)return e.actionError(`填写结果: 无法填写元素 ${t.index},元素不是 input、textarea 或 contenteditable`);isInShadowDom(i)&&dispatchComposedEvents(i,"input","change")}return await waitForDomSettled(),e.buildBrowserStateResponse(r)}async function handleSelect(t,e){const r=t.responseMode??"diff";if(t.index===void 0||typeof t.text!="string")return e.actionError("选择结果: 缺少元素索引或文本内容");let n=e.getRefMap().get(t.index);if(!n)return e.actionError(`选择失败: ref 索引 ${t.index} 已失效(页面可能已刷新),已自动重新加载页面状态,请使用新的 ref 索引重试。`);let i=null;if(n instanceof HTMLSelectElement)i=n;else{const o=n.querySelector("select")??n.shadowRoot?.querySelector("select");o&&(i=o)}return i?(await selectOptionElement(i,t.text),isInShadowDom(i)&&dispatchComposedEvents(i,"change"),await waitForDomSettled(),e.buildBrowserStateResponse(r)):e.actionError(`选择结果: 无法选择元素 ${t.index},未找到对应的 <select> 元素`)}function getScrollInfo(t=window){if(t===window){const e=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight),r=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth),n=window.scrollY,i=window.scrollX,o=Math.max(0,e-(window.innerHeight+n)),s=Math.max(0,r-(window.innerWidth+i));return{scrollY:n,scrollX:i,pixelsAbove:n,pixelsBelow:o,pixelsLeft:i,pixelsRight:s,pagesAbove:window.innerHeight>0?n/window.innerHeight:0,pagesBelow:window.innerHeight>0?o/window.innerHeight:0,atTop:n<=1,atBottom:o<=1,atLeft:i<=1,atRight:s<=1}}else{const e=t,r=e.scrollTop,n=e.scrollLeft,i=e.scrollHeight-e.clientHeight-r,o=e.scrollWidth-e.clientWidth-n;return{scrollY:r,scrollX:n,pixelsAbove:r,pixelsBelow:Math.max(0,i),pixelsLeft:n,pixelsRight:Math.max(0,o),pagesAbove:e.clientHeight>0?r/e.clientHeight:0,pagesBelow:e.clientHeight>0?Math.max(0,i)/e.clientHeight:0,atTop:r<=1,atBottom:i<=1,atLeft:n<=1,atRight:o<=1}}}function waitForScrollEnd(t,e=2e3){return new Promise(r=>{let n=!1;const i=t===window?document:t,o=()=>{n||(n=!0,i.removeEventListener("scrollend",s),clearTimeout(a),r())},s=()=>o(),a=setTimeout(o,e);i.addEventListener("scrollend",s,{once:!0})})}async function handleScroll(t,e){const r=t.responseMode??"diff";if(t.down===void 0&&t.right===void 0)return e.errContent("滚动结果: 缺少滚动方向参数");let n=window;if(t.index!==void 0){const m=e.getRefMap().get(t.index);if(!m)return e.refreshOnStaleRef("滚动",t.index);n=m}const i=getScrollInfo(n);if(t.right!==void 0){const m=t.pixels??300;n.scrollBy({left:t.right?m:-m,behavior:"smooth"})}else{const m=t.pixels??Math.round((t.numPages??1)*window.innerHeight);n.scrollBy({top:t.down?m:-m,behavior:"smooth"})}await waitForScrollEnd(n);const o=getScrollInfo(n),s=Math.round(o.scrollY-i.scrollY),a=Math.round(o.scrollX-i.scrollX),l=t.right!==void 0;let c;if(Math.abs(s)<1&&Math.abs(a)<1)l?c=t.right?"⚠️ 已到达右边界,无法继续向右滚动":"⚠️ 已到达左边界,无法继续向左滚动":c=t.down?"⚠️ 已到达底部,无法继续向下滚动":"⚠️ 已到达顶部,无法继续向上滚动";else{const m=l?`水平滚动 ${a}px`:`垂直滚动 ${s}px`;let g="";l?t.right&&o.atRight?g=",已到达右边界":!t.right&&o.atLeft&&(g=",已到达左边界"):t.down&&o.atBottom?g=",已到达底部":!t.down&&o.atTop&&(g=",已到达顶部"),c=`✅ ${m}${g}`}const u=t.right!==void 0?`当前水平滚动位置: scrollX=${Math.round(o.scrollX)}px,左侧 ${o.pagesAbove.toFixed(1)} 屏,右侧 ${o.pagesBelow.toFixed(1)} 屏`:`当前滚动位置: scrollY=${Math.round(o.scrollY)}px,上方 ${o.pagesAbove.toFixed(1)} 屏,下方 ${o.pagesBelow.toFixed(1)} 屏`,f=`[滚动结果] ${c}
|
|
410
|
+
${u}`,h=await e.buildBrowserStateResponse(r);return h.content[0].text=withStateFields(h.content[0].text,{scrollResult:f}),h}async function handleExecuteJavascript(t,e){if(!t.script)return e.errContent("脚本执行异常: 缺少javascript代码");let r=await new Function(`return (async () => { ${t.script} })()`)();if(r===void 0)try{r=await new Function(`return (async () => (${t.script}))()`)()}catch{}return await e.pageController.hideMask(),{content:[{type:"text",text:`脚本执行结果: ${JSON.stringify(r)}`}]}}async function handleSearchTree(t,e){if(!t.query)return e.errContent("搜索失败: 缺少 query 参数");const r=searchA11yTree(t.query,document.body,{...getPageAgentToolConfig().a11yConfig,contextLines:t.contextLines,maxMatches:t.maxMatches});e.setRefMap(r.refMap),e.stateCache.update(window.location.href,r.yaml),await e.pageController.hideMask();const n=detectPageDialog(),i=detectValidationErrors();if(n.length===0&&i.length===0)return{content:[{type:"text",text:r.text}]};const o={...n.length>0?{dialogs:n}:{},...i.length>0?{validationErrors:i}:{}};return{content:[{type:"text",text:`${JSON.stringify(o)}
|
|
411
|
+
${r.text}`}]}}async function handleHover(t,e){if(t.index===void 0)return e.errContent("悬浮结果: 缺少元素索引");const r=e.getRefMap().get(t.index);if(!r)return e.refreshOnStaleRef("悬浮",t.index);let n=r;if(r.shadowRoot&&!(r instanceof HTMLButtonElement)&&!(r instanceof HTMLAnchorElement)){const c=r.shadowRoot.querySelector('button, a, [role="button"], [role="link"]');c&&(n=c)}const i=n.getBoundingClientRect(),o=i.left+i.width/2,s=i.top+i.height/2,a=[{type:"pointerenter",bubbles:!1,usePointer:!0},{type:"pointerover",bubbles:!0,usePointer:!0},{type:"pointermove",bubbles:!0,usePointer:!0},{type:"mouseenter",bubbles:!1,usePointer:!1},{type:"mouseover",bubbles:!0,usePointer:!1},{type:"mousemove",bubbles:!0,usePointer:!1}];for(const{type:c,bubbles:u,usePointer:f}of a){const h=f?PointerEvent:MouseEvent;n.dispatchEvent(new h(c,{bubbles:u,cancelable:!0,view:window,clientX:o,clientY:s}))}await waitForDomSettled();const l=t.responseMode??"diff";return e.buildBrowserStateResponse(l)}function registerPageAgentTool(t={}){initializeBuiltinWebMCP(),setPageAgentToolConfig(t,{mode:"replace"}),window.__webmcpcli_beforeGetBrowserState=window.__webmcpcli_beforeGetBrowserState||null;const e=new PageController({enableMask:!1});e.maskReady=(async()=>{e.mask=new SimulatorMask$1})();const r=new PageStateCache;let n=new Map;async function i(u){return{content:[{type:"text",text:u}]}}async function o(u){const f=await createActionErrorResult(u,a);return t.removeMaskAfterToolCall&&await e.hideMask(),f}async function s(u,f){const h=await a("full"),m=`⚠️ ${u}失败: ref 索引 ${f} 已失效(页面可能已刷新),已自动重新加载页面状态,请使用新的 ref 索引重试。`;return{content:[{type:"text",text:withStateFields(h.content[0].text,{warning:m})}]}}async function a(u="diff"){const f=window.location.href,h=document.title,{yaml:m,refMap:g}=buildA11yTree(document.body,getPageAgentToolConfig().a11yConfig);n=g,getPageAgentToolConfig().enableHighlight&&(highlight(g),globalRemoveListener());const A=r.update(f,m),_=detectPageDialog(),p=detectValidationErrors(),v=detectVisibleTooltips();let S="";u==="full"?S=m:u==="diff"?S=A.isFullRefresh?m:A.diffText:u==="both"&&(S=`【全量页面树】:
|
|
412
|
+
${m}
|
|
566
413
|
|
|
567
414
|
【增量差异】:
|
|
568
|
-
${
|
|
415
|
+
${A.isFullRefresh?"(首次/刷新,无增量差异)":A.diffText}`);const b={url:f,title:h,content:S,..._.length>0?{dialogs:_}:{},...p.length>0?{validationErrors:p}:{},...v.length>0?{tooltips:v}:{}};return{content:[{type:"text",text:JSON.stringify(b)}]}}const l={pageController:e,stateCache:r,getRefMap:()=>n,setRefMap:u=>{n=u},buildBrowserStateResponse:a,refreshOnStaleRef:s,errContent:i,actionError:o};async function c(u){try{let f;switch(u.action){case"browserState":f=await handleBrowserState(u,l);break;case"click":await e.showMask(),e.mask.borderElement(n.get(u.index)),f=await handleClick(u,l),e.mask.removeBorderElement(),t.removeMaskAfterToolCall&&await e.hideMask();break;case"fill":await e.showMask(),e.mask.borderElement(n.get(u.index)),f=await handleFill(u,l),e.mask.removeBorderElement(),t.removeMaskAfterToolCall&&await e.hideMask();break;case"select":await e.showMask(),e.mask.borderElement(n.get(u.index)),f=await handleSelect(u,l),e.mask.removeBorderElement(),t.removeMaskAfterToolCall&&await e.hideMask();break;case"scroll":await e.showMask(),f=await handleScroll(u,l),t.removeMaskAfterToolCall&&await e.hideMask();break;case"executeJavascript":f=await handleExecuteJavascript(u,l);break;case"searchTree":f=await handleSearchTree(u,l);break;case"hover":f=await handleHover(u,l);break;default:f={content:[{type:"text",text:`未知操作: ${u.action}`}]}}return f}catch(f){const h={click:"点击",fill:"填写",select:"选择"};if(u.action in h)return o(`${h[u.action]}执行异常: ${f instanceof Error?f.message:String(f)}`);throw t.removeMaskAfterToolCall&&await e.hideMask(),f}}document.modelContext.registerTool({name:"page-agent-tool",description:pageAgentPrompt,inputSchema:zodToJsonSchema(inputSchema),async execute(u){try{return c(u)}catch(f){return{content:[{type:"text",text:`异常: ${String(f)}`}]}}}}),setupPageAgentToolEventBridge(c,e)}const consoleCloudPageAgentToolOptions={enableHighlight:!1,a11yConfig:{roles:[{role:"tablist",selector:"ul.ti3-tabs"},{role:"tab",selector:".ti3-tabs-text"},{role:"tabpanel",selector:["ti-tab.ti3-tab-pane",".ti3-tab-pane"]},{role:"combobox",selector:[".ti3-select-dominator-container",".selected-label",".sort-select",".service-select",".region-select",'[cf-uba="searchableRegion..open"]']},{role:"button",selector:[".modules-service-list-menu-service-icon-container",".ti3-btn-only-icon-noborder",".ti3-select-dominator-dropdown-btn",".modules-right-sidebar-icon-item-wrapper",".modules-right-sidebar-hide-state-plugin",".components-service-list-container-service-list-input-service-close",".modules-searchable-region-region-panel-close",".modules-searchable-region-region-panel-search-btn",'[cf-uba="rightSidebar..hideBtn"]',".ti-global-help-panel-header-icon","ti-icon[name]","tp-icon[name]","tp-icon.common-icon","ti-icon.common-icon","ti-icon.ti3-icon-full-screen","ti-icon.ti3-icon-close","tp-icon.ti3-icon-full-screen","tp-icon.ti3-icon-close"]},{role:"menuitem",selector:[".components-service-list-left-box-sidebar-visit-panel > li",".modules-menus-menu-item",".components-menu-wrapper-menu-text"]},{role:"option",selector:[".region-selector-item",".modules-searchable-region-project-item-region-item",".modules-searchable-region-region-panel-recent-region-item",".ti3-multiselect-box-cell"]},{role:"dialog",selector:['[class*="ti3-modal"]','[class*="ti3-message-box"]','[class*="drawer"]',".modules-layout-module-sidebar-panel"]},{role:"tooltip",selector:["tp-helptip",'[class*="ti3-tooltip"]',".tp-helptip-content",".ti3-tooltip",".ti3-tooltip-popper"]}],states:{selected:[{selector:"li.ti3-tab-li.ti3-tab-active"},{selector:".ti3-btn-item-container.ti3-active"},{selector:".components-service-list-left-box-active"},{selector:[".modules-searchable-region-project-item-region-item-selected",".components-search-content-search-select-search-select-selected"]}],hasPopup:[{selector:[".ti3-select-dominator-container",".selected-label",".sort-select",".service-select",".region-select",'[cf-uba="searchableRegion..open"]','[cf-uba="serviceList..open"]','[cf-uba="userinfo"]',"tp-helptip"]}],disabled:[{selector:".ti3-disabled"}],error:[{selector:[".ti3-unifyvalid-error",".ti3-error",".ti-error",".lego-text-error",".lego-error"]}],warning:[{selector:[".ti3-warning",".ti-warning",".lego-text-warning"]}],expanded:[{match:t=>{try{if(!t.matches(".modules-layout-module-sidebar-panel, .modules-searchable-region-region-panel, .ti3-dropdown-container"))return!1;const e=window.getComputedStyle(t);return e.display!=="none"&&e.visibility!=="hidden"&&e.opacity!=="0"}catch{return!1}}}]},exposedAttributes:["cf-uba","data-qa-id","name"],whitelist:[".modules-service-list-menu-service-icon-container",".ti3-tabs-text","tp-helptip",'[cf-uba="cloudShell"]','[cf-uba="messageBox"]','[cf-uba="helpFeedback"]','[cf-uba="globalMessage"]','[cf-uba="rightSidebar..hideBtn"]',".ti-global-help-panel-header-icon","ti-icon[name]","tp-icon[name]","tp-icon.common-icon","ti-icon.common-icon","ti-icon.ti3-icon-full-screen"],blacklist:["noscript","pan-gu","#webmcpcli-highlight-container","#page-agent-runtime_simulator-mask","#J_header","#J_rightSidebar","#cf_service_icon","tp-helptip"]}};function isConsoleCloudHost(t=typeof location<"u"?location.hostname:""){return/(^|\.)console\.huaweicloud\.com$/i.test(t)}const runtimeApi={initializeBuiltinWebMCP,registerPageAgentTool,getPageAgentToolConfig,setPageAgentToolConfig,defineA11yConfig,consoleCloudPageAgentToolOptions,isConsoleCloudHost};typeof window<"u"&&(Object.assign(window,runtimeApi),window.WebMCP||(window.WebMCP={}),Object.assign(window.WebMCP,runtimeApi)),(function(){try{if(typeof document<"u"){var t=document.createElement("style");t.appendChild(document.createTextNode(`._wrapper_1ooyb_1 {
|
|
569
416
|
position: fixed;
|
|
570
417
|
inset: 0;
|
|
571
418
|
z-index: 2147483641; /* 确保在所有元素之上,除了 panel */
|