@opentiny/next-sdk 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/agent/AgentModelProvider.ts +78 -81
  2. package/agent/type.ts +6 -9
  3. package/agent/utils/getAISDKTools.ts +0 -1
  4. package/agent/utils/getBuiltinMcpTools.ts +7 -7
  5. package/core.ts +0 -3
  6. package/dist/SimulatorMask-BHVXyogh-CARX3Rff.js +361 -0
  7. package/dist/agent/type.d.ts +4 -12
  8. package/dist/agent/utils/getBuiltinMcpTools.d.ts +3 -3
  9. package/dist/core.d.ts +0 -1
  10. package/dist/core.js +16 -17
  11. package/dist/index-R_HIbfUX.js +6604 -0
  12. package/dist/index.d.ts +11 -3
  13. package/dist/index.js +76 -4969
  14. package/dist/{initialize-builtin-WebMCP-HgObT902.js → initialize-builtin-WebMCP-JaoKwVlm.js} +1156 -1037
  15. package/dist/page-tools/a11y/build.d.ts +10 -0
  16. package/dist/page-tools/a11y/config.d.ts +96 -0
  17. package/dist/page-tools/a11y/constants.d.ts +11 -0
  18. package/dist/page-tools/a11y/search.d.ts +17 -0
  19. package/dist/page-tools/a11y/types.d.ts +95 -0
  20. package/dist/page-tools/a11y/utils.d.ts +55 -0
  21. package/dist/page-tools/a11y/vnode.d.ts +40 -0
  22. package/dist/page-tools/a11y-tree.d.ts +9 -99
  23. package/dist/page-tools/configs/console-cloud.d.ts +6 -0
  24. package/dist/page-tools/constants.d.ts +10 -0
  25. package/dist/page-tools/context.d.ts +40 -0
  26. package/dist/page-tools/handlers/browserState.d.ts +8 -0
  27. package/dist/page-tools/handlers/click.d.ts +8 -0
  28. package/dist/page-tools/handlers/executeJavascript.d.ts +8 -0
  29. package/dist/page-tools/handlers/fill.d.ts +8 -0
  30. package/dist/page-tools/handlers/scroll.d.ts +8 -0
  31. package/dist/page-tools/handlers/searchTree.d.ts +9 -0
  32. package/dist/page-tools/handlers/select.d.ts +8 -0
  33. package/dist/page-tools/page-agent-highlight/index.d.ts +21 -0
  34. package/dist/page-tools/page-agent-mask/SimulatorMask.d.ts +16 -0
  35. package/dist/page-tools/page-agent-mask/checkDarkMode.d.ts +5 -0
  36. package/dist/page-tools/page-agent-tool-event.d.ts +26 -0
  37. package/dist/page-tools/page-agent-tool.d.ts +3 -8
  38. package/dist/page-tools/schema.d.ts +44 -0
  39. package/dist/page-tools/tool-config.d.ts +50 -0
  40. package/dist/page-tools/utils/dom.d.ts +6 -0
  41. package/dist/page-tools/utils/scroll.d.ts +15 -0
  42. package/dist/runtime.d.ts +7 -0
  43. package/dist/runtime.js +732 -0
  44. package/dist/utils/builtinProxy.d.ts +1 -1
  45. package/dist/vitest.config.d.ts +2 -0
  46. package/index.ts +35 -5
  47. package/package.json +23 -29
  48. package/page-tools/a11y/build.ts +74 -0
  49. package/page-tools/a11y/config.ts +465 -0
  50. package/page-tools/a11y/constants.ts +131 -0
  51. package/page-tools/a11y/search.ts +127 -0
  52. package/page-tools/a11y/types.ts +105 -0
  53. package/page-tools/a11y/utils.ts +239 -0
  54. package/page-tools/a11y/vnode.ts +439 -0
  55. package/page-tools/a11y-tree.ts +9 -527
  56. package/page-tools/bridge.ts +23 -3
  57. package/page-tools/configs/console-cloud.ts +172 -0
  58. package/page-tools/constants.ts +12 -0
  59. package/page-tools/context.ts +50 -0
  60. package/page-tools/handlers/browserState.ts +12 -0
  61. package/page-tools/handlers/click.ts +30 -0
  62. package/page-tools/handlers/executeJavascript.ts +22 -0
  63. package/page-tools/handlers/fill.ts +65 -0
  64. package/page-tools/handlers/scroll.ts +66 -0
  65. package/page-tools/handlers/searchTree.ts +27 -0
  66. package/page-tools/handlers/select.ts +39 -0
  67. package/page-tools/page-agent-highlight/index.ts +245 -0
  68. package/page-tools/page-agent-mask/SimulatorMask.module.css +14 -0
  69. package/page-tools/page-agent-mask/SimulatorMask.ts +299 -0
  70. package/page-tools/page-agent-mask/checkDarkMode.ts +181 -0
  71. package/page-tools/page-agent-mask/cursor-border.svg +3 -0
  72. package/page-tools/page-agent-mask/cursor-fill.svg +5 -0
  73. package/page-tools/page-agent-mask/cursor.module.css +70 -0
  74. package/page-tools/page-agent-mask/hauwei.svg +25 -0
  75. package/page-tools/page-agent-prompt.md +34 -18
  76. package/page-tools/page-agent-tool-event.ts +113 -0
  77. package/page-tools/page-agent-tool.ts +146 -162
  78. package/page-tools/schema.ts +52 -0
  79. package/page-tools/tool-config.ts +100 -0
  80. package/page-tools/utils/dom.ts +158 -0
  81. package/page-tools/utils/scroll.ts +58 -0
  82. package/runtime.ts +44 -0
  83. package/test/page-tools/a11y/build.test.ts +638 -0
  84. package/test/page-tools/a11y/config.test.ts +370 -0
  85. package/test/page-tools/configs/console-cloud.test.ts +168 -0
  86. package/test/page-tools/page-agent-highlight.test.ts +110 -0
  87. package/test/page-tools/page-agent-tool-dispatch.test.ts +208 -0
  88. package/test/page-tools/page-agent-tool.test.ts +102 -0
  89. package/test/page-tools/tool-config.test.ts +112 -0
  90. package/test/page-tools/utils/dom.test.ts +122 -0
  91. package/utils/builtinProxy.ts +45 -13
  92. package/vite.config.runtime.ts +22 -0
  93. package/vite.config.ts +52 -8
  94. package/vitest.config.ts +10 -0
  95. package/McpSdk.ts +0 -14
  96. package/WebAgent.ts +0 -5
  97. package/WebMcp.ts +0 -26
  98. package/Zod.ts +0 -1
  99. package/dist/McpSdk.d.ts +0 -14
  100. package/dist/SimulatorMask-BHVXyogh-BFEGpD5S.js +0 -1048
  101. package/dist/SimulatorMask-BHVXyogh-CCYbrb84.js +0 -801
  102. package/dist/WebAgent.d.ts +0 -5
  103. package/dist/WebMcp.d.ts +0 -23
  104. package/dist/Zod.d.ts +0 -1
  105. package/dist/index.es.dev.js +0 -59017
  106. package/dist/index.es.js +0 -46795
  107. package/dist/index.umd.dev.js +0 -60355
  108. package/dist/index.umd.js +0 -1248
  109. package/dist/mcpsdk@1.25.3.dev.js +0 -22780
  110. package/dist/mcpsdk@1.25.3.es.dev.js +0 -22778
  111. package/dist/mcpsdk@1.25.3.es.js +0 -16960
  112. package/dist/mcpsdk@1.25.3.js +0 -48
  113. package/dist/transport/ExtensionClientTransport.d.ts +0 -24
  114. package/dist/transport/ExtensionContentServerTransport.d.ts +0 -39
  115. package/dist/transport/ExtensionPageServerTransport.d.ts +0 -36
  116. package/dist/transport/messages.d.ts +0 -9
  117. package/dist/vite.config.mcpSdk.d.ts +0 -2
  118. package/dist/vite.config.webAgent.d.ts +0 -2
  119. package/dist/vite.config.webMcp.d.ts +0 -2
  120. package/dist/vite.config.webMcpFull.d.ts +0 -2
  121. package/dist/vite.config.zod.d.ts +0 -2
  122. package/dist/webagent.dev.js +0 -49360
  123. package/dist/webagent.es.dev.js +0 -49071
  124. package/dist/webagent.es.js +0 -39219
  125. package/dist/webagent.js +0 -642
  126. package/dist/webmcp-full.dev.js +0 -31336
  127. package/dist/webmcp-full.es.dev.js +0 -30283
  128. package/dist/webmcp-full.es.js +0 -22889
  129. package/dist/webmcp-full.js +0 -645
  130. package/dist/webmcp.dev.js +0 -9572
  131. package/dist/webmcp.es.dev.js +0 -8518
  132. package/dist/webmcp.es.js +0 -6727
  133. package/dist/webmcp.js +0 -602
  134. package/dist/zod@3.25.76.dev.js +0 -4037
  135. package/dist/zod@3.25.76.es.dev.js +0 -4033
  136. package/dist/zod@3.25.76.es.js +0 -2945
  137. package/dist/zod@3.25.76.js +0 -1
  138. package/transport/ExtensionClientTransport.ts +0 -100
  139. package/transport/ExtensionContentServerTransport.ts +0 -162
  140. package/transport/ExtensionPageServerTransport.ts +0 -149
  141. package/transport/messages.ts +0 -63
  142. package/vite-build-tsc.ts +0 -63
  143. package/vite-env.d.ts +0 -10
  144. package/vite.config.mcpSdk.ts +0 -28
  145. package/vite.config.webAgent.ts +0 -19
  146. package/vite.config.webMcp.ts +0 -40
  147. package/vite.config.webMcpFull.ts +0 -19
  148. package/vite.config.zod.ts +0 -23
  149. /package/dist/{vite-build-tsc.d.ts → vite.config.runtime.d.ts} +0 -0
@@ -1 +0,0 @@
1
- (function(U,g){typeof exports=="object"&&typeof module<"u"?g(exports):typeof define=="function"&&define.amd?define(["exports"],g):(U=typeof globalThis<"u"?globalThis:U||self,g(U.Zod={}))})(this,(function(U){"use strict";var g;(function(r){r.assertEqual=n=>{};function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{const a={};for(const i of n)a[i]=i;return a},r.getValidEnumValues=n=>{const a=r.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),i={};for(const o of a)i[o]=n[o];return r.objectValues(i)},r.objectValues=n=>r.objectKeys(n).map(function(a){return n[a]}),r.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const a=[];for(const i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},r.find=(n,a)=>{for(const i of n)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function s(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=s,r.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(g||(g={}));var ye;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(ye||(ye={}));const u=g.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),R=r=>{switch(typeof r){case"undefined":return u.undefined;case"string":return u.string;case"number":return Number.isNaN(r)?u.nan:u.number;case"boolean":return u.boolean;case"function":return u.function;case"bigint":return u.bigint;case"symbol":return u.symbol;case"object":return Array.isArray(r)?u.array:r===null?u.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?u.promise:typeof Map<"u"&&r instanceof Map?u.map:typeof Set<"u"&&r instanceof Set?u.set:typeof Date<"u"&&r instanceof Date?u.date:u.object;default:return u.unknown}},c=g.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"]),Me=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class w extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},s={_errors:[]},n=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)s._errors.push(t(i));else{let o=s,f=0;for(;f<i.path.length;){const l=i.path[f];f===i.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(t(i))):o[l]=o[l]||{_errors:[]},o=o[l],f++}}};return n(this),s}static assert(e){if(!(e instanceof w))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,g.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},s=[];for(const n of this.issues)if(n.path.length>0){const a=n.path[0];t[a]=t[a]||[],t[a].push(e(n))}else s.push(e(n));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}w.create=r=>new w(r);const B=(r,e)=>{let t;switch(r.code){case c.invalid_type:r.received===u.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case c.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,g.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:t=`Unrecognized key(s) in object: ${g.joinValues(r.keys,", ")}`;break;case c.invalid_union:t="Invalid input";break;case c.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${g.joinValues(r.options)}`;break;case c.invalid_enum_value:t=`Invalid enum value. Expected ${g.joinValues(r.options)}, received '${r.received}'`;break;case c.invalid_arguments:t="Invalid function arguments";break;case c.invalid_return_type:t="Invalid function return type";break;case c.invalid_date:t="Invalid date";break;case c.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:g.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case c.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case c.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case c.custom:t="Invalid input";break;case c.invalid_intersection_types:t="Intersection results could not be merged";break;case c.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case c.not_finite:t="Number must be finite";break;default:t=e.defaultError,g.assertNever(r)}return{message:t}};let we=B;function Ve(r){we=r}function de(){return we}const ue=r=>{const{data:e,path:t,errorMaps:s,issueData:n}=r,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let o="";const f=s.filter(l=>!!l).slice().reverse();for(const l of f)o=l(i,{data:e,defaultError:o}).message;return{...n,path:a,message:o}},Pe=[];function d(r,e){const t=de(),s=ue({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===B?void 0:B].filter(n=>!!n)});r.common.issues.push(s)}class k{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const n of t){if(n.status==="aborted")return p;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const n of t){const a=await n.key,i=await n.value;s.push({key:a,value:i})}return k.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const n of t){const{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return p;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(s[a.value]=i.value)}return{status:e.value,value:s}}}const p=Object.freeze({status:"aborted"}),F=r=>({status:"dirty",value:r}),b=r=>({status:"valid",value:r}),_e=r=>r.status==="aborted",ge=r=>r.status==="dirty",P=r=>r.status==="valid",H=r=>typeof Promise<"u"&&r instanceof Promise;var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));class A{constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=n}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 Te=(r,e)=>{if(P(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new w(r.common.issues);return this._error=t,this._error}}};function y(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:n}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,o)=>{const{message:f}=r;return i.code==="invalid_enum_value"?{message:f??o.defaultError}:typeof o.data>"u"?{message:f??s??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:f??t??o.defaultError}},description:n}}class _{get description(){return this._def.description}_getType(e){return R(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new k,ctx:{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(H(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},n=this._parseSync({data:e,path:s.path,parent:s});return Te(s,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return P(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>P(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},n=this._parse({data:e,path:s.path,parent:s}),a=await(H(n)?n:Promise.resolve(n));return Te(s,a)}refine(e,t){const s=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{const i=e(n),o=()=>a.addIssue({code:c.custom,...s(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(f=>f?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof t=="function"?t(s,n):t),!1))}_refinement(e){return new O({schema:this,typeName:m.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:t=>this["~validate"](t)}}optional(){return Z.create(this,this._def)}nullable(){return V.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return S.create(this)}promise(){return Y.create(this,this._def)}or(e){return K.create([this,e],this._def)}and(e){return ee.create(this,e,this._def)}transform(e){return new O({...y(this._def),schema:this,typeName:m.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ae({...y(this._def),innerType:this,defaultValue:t,typeName:m.ZodDefault})}brand(){return new ke({typeName:m.ZodBranded,type:this,...y(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ie({...y(this._def),innerType:this,catchValue:t,typeName:m.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return oe.create(this,e)}readonly(){return ce.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ze=/^c[^\s-]{8,}$/i,Le=/^[0-9a-z]+$/,De=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ue=/^[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,Be=/^[a-z0-9_-]{21}$/i,Fe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,We=/^[-+]?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)?)??$/,qe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Je="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ve;const Ye=/^(?:(?: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])$/,He=/^(?:(?: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])$/,Ge=/^(([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]))$/,Qe=/^(([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])$/,Xe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ke=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ce="((\\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])))",et=new RegExp(`^${Ce}$`);function Se(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);const t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function tt(r){return new RegExp(`^${Se(r)}$`)}function Oe(r){let e=`${Ce}T${Se(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function rt(r,e){return!!((e==="v4"||!e)&&Ye.test(r)||(e==="v6"||!e)&&Ge.test(r))}function st(r,e){if(!Fe.test(r))return!1;try{const[t]=r.split(".");if(!t)return!1;const s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function nt(r,e){return!!((e==="v4"||!e)&&He.test(r)||(e==="v6"||!e)&&Qe.test(r))}class C extends _{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==u.string){const a=this._getOrReturnCtx(e);return d(a,{code:c.invalid_type,expected:u.string,received:a.parsedType}),p}const s=new k;let n;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),d(n,{code:c.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),d(n,{code:c.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(n=this._getOrReturnCtx(e,n),i?d(n,{code:c.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&d(n,{code:c.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),s.dirty())}else if(a.kind==="email")qe.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"email",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="emoji")ve||(ve=new RegExp(Je,"u")),ve.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"emoji",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="uuid")Ue.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"uuid",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="nanoid")Be.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"nanoid",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid")ze.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"cuid",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid2")Le.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"cuid2",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="ulid")De.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"ulid",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),d(n,{validation:"url",code:c.invalid_string,message:a.message}),s.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"regex",code:c.invalid_string,message:a.message}),s.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),d(n,{code:c.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),s.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(n=this._getOrReturnCtx(e,n),d(n,{code:c.invalid_string,validation:{startsWith:a.value},message:a.message}),s.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),d(n,{code:c.invalid_string,validation:{endsWith:a.value},message:a.message}),s.dirty()):a.kind==="datetime"?Oe(a).test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{code:c.invalid_string,validation:"datetime",message:a.message}),s.dirty()):a.kind==="date"?et.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{code:c.invalid_string,validation:"date",message:a.message}),s.dirty()):a.kind==="time"?tt(a).test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{code:c.invalid_string,validation:"time",message:a.message}),s.dirty()):a.kind==="duration"?We.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"duration",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="ip"?rt(e.data,a.version)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"ip",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="jwt"?st(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"jwt",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="cidr"?nt(e.data,a.version)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"cidr",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="base64"?Xe.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"base64",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="base64url"?Ke.test(e.data)||(n=this._getOrReturnCtx(e,n),d(n,{validation:"base64url",code:c.invalid_string,message:a.message}),s.dirty()):g.assertNever(a);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(n=>e.test(n),{validation:t,code:c.invalid_string,...h.errToObj(s)})}_addCheck(e){return new C({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.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,...h.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,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new C({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new C({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new C({...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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}C.create=r=>new C({checks:[],typeName:m.ZodString,coerce:r?.coerce??!1,...y(r)});function at(r,e){const t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=t>s?t:s,a=Number.parseInt(r.toFixed(n).replace(".","")),i=Number.parseInt(e.toFixed(n).replace(".",""));return a%i/10**n}class I extends _{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)!==u.number){const a=this._getOrReturnCtx(e);return d(a,{code:c.invalid_type,expected:u.number,received:a.parsedType}),p}let s;const n=new k;for(const a of this._def.checks)a.kind==="int"?g.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:c.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?at(e.data,a.value)!==0&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:c.not_finite,message:a.message}),n.dirty()):g.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,s,n){return new I({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new I({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&g.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}I.create=r=>new I({checks:[],typeName:m.ZodNumber,coerce:r?.coerce||!1,...y(r)});class $ extends _{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)!==u.bigint)return this._getInvalidInput(e);let s;const n=new k;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):g.assertNever(a);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return d(t,{code:c.invalid_type,expected:u.bigint,received:t.parsedType}),p}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,s,n){return new $({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new $({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}$.create=r=>new $({checks:[],typeName:m.ZodBigInt,coerce:r?.coerce??!1,...y(r)});class G extends _{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==u.boolean){const s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.boolean,received:s.parsedType}),p}return b(e.data)}}G.create=r=>new G({typeName:m.ZodBoolean,coerce:r?.coerce||!1,...y(r)});class z extends _{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==u.date){const a=this._getOrReturnCtx(e);return d(a,{code:c.invalid_type,expected:u.date,received:a.parsedType}),p}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return d(a,{code:c.invalid_date}),p}const s=new k;let n;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),d(n,{code:c.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),s.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),d(n,{code:c.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),s.dirty()):g.assertNever(a);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new z({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}z.create=r=>new z({checks:[],coerce:r?.coerce||!1,typeName:m.ZodDate,...y(r)});class le extends _{_parse(e){if(this._getType(e)!==u.symbol){const s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.symbol,received:s.parsedType}),p}return b(e.data)}}le.create=r=>new le({typeName:m.ZodSymbol,...y(r)});class Q extends _{_parse(e){if(this._getType(e)!==u.undefined){const s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.undefined,received:s.parsedType}),p}return b(e.data)}}Q.create=r=>new Q({typeName:m.ZodUndefined,...y(r)});class X extends _{_parse(e){if(this._getType(e)!==u.null){const s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.null,received:s.parsedType}),p}return b(e.data)}}X.create=r=>new X({typeName:m.ZodNull,...y(r)});class W extends _{constructor(){super(...arguments),this._any=!0}_parse(e){return b(e.data)}}W.create=r=>new W({typeName:m.ZodAny,...y(r)});class L extends _{constructor(){super(...arguments),this._unknown=!0}_parse(e){return b(e.data)}}L.create=r=>new L({typeName:m.ZodUnknown,...y(r)});class j extends _{_parse(e){const t=this._getOrReturnCtx(e);return d(t,{code:c.invalid_type,expected:u.never,received:t.parsedType}),p}}j.create=r=>new j({typeName:m.ZodNever,...y(r)});class fe extends _{_parse(e){if(this._getType(e)!==u.undefined){const s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.void,received:s.parsedType}),p}return b(e.data)}}fe.create=r=>new fe({typeName:m.ZodVoid,...y(r)});class S extends _{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==u.array)return d(t,{code:c.invalid_type,expected:u.array,received:t.parsedType}),p;if(n.exactLength!==null){const i=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(i||o)&&(d(t,{code:i?c.too_big:c.too_small,minimum:o?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),s.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(d(t,{code:c.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(d(t,{code:c.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>n.type._parseAsync(new A(t,i,t.path,o)))).then(i=>k.mergeArray(s,i));const a=[...t.data].map((i,o)=>n.type._parseSync(new A(t,i,t.path,o)));return k.mergeArray(s,a)}get element(){return this._def.type}min(e,t){return new S({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new S({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new S({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}}S.create=(r,e)=>new S({type:r,minLength:null,maxLength:null,exactLength:null,typeName:m.ZodArray,...y(e)});function q(r){if(r instanceof x){const e={};for(const t in r.shape){const s=r.shape[t];e[t]=Z.create(q(s))}return new x({...r._def,shape:()=>e})}else return r instanceof S?new S({...r._def,type:q(r.element)}):r instanceof Z?Z.create(q(r.unwrap())):r instanceof V?V.create(q(r.unwrap())):r instanceof N?N.create(r.items.map(e=>q(e))):r}class x extends _{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(),t=g.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==u.object){const l=this._getOrReturnCtx(e);return d(l,{code:c.invalid_type,expected:u.object,received:l.parsedType}),p}const{status:s,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof j&&this._def.unknownKeys==="strip"))for(const l in n.data)i.includes(l)||o.push(l);const f=[];for(const l of i){const v=a[l],T=n.data[l];f.push({key:{status:"valid",value:l},value:v._parse(new A(n,T,n.path,l)),alwaysSet:l in n.data})}if(this._def.catchall instanceof j){const l=this._def.unknownKeys;if(l==="passthrough")for(const v of o)f.push({key:{status:"valid",value:v},value:{status:"valid",value:n.data[v]}});else if(l==="strict")o.length>0&&(d(n,{code:c.unrecognized_keys,keys:o}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const v of o){const T=n.data[v];f.push({key:{status:"valid",value:v},value:l._parse(new A(n,T,n.path,v)),alwaysSet:v in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const l=[];for(const v of f){const T=await v.key,$e=await v.value;l.push({key:T,value:$e,alwaysSet:v.alwaysSet})}return l}).then(l=>k.mergeObjectSync(s,l)):k.mergeObjectSync(s,f)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new x({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{const n=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new x({...this._def,unknownKeys:"strip"})}passthrough(){return new x({...this._def,unknownKeys:"passthrough"})}extend(e){return new x({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new x({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:m.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new x({...this._def,catchall:e})}pick(e){const t={};for(const s of g.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new x({...this._def,shape:()=>t})}omit(e){const t={};for(const s of g.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new x({...this._def,shape:()=>t})}deepPartial(){return q(this)}partial(e){const t={};for(const s of g.objectKeys(this.shape)){const n=this.shape[s];e&&!e[s]?t[s]=n:t[s]=n.optional()}return new x({...this._def,shape:()=>t})}required(e){const t={};for(const s of g.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let a=this.shape[s];for(;a instanceof Z;)a=a._def.innerType;t[s]=a}return new x({...this._def,shape:()=>t})}keyof(){return Ae(g.objectKeys(this.shape))}}x.create=(r,e)=>new x({shape:()=>r,unknownKeys:"strip",catchall:j.create(),typeName:m.ZodObject,...y(e)}),x.strictCreate=(r,e)=>new x({shape:()=>r,unknownKeys:"strict",catchall:j.create(),typeName:m.ZodObject,...y(e)}),x.lazycreate=(r,e)=>new x({shape:r,unknownKeys:"strip",catchall:j.create(),typeName:m.ZodObject,...y(e)});class K extends _{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function n(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new w(o.ctx.common.issues));return d(t,{code:c.invalid_union,unionErrors:i}),p}if(t.common.async)return Promise.all(s.map(async a=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);{let a;const i=[];for(const f of s){const l={...t,common:{...t.common,issues:[]},parent:null},v=f._parseSync({data:t.data,path:t.path,parent:l});if(v.status==="valid")return v;v.status==="dirty"&&!a&&(a={result:v,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(f=>new w(f));return d(t,{code:c.invalid_union,unionErrors:o}),p}}get options(){return this._def.options}}K.create=(r,e)=>new K({options:r,typeName:m.ZodUnion,...y(e)});const E=r=>r instanceof re?E(r.schema):r instanceof O?E(r.innerType()):r instanceof se?[r.value]:r instanceof M?r.options:r instanceof ne?g.objectValues(r.enum):r instanceof ae?E(r._def.innerType):r instanceof Q?[void 0]:r instanceof X?[null]:r instanceof Z?[void 0,...E(r.unwrap())]:r instanceof V?[null,...E(r.unwrap())]:r instanceof ke||r instanceof ce?E(r.unwrap()):r instanceof ie?E(r._def.innerType):[];class he extends _{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.object)return d(t,{code:c.invalid_type,expected:u.object,received:t.parsedType}),p;const s=this.discriminator,n=t.data[s],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(d(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),p)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){const n=new Map;for(const a of t){const i=E(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of i){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,a)}}return new he({typeName:m.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...y(s)})}}function xe(r,e){const t=R(r),s=R(e);if(r===e)return{valid:!0,data:r};if(t===u.object&&s===u.object){const n=g.objectKeys(e),a=g.objectKeys(r).filter(o=>n.indexOf(o)!==-1),i={...r,...e};for(const o of a){const f=xe(r[o],e[o]);if(!f.valid)return{valid:!1};i[o]=f.data}return{valid:!0,data:i}}else if(t===u.array&&s===u.array){if(r.length!==e.length)return{valid:!1};const n=[];for(let a=0;a<r.length;a++){const i=r[a],o=e[a],f=xe(i,o);if(!f.valid)return{valid:!1};n.push(f.data)}return{valid:!0,data:n}}else return t===u.date&&s===u.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class ee extends _{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=(a,i)=>{if(_e(a)||_e(i))return p;const o=xe(a.value,i.value);return o.valid?((ge(a)||ge(i))&&t.dirty(),{status:t.value,value:o.data}):(d(s,{code:c.invalid_intersection_types}),p)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([a,i])=>n(a,i)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}ee.create=(r,e,t)=>new ee({left:r,right:e,typeName:m.ZodIntersection,...y(t)});class N extends _{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.array)return d(s,{code:c.invalid_type,expected:u.array,received:s.parsedType}),p;if(s.data.length<this._def.items.length)return d(s,{code:c.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),p;!this._def.rest&&s.data.length>this._def.items.length&&(d(s,{code:c.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...s.data].map((i,o)=>{const f=this._def.items[o]||this._def.rest;return f?f._parse(new A(s,i,s.path,o)):null}).filter(i=>!!i);return s.common.async?Promise.all(a).then(i=>k.mergeArray(t,i)):k.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new N({...this._def,rest:e})}}N.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new N({items:r,typeName:m.ZodTuple,rest:null,...y(e)})};class te extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.object)return d(s,{code:c.invalid_type,expected:u.object,received:s.parsedType}),p;const n=[],a=this._def.keyType,i=this._def.valueType;for(const o in s.data)n.push({key:a._parse(new A(s,o,s.path,o)),value:i._parse(new A(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?k.mergeObjectAsync(t,n):k.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof _?new te({keyType:e,valueType:t,typeName:m.ZodRecord,...y(s)}):new te({keyType:C.create(),valueType:e,typeName:m.ZodRecord,...y(t)})}}class pe extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.map)return d(s,{code:c.invalid_type,expected:u.map,received:s.parsedType}),p;const n=this._def.keyType,a=this._def.valueType,i=[...s.data.entries()].map(([o,f],l)=>({key:n._parse(new A(s,o,s.path,[l,"key"])),value:a._parse(new A(s,f,s.path,[l,"value"]))}));if(s.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const f of i){const l=await f.key,v=await f.value;if(l.status==="aborted"||v.status==="aborted")return p;(l.status==="dirty"||v.status==="dirty")&&t.dirty(),o.set(l.value,v.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const f of i){const l=f.key,v=f.value;if(l.status==="aborted"||v.status==="aborted")return p;(l.status==="dirty"||v.status==="dirty")&&t.dirty(),o.set(l.value,v.value)}return{status:t.value,value:o}}}}pe.create=(r,e,t)=>new pe({valueType:e,keyType:r,typeName:m.ZodMap,...y(t)});class D extends _{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.set)return d(s,{code:c.invalid_type,expected:u.set,received:s.parsedType}),p;const n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(d(s,{code:c.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&(d(s,{code:c.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function i(f){const l=new Set;for(const v of f){if(v.status==="aborted")return p;v.status==="dirty"&&t.dirty(),l.add(v.value)}return{status:t.value,value:l}}const o=[...s.data.values()].map((f,l)=>a._parse(new A(s,f,s.path,l)));return s.common.async?Promise.all(o).then(f=>i(f)):i(o)}min(e,t){return new D({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new D({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}D.create=(r,e)=>new D({valueType:r,minSize:null,maxSize:null,typeName:m.ZodSet,...y(e)});class J extends _{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.function)return d(t,{code:c.invalid_type,expected:u.function,received:t.parsedType}),p;function s(o,f){return ue({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,de(),B].filter(l=>!!l),issueData:{code:c.invalid_arguments,argumentsError:f}})}function n(o,f){return ue({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,de(),B].filter(l=>!!l),issueData:{code:c.invalid_return_type,returnTypeError:f}})}const a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Y){const o=this;return b(async function(...f){const l=new w([]),v=await o._def.args.parseAsync(f,a).catch(be=>{throw l.addIssue(s(f,be)),l}),T=await Reflect.apply(i,this,v);return await o._def.returns._def.type.parseAsync(T,a).catch(be=>{throw l.addIssue(n(T,be)),l})})}else{const o=this;return b(function(...f){const l=o._def.args.safeParse(f,a);if(!l.success)throw new w([s(f,l.error)]);const v=Reflect.apply(i,this,l.data),T=o._def.returns.safeParse(v,a);if(!T.success)throw new w([n(v,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new J({...this._def,args:N.create(e).rest(L.create())})}returns(e){return new J({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new J({args:e||N.create([]).rest(L.create()),returns:t||L.create(),typeName:m.ZodFunction,...y(s)})}}class re extends _{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}re.create=(r,e)=>new re({getter:r,typeName:m.ZodLazy,...y(e)});class se extends _{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return d(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),p}return{status:"valid",value:e.data}}get value(){return this._def.value}}se.create=(r,e)=>new se({value:r,typeName:m.ZodLiteral,...y(e)});function Ae(r,e){return new M({values:r,typeName:m.ZodEnum,...y(e)})}class M extends _{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return d(t,{expected:g.joinValues(s),received:t.parsedType,code:c.invalid_type}),p}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return d(t,{received:t.data,code:c.invalid_enum_value,options:s}),p}return b(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return M.create(e,{...this._def,...t})}exclude(e,t=this._def){return M.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}M.create=Ae;class ne extends _{_parse(e){const t=g.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==u.string&&s.parsedType!==u.number){const n=g.objectValues(t);return d(s,{expected:g.joinValues(n),received:s.parsedType,code:c.invalid_type}),p}if(this._cache||(this._cache=new Set(g.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=g.objectValues(t);return d(s,{received:s.data,code:c.invalid_enum_value,options:n}),p}return b(e.data)}get enum(){return this._def.values}}ne.create=(r,e)=>new ne({values:r,typeName:m.ZodNativeEnum,...y(e)});class Y extends _{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.promise&&t.common.async===!1)return d(t,{code:c.invalid_type,expected:u.promise,received:t.parsedType}),p;const s=t.parsedType===u.promise?t.data:Promise.resolve(t.data);return b(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Y.create=(r,e)=>new Y({type:r,typeName:m.ZodPromise,...y(e)});class O extends _{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===m.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{d(s,i),i.fatal?t.abort():t.dirty()},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){const i=n.transform(s.data,a);if(s.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return p;const f=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return f.status==="aborted"?p:f.status==="dirty"||t.value==="dirty"?F(f.value):f});{if(t.value==="aborted")return p;const o=this._def.schema._parseSync({data:i,path:s.path,parent:s});return o.status==="aborted"?p:o.status==="dirty"||t.value==="dirty"?F(o.value):o}}if(n.type==="refinement"){const i=o=>{const f=n.refinement(o,a);if(s.common.async)return Promise.resolve(f);if(f instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?p:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?p:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(s.common.async===!1){const i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!P(i))return p;const o=n.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>P(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):p);g.assertNever(n)}}O.create=(r,e,t)=>new O({schema:r,typeName:m.ZodEffects,effect:e,...y(t)}),O.createWithPreprocess=(r,e,t)=>new O({schema:e,effect:{type:"preprocess",transform:r},typeName:m.ZodEffects,...y(t)});class Z extends _{_parse(e){return this._getType(e)===u.undefined?b(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Z.create=(r,e)=>new Z({innerType:r,typeName:m.ZodOptional,...y(e)});class V extends _{_parse(e){return this._getType(e)===u.null?b(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}V.create=(r,e)=>new V({innerType:r,typeName:m.ZodNullable,...y(e)});class ae extends _{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===u.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ae.create=(r,e)=>new ae({innerType:r,typeName:m.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...y(e)});class ie extends _{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return H(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new w(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new w(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}ie.create=(r,e)=>new ie({innerType:r,typeName:m.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...y(e)});class me extends _{_parse(e){if(this._getType(e)!==u.nan){const s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.nan,received:s.parsedType}),p}return{status:"valid",value:e.data}}}me.create=r=>new me({typeName:m.ZodNaN,...y(r)});const it=Symbol("zod_brand");class ke extends _{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class oe extends _{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?p:a.status==="dirty"?(t.dirty(),F(a.value)):this._def.out._parseAsync({data:a.value,path:s.path,parent:s})})();{const n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?p:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,t){return new oe({in:e,out:t,typeName:m.ZodPipeline})}}class ce extends _{_parse(e){const t=this._def.innerType._parse(e),s=n=>(P(n)&&(n.value=Object.freeze(n.value)),n);return H(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}}ce.create=(r,e)=>new ce({innerType:r,typeName:m.ZodReadonly,...y(e)});function Ne(r,e){const t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Ze(r,e={},t){return r?W.create().superRefine((s,n)=>{const a=r(s);if(a instanceof Promise)return a.then(i=>{if(!i){const o=Ne(e,s),f=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:f})}});if(!a){const i=Ne(e,s),o=i.fatal??t??!0;n.addIssue({code:"custom",...i,fatal:o})}}):W.create()}const ot={object:x.lazycreate};var m;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(m||(m={}));const ct=(r,e={message:`Input not instance of ${r.name}`})=>Ze(t=>t instanceof r,e),Re=C.create,je=I.create,dt=me.create,ut=$.create,Ee=G.create,lt=z.create,ft=le.create,ht=Q.create,pt=X.create,mt=W.create,yt=L.create,_t=j.create,gt=fe.create,vt=S.create,xt=x.create,kt=x.strictCreate,bt=K.create,wt=he.create,Tt=ee.create,Ct=N.create,St=te.create,Ot=pe.create,At=D.create,Nt=J.create,Zt=re.create,Rt=se.create,jt=M.create,Et=ne.create,It=Y.create,Ie=O.create,$t=Z.create,Mt=V.create,Vt=O.createWithPreprocess,Pt=oe.create,zt=Object.freeze(Object.defineProperty({__proto__:null,BRAND:it,DIRTY:F,EMPTY_PATH:Pe,INVALID:p,NEVER:p,OK:b,ParseStatus:k,Schema:_,ZodAny:W,ZodArray:S,ZodBigInt:$,ZodBoolean:G,ZodBranded:ke,ZodCatch:ie,ZodDate:z,ZodDefault:ae,ZodDiscriminatedUnion:he,ZodEffects:O,ZodEnum:M,ZodError:w,get ZodFirstPartyTypeKind(){return m},ZodFunction:J,ZodIntersection:ee,ZodIssueCode:c,ZodLazy:re,ZodLiteral:se,ZodMap:pe,ZodNaN:me,ZodNativeEnum:ne,ZodNever:j,ZodNull:X,ZodNullable:V,ZodNumber:I,ZodObject:x,ZodOptional:Z,ZodParsedType:u,ZodPipeline:oe,ZodPromise:Y,ZodReadonly:ce,ZodRecord:te,ZodSchema:_,ZodSet:D,ZodString:C,ZodSymbol:le,ZodTransformer:O,ZodTuple:N,ZodType:_,ZodUndefined:Q,ZodUnion:K,ZodUnknown:L,ZodVoid:fe,addIssueToContext:d,any:mt,array:vt,bigint:ut,boolean:Ee,coerce:{string:(r=>C.create({...r,coerce:!0})),number:(r=>I.create({...r,coerce:!0})),boolean:(r=>G.create({...r,coerce:!0})),bigint:(r=>$.create({...r,coerce:!0})),date:(r=>z.create({...r,coerce:!0}))},custom:Ze,date:lt,datetimeRegex:Oe,defaultErrorMap:B,discriminatedUnion:wt,effect:Ie,enum:jt,function:Nt,getErrorMap:de,getParsedType:R,instanceof:ct,intersection:Tt,isAborted:_e,isAsync:H,isDirty:ge,isValid:P,late:ot,lazy:Zt,literal:Rt,makeIssue:ue,map:Ot,nan:dt,nativeEnum:Et,never:_t,null:pt,nullable:Mt,number:je,object:xt,get objectUtil(){return ye},oboolean:()=>Ee().optional(),onumber:()=>je().optional(),optional:$t,ostring:()=>Re().optional(),pipeline:Pt,preprocess:Vt,promise:It,quotelessJson:Me,record:St,set:At,setErrorMap:Ve,strictObject:kt,string:Re,symbol:ft,transformer:Ie,tuple:Ct,undefined:ht,union:bt,unknown:yt,get util(){return g},void:gt},Symbol.toStringTag,{value:"Module"}));U.z=zt,Object.defineProperty(U,Symbol.toStringTag,{value:"Module"})}));
@@ -1,100 +0,0 @@
1
- import type { Transport, TransportSendOptions } from '@modelcontextprotocol/sdk/shared/transport.js'
2
- import { type JSONRPCMessage, JSONRPCMessageSchema } from '@modelcontextprotocol/sdk/types.js'
3
- import { onRuntimeMessage, sendRuntimeMessage } from './messages'
4
-
5
- declare const chrome: any
6
-
7
- /**
8
- * Chrome 扩展客户端 Transport, 用于 Sidepanel 中的标准的 MCP Transport 接口
9
- * 使用 targetSessionId 连接到特定的 Server
10
- */
11
- export class ExtensionClientTransport implements Transport {
12
- // MCP Transport 必需的回调
13
- onmessage?: (message: JSONRPCMessage) => void // 接收到消息时的回调
14
- onerror?: (error: Error) => void // 发生错误时的回调
15
- onclose?: () => void // 连接关闭时的回调
16
-
17
- readonly targetSessionId: string
18
- private _messageListener: () => void
19
-
20
- // 内部状态
21
- private _isStarted: boolean = false // 是否已启动
22
- private _isClosed: boolean = false // 是否已关闭
23
- private _throwError(whenFn: () => boolean, message: string) {
24
- if (whenFn()) {
25
- const error = new Error(message)
26
- console.log(message, error)
27
- if (this.onerror) {
28
- this.onerror(error)
29
- }
30
- throw error
31
- }
32
- }
33
-
34
- constructor(targetSessionId: string) {
35
- this.targetSessionId = targetSessionId
36
-
37
- /** 监听 server 消息 */
38
- this._messageListener = onRuntimeMessage(
39
- 'mcp-server-to-client',
40
- (data: { sessionId: string; mcpMessage: any }) => {
41
- try {
42
- if (data.sessionId !== this.targetSessionId) return
43
-
44
- const mcpMessage = JSONRPCMessageSchema.parse(data.mcpMessage)
45
- this.onmessage?.(mcpMessage)
46
- } catch (error) {
47
- console.log('【Client Transport】处理server消息错误:', error)
48
- }
49
- },
50
- 'content->bg'
51
- )
52
- }
53
-
54
- /** 启动 transport,开始监听消息 */
55
- async start() {
56
- this._throwError(() => this._isClosed, '【Client Transport】 未启动,无法重新启动')
57
- this._isStarted = true
58
- }
59
-
60
- /** 发送消息到 MCP Server */
61
- async send(message: JSONRPCMessage, _options?: TransportSendOptions): Promise<void> {
62
- this._throwError(() => !this._isStarted, '【Client Transport】 未启动,无法发送消息')
63
- this._throwError(() => this._isClosed, '【Client Transport】 已关闭,无法发送消息')
64
-
65
- // 查询 当前sessionId的最后一个tabid
66
- let tabId: number | undefined
67
- if (chrome.sessionRegistry) {
68
- const sessionInfo = chrome.sessionRegistry.get(this.targetSessionId)
69
- if (sessionInfo && sessionInfo.tabIds.length > 0) {
70
- tabId = sessionInfo.tabIds[sessionInfo.tabIds.length - 1]
71
- }
72
- }
73
-
74
- if (tabId == null) {
75
- tabId = await chrome.runtime.sendMessage({ type: 'get-session-tab-id', sessionId: this.targetSessionId })
76
- }
77
-
78
- this._throwError(() => tabId == null, `【Client Transport】后台未找到活动的tabId用于${this.targetSessionId}`)
79
-
80
- sendRuntimeMessage(
81
- 'mcp-client-to-server',
82
- { sessionId: this.targetSessionId, tabId, mcpMessage: message },
83
- 'bg->content'
84
- )
85
- }
86
-
87
- /** 关闭 transport */
88
- async close() {
89
- if (this._isClosed) return
90
-
91
- try {
92
- this._isClosed = true
93
- this._isStarted = false
94
- this._messageListener && this._messageListener()
95
- this.onclose && this.onclose()
96
- } catch (error) {
97
- this._throwError(() => true, '【Client Transport】 关闭时发生错误')
98
- }
99
- }
100
- }
@@ -1,162 +0,0 @@
1
- import type { Transport, TransportSendOptions } from '@modelcontextprotocol/sdk/shared/transport.js'
2
- import { type JSONRPCMessage, JSONRPCMessageSchema } from '@modelcontextprotocol/sdk/types.js'
3
- import { randomUUID } from '../utils/uuid'
4
- import { onRuntimeMessage, sendRuntimeMessage, sendWindowMessage } from './messages'
5
-
6
- declare const document: Document
7
- declare const chrome: any
8
-
9
- /** 服务器注册信息接口 */
10
- export interface ContentScriptServerInfo {
11
- /** 服务器名称 */
12
- name: string
13
- /** 服务器版本 */
14
- version: string
15
- /** 服务器描述(可选) */
16
- description?: string
17
- /** 服务器 URL(由 transport 自动添加) */
18
- url?: string
19
- /** 页面标题(由 transport 自动添加) */
20
- title?: string
21
- }
22
-
23
- /**
24
- * Chrome 扩展的页面Content Script中,实现标准的 MCP Transport
25
- * 使用 sessionId 进行消息路由的唯一标识
26
- */
27
- export class ContentScriptServerTransport implements Transport {
28
- // MCP Transport 必需的回调
29
- onmessage?: (message: JSONRPCMessage) => void // 接收到消息时的回调
30
- onerror?: (error: Error) => void // 发生错误时的回调
31
- onclose?: () => void // 连接关闭时的回调
32
-
33
- // 会话ID,用于标识此 transport 实例并路由消息
34
- readonly sessionId: string
35
- readonly tabId: number
36
-
37
- // 内部状态
38
- private _isStarted: boolean = false
39
- private _isClosed: boolean = false
40
- private _lastRegistration: ContentScriptServerInfo | null = null // 最后一次注册信息(用于 Sidepanel 刷新后重新注册)
41
- private _throwError(whenFn: () => boolean, message: string) {
42
- if (whenFn()) {
43
- const error = new Error(message)
44
- console.log(message, error)
45
- if (this.onerror) {
46
- this.onerror(error)
47
- }
48
- throw error
49
- }
50
- }
51
-
52
- constructor(sessionId: string | null = null, tabId: number) {
53
- // 如果提供了 sessionId,使用提供的;否则随机生成
54
- this.sessionId = sessionId || randomUUID()
55
- this.tabId = tabId
56
-
57
- // 移除对 sidepanel-ready 的监听,因为现在的注册信息将直接发送给长期驻留的 background,不丢失状态
58
- }
59
-
60
- /** 启动 transport,开始监听MCP client 消息 */
61
- async start() {
62
- console.log('【Content Svr Transport】 启动 start', this.sessionId)
63
- // 防止重复启动
64
- if (this._isStarted) return
65
-
66
- if (this._isClosed) throw new Error('【Content Svr Transport】 已关闭,无法重新启动')
67
-
68
- onRuntimeMessage(
69
- 'mcp-client-to-server',
70
- (data: any) => {
71
- if (data.sessionId !== this.sessionId || data.tabId !== this.tabId) return
72
-
73
- try {
74
- console.log('【Content Svr Transport】 即将处理 mcpMessage', data.mcpMessage)
75
- const mcpMessage = JSONRPCMessageSchema.parse(data.mcpMessage)
76
- this.onmessage?.(mcpMessage)
77
-
78
- // 判断是否为工具调用
79
- const toolName = data.mcpMessage.params?.name
80
- if (toolName) {
81
- sendWindowMessage(
82
- 'update-page-app-message',
83
- { status: 'run', message: data.mcpMessage.params?.name },
84
- 'page->content' // 此处应该是 content->content, 但为了和pageServerTransport统一。
85
- )
86
- }
87
- } catch (error) {
88
- console.log('【Content Svr Transport】 处理消息时发生错误:', error)
89
- }
90
- },
91
- 'bg->content',
92
- this.tabId
93
- )
94
-
95
- this._isStarted = true
96
- }
97
-
98
- /** 发送消息到 MCP Client */
99
- async send(message: JSONRPCMessage, _options?: TransportSendOptions): Promise<void> {
100
- // 检查状态
101
- this._throwError(() => !this._isStarted, '【Content Svr Transport】 未启动,无法发送消息')
102
- this._throwError(() => this._isClosed, '【Content Svr Transport】 已关闭,无法发送消息')
103
-
104
- try {
105
- console.log('【Content Svr Transport】 发送消息到 MCP Client', message)
106
- sendRuntimeMessage(
107
- 'mcp-server-to-client',
108
- {
109
- sessionId: this.sessionId,
110
- mcpMessage: message
111
- },
112
- 'content->bg'
113
- )
114
-
115
- // 判断是否为工具调用成功了!
116
- if ('result' in message && message.result?.content) {
117
- sendWindowMessage(
118
- 'update-page-app-message',
119
- { status: 'ready', message: '' },
120
- 'page->content' // 此处应该是 content->content, 但为了和pageServerTransport统一。
121
- )
122
- }
123
- } catch (error) {
124
- this._throwError(() => true, '【Content Svr Transport】发送消息失败' + String(error))
125
- }
126
- }
127
-
128
- /** 通知 Sidepanel 此 Server 已启动并准备接受连接 */
129
- async notifyRegistration(serverInfo: ContentScriptServerInfo): Promise<void> {
130
- if (!this._isStarted) return
131
-
132
- // 保存注册信息,用于 Sidepanel 刷新后重新注册
133
- this._lastRegistration = serverInfo
134
-
135
- sendRuntimeMessage(
136
- 'mcp-server-register',
137
- {
138
- sessionId: this.sessionId,
139
- serverInfo: {
140
- ...serverInfo,
141
- url: window.location.origin,
142
- title: document.title
143
- }
144
- },
145
- 'content->bg'
146
- )
147
- }
148
-
149
- async close() {
150
- if (this._isClosed) return
151
-
152
- try {
153
- this._isClosed = true
154
- this._isStarted = false
155
- if (this.onclose) {
156
- this.onclose()
157
- }
158
- } catch (error) {
159
- this._throwError(() => true, '【Content Svr Transport】 关闭时发生错误' + String(error))
160
- }
161
- }
162
- }
@@ -1,149 +0,0 @@
1
- import type { Transport, TransportSendOptions } from '@modelcontextprotocol/sdk/shared/transport.js'
2
- import { type JSONRPCMessage, JSONRPCMessageSchema } from '@modelcontextprotocol/sdk/types.js'
3
- import { randomUUID } from '../utils/uuid'
4
- import { onWindowMessage, sendWindowMessage } from './messages'
5
-
6
- declare const window: Window & typeof globalThis
7
- declare const document: Document
8
-
9
- /** 服务器注册信息接口 */
10
- export interface ServerInfo {
11
- name: string
12
- version: string
13
- description?: string
14
- url?: string
15
- title?: string
16
- }
17
-
18
- /**
19
- * Chrome 扩展服务端 Transport 用于【页面脚本】中的标准的 MCP Transport 接口
20
- * 使用 sessionId 进行消息路由
21
- * 支持固定 sessionId,避免页面刷新时 sessionId 改变
22
- */
23
- export class ExtensionPageServerTransport implements Transport {
24
- // MCP Transport 必需的回调
25
- onmessage?: (message: JSONRPCMessage) => void // 接收到消息时的回调
26
- onerror?: (error: Error) => void // 发生错误时的回调
27
- onclose?: () => void // 连接关闭时的回调
28
-
29
- // 会话ID,用于标识此 transport 实例并路由消息
30
- readonly sessionId: string
31
-
32
- // 内部状态
33
-
34
- private _messageListener2: () => void
35
- private _isStarted: boolean = false
36
- private _isClosed: boolean = false
37
- private _lastRegistration: ServerInfo | null = null // 最后一次注册信息(用于 Sidepanel 刷新后重新注册)
38
- private _throwError(whenFn: () => boolean, message: string) {
39
- if (whenFn()) {
40
- const error = new Error(message)
41
- console.log(message, error)
42
- if (this.onerror) {
43
- this.onerror(error)
44
- }
45
- throw error
46
- }
47
- }
48
-
49
- constructor(sessionId: string | null = null) {
50
- // 如果提供了 sessionId,使用提供的;否则随机生成
51
- this.sessionId = sessionId || randomUUID()
52
-
53
- // 移除了对 sidepanel-ready-to-page 的监听,因为信息直接发往常驻的 background
54
-
55
- this._messageListener2 = onWindowMessage(
56
- 'mcp-client-to-server-to-page',
57
- (data) => {
58
- if (data.sessionId !== this.sessionId) return
59
-
60
- console.log('【Page Svr Transport】 即将处理 mcpMessage', data.mcpMessage)
61
- const mcpMessage = JSONRPCMessageSchema.parse(data.mcpMessage)
62
- this.onmessage?.(mcpMessage)
63
-
64
- // 判断是否为工具调用
65
- const toolName = data.mcpMessage.params?.name
66
- if (toolName) {
67
- sendWindowMessage(
68
- 'update-page-app-message',
69
- { status: 'run', message: data.mcpMessage.params?.name },
70
- 'page->content'
71
- )
72
- }
73
- },
74
- 'content->page'
75
- )
76
- }
77
-
78
- /** 启动 transport,开始监听消息 */
79
- async start() {
80
- if (this._isStarted) return
81
- if (this._isClosed) throw new Error('【Page Svr Transport】 已关闭,无法重新启动')
82
-
83
- this._isStarted = true
84
- }
85
-
86
- /** 发送消息到 MCP Client */
87
- async send(message: JSONRPCMessage, _options?: TransportSendOptions): Promise<void> {
88
- // 检查状态
89
- this._throwError(() => !this._isStarted, '【Page Svr Transport】 未启动,无法发送消息')
90
- this._throwError(() => this._isClosed, '【Page Svr Transport】 已关闭,无法发送消息')
91
-
92
- sendWindowMessage(
93
- 'mcp-server-to-client-from-page',
94
- {
95
- sessionId: this.sessionId,
96
- mcpMessage: message
97
- },
98
- 'page->content'
99
- )
100
-
101
- // 判断是否为工具调用成功了!
102
- if ('result' in message && message.result?.content) {
103
- sendWindowMessage(
104
- 'update-page-app-message',
105
- { status: 'ready', message: '' },
106
- 'page->content' // 此处应该是 content->content, 但为了和pageServerTransport统一。
107
- )
108
- }
109
- }
110
-
111
- /** 通知 Sidepanel 此 Server 已启动并准备接受连接 */
112
- async notifyRegistration(serverInfo: ServerInfo): Promise<void> {
113
- this._throwError(() => !this._isStarted, '【Page Svr Transport】 未启动,无法注册消息')
114
- this._lastRegistration = serverInfo
115
-
116
- try {
117
- sendWindowMessage(
118
- 'mcp-server-register-from-page',
119
- {
120
- sessionId: this.sessionId,
121
- serverInfo: {
122
- ...serverInfo,
123
- url: window.location.origin,
124
- title: document.title
125
- }
126
- },
127
- 'page->content'
128
- )
129
- } catch (error) {
130
- this._throwError(() => true, '【Page Svr Transport】 注册 server 失败' + String(error))
131
- }
132
- }
133
-
134
- /** 关闭 transport */
135
- async close() {
136
- if (this._isClosed) return
137
-
138
- try {
139
-
140
- this._messageListener2 && this._messageListener2()
141
-
142
- this._isClosed = true
143
- this._isStarted = false
144
- this.onclose && this.onclose()
145
- } catch (error) {
146
- this._throwError(() => true, '【Page Svr Transport】 关闭时发生错误' + String(error))
147
- }
148
- }
149
- }
@@ -1,63 +0,0 @@
1
- /**
2
- * wxt 依赖于 next-sdk, 但是 transports 又依赖于事件系统,会造成循环依赖。
3
- * 由于目前消息都是:“无状态” 发送,所以不是同一份代码也没关系。
4
- *
5
- * 所以同步一份“事件系统代码”在这里。
6
- */
7
- /**
8
- * 消息系统说明:
9
- * 1、 根据type, direction 2个条件,进行事件匹配
10
- * 2、 side, bg 向page 发消息,必须 content 中转一次
11
- */
12
- declare const chrome: any
13
-
14
- // *************************** content - page 的消息 ***************************
15
- type WindowDirection = 'page->content' | 'content->page' | 'page->page' | 'content->content'
16
- type WindowHandler = (data: any) => void
17
- export const sendWindowMessage = (type: string, data: any, direction: WindowDirection) => {
18
- window.postMessage({ type, direction, data }, '*')
19
- }
20
-
21
- export const onWindowMessage = (type: string, cb: WindowHandler, direction: WindowDirection) => {
22
- const handler = async function (event: MessageEvent<any>) {
23
- if (event.source === window && event.data.type === type && event.data.direction === direction) {
24
- await cb(event.data.data)
25
- }
26
- }
27
- window.addEventListener('message', handler)
28
- return () => window.removeEventListener('message', handler)
29
- }
30
-
31
- // *************************** content - side - bg 通过 runtime中转消息 ***************************
32
- type RuntimeDirection = 'content->side' | 'side->content' | 'side->bg' | 'bg->side' | 'content->bg' | 'bg->content'
33
- type RuntimeHandler = (message: any, sender: any, sendResponse: (response?: any) => void) => any
34
-
35
- // 1、runtime 之间直接互发, 但是向content发送时,是广播所有的tabs。
36
- // 2、返回值固定为sender
37
- export const sendRuntimeMessage = (type: string, data: any, direction: RuntimeDirection) => {
38
- if (direction.endsWith('content')) {
39
- chrome.tabs.query({}, (tabs: any[]) => {
40
- tabs.forEach((tab) => {
41
- chrome.tabs.sendMessage(tab.id!, { type, data, direction, tabId: tab.id! })
42
- })
43
- })
44
- } else {
45
- return chrome.runtime.sendMessage({ direction, type, data })
46
- }
47
- }
48
-
49
- // 回调只能拿到 data,sender, 不提供 sendResponse。 如果需要返回值, 必须重新发送一个新消息才行。
50
- export const onRuntimeMessage = (type: string, cb: RuntimeHandler, direction: RuntimeDirection, selfTabid?: number) => {
51
- const handler: RuntimeHandler = (message: any, sender, sendResponse) => {
52
- if (message.type === type && message.direction === direction) {
53
- if (!selfTabid || (selfTabid && message.tabId === selfTabid)) {
54
- const { data } = message
55
- cb(data, sender, sendResponse)
56
- sendResponse(sender) // 默认永远返回sender
57
- }
58
- }
59
- }
60
- chrome.runtime.onMessage.addListener(handler)
61
-
62
- return () => chrome.runtime.onMessage.removeListener(handler)
63
- }