@reqvire-org/ads 0.3.43 → 0.3.45

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 (165) hide show
  1. package/README.md +32 -10
  2. package/dist/assets.mjs +49 -3
  3. package/dist/brand-assets.mjs +174 -7
  4. package/dist/check.mjs +4 -2
  5. package/dist/cli.mjs +21 -9
  6. package/dist/config.mjs +60 -3
  7. package/dist/create.mjs +48 -0
  8. package/dist/image-size.mjs +28 -0
  9. package/dist/index.mjs +1 -0
  10. package/dist/init.mjs +2 -2
  11. package/dist/mcp/server.mjs +3 -1
  12. package/dist/mcp/skills.mjs +1 -1
  13. package/dist/preview-bun.mjs +4 -2
  14. package/dist/scenario-groups.mjs +2 -2
  15. package/dist/scenario-registry.mjs +3 -3
  16. package/dist/scenarios-compiler.mjs +1 -1
  17. package/dist/scenarios.mjs +4 -2
  18. package/dist/showcase/client.bundle.js +22 -22
  19. package/dist/showcase/draft-navigation.js +1 -1
  20. package/dist/showcase/index.html +1 -0
  21. package/dist/skills/ads-break-ui/SKILL.md +1 -1
  22. package/dist/skills/ads-designer/README.md +2 -2
  23. package/dist/skills/ads-designer/SKILL.md +44 -54
  24. package/dist/skills/ads-designer/references/branding.md +104 -0
  25. package/dist/skills/ads-designer/references/cli.md +5 -4
  26. package/dist/skills/ads-import/SKILL.md +1 -1
  27. package/dist/skills/ads-import/references/branding.md +13 -5
  28. package/dist/skills/ads-import/references/cli.md +5 -4
  29. package/dist/skills/ads-motion/SKILL.md +1 -1
  30. package/dist/skills/ads-port/SKILL.md +1 -1
  31. package/dist/skills/ads-port/references/cli.md +5 -4
  32. package/dist/{bootstrap-ds-preact → starters/preact}/ds.config.json +2 -1
  33. package/dist/{bootstrap-ds → starters/react}/ADS.md +2 -2
  34. package/dist/{bootstrap-ds → starters/react}/README.md +18 -22
  35. package/dist/starters/react/design-system/assets/brand/README.md +36 -0
  36. package/dist/starters/react/design-system/assets/brand/app-icon.svg +4 -0
  37. package/dist/starters/react/design-system/assets/brand/logo.dark.svg +6 -0
  38. package/dist/starters/react/design-system/assets/brand/logo.svg +6 -0
  39. package/dist/starters/react/design-system/brand/Icons/AppIcon/AppIcon.ads.fixture.ts +7 -0
  40. package/dist/starters/react/design-system/brand/Icons/AppIcon/AppIcon.ads.scenario.tsx +4 -0
  41. package/dist/starters/react/design-system/brand/Identity/Logo/Logo.ads.fixture.ts +7 -0
  42. package/dist/starters/react/design-system/brand/Identity/Logo/Logo.ads.scenario.tsx +4 -0
  43. package/dist/starters/react/design-system/components/Content/Logo/Logo.ads.fixture.ts +1 -0
  44. package/dist/starters/react/design-system/components/Content/Logo/Logo.ads.scenario.tsx +12 -0
  45. package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +41 -0
  46. package/dist/starters/react/design-system/components/Content/Logo/README.md +10 -0
  47. package/dist/{bootstrap-ds → starters/react}/design-system/index.ts +1 -0
  48. package/dist/starters/react/design-system/review/brand-preview/BrandPreview.tsx +115 -0
  49. package/dist/{bootstrap-ds → starters/react}/design-system/review/index.ts +1 -0
  50. package/dist/{skills/ads-designer/assets/bootstrap-ds → starters/react}/ds.config.json +2 -1
  51. package/dist/{bootstrap-ds → starters/react}/tsconfig.build.json +2 -1
  52. package/dist/task-cache.mjs +1 -1
  53. package/dist/token-fixtures.mjs +1 -1
  54. package/dist/units.mjs +6 -6
  55. package/dist/validation.mjs +1 -1
  56. package/docs/ADS.md +9 -6
  57. package/docs/ARCHITECTURE.md +1 -1
  58. package/docs/CHANGELOG.md +59 -12
  59. package/docs/GUIDE.md +61 -18
  60. package/package.json +3 -5
  61. package/dist/bootstrap-ds/design-system/assets/brand/README.md +0 -29
  62. package/dist/bootstrap-ds/ds.config.json +0 -19
  63. package/dist/skills/ads-designer/assets/bootstrap-ds/ADS.md +0 -258
  64. package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +0 -120
  65. package/dist/skills/ads-designer/assets/bootstrap-ds/biome.css.json +0 -21
  66. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/assets/brand/README.md +0 -29
  67. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/assets/fonts/.gitkeep +0 -0
  68. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Actions/Button/Button.ads.fixture.ts +0 -1
  69. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Actions/Button/Button.ads.scenario.tsx +0 -13
  70. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Actions/Button/Button.tsx +0 -49
  71. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Actions/Button/README.md +0 -12
  72. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Forms/TextField/README.md +0 -14
  73. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Forms/TextField/TextField.ads.fixture.ts +0 -6
  74. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Forms/TextField/TextField.ads.scenario.tsx +0 -13
  75. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Forms/TextField/TextField.tsx +0 -57
  76. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/composition/Search/SearchPage/README.md +0 -4
  77. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/composition/Search/SearchPage/SearchPage.ads.fixture.ts +0 -7
  78. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/composition/Search/SearchPage/SearchPage.ads.scenario.tsx +0 -16
  79. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/controllers/.gitkeep +0 -0
  80. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/index.ts +0 -7
  81. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/patterns/Search/SearchBar/README.md +0 -12
  82. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/patterns/Search/SearchBar/SearchBar.ads.fixture.ts +0 -1
  83. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/patterns/Search/SearchBar/SearchBar.ads.scenario.tsx +0 -11
  84. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/patterns/Search/SearchBar/SearchBar.tsx +0 -41
  85. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/review/demo-frame/DemoFrame.tsx +0 -29
  86. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/review/index.ts +0 -3
  87. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/review/screen-frame/ScreenFrame.tsx +0 -34
  88. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/review/token-preview/TokenPreview.tsx +0 -119
  89. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/showcase/mcp/index.html +0 -1
  90. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/showcase/mcp/main.tsx +0 -8
  91. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/styles.css +0 -5
  92. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/Color.ads.fixture.ts +0 -18
  93. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/Color.ads.scenario.tsx +0 -4
  94. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/SpaceTypeMotion.ads.fixture.ts +0 -36
  95. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/SpaceTypeMotion.ads.scenario.tsx +0 -4
  96. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/base.css +0 -30
  97. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/colors.css +0 -29
  98. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/elevation.css +0 -15
  99. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/spacing.css +0 -15
  100. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/typography.css +0 -13
  101. package/dist/skills/ads-designer/assets/bootstrap-ds/gitignore.template +0 -8
  102. package/dist/skills/ads-designer/assets/bootstrap-ds/package-lock.json +0 -4660
  103. package/dist/skills/ads-designer/assets/bootstrap-ds/package.json +0 -42
  104. package/dist/skills/ads-designer/assets/bootstrap-ds/scripts/build-mcp-previews.mjs +0 -3
  105. package/dist/skills/ads-designer/assets/bootstrap-ds/src/vite-env.d.ts +0 -7
  106. package/dist/skills/ads-designer/assets/bootstrap-ds/tsconfig.build.json +0 -19
  107. package/dist/skills/ads-designer/assets/bootstrap-ds/tsconfig.json +0 -35
  108. package/dist/skills/ads-designer/assets/bootstrap-ds/vite.config.ts +0 -23
  109. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/design-system/review/demo-frame/DemoFrame.tsx +0 -29
  110. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/design-system/review/screen-frame/ScreenFrame.tsx +0 -34
  111. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/design-system/review/token-preview/TokenPreview.tsx +0 -119
  112. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/design-system/showcase/mcp/main.tsx +0 -6
  113. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/ds.config.json +0 -19
  114. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/package.json +0 -38
  115. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/src/vite-env.d.ts +0 -7
  116. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/tsconfig.json +0 -36
  117. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/vite.config.ts +0 -23
  118. /package/dist/{bootstrap-ds-preact → starters/preact}/design-system/review/demo-frame/DemoFrame.tsx +0 -0
  119. /package/dist/{bootstrap-ds-preact → starters/preact}/design-system/review/screen-frame/ScreenFrame.tsx +0 -0
  120. /package/dist/{bootstrap-ds-preact → starters/preact}/design-system/review/token-preview/TokenPreview.tsx +0 -0
  121. /package/dist/{bootstrap-ds-preact → starters/preact}/design-system/showcase/mcp/main.tsx +0 -0
  122. /package/dist/{bootstrap-ds-preact → starters/preact}/package.json +0 -0
  123. /package/dist/{bootstrap-ds-preact → starters/preact}/src/vite-env.d.ts +0 -0
  124. /package/dist/{bootstrap-ds-preact → starters/preact}/tsconfig.json +0 -0
  125. /package/dist/{bootstrap-ds-preact → starters/preact}/vite.config.ts +0 -0
  126. /package/dist/{bootstrap-ds → starters/react}/biome.css.json +0 -0
  127. /package/dist/{bootstrap-ds → starters/react}/design-system/assets/fonts/.gitkeep +0 -0
  128. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Actions/Button/Button.ads.fixture.ts +0 -0
  129. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Actions/Button/Button.ads.scenario.tsx +0 -0
  130. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Actions/Button/Button.tsx +0 -0
  131. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Actions/Button/README.md +0 -0
  132. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Forms/TextField/README.md +0 -0
  133. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Forms/TextField/TextField.ads.fixture.ts +0 -0
  134. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Forms/TextField/TextField.ads.scenario.tsx +0 -0
  135. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Forms/TextField/TextField.tsx +0 -0
  136. /package/dist/{bootstrap-ds → starters/react}/design-system/composition/Search/SearchPage/README.md +0 -0
  137. /package/dist/{bootstrap-ds → starters/react}/design-system/composition/Search/SearchPage/SearchPage.ads.fixture.ts +0 -0
  138. /package/dist/{bootstrap-ds → starters/react}/design-system/composition/Search/SearchPage/SearchPage.ads.scenario.tsx +0 -0
  139. /package/dist/{bootstrap-ds → starters/react}/design-system/controllers/.gitkeep +0 -0
  140. /package/dist/{bootstrap-ds → starters/react}/design-system/patterns/Search/SearchBar/README.md +0 -0
  141. /package/dist/{bootstrap-ds → starters/react}/design-system/patterns/Search/SearchBar/SearchBar.ads.fixture.ts +0 -0
  142. /package/dist/{bootstrap-ds → starters/react}/design-system/patterns/Search/SearchBar/SearchBar.ads.scenario.tsx +0 -0
  143. /package/dist/{bootstrap-ds → starters/react}/design-system/patterns/Search/SearchBar/SearchBar.tsx +0 -0
  144. /package/dist/{bootstrap-ds → starters/react}/design-system/review/demo-frame/DemoFrame.tsx +0 -0
  145. /package/dist/{bootstrap-ds → starters/react}/design-system/review/screen-frame/ScreenFrame.tsx +0 -0
  146. /package/dist/{bootstrap-ds → starters/react}/design-system/review/token-preview/TokenPreview.tsx +0 -0
  147. /package/dist/{bootstrap-ds → starters/react}/design-system/showcase/mcp/index.html +0 -0
  148. /package/dist/{bootstrap-ds → starters/react}/design-system/showcase/mcp/main.tsx +0 -0
  149. /package/dist/{bootstrap-ds → starters/react}/design-system/styles.css +0 -0
  150. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/Color.ads.fixture.ts +0 -0
  151. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/Color.ads.scenario.tsx +0 -0
  152. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/SpaceTypeMotion.ads.fixture.ts +0 -0
  153. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/SpaceTypeMotion.ads.scenario.tsx +0 -0
  154. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/base.css +0 -0
  155. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/colors.css +0 -0
  156. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/elevation.css +0 -0
  157. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/spacing.css +0 -0
  158. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/typography.css +0 -0
  159. /package/dist/{bootstrap-ds → starters/react}/gitignore.template +0 -0
  160. /package/dist/{bootstrap-ds → starters/react}/package-lock.json +0 -0
  161. /package/dist/{bootstrap-ds → starters/react}/package.json +0 -0
  162. /package/dist/{bootstrap-ds → starters/react}/scripts/build-mcp-previews.mjs +0 -0
  163. /package/dist/{bootstrap-ds → starters/react}/src/vite-env.d.ts +0 -0
  164. /package/dist/{bootstrap-ds → starters/react}/tsconfig.json +0 -0
  165. /package/dist/{bootstrap-ds → starters/react}/vite.config.ts +0 -0
@@ -1,7 +1,7 @@
1
1
  function pa(e){if(e?.failure?.scope!=="project")return"Preview build failed";if(e.failure.phase==="validation")return"Project validation failed";if(e.failure.phase==="discovery")return"Project scenario discovery failed";return"Project preview build failed"}function od(e=[]){return e.map((t)=>{let r=t.file?t.file+(t.line?`:${t.line}`:"")+(t.column?`:${t.column}`:""):"";return(r?`${r}: `:"")+t.message}).join(`
2
- `)}var{create:MS,defineProperty:ha,getOwnPropertyDescriptor:jS,getOwnPropertyNames:LS,getPrototypeOf:US}=Object,ZS=Object.prototype.hasOwnProperty,nd=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),sd=(e,t)=>{let r={};for(var o in e)ha(r,o,{get:e[o],enumerable:!0});if(t)ha(r,Symbol.toStringTag,{value:"Module"});return r},DS=(e,t,r,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(var n=LS(t),s=0,i=n.length,a;s<i;s++)if(a=n[s],!ZS.call(e,a)&&a!==r)ha(e,a,{get:((l)=>t[l]).bind(null,a),enumerable:!(o=jS(t,a))||o.enumerable})}return e},id=(e,t,r)=>(r=e!=null?MS(US(e)):{},DS(t||!e||!e.__esModule?ha(r,"default",{value:e,enumerable:!0}):r,e));var FS=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),ad=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),HS=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),VS=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function cd(e){return typeof e==="string"&&ad.has(e.replace(/#$/,""))}function ld(e,t){if(!("$schema"in e)||typeof e.$schema!=="string")return"2020-12";let r=e.$schema.replace(/#$/,"");if(FS.has(r))return"2020-12";if(ad.has(r))return"2019-09";if(HS.has(r)||VS.has(r))return"draft-7";throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var ud,Mc=Object.freeze({status:"aborted"});function _(e,t,r){function o(a,l){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let u=i.prototype,d=Object.keys(u);for(let m=0;m<d.length;m++){let f=d[m];if(!(f in a))a[f]=u[f].bind(a)}}let n=r?.Parent??Object;class s extends n{}Object.defineProperty(s,"name",{value:e});function i(a){var l;let u=r?.Parent?new s:this;o(u,a),(l=u._zod).deferred??(l.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:o}),Object.defineProperty(i,Symbol.hasInstance,{value:(a)=>{if(r?.Parent&&a instanceof r.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(i,"name",{value:e}),i}var JS=Symbol("zod_brand");class kt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class On extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(ud=globalThis).__zod_globalConfig??(ud.__zod_globalConfig={});var io=globalThis.__zod_globalConfig;function je(e){if(e)Object.assign(io,e);return io}function fa(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function Lc(e,t="|"){return e.map((r)=>Fc(r)).join(t)}function Nn(e,t){if(typeof t==="bigint")return t.toString();return t}function qn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function ga(e){return e===null||e===void 0}function Sa(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function pd(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-o)<n)return 0;return r-o}var dd=Symbol("evaluating");function Q(e,t,r){let o=void 0;Object.defineProperty(e,t,{get(){if(o===dd)return;if(o===void 0)o=dd,o=r();return o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function yr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Wt(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function Uc(e){return JSON.stringify(e)}function hd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Zc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ao(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var md=qn(()=>{if(io.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function vr(e){if(ao(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(ao(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Dc(e){if(vr(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var fd=new Set(["string","number","symbol"]);function Kt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(e,t,r){let o=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)o._zod.parent=e;return o}function M(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Fc(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function gd(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Sd={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function BS(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s=Wt(e._zod.def,{get shape(){let i={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;i[a]=r.shape[a]}return yr(this,"shape",i),i},checks:[]});return rt(e,s)}function WS(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=Wt(e._zod.def,{get shape(){let i={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete i[a]}return yr(this,"shape",i),i},checks:[]});return rt(e,s)}function KS(e,t){if(!vr(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=Wt(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return yr(this,"shape",s),s}});return rt(e,n)}function GS(e,t){if(!vr(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=Wt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return yr(this,"shape",o),o}});return rt(e,r)}function YS(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Wt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return yr(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return rt(e,r)}function XS(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let i=Wt(t._zod.def,{get shape(){let a=t._zod.def.shape,l={...a};if(r)for(let u in r){if(!(u in a))throw Error(`Unrecognized key: "${u}"`);if(!r[u])continue;l[u]=e?new e({type:"optional",innerType:a[u]}):a[u]}else for(let u in a)l[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return yr(this,"shape",l),l},checks:[]});return rt(t,i)}function QS(e,t,r){let o=Wt(t._zod.def,{get shape(){let n=t._zod.def.shape,s={...n};if(r)for(let i in r){if(!(i in s))throw Error(`Unrecognized key: "${i}"`);if(!r[i])continue;s[i]=new e({type:"nonoptional",innerType:n[i]})}else for(let i in n)s[i]=new e({type:"nonoptional",innerType:n[i]});return yr(this,"shape",s),s}});return rt(t,o)}function zr(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function _d(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Gt(e,t){return t.map((r)=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function ma(e){return typeof e==="string"?e:e?.message}function ot(e,t,r){let o=e.message?e.message:ma(e.inst?._zod.def?.error?.(e))??ma(t?.error?.(e))??ma(r.customError?.(e))??ma(r.localeError?.(e))??"Invalid input",{inst:n,continue:s,input:i,...a}=e;if(a.path??(a.path=[]),a.message=o,t?.reportInput)a.input=i;return a}function _a(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function bd(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function wr(...e){let[t,r,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:o};return{...t}}var yd=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Nn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ba=_("$ZodError",yd),Hc=_("$ZodError",yd,{Parent:Error});function Vc(e,t=(r)=>r.message){let r={},o=[];for(let n of e.issues)if(n.path.length>0)r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n));else o.push(t(n));return{formErrors:o,fieldErrors:r}}function Jc(e,t=(r)=>r.message){let r={_errors:[]},o=(n,s=[])=>{for(let i of n.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map((a)=>o({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")o({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")o({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(t(i));else{let l=r,u=0;while(u<a.length){let d=a[u];if(u!==a.length-1)l[d]=l[d]||{_errors:[]};else l[d]=l[d]||{_errors:[]},l[d]._errors.push(t(i));l=l[d],u++}}}};return o(e),r}var ya=(e)=>(t,r,o,n)=>{let s=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new kt;if(i.issues.length){let a=new(n?.Err??e)(i.issues.map((l)=>ot(l,s,je())));throw Zc(a,n?.callee),a}return i.value};var va=(e)=>async(t,r,o,n)=>{let s=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)i=await i;if(i.issues.length){let a=new(n?.Err??e)(i.issues.map((l)=>ot(l,s,je())));throw Zc(a,n?.callee),a}return i.value};var An=(e)=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new kt;return s.issues.length?{success:!1,error:new(e??ba)(s.issues.map((i)=>ot(i,n,je())))}:{success:!0,data:s.value}},vd=An(Hc),Mn=(e)=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)s=await s;return s.issues.length?{success:!1,error:new e(s.issues.map((i)=>ot(i,n,je())))}:{success:!0,data:s.value}},zd=Mn(Hc),wd=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return ya(e)(t,r,n)};var Rd=(e)=>(t,r,o)=>ya(e)(t,r,o);var xd=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return va(e)(t,r,n)};var Pd=(e)=>async(t,r,o)=>va(e)(t,r,o);var Td=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return An(e)(t,r,n)};var Ed=(e)=>(t,r,o)=>An(e)(t,r,o);var kd=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Mn(e)(t,r,n)};var $d=(e)=>async(t,r,o)=>Mn(e)(t,r,o);var Cd=/^[cC][0-9a-z]{6,}$/,Id=/^[0-9a-z]+$/,Od=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Nd=/^[0-9a-vA-V]{20}$/,qd=/^[A-Za-z0-9]{27}$/,Ad=/^[a-zA-Z0-9_-]{21}$/,Md=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var jd=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Bc=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var Ld=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var t_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Ud(){return new RegExp(t_,"u")}var Zd=/^(?:(?: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])$/,Dd=/^(([0-9a-fA-F]{1,4}:){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}|:))$/;var Fd=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,Hd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Vd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Wc=/^[A-Za-z0-9_-]*$/;var Jd=/^https?$/,Bd=/^\+[1-9]\d{6,14}$/,Wd="(?:(?:\\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])))",Kd=new RegExp(`^${Wd}$`);function Gd(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Yd(e){return new RegExp(`^${Gd(e)}$`)}function Xd(e){let t=Gd({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${Wd}T(?:${o})$`)}var Qd=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var ep=/^-?\d+$/,Kc=/^-?\d+(?:\.\d+)?$/,tp=/^(?:true|false)$/i,rp=/^null$/i;var op=/^undefined$/i;var np=/^[^A-Z]*$/,sp=/^[^a-z]*$/;var ze=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),ip={number:"number",bigint:"bigint",object:"date"},Gc=_("$ZodCheckLessThan",(e,t)=>{ze.init(e,t);let r=ip[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,s=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<s)if(t.inclusive)n.maximum=t.value;else n.exclusiveMaximum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value<=t.value:o.value<t.value)return;o.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Yc=_("$ZodCheckGreaterThan",(e,t)=>{ze.init(e,t);let r=ip[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,s=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>s)if(t.inclusive)n.minimum=t.value;else n.exclusiveMinimum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value>=t.value:o.value>t.value)return;o.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ap=_("$ZodCheckMultipleOf",(e,t)=>{ze.init(e,t),e._zod.onattach.push((r)=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):pd(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),cp=_("$ZodCheckNumberFormat",(e,t)=>{ze.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,s]=Sd[t.format];e._zod.onattach.push((i)=>{let a=i._zod.bag;if(a.format=t.format,a.minimum=n,a.maximum=s,r)a.pattern=ep}),e._zod.check=(i)=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});else i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}if(a<n)i.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort});if(a>s)i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var lp=_("$ZodCheckMaxLength",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!ga(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<n)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let n=o.value;if(n.length<=t.maximum)return;let i=_a(n);o.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),up=_("$ZodCheckMinLength",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!ga(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>n)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let n=o.value;if(n.length>=t.minimum)return;let i=_a(n);o.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),dp=_("$ZodCheckLengthEquals",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!ga(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=(o)=>{let n=o.value,s=n.length;if(s===t.length)return;let i=_a(n),a=s>t.length;o.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Ln=_("$ZodCheckStringFormat",(e,t)=>{var r,o;if(ze.init(e,t),e._zod.onattach.push((n)=>{let s=n._zod.bag;if(s.format=t.format,t.pattern)s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(o=e._zod).check??(o.check=()=>{})}),pp=_("$ZodCheckRegex",(e,t)=>{Ln.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),hp=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=np),Ln.init(e,t)}),mp=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=sp),Ln.init(e,t)}),fp=_("$ZodCheckIncludes",(e,t)=>{ze.init(e,t);let r=Kt(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push((n)=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),e._zod.check=(n)=>{if(n.value.includes(t.includes,t.position))return;n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),gp=_("$ZodCheckStartsWith",(e,t)=>{ze.init(e,t);let r=new RegExp(`^${Kt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.startsWith(t.prefix))return;o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Sp=_("$ZodCheckEndsWith",(e,t)=>{ze.init(e,t);let r=new RegExp(`.*${Kt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.endsWith(t.suffix))return;o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var _p=_("$ZodCheckOverwrite",(e,t)=>{ze.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class Xc{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
3
- `).filter((s)=>s),o=Math.min(...r.map((s)=>s.length-s.trimStart().length)),n=r.map((s)=>s.slice(o)).map((s)=>" ".repeat(this.indent*2)+s);for(let s of n)this.content.push(s)}compile(){let e=Function,t=this?.args,o=[...(this?.content??[""]).map((n)=>` ${n}`)];return new e(...t,o.join(`
4
- `))}}var yp={major:4,minor:4,patch:3};var re=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=yp;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let n of o)for(let s of n._zod.onattach)s(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(i,a,l)=>{let u=zr(i),d;for(let m of a){if(m._zod.def.when){if(_d(i))continue;if(!m._zod.def.when(i))continue}else if(u)continue;let f=i.issues.length,S=m._zod.check(i);if(S instanceof Promise&&l?.async===!1)throw new kt;if(d||S instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await S,i.issues.length===f)return;if(!u)u=zr(i,f)});else{if(i.issues.length===f)continue;if(!u)u=zr(i,f)}}if(d)return d.then(()=>i);return i},s=(i,a,l)=>{if(zr(i))return i.aborted=!0,i;let u=n(a,o,l);if(u instanceof Promise){if(l.async===!1)throw new kt;return u.then((d)=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction==="backward"){let u=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>s(d,i,a));return s(u,i,a)}let l=e._zod.parse(i,a);if(l instanceof Promise){if(a.async===!1)throw new kt;return l.then((u)=>n(u,o,a))}return n(l,o,a)}}Q(e,"~standard",()=>({validate:(n)=>{try{let s=vd(e,n);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return zd(e,n).then((i)=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Ra=_("$ZodString",(e,t)=>{re.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Qd(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ie=_("$ZodStringFormat",(e,t)=>{Ln.init(e,t),Ra.init(e,t)}),kp=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=jd),ie.init(e,t)}),$p=_("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Bc(o))}else t.pattern??(t.pattern=Bc());ie.init(e,t)}),Cp=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ld),ie.init(e,t)}),Ip=_("$ZodURL",(e,t)=>{ie.init(e,t),e._zod.check=(r)=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===Jd.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let n=new URL(o);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(n.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})}if(t.normalize)r.value=n.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Op=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ud()),ie.init(e,t)}),Np=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ad),ie.init(e,t)}),qp=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Cd),ie.init(e,t)}),Ap=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Id),ie.init(e,t)}),Mp=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Od),ie.init(e,t)}),jp=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Nd),ie.init(e,t)}),Lp=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=qd),ie.init(e,t)}),Up=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Xd(t)),ie.init(e,t)}),Zp=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Kd),ie.init(e,t)}),Dp=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Yd(t)),ie.init(e,t)}),Fp=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Md),ie.init(e,t)}),Hp=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Zd),ie.init(e,t),e._zod.bag.format="ipv4"}),Vp=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Dd),ie.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var Jp=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Fd),ie.init(e,t)}),Bp=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Hd),ie.init(e,t),e._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[n,s]=o;if(!s)throw Error();let i=Number(s);if(`${i}`!==s)throw Error();if(i<0||i>128)throw Error();new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Wp(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Kp=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Vd),ie.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(Wp(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function r_(e){if(!Wc.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Wp(r)}var Gp=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Wc),ie.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(r_(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Yp=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Bd),ie.init(e,t)});function o_(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(t&&(!("alg"in n)||n.alg!==t))return!1;return!0}catch{return!1}}var Xp=_("$ZodJWT",(e,t)=>{ie.init(e,t),e._zod.check=(r)=>{if(o_(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var el=_("$ZodNumber",(e,t)=>{re.init(e,t),e._zod.pattern=e._zod.bag.pattern??Kc,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(i){}let n=r.value;if(typeof n==="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let s=typeof n==="number"?Number.isNaN(n)?"NaN":!Number.isFinite(n)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...s?{received:s}:{}}),r}}),Qp=_("$ZodNumberFormat",(e,t)=>{cp.init(e,t),el.init(e,t)}),eh=_("$ZodBoolean",(e,t)=>{re.init(e,t),e._zod.pattern=tp,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(s){}let n=r.value;if(typeof n==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}});var th=_("$ZodUndefined",(e,t)=>{re.init(e,t),e._zod.pattern=op,e._zod.values=new Set([void 0]),e._zod.parse=(r,o)=>{let n=r.value;if(typeof n>"u")return r;return r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),r}}),rh=_("$ZodNull",(e,t)=>{re.init(e,t),e._zod.pattern=rp,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;if(n===null)return r;return r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),oh=_("$ZodAny",(e,t)=>{re.init(e,t),e._zod.parse=(r)=>r}),nh=_("$ZodUnknown",(e,t)=>{re.init(e,t),e._zod.parse=(r)=>r}),sh=_("$ZodNever",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function vp(e,t,r){if(e.issues.length)t.issues.push(...Gt(r,e.issues));t.value[r]=e.value}var ih=_("$ZodArray",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let s=[];for(let i=0;i<n.length;i++){let a=n[i],l=t.element._zod.run({value:a,issues:[]},o);if(l instanceof Promise)s.push(l.then((u)=>vp(u,r,i)));else vp(l,r,i)}if(s.length)return Promise.all(s).then(()=>r);return r}});function wa(e,t,r,o,n,s){let i=r in o;if(e.issues.length){if(n&&s&&!i)return;t.issues.push(...Gt(r,e.issues))}if(!i&&!n){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(i)t.value[r]=void 0}else t.value[r]=e.value}function ah(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${o}": expected a Zod schema`);let r=gd(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function ch(e,t,r,o,n,s){let i=[],a=n.keySet,l=n.catchall._zod,u=l.def.type,d=l.optin==="optional",m=l.optout==="optional";for(let f in t){if(f==="__proto__")continue;if(a.has(f))continue;if(u==="never"){i.push(f);continue}let S=l.run({value:t[f],issues:[]},o);if(S instanceof Promise)e.push(S.then((b)=>wa(b,r,f,t,d,m)));else wa(S,r,f,t,d,m)}if(i.length)r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s});if(!e.length)return r;return Promise.all(e).then(()=>r)}var n_=_("$ZodObject",(e,t)=>{if(re.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}let o=qn(()=>ah(t));Q(e._zod,"propValues",()=>{let a=t.shape,l={};for(let u in a){let d=a[u]._zod;if(d.values){l[u]??(l[u]=new Set);for(let m of d.values)l[u].add(m)}}return l});let n=ao,s=t.catchall,i;e._zod.parse=(a,l)=>{i??(i=o.value);let u=a.value;if(!n(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};let d=[],m=i.shape;for(let f of i.keys){let S=m[f],b=S._zod.optin==="optional",y=S._zod.optout==="optional",v=S._zod.run({value:u[f],issues:[]},l);if(v instanceof Promise)d.push(v.then((U)=>wa(U,a,f,u,b,y)));else wa(v,a,f,u,b,y)}if(!s)return d.length?Promise.all(d).then(()=>a):a;return ch(d,u,a,l,o.value,e)}}),lh=_("$ZodObjectJIT",(e,t)=>{n_.init(e,t);let r=e._zod.parse,o=qn(()=>ah(t)),n=(f)=>{let S=new Xc(["shape","payload","ctx"]),b=o.value,y=(x)=>{let Z=Uc(x);return`shape[${Z}]._zod.run({ value: input[${Z}], issues: [] }, ctx)`};S.write("const input = payload.value;");let v=Object.create(null),U=0;for(let x of b.keys)v[x]=`key_${U++}`;S.write("const newResult = {};");for(let x of b.keys){let Z=v[x],R=Uc(x),w=f[x],D=w?._zod?.optin==="optional",X=w?._zod?.optout==="optional";if(S.write(`const ${Z} = ${y(x)};`),D&&X)S.write(`
2
+ `)}var{create:MS,defineProperty:ha,getOwnPropertyDescriptor:jS,getOwnPropertyNames:LS,getPrototypeOf:US}=Object,ZS=Object.prototype.hasOwnProperty,nd=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),sd=(e,t)=>{let r={};for(var o in e)ha(r,o,{get:e[o],enumerable:!0});if(t)ha(r,Symbol.toStringTag,{value:"Module"});return r},DS=(e,t,r,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(var n=LS(t),i=0,s=n.length,a;i<s;i++)if(a=n[i],!ZS.call(e,a)&&a!==r)ha(e,a,{get:((l)=>t[l]).bind(null,a),enumerable:!(o=jS(t,a))||o.enumerable})}return e},id=(e,t,r)=>(r=e!=null?MS(US(e)):{},DS(t||!e||!e.__esModule?ha(r,"default",{value:e,enumerable:!0}):r,e));var FS=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),ad=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),HS=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),VS=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function cd(e){return typeof e==="string"&&ad.has(e.replace(/#$/,""))}function ld(e,t){if(!("$schema"in e)||typeof e.$schema!=="string")return"2020-12";let r=e.$schema.replace(/#$/,"");if(FS.has(r))return"2020-12";if(ad.has(r))return"2019-09";if(HS.has(r)||VS.has(r))return"draft-7";throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var ud,jc=Object.freeze({status:"aborted"});function _(e,t,r){function o(a,l){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let u=s.prototype,d=Object.keys(u);for(let m=0;m<d.length;m++){let f=d[m];if(!(f in a))a[f]=u[f].bind(a)}}let n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function s(a){var l;let u=r?.Parent?new i:this;o(u,a),(l=u._zod).deferred??(l.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:(a)=>{if(r?.Parent&&a instanceof r.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var JS=Symbol("zod_brand");class kt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class On extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(ud=globalThis).__zod_globalConfig??(ud.__zod_globalConfig={});var io=globalThis.__zod_globalConfig;function je(e){if(e)Object.assign(io,e);return io}function fa(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function Uc(e,t="|"){return e.map((r)=>Hc(r)).join(t)}function Nn(e,t){if(typeof t==="bigint")return t.toString();return t}function qn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function ga(e){return e===null||e===void 0}function Sa(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function pd(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-o)<n)return 0;return r-o}var dd=Symbol("evaluating");function Q(e,t,r){let o=void 0;Object.defineProperty(e,t,{get(){if(o===dd)return;if(o===void 0)o=dd,o=r();return o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function yr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Wt(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function Zc(e){return JSON.stringify(e)}function hd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Dc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ao(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var md=qn(()=>{if(io.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function vr(e){if(ao(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(ao(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Fc(e){if(vr(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var fd=new Set(["string","number","symbol"]);function Kt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(e,t,r){let o=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)o._zod.parent=e;return o}function M(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Hc(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function gd(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Sd={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function BS(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=Wt(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;s[a]=r.shape[a]}return yr(this,"shape",s),s},checks:[]});return rt(e,i)}function WS(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=Wt(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete s[a]}return yr(this,"shape",s),s},checks:[]});return rt(e,i)}function KS(e,t){if(!vr(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=Wt(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return yr(this,"shape",i),i}});return rt(e,n)}function GS(e,t){if(!vr(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=Wt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return yr(this,"shape",o),o}});return rt(e,r)}function YS(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Wt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return yr(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return rt(e,r)}function XS(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let s=Wt(t._zod.def,{get shape(){let a=t._zod.def.shape,l={...a};if(r)for(let u in r){if(!(u in a))throw Error(`Unrecognized key: "${u}"`);if(!r[u])continue;l[u]=e?new e({type:"optional",innerType:a[u]}):a[u]}else for(let u in a)l[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return yr(this,"shape",l),l},checks:[]});return rt(t,s)}function QS(e,t,r){let o=Wt(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in i))throw Error(`Unrecognized key: "${s}"`);if(!r[s])continue;i[s]=new e({type:"nonoptional",innerType:n[s]})}else for(let s in n)i[s]=new e({type:"nonoptional",innerType:n[s]});return yr(this,"shape",i),i}});return rt(t,o)}function zr(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function _d(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Gt(e,t){return t.map((r)=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function ma(e){return typeof e==="string"?e:e?.message}function ot(e,t,r){let o=e.message?e.message:ma(e.inst?._zod.def?.error?.(e))??ma(t?.error?.(e))??ma(r.customError?.(e))??ma(r.localeError?.(e))??"Invalid input",{inst:n,continue:i,input:s,...a}=e;if(a.path??(a.path=[]),a.message=o,t?.reportInput)a.input=s;return a}function _a(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function bd(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function wr(...e){let[t,r,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:o};return{...t}}var yd=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Nn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ba=_("$ZodError",yd),Vc=_("$ZodError",yd,{Parent:Error});function Jc(e,t=(r)=>r.message){let r={},o=[];for(let n of e.issues)if(n.path.length>0)r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n));else o.push(t(n));return{formErrors:o,fieldErrors:r}}function Bc(e,t=(r)=>r.message){let r={_errors:[]},o=(n,i=[])=>{for(let s of n.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>o({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")o({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let l=r,u=0;while(u<a.length){let d=a[u];if(u!==a.length-1)l[d]=l[d]||{_errors:[]};else l[d]=l[d]||{_errors:[]},l[d]._errors.push(t(s));l=l[d],u++}}}};return o(e),r}var ya=(e)=>(t,r,o,n)=>{let i=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new kt;if(s.issues.length){let a=new(n?.Err??e)(s.issues.map((l)=>ot(l,i,je())));throw Dc(a,n?.callee),a}return s.value};var va=(e)=>async(t,r,o,n)=>{let i=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)s=await s;if(s.issues.length){let a=new(n?.Err??e)(s.issues.map((l)=>ot(l,i,je())));throw Dc(a,n?.callee),a}return s.value};var An=(e)=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new kt;return i.issues.length?{success:!1,error:new(e??ba)(i.issues.map((s)=>ot(s,n,je())))}:{success:!0,data:i.value}},vd=An(Vc),Mn=(e)=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)i=await i;return i.issues.length?{success:!1,error:new e(i.issues.map((s)=>ot(s,n,je())))}:{success:!0,data:i.value}},zd=Mn(Vc),wd=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return ya(e)(t,r,n)};var Rd=(e)=>(t,r,o)=>ya(e)(t,r,o);var xd=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return va(e)(t,r,n)};var Pd=(e)=>async(t,r,o)=>va(e)(t,r,o);var Td=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return An(e)(t,r,n)};var Ed=(e)=>(t,r,o)=>An(e)(t,r,o);var kd=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Mn(e)(t,r,n)};var $d=(e)=>async(t,r,o)=>Mn(e)(t,r,o);var Cd=/^[cC][0-9a-z]{6,}$/,Id=/^[0-9a-z]+$/,Od=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Nd=/^[0-9a-vA-V]{20}$/,qd=/^[A-Za-z0-9]{27}$/,Ad=/^[a-zA-Z0-9_-]{21}$/,Md=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var jd=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Wc=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var Ld=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var t_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Ud(){return new RegExp(t_,"u")}var Zd=/^(?:(?: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])$/,Dd=/^(([0-9a-fA-F]{1,4}:){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}|:))$/;var Fd=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,Hd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Vd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Kc=/^[A-Za-z0-9_-]*$/;var Jd=/^https?$/,Bd=/^\+[1-9]\d{6,14}$/,Wd="(?:(?:\\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])))",Kd=new RegExp(`^${Wd}$`);function Gd(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Yd(e){return new RegExp(`^${Gd(e)}$`)}function Xd(e){let t=Gd({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${Wd}T(?:${o})$`)}var Qd=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var ep=/^-?\d+$/,Gc=/^-?\d+(?:\.\d+)?$/,tp=/^(?:true|false)$/i,rp=/^null$/i;var op=/^undefined$/i;var np=/^[^A-Z]*$/,sp=/^[^a-z]*$/;var ze=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),ip={number:"number",bigint:"bigint",object:"date"},Yc=_("$ZodCheckLessThan",(e,t)=>{ze.init(e,t);let r=ip[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,i=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<i)if(t.inclusive)n.maximum=t.value;else n.exclusiveMaximum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value<=t.value:o.value<t.value)return;o.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Xc=_("$ZodCheckGreaterThan",(e,t)=>{ze.init(e,t);let r=ip[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>i)if(t.inclusive)n.minimum=t.value;else n.exclusiveMinimum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value>=t.value:o.value>t.value)return;o.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ap=_("$ZodCheckMultipleOf",(e,t)=>{ze.init(e,t),e._zod.onattach.push((r)=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):pd(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),cp=_("$ZodCheckNumberFormat",(e,t)=>{ze.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,i]=Sd[t.format];e._zod.onattach.push((s)=>{let a=s._zod.bag;if(a.format=t.format,a.minimum=n,a.maximum=i,r)a.pattern=ep}),e._zod.check=(s)=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}if(a<n)s.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort});if(a>i)s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var lp=_("$ZodCheckMaxLength",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!ga(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<n)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let n=o.value;if(n.length<=t.maximum)return;let s=_a(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),up=_("$ZodCheckMinLength",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!ga(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>n)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let n=o.value;if(n.length>=t.minimum)return;let s=_a(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),dp=_("$ZodCheckLengthEquals",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!ga(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=(o)=>{let n=o.value,i=n.length;if(i===t.length)return;let s=_a(n),a=i>t.length;o.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Ln=_("$ZodCheckStringFormat",(e,t)=>{var r,o;if(ze.init(e,t),e._zod.onattach.push((n)=>{let i=n._zod.bag;if(i.format=t.format,t.pattern)i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(o=e._zod).check??(o.check=()=>{})}),pp=_("$ZodCheckRegex",(e,t)=>{Ln.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),hp=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=np),Ln.init(e,t)}),mp=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=sp),Ln.init(e,t)}),fp=_("$ZodCheckIncludes",(e,t)=>{ze.init(e,t);let r=Kt(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push((n)=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),e._zod.check=(n)=>{if(n.value.includes(t.includes,t.position))return;n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),gp=_("$ZodCheckStartsWith",(e,t)=>{ze.init(e,t);let r=new RegExp(`^${Kt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.startsWith(t.prefix))return;o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Sp=_("$ZodCheckEndsWith",(e,t)=>{ze.init(e,t);let r=new RegExp(`.*${Kt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.endsWith(t.suffix))return;o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var _p=_("$ZodCheckOverwrite",(e,t)=>{ze.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class Qc{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
3
+ `).filter((i)=>i),o=Math.min(...r.map((i)=>i.length-i.trimStart().length)),n=r.map((i)=>i.slice(o)).map((i)=>" ".repeat(this.indent*2)+i);for(let i of n)this.content.push(i)}compile(){let e=Function,t=this?.args,o=[...(this?.content??[""]).map((n)=>` ${n}`)];return new e(...t,o.join(`
4
+ `))}}var yp={major:4,minor:4,patch:3};var re=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=yp;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let n of o)for(let i of n._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(s,a,l)=>{let u=zr(s),d;for(let m of a){if(m._zod.def.when){if(_d(s))continue;if(!m._zod.def.when(s))continue}else if(u)continue;let f=s.issues.length,S=m._zod.check(s);if(S instanceof Promise&&l?.async===!1)throw new kt;if(d||S instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await S,s.issues.length===f)return;if(!u)u=zr(s,f)});else{if(s.issues.length===f)continue;if(!u)u=zr(s,f)}}if(d)return d.then(()=>s);return s},i=(s,a,l)=>{if(zr(s))return s.aborted=!0,s;let u=n(a,o,l);if(u instanceof Promise){if(l.async===!1)throw new kt;return u.then((d)=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let u=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>i(d,s,a));return i(u,s,a)}let l=e._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new kt;return l.then((u)=>n(u,o,a))}return n(l,o,a)}}Q(e,"~standard",()=>({validate:(n)=>{try{let i=vd(e,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch(i){return zd(e,n).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Ra=_("$ZodString",(e,t)=>{re.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Qd(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ae=_("$ZodStringFormat",(e,t)=>{Ln.init(e,t),Ra.init(e,t)}),kp=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=jd),ae.init(e,t)}),$p=_("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Wc(o))}else t.pattern??(t.pattern=Wc());ae.init(e,t)}),Cp=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ld),ae.init(e,t)}),Ip=_("$ZodURL",(e,t)=>{ae.init(e,t),e._zod.check=(r)=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===Jd.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let n=new URL(o);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(n.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})}if(t.normalize)r.value=n.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Op=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ud()),ae.init(e,t)}),Np=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ad),ae.init(e,t)}),qp=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Cd),ae.init(e,t)}),Ap=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Id),ae.init(e,t)}),Mp=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Od),ae.init(e,t)}),jp=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Nd),ae.init(e,t)}),Lp=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=qd),ae.init(e,t)}),Up=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Xd(t)),ae.init(e,t)}),Zp=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Kd),ae.init(e,t)}),Dp=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Yd(t)),ae.init(e,t)}),Fp=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Md),ae.init(e,t)}),Hp=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Zd),ae.init(e,t),e._zod.bag.format="ipv4"}),Vp=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Dd),ae.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var Jp=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Fd),ae.init(e,t)}),Bp=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Hd),ae.init(e,t),e._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[n,i]=o;if(!i)throw Error();let s=Number(i);if(`${s}`!==i)throw Error();if(s<0||s>128)throw Error();new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Wp(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Kp=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Vd),ae.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(Wp(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function r_(e){if(!Kc.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Wp(r)}var Gp=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Kc),ae.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(r_(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Yp=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Bd),ae.init(e,t)});function o_(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(t&&(!("alg"in n)||n.alg!==t))return!1;return!0}catch{return!1}}var Xp=_("$ZodJWT",(e,t)=>{ae.init(e,t),e._zod.check=(r)=>{if(o_(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var tl=_("$ZodNumber",(e,t)=>{re.init(e,t),e._zod.pattern=e._zod.bag.pattern??Gc,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(s){}let n=r.value;if(typeof n==="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i=typeof n==="number"?Number.isNaN(n)?"NaN":!Number.isFinite(n)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}}),Qp=_("$ZodNumberFormat",(e,t)=>{cp.init(e,t),tl.init(e,t)}),eh=_("$ZodBoolean",(e,t)=>{re.init(e,t),e._zod.pattern=tp,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(i){}let n=r.value;if(typeof n==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}});var th=_("$ZodUndefined",(e,t)=>{re.init(e,t),e._zod.pattern=op,e._zod.values=new Set([void 0]),e._zod.parse=(r,o)=>{let n=r.value;if(typeof n>"u")return r;return r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),r}}),rh=_("$ZodNull",(e,t)=>{re.init(e,t),e._zod.pattern=rp,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;if(n===null)return r;return r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),oh=_("$ZodAny",(e,t)=>{re.init(e,t),e._zod.parse=(r)=>r}),nh=_("$ZodUnknown",(e,t)=>{re.init(e,t),e._zod.parse=(r)=>r}),sh=_("$ZodNever",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function vp(e,t,r){if(e.issues.length)t.issues.push(...Gt(r,e.issues));t.value[r]=e.value}var ih=_("$ZodArray",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let i=[];for(let s=0;s<n.length;s++){let a=n[s],l=t.element._zod.run({value:a,issues:[]},o);if(l instanceof Promise)i.push(l.then((u)=>vp(u,r,s)));else vp(l,r,s)}if(i.length)return Promise.all(i).then(()=>r);return r}});function wa(e,t,r,o,n,i){let s=r in o;if(e.issues.length){if(n&&i&&!s)return;t.issues.push(...Gt(r,e.issues))}if(!s&&!n){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(s)t.value[r]=void 0}else t.value[r]=e.value}function ah(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${o}": expected a Zod schema`);let r=gd(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function ch(e,t,r,o,n,i){let s=[],a=n.keySet,l=n.catchall._zod,u=l.def.type,d=l.optin==="optional",m=l.optout==="optional";for(let f in t){if(f==="__proto__")continue;if(a.has(f))continue;if(u==="never"){s.push(f);continue}let S=l.run({value:t[f],issues:[]},o);if(S instanceof Promise)e.push(S.then((b)=>wa(b,r,f,t,d,m)));else wa(S,r,f,t,d,m)}if(s.length)r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i});if(!e.length)return r;return Promise.all(e).then(()=>r)}var n_=_("$ZodObject",(e,t)=>{if(re.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}let o=qn(()=>ah(t));Q(e._zod,"propValues",()=>{let a=t.shape,l={};for(let u in a){let d=a[u]._zod;if(d.values){l[u]??(l[u]=new Set);for(let m of d.values)l[u].add(m)}}return l});let n=ao,i=t.catchall,s;e._zod.parse=(a,l)=>{s??(s=o.value);let u=a.value;if(!n(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};let d=[],m=s.shape;for(let f of s.keys){let S=m[f],b=S._zod.optin==="optional",y=S._zod.optout==="optional",v=S._zod.run({value:u[f],issues:[]},l);if(v instanceof Promise)d.push(v.then((U)=>wa(U,a,f,u,b,y)));else wa(v,a,f,u,b,y)}if(!i)return d.length?Promise.all(d).then(()=>a):a;return ch(d,u,a,l,o.value,e)}}),lh=_("$ZodObjectJIT",(e,t)=>{n_.init(e,t);let r=e._zod.parse,o=qn(()=>ah(t)),n=(f)=>{let S=new Qc(["shape","payload","ctx"]),b=o.value,y=(x)=>{let Z=Zc(x);return`shape[${Z}]._zod.run({ value: input[${Z}], issues: [] }, ctx)`};S.write("const input = payload.value;");let v=Object.create(null),U=0;for(let x of b.keys)v[x]=`key_${U++}`;S.write("const newResult = {};");for(let x of b.keys){let Z=v[x],R=Zc(x),w=f[x],D=w?._zod?.optin==="optional",X=w?._zod?.optout==="optional";if(S.write(`const ${Z} = ${y(x)};`),D&&X)S.write(`
5
5
  if (${Z}.issues.length) {
6
6
  if (${R} in input) {
7
7
  payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
@@ -60,31 +60,31 @@ function pa(e){if(e?.failure?.scope!=="project")return"Preview build failed";if(
60
60
  newResult[${R}] = ${Z}.value;
61
61
  }
62
62
 
63
- `)}S.write("payload.value = newResult;"),S.write("return payload;");let H=S.compile();return(x,Z)=>H(f,x,Z)},s,i=ao,a=!io.jitless,u=a&&md.value,d=t.catchall,m;e._zod.parse=(f,S)=>{m??(m=o.value);let b=f.value;if(!i(b))return f.issues.push({expected:"object",code:"invalid_type",input:b,inst:e}),f;if(a&&u&&S?.async===!1&&S.jitless!==!0){if(!s)s=n(t.shape);if(f=s(f,S),!d)return f;return ch([],b,f,S,m,e)}return r(f,S)}});function zp(e,t,r,o){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let n=e.filter((s)=>!zr(s));if(n.length===1)return t.value=n[0].value,n[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((s)=>s.issues.map((i)=>ot(i,o,je())))}),t}var tl=_("$ZodUnion",(e,t)=>{re.init(e,t),Q(e._zod,"optin",()=>t.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),Q(e._zod,"optout",()=>t.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),Q(e._zod,"values",()=>{if(t.options.every((o)=>o._zod.values))return new Set(t.options.flatMap((o)=>Array.from(o._zod.values)));return}),Q(e._zod,"pattern",()=>{if(t.options.every((o)=>o._zod.pattern)){let o=t.options.map((n)=>n._zod.pattern);return new RegExp(`^(${o.map((n)=>Sa(n.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,n)=>{if(r)return r(o,n);let s=!1,i=[];for(let a of t.options){let l=a._zod.run({value:o.value,issues:[]},n);if(l instanceof Promise)i.push(l),s=!0;else{if(l.issues.length===0)return l;i.push(l)}}if(!s)return zp(i,o,e,n);return Promise.all(i).then((a)=>zp(a,o,e,n))}});var uh=_("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,tl.init(e,t);let r=e._zod.parse;Q(e._zod,"propValues",()=>{let n={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[a,l]of Object.entries(i)){if(!n[a])n[a]=new Set;for(let u of l)n[a].add(u)}}return n});let o=qn(()=>{let n=t.options,s=new Map;for(let i of n){let a=i._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let l of a){if(s.has(l))throw Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,i)}}return s});e._zod.parse=(n,s)=>{let i=n.value;if(!ao(i))return n.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),n;let a=o.value.get(i?.[t.discriminator]);if(a)return a._zod.run(n,s);if(t.unionFallback||s.direction==="backward")return r(n,s);return n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(o.value.keys()),input:i,path:[t.discriminator],inst:e}),n}}),dh=_("$ZodIntersection",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value,s=t.left._zod.run({value:n,issues:[]},o),i=t.right._zod.run({value:n,issues:[]},o);if(s instanceof Promise||i instanceof Promise)return Promise.all([s,i]).then(([l,u])=>wp(r,l,u));return wp(r,s,i)}});function Qc(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(vr(e)&&vr(t)){let r=Object.keys(t),o=Object.keys(e).filter((s)=>r.indexOf(s)!==-1),n={...e,...t};for(let s of o){let i=Qc(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};n[s]=i.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<e.length;o++){let n=e[o],s=t[o],i=Qc(n,s);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function wp(e,t,r){let o=new Map,n;for(let a of t.issues)if(a.code==="unrecognized_keys"){n??(n=a);for(let l of a.keys){if(!o.has(l))o.set(l,{});o.get(l).l=!0}}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let l of a.keys){if(!o.has(l))o.set(l,{});o.get(l).r=!0}else e.issues.push(a);let s=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&n)e.issues.push({...n,keys:s});if(zr(e))return e;let i=Qc(t.value,r.value);if(!i.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}var ph=_("$ZodRecord",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!vr(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let s=[],i=t.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){a.add(typeof u==="number"?u.toString():u);let d=t.keyType._zod.run({value:u,issues:[]},o);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((S)=>ot(S,o,je())),input:u,path:[u],inst:e});continue}let m=d.value,f=t.valueType._zod.run({value:n[u],issues:[]},o);if(f instanceof Promise)s.push(f.then((S)=>{if(S.issues.length)r.issues.push(...Gt(u,S.issues));r.value[m]=S.value}));else{if(f.issues.length)r.issues.push(...Gt(u,f.issues));r.value[m]=f.value}}let l;for(let u in n)if(!a.has(u))l=l??[],l.push(u);if(l&&l.length>0)r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:l})}else{r.value={};for(let a of Reflect.ownKeys(n)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(n,a))continue;let l=t.keyType._zod.run({value:a,issues:[]},o);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&Kc.test(a)&&l.issues.length){let m=t.keyType._zod.run({value:Number(a),issues:[]},o);if(m instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(m.issues.length===0)l=m}if(l.issues.length){if(t.mode==="loose")r.value[a]=n[a];else r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((m)=>ot(m,o,je())),input:a,path:[a],inst:e});continue}let d=t.valueType._zod.run({value:n[a],issues:[]},o);if(d instanceof Promise)s.push(d.then((m)=>{if(m.issues.length)r.issues.push(...Gt(a,m.issues));r.value[l.value]=m.value}));else{if(d.issues.length)r.issues.push(...Gt(a,d.issues));r.value[l.value]=d.value}}}if(s.length)return Promise.all(s).then(()=>r);return r}});var hh=_("$ZodEnum",(e,t)=>{re.init(e,t);let r=fa(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter((n)=>fd.has(typeof n)).map((n)=>typeof n==="string"?Kt(n):n.toString()).join("|")})$`),e._zod.parse=(n,s)=>{let i=n.value;if(o.has(i))return n;return n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),mh=_("$ZodLiteral",(e,t)=>{if(re.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map((o)=>typeof o==="string"?Kt(o):o?Kt(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,n)=>{let s=o.value;if(r.has(s))return o;return o.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),o}});var fh=_("$ZodTransform",(e,t)=>{re.init(e,t),e._zod.optin="optional",e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new On(e.constructor.name);let n=t.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then((i)=>(r.value=i,r.fallback=!0,r));if(n instanceof Promise)throw new kt;return r.value=n,r.fallback=!0,r}});function Rp(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var rl=_("$ZodOptional",(e,t)=>{re.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Q(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Sa(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(t.innerType._zod.optin==="optional"){let n=r.value,s=t.innerType._zod.run(r,o);if(s instanceof Promise)return s.then((i)=>Rp(i,n));return Rp(s,n)}if(r.value===void 0)return r;return t.innerType._zod.run(r,o)}}),gh=_("$ZodExactOptional",(e,t)=>{rl.init(e,t),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,o)=>t.innerType._zod.run(r,o)}),Sh=_("$ZodNullable",(e,t)=>{re.init(e,t),Q(e._zod,"optin",()=>t.innerType._zod.optin),Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Sa(r.source)}|null)$`):void 0}),Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>{if(r.value===null)return r;return t.innerType._zod.run(r,o)}}),_h=_("$ZodDefault",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>xp(s,t));return xp(n,t)}});function xp(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var bh=_("$ZodPrefault",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,o)}}),yh=_("$ZodNonOptional",(e,t)=>{re.init(e,t),Q(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>Pp(s,e));return Pp(n,e)}});function Pp(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var vh=_("$ZodCatch",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>{if(r.value=s.value,s.issues.length)r.value=t.catchValue({...r,error:{issues:s.issues.map((i)=>ot(i,o,je()))},input:r.value}),r.issues=[],r.fallback=!0;return r});if(r.value=n.value,n.issues.length)r.value=t.catchValue({...r,error:{issues:n.issues.map((s)=>ot(s,o,je()))},input:r.value}),r.issues=[],r.fallback=!0;return r}});var ol=_("$ZodPipe",(e,t)=>{re.init(e,t),Q(e._zod,"values",()=>t.in._zod.values),Q(e._zod,"optin",()=>t.in._zod.optin),Q(e._zod,"optout",()=>t.out._zod.optout),Q(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if(o.direction==="backward"){let s=t.out._zod.run(r,o);if(s instanceof Promise)return s.then((i)=>za(i,t.in,o));return za(s,t.in,o)}let n=t.in._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>za(s,t.out,o));return za(n,t.out,o)}});function za(e,t,r){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var zh=_("$ZodPreprocess",(e,t)=>{ol.init(e,t)}),wh=_("$ZodReadonly",(e,t)=>{re.init(e,t),Q(e._zod,"propValues",()=>t.innerType._zod.propValues),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"optin",()=>t.innerType?._zod?.optin),Q(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then(Tp);return Tp(n)}});function Tp(e){return e.value=Object.freeze(e.value),e}var Rh=_("$ZodLazy",(e,t)=>{re.init(e,t),Q(e._zod,"innerType",()=>{let r=t;if(!r._cachedInner)r._cachedInner=t.getter();return r._cachedInner}),Q(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Q(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Q(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Q(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,o)=>e._zod.innerType._zod.run(r,o)}),xh=_("$ZodCustom",(e,t)=>{ze.init(e,t),re.init(e,t),e._zod.parse=(r,o)=>r,e._zod.check=(r)=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then((s)=>Ep(s,r,o,e));Ep(n,r,o,e);return}});function Ep(e,t,r,o){if(!e){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};if(o._zod.def.params)n.params=o._zod.def.params;t.issues.push(wr(n))}}var s_=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let s=o[n.expected]??n.expected,i=bd(n.input),a=o[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":if(n.values.length===1)return`Invalid input: expected ${Fc(n.values[0])}`;return`Invalid option: expected one of ${Lc(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",i=t(n.origin);if(i)return`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${i.unit??"elements"}`;return`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",i=t(n.origin);if(i)return`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${i.unit}`;return`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;if(s.format==="starts_with")return`Invalid string: must start with "${s.prefix}"`;if(s.format==="ends_with")return`Invalid string: must end with "${s.suffix}"`;if(s.format==="includes")return`Invalid string: must include "${s.includes}"`;if(s.format==="regex")return`Invalid string: must match pattern ${s.pattern}`;return`Invalid ${r[s.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Lc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":if(n.options&&Array.isArray(n.options)&&n.options.length>0)return`Invalid discriminator value. Expected ${n.options.map((i)=>`'${i}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function nl(){return{localeError:s_()}}var Ph,i_=Symbol("ZodOutput"),a_=Symbol("ZodInput");class Th{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Eh(){return new Th}(Ph=globalThis).__zod_globalRegistry??(Ph.__zod_globalRegistry=Eh());var Yt=globalThis.__zod_globalRegistry;function kh(e,t){return new e({type:"string",...M(t)})}function sl(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...M(t)})}function il(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...M(t)})}function $h(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...M(t)})}function Ch(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(t)})}function Ih(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(t)})}function Oh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(t)})}function al(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...M(t)})}function Nh(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...M(t)})}function qh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(t)})}function Ah(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...M(t)})}function Mh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(t)})}function jh(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...M(t)})}function Lh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...M(t)})}function Uh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(t)})}function Zh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(t)})}function Dh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(t)})}function Fh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(t)})}function Hh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(t)})}function Vh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...M(t)})}function Jh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...M(t)})}function Bh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...M(t)})}function Wh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...M(t)})}function Kh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(t)})}function Gh(e,t){return new e({type:"string",format:"date",check:"string_format",...M(t)})}function Yh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...M(t)})}function Xh(e,t){return new e({type:"string",format:"duration",check:"string_format",...M(t)})}function Qh(e,t){return new e({type:"number",checks:[],...M(t)})}function em(e,t){return new e({type:"number",coerce:!0,checks:[],...M(t)})}function tm(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...M(t)})}function rm(e,t){return new e({type:"boolean",...M(t)})}function om(e,t){return new e({type:"undefined",...M(t)})}function nm(e,t){return new e({type:"null",...M(t)})}function sm(e){return new e({type:"any"})}function im(e){return new e({type:"unknown"})}function am(e,t){return new e({type:"never",...M(t)})}function xa(e,t){return new Gc({check:"less_than",...M(t),value:e,inclusive:!1})}function Un(e,t){return new Gc({check:"less_than",...M(t),value:e,inclusive:!0})}function Pa(e,t){return new Yc({check:"greater_than",...M(t),value:e,inclusive:!1})}function Zn(e,t){return new Yc({check:"greater_than",...M(t),value:e,inclusive:!0})}function Ta(e,t){return new ap({check:"multiple_of",...M(t),value:e})}function Ea(e,t){return new lp({check:"max_length",...M(t),maximum:e})}function co(e,t){return new up({check:"min_length",...M(t),minimum:e})}function ka(e,t){return new dp({check:"length_equals",...M(t),length:e})}function cl(e,t){return new pp({check:"string_format",format:"regex",...M(t),pattern:e})}function ll(e){return new hp({check:"string_format",format:"lowercase",...M(e)})}function ul(e){return new mp({check:"string_format",format:"uppercase",...M(e)})}function dl(e,t){return new fp({check:"string_format",format:"includes",...M(t),includes:e})}function pl(e,t){return new gp({check:"string_format",format:"starts_with",...M(t),prefix:e})}function hl(e,t){return new Sp({check:"string_format",format:"ends_with",...M(t),suffix:e})}function Xt(e){return new _p({check:"overwrite",tx:e})}function ml(e){return Xt((t)=>t.normalize(e))}function fl(){return Xt((e)=>e.trim())}function gl(){return Xt((e)=>e.toLowerCase())}function Sl(){return Xt((e)=>e.toUpperCase())}function _l(){return Xt((e)=>hd(e))}function cm(e,t,r){return new e({type:"array",element:t,...M(r)})}function lm(e,t,r){return new e({type:"custom",check:"custom",fn:t,...M(r)})}function um(e,t){let r=c_((o)=>(o.addIssue=(n)=>{if(typeof n==="string")o.issues.push(wr(n,o.value,r._zod.def));else{let s=n;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=o.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),o.issues.push(wr(s))}},e(o.value,o)),t);return r}function c_(e,t){let r=new ze({check:"custom",...M(t)});return r._zod.check=e,r}function Fn(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??Yt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function oe(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,r.schemaPath.includes(e))s.cycle=r.path;return s.schema}let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,d);else{let f=i.schema,S=t.processors[n.type];if(!S)throw Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);S(e,t,f,d)}let m=e._zod.parent;if(m){if(!i.ref)i.ref=m;oe(m,t,d),t.seen.get(m).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Object.assign(i.schema,l);if(t.io==="input"&&Ne(e))delete i.schema.examples,delete i.schema.default;if(t.io==="input"&&"_prefault"in i.schema)(o=i.schema).default??(o.default=i.schema._prefault);return delete i.schema._prefault,t.seen.get(e).schema}function Hn(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let l=o.get(a);if(l&&l!==i[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,i[0])}}let n=(i)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let m=e.external.registry.get(i[0])?.id,f=e.external.uri??((b)=>b);if(m)return{ref:f(m)};let S=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=S,{defId:S,ref:`${f("__shared")}#/${a}/${S}`}}if(i[1]===r)return{ref:"#"};let u=`${"#"}/${a}/`,d=i[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},s=(i)=>{if(i[1].schema.$ref)return;let a=i[1],{ref:l,defId:u}=n(i);if(a.def={...a.schema},u)a.defId=u;let d=a.schema;for(let m in d)delete d[m];d.$ref=l};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
63
+ `)}S.write("payload.value = newResult;"),S.write("return payload;");let H=S.compile();return(x,Z)=>H(f,x,Z)},i,s=ao,a=!io.jitless,u=a&&md.value,d=t.catchall,m;e._zod.parse=(f,S)=>{m??(m=o.value);let b=f.value;if(!s(b))return f.issues.push({expected:"object",code:"invalid_type",input:b,inst:e}),f;if(a&&u&&S?.async===!1&&S.jitless!==!0){if(!i)i=n(t.shape);if(f=i(f,S),!d)return f;return ch([],b,f,S,m,e)}return r(f,S)}});function zp(e,t,r,o){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let n=e.filter((i)=>!zr(i));if(n.length===1)return t.value=n[0].value,n[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((i)=>i.issues.map((s)=>ot(s,o,je())))}),t}var rl=_("$ZodUnion",(e,t)=>{re.init(e,t),Q(e._zod,"optin",()=>t.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),Q(e._zod,"optout",()=>t.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),Q(e._zod,"values",()=>{if(t.options.every((o)=>o._zod.values))return new Set(t.options.flatMap((o)=>Array.from(o._zod.values)));return}),Q(e._zod,"pattern",()=>{if(t.options.every((o)=>o._zod.pattern)){let o=t.options.map((n)=>n._zod.pattern);return new RegExp(`^(${o.map((n)=>Sa(n.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,n)=>{if(r)return r(o,n);let i=!1,s=[];for(let a of t.options){let l=a._zod.run({value:o.value,issues:[]},n);if(l instanceof Promise)s.push(l),i=!0;else{if(l.issues.length===0)return l;s.push(l)}}if(!i)return zp(s,o,e,n);return Promise.all(s).then((a)=>zp(a,o,e,n))}});var uh=_("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,rl.init(e,t);let r=e._zod.parse;Q(e._zod,"propValues",()=>{let n={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,l]of Object.entries(s)){if(!n[a])n[a]=new Set;for(let u of l)n[a].add(u)}}return n});let o=qn(()=>{let n=t.options,i=new Map;for(let s of n){let a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let l of a){if(i.has(l))throw Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});e._zod.parse=(n,i)=>{let s=n.value;if(!ao(s))return n.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),n;let a=o.value.get(s?.[t.discriminator]);if(a)return a._zod.run(n,i);if(t.unionFallback||i.direction==="backward")return r(n,i);return n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(o.value.keys()),input:s,path:[t.discriminator],inst:e}),n}}),dh=_("$ZodIntersection",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value,i=t.left._zod.run({value:n,issues:[]},o),s=t.right._zod.run({value:n,issues:[]},o);if(i instanceof Promise||s instanceof Promise)return Promise.all([i,s]).then(([l,u])=>wp(r,l,u));return wp(r,i,s)}});function el(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(vr(e)&&vr(t)){let r=Object.keys(t),o=Object.keys(e).filter((i)=>r.indexOf(i)!==-1),n={...e,...t};for(let i of o){let s=el(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};n[i]=s.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<e.length;o++){let n=e[o],i=t[o],s=el(n,i);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function wp(e,t,r){let o=new Map,n;for(let a of t.issues)if(a.code==="unrecognized_keys"){n??(n=a);for(let l of a.keys){if(!o.has(l))o.set(l,{});o.get(l).l=!0}}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let l of a.keys){if(!o.has(l))o.set(l,{});o.get(l).r=!0}else e.issues.push(a);let i=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&n)e.issues.push({...n,keys:i});if(zr(e))return e;let s=el(t.value,r.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var ph=_("$ZodRecord",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!vr(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let i=[],s=t.keyType._zod.values;if(s){r.value={};let a=new Set;for(let u of s)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){a.add(typeof u==="number"?u.toString():u);let d=t.keyType._zod.run({value:u,issues:[]},o);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((S)=>ot(S,o,je())),input:u,path:[u],inst:e});continue}let m=d.value,f=t.valueType._zod.run({value:n[u],issues:[]},o);if(f instanceof Promise)i.push(f.then((S)=>{if(S.issues.length)r.issues.push(...Gt(u,S.issues));r.value[m]=S.value}));else{if(f.issues.length)r.issues.push(...Gt(u,f.issues));r.value[m]=f.value}}let l;for(let u in n)if(!a.has(u))l=l??[],l.push(u);if(l&&l.length>0)r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:l})}else{r.value={};for(let a of Reflect.ownKeys(n)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(n,a))continue;let l=t.keyType._zod.run({value:a,issues:[]},o);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&Gc.test(a)&&l.issues.length){let m=t.keyType._zod.run({value:Number(a),issues:[]},o);if(m instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(m.issues.length===0)l=m}if(l.issues.length){if(t.mode==="loose")r.value[a]=n[a];else r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((m)=>ot(m,o,je())),input:a,path:[a],inst:e});continue}let d=t.valueType._zod.run({value:n[a],issues:[]},o);if(d instanceof Promise)i.push(d.then((m)=>{if(m.issues.length)r.issues.push(...Gt(a,m.issues));r.value[l.value]=m.value}));else{if(d.issues.length)r.issues.push(...Gt(a,d.issues));r.value[l.value]=d.value}}}if(i.length)return Promise.all(i).then(()=>r);return r}});var hh=_("$ZodEnum",(e,t)=>{re.init(e,t);let r=fa(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter((n)=>fd.has(typeof n)).map((n)=>typeof n==="string"?Kt(n):n.toString()).join("|")})$`),e._zod.parse=(n,i)=>{let s=n.value;if(o.has(s))return n;return n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),mh=_("$ZodLiteral",(e,t)=>{if(re.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map((o)=>typeof o==="string"?Kt(o):o?Kt(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,n)=>{let i=o.value;if(r.has(i))return o;return o.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),o}});var fh=_("$ZodTransform",(e,t)=>{re.init(e,t),e._zod.optin="optional",e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new On(e.constructor.name);let n=t.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then((s)=>(r.value=s,r.fallback=!0,r));if(n instanceof Promise)throw new kt;return r.value=n,r.fallback=!0,r}});function Rp(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var ol=_("$ZodOptional",(e,t)=>{re.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Q(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Sa(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(t.innerType._zod.optin==="optional"){let n=r.value,i=t.innerType._zod.run(r,o);if(i instanceof Promise)return i.then((s)=>Rp(s,n));return Rp(i,n)}if(r.value===void 0)return r;return t.innerType._zod.run(r,o)}}),gh=_("$ZodExactOptional",(e,t)=>{ol.init(e,t),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,o)=>t.innerType._zod.run(r,o)}),Sh=_("$ZodNullable",(e,t)=>{re.init(e,t),Q(e._zod,"optin",()=>t.innerType._zod.optin),Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Sa(r.source)}|null)$`):void 0}),Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>{if(r.value===null)return r;return t.innerType._zod.run(r,o)}}),_h=_("$ZodDefault",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>xp(i,t));return xp(n,t)}});function xp(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var bh=_("$ZodPrefault",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,o)}}),yh=_("$ZodNonOptional",(e,t)=>{re.init(e,t),Q(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>Pp(i,e));return Pp(n,e)}});function Pp(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var vh=_("$ZodCatch",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>{if(r.value=i.value,i.issues.length)r.value=t.catchValue({...r,error:{issues:i.issues.map((s)=>ot(s,o,je()))},input:r.value}),r.issues=[],r.fallback=!0;return r});if(r.value=n.value,n.issues.length)r.value=t.catchValue({...r,error:{issues:n.issues.map((i)=>ot(i,o,je()))},input:r.value}),r.issues=[],r.fallback=!0;return r}});var nl=_("$ZodPipe",(e,t)=>{re.init(e,t),Q(e._zod,"values",()=>t.in._zod.values),Q(e._zod,"optin",()=>t.in._zod.optin),Q(e._zod,"optout",()=>t.out._zod.optout),Q(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if(o.direction==="backward"){let i=t.out._zod.run(r,o);if(i instanceof Promise)return i.then((s)=>za(s,t.in,o));return za(i,t.in,o)}let n=t.in._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>za(i,t.out,o));return za(n,t.out,o)}});function za(e,t,r){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var zh=_("$ZodPreprocess",(e,t)=>{nl.init(e,t)}),wh=_("$ZodReadonly",(e,t)=>{re.init(e,t),Q(e._zod,"propValues",()=>t.innerType._zod.propValues),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"optin",()=>t.innerType?._zod?.optin),Q(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then(Tp);return Tp(n)}});function Tp(e){return e.value=Object.freeze(e.value),e}var Rh=_("$ZodLazy",(e,t)=>{re.init(e,t),Q(e._zod,"innerType",()=>{let r=t;if(!r._cachedInner)r._cachedInner=t.getter();return r._cachedInner}),Q(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Q(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Q(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Q(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,o)=>e._zod.innerType._zod.run(r,o)}),xh=_("$ZodCustom",(e,t)=>{ze.init(e,t),re.init(e,t),e._zod.parse=(r,o)=>r,e._zod.check=(r)=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then((i)=>Ep(i,r,o,e));Ep(n,r,o,e);return}});function Ep(e,t,r,o){if(!e){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};if(o._zod.def.params)n.params=o._zod.def.params;t.issues.push(wr(n))}}var s_=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=bd(n.input),a=o[s]??s;return`Invalid input: expected ${i}, received ${a}`}case"invalid_value":if(n.values.length===1)return`Invalid input: expected ${Hc(n.values[0])}`;return`Invalid option: expected one of ${Uc(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${s.unit??"elements"}`;return`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${s.unit}`;return`Too small: expected ${n.origin} to be ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Uc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":if(n.options&&Array.isArray(n.options)&&n.options.length>0)return`Invalid discriminator value. Expected ${n.options.map((s)=>`'${s}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function sl(){return{localeError:s_()}}var Ph,i_=Symbol("ZodOutput"),a_=Symbol("ZodInput");class Th{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Eh(){return new Th}(Ph=globalThis).__zod_globalRegistry??(Ph.__zod_globalRegistry=Eh());var Yt=globalThis.__zod_globalRegistry;function kh(e,t){return new e({type:"string",...M(t)})}function il(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...M(t)})}function al(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...M(t)})}function $h(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...M(t)})}function Ch(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(t)})}function Ih(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(t)})}function Oh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(t)})}function cl(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...M(t)})}function Nh(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...M(t)})}function qh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(t)})}function Ah(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...M(t)})}function Mh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(t)})}function jh(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...M(t)})}function Lh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...M(t)})}function Uh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(t)})}function Zh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(t)})}function Dh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(t)})}function Fh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(t)})}function Hh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(t)})}function Vh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...M(t)})}function Jh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...M(t)})}function Bh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...M(t)})}function Wh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...M(t)})}function Kh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(t)})}function Gh(e,t){return new e({type:"string",format:"date",check:"string_format",...M(t)})}function Yh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...M(t)})}function Xh(e,t){return new e({type:"string",format:"duration",check:"string_format",...M(t)})}function Qh(e,t){return new e({type:"number",checks:[],...M(t)})}function em(e,t){return new e({type:"number",coerce:!0,checks:[],...M(t)})}function tm(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...M(t)})}function rm(e,t){return new e({type:"boolean",...M(t)})}function om(e,t){return new e({type:"undefined",...M(t)})}function nm(e,t){return new e({type:"null",...M(t)})}function sm(e){return new e({type:"any"})}function im(e){return new e({type:"unknown"})}function am(e,t){return new e({type:"never",...M(t)})}function xa(e,t){return new Yc({check:"less_than",...M(t),value:e,inclusive:!1})}function Un(e,t){return new Yc({check:"less_than",...M(t),value:e,inclusive:!0})}function Pa(e,t){return new Xc({check:"greater_than",...M(t),value:e,inclusive:!1})}function Zn(e,t){return new Xc({check:"greater_than",...M(t),value:e,inclusive:!0})}function Ta(e,t){return new ap({check:"multiple_of",...M(t),value:e})}function Ea(e,t){return new lp({check:"max_length",...M(t),maximum:e})}function co(e,t){return new up({check:"min_length",...M(t),minimum:e})}function ka(e,t){return new dp({check:"length_equals",...M(t),length:e})}function ll(e,t){return new pp({check:"string_format",format:"regex",...M(t),pattern:e})}function ul(e){return new hp({check:"string_format",format:"lowercase",...M(e)})}function dl(e){return new mp({check:"string_format",format:"uppercase",...M(e)})}function pl(e,t){return new fp({check:"string_format",format:"includes",...M(t),includes:e})}function hl(e,t){return new gp({check:"string_format",format:"starts_with",...M(t),prefix:e})}function ml(e,t){return new Sp({check:"string_format",format:"ends_with",...M(t),suffix:e})}function Xt(e){return new _p({check:"overwrite",tx:e})}function fl(e){return Xt((t)=>t.normalize(e))}function gl(){return Xt((e)=>e.trim())}function Sl(){return Xt((e)=>e.toLowerCase())}function _l(){return Xt((e)=>e.toUpperCase())}function bl(){return Xt((e)=>hd(e))}function cm(e,t,r){return new e({type:"array",element:t,...M(r)})}function lm(e,t,r){return new e({type:"custom",check:"custom",fn:t,...M(r)})}function um(e,t){let r=c_((o)=>(o.addIssue=(n)=>{if(typeof n==="string")o.issues.push(wr(n,o.value,r._zod.def));else{let i=n;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=o.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),o.issues.push(wr(i))}},e(o.value,o)),t);return r}function c_(e,t){let r=new ze({check:"custom",...M(t)});return r._zod.check=e,r}function Fn(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??Yt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function oe(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,i=t.seen.get(e);if(i){if(i.count++,r.schemaPath.includes(e))i.cycle=r.path;return i.schema}let s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s);let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,d);else{let f=s.schema,S=t.processors[n.type];if(!S)throw Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);S(e,t,f,d)}let m=e._zod.parent;if(m){if(!s.ref)s.ref=m;oe(m,t,d),t.seen.get(m).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Object.assign(s.schema,l);if(t.io==="input"&&Ne(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(o=s.schema).default??(o.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function Hn(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let l=o.get(a);if(l&&l!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,s[0])}}let n=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let m=e.external.registry.get(s[0])?.id,f=e.external.uri??((b)=>b);if(m)return{ref:f(m)};let S=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=S,{defId:S,ref:`${f("__shared")}#/${a}/${S}`}}if(s[1]===r)return{ref:"#"};let u=`${"#"}/${a}/`,d=s[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},i=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:l,defId:u}=n(s);if(a.def={...a.schema},u)a.defId=u;let d=a.schema;for(let m in d)delete d[m];d.$ref=l};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
64
64
 
65
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1){if(e.reused==="ref"){s(i);continue}}}}function Vn(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(a)=>{let l=e.seen.get(a);if(l.ref===null)return;let u=l.def??l.schema,d={...u},m=l.ref;if(l.ref=null,m){o(m);let S=e.seen.get(m),b=S.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))u.allOf=u.allOf??[],u.allOf.push(b);else Object.assign(u,b);if(Object.assign(u,d),a._zod.parent===m)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(!(v in d))delete u[v]}if(b.$ref&&S.def)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(v in S.def&&JSON.stringify(u[v])===JSON.stringify(S.def[v]))delete u[v]}}let f=a._zod.parent;if(f&&f!==m){o(f);let S=e.seen.get(f);if(S?.schema.$ref){if(u.$ref=S.schema.$ref,S.def)for(let b in u){if(b==="$ref"||b==="allOf")continue;if(b in S.def&&JSON.stringify(u[b])===JSON.stringify(S.def[b]))delete u[b]}}}e.override({zodSchema:a,jsonSchema:u,path:l.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let n={};if(e.target==="draft-2020-12")n.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")n.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")n.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");n.$id=e.external.uri(a)}Object.assign(n,r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&n.id===s)delete n.id;let i=e.external?.defs??{};for(let a of e.seen.entries()){let l=a[1];if(l.def&&l.defId){if(l.def.id===l.defId)delete l.def.id;i[l.defId]=l.def}}if(e.external);else if(Object.keys(i).length>0)if(e.target==="draft-2020-12")n.$defs=i;else n.definitions=i;try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dn(t,"input",e.processors),output:Dn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Ne(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Ne(o.element,r);if(o.type==="set")return Ne(o.valueType,r);if(o.type==="lazy")return Ne(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return Ne(o.innerType,r);if(o.type==="intersection")return Ne(o.left,r)||Ne(o.right,r);if(o.type==="record"||o.type==="map")return Ne(o.keyType,r)||Ne(o.valueType,r);if(o.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Ne(o.in,r)||Ne(o.out,r)}if(o.type==="object"){for(let n in o.shape)if(Ne(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Ne(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Ne(n,r))return!0;if(o.rest&&Ne(o.rest,r))return!0;return!1}return!1}var dm=(e,t={})=>(r)=>{let o=Fn({...r,processors:t});return oe(e,o),Hn(o,e),Vn(o,e)},Dn=(e,t,r={})=>(o)=>{let{libraryOptions:n,target:s}=o??{},i=Fn({...n??{},target:s,io:t,processors:r});return oe(e,i),Hn(i,e),Vn(i,e)};var l_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},bl=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:s,maximum:i,format:a,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof s==="number")n.minLength=s;if(typeof i==="number")n.maxLength=i;if(a){if(n.format=l_[a]??a,n.format==="")delete n.format;if(a==="time")delete n.format}if(u)n.contentEncoding=u;if(l&&l.size>0){let d=[...l];if(d.length===1)n.pattern=d[0].source;else if(d.length>1)n.allOf=[...d.map((m)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))]}},yl=(e,t,r,o)=>{let n=r,{minimum:s,maximum:i,format:a,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))n.type="integer";else n.type="number";let m=typeof d==="number"&&d>=(s??Number.NEGATIVE_INFINITY),f=typeof u==="number"&&u<=(i??Number.POSITIVE_INFINITY),S=t.target==="draft-04"||t.target==="openapi-3.0";if(m)if(S)n.minimum=d,n.exclusiveMinimum=!0;else n.exclusiveMinimum=d;else if(typeof s==="number")n.minimum=s;if(f)if(S)n.maximum=u,n.exclusiveMaximum=!0;else n.exclusiveMaximum=u;else if(typeof i==="number")n.maximum=i;if(typeof l==="number")n.multipleOf=l},vl=(e,t,r,o)=>{r.type="boolean"},hm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},mm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},zl=(e,t,r,o)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},wl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},fm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},Rl=(e,t,r,o)=>{r.not={}},xl=(e,t,r,o)=>{},Pl=(e,t,r,o)=>{},gm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},Tl=(e,t,r,o)=>{let n=e._zod.def,s=fa(n.entries);if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";r.enum=s},El=(e,t,r,o)=>{let n=e._zod.def,s=[];for(let i of n.values)if(i===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else s.push(Number(i));else s.push(i);if(s.length===0);else if(s.length===1){let i=s[0];if(r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[i];else r.const=i}else{if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";if(s.every((i)=>typeof i==="boolean"))r.type="boolean";if(s.every((i)=>i===null))r.type="null";r.enum=s}},Sm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},_m=(e,t,r,o)=>{let n=r,s=e._zod.pattern;if(!s)throw Error("Pattern not found in template literal");n.type="string",n.pattern=s.source},bm=(e,t,r,o)=>{let n=r,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:a,mime:l}=e._zod.bag;if(i!==void 0)s.minLength=i;if(a!==void 0)s.maxLength=a;if(l)if(l.length===1)s.contentMediaType=l[0],Object.assign(n,s);else Object.assign(n,s),n.anyOf=l.map((u)=>({contentMediaType:u}));else Object.assign(n,s)},ym=(e,t,r,o)=>{r.type="boolean"},kl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},vm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},$l=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},zm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},wm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},Cl=(e,t,r,o)=>{let n=r,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;if(typeof i==="number")n.minItems=i;if(typeof a==="number")n.maxItems=a;n.type="array",n.items=oe(s.element,t,{...o,path:[...o.path,"items"]})},Il=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="object",n.properties={};let i=s.shape;for(let u in i)n.properties[u]=oe(i[u],t,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(i)),l=new Set([...a].filter((u)=>{let d=s.shape[u]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(l.size>0)n.required=Array.from(l);if(s.catchall?._zod.def.type==="never")n.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")n.additionalProperties=!1}else if(s.catchall)n.additionalProperties=oe(s.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Ol=(e,t,r,o)=>{let n=e._zod.def,s=n.inclusive===!1,i=n.options.map((a,l)=>oe(a,t,{...o,path:[...o.path,s?"oneOf":"anyOf",l]}));if(s)r.oneOf=i;else r.anyOf=i},Nl=(e,t,r,o)=>{let n=e._zod.def,s=oe(n.left,t,{...o,path:[...o.path,"allOf",0]}),i=oe(n.right,t,{...o,path:[...o.path,"allOf",1]}),a=(u)=>("allOf"in u)&&Object.keys(u).length===1,l=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=l},Rm=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",l=s.items.map((f,S)=>oe(f,t,{...o,path:[...o.path,i,S]})),u=s.rest?oe(s.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(n.prefixItems=l,u)n.items=u}else if(t.target==="openapi-3.0"){if(n.items={anyOf:l},u)n.items.anyOf.push(u);if(n.minItems=l.length,!u)n.maxItems=l.length}else if(n.items=l,u)n.additionalItems=u;let{minimum:d,maximum:m}=e._zod.bag;if(typeof d==="number")n.minItems=d;if(typeof m==="number")n.maxItems=m},ql=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="object";let i=s.keyType,l=i._zod.bag?.patterns;if(s.mode==="loose"&&l&&l.size>0){let d=oe(s.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let m of l)n.patternProperties[m.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")n.propertyNames=oe(s.keyType,t,{...o,path:[...o.path,"propertyNames"]});n.additionalProperties=oe(s.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=i._zod.values;if(u){let d=[...u].filter((m)=>typeof m==="string"||typeof m==="number");if(d.length>0)n.required=d}},Al=(e,t,r,o)=>{let n=e._zod.def,s=oe(n.innerType,t,o),i=t.seen.get(e);if(t.target==="openapi-3.0")i.ref=n.innerType,r.nullable=!0;else r.anyOf=[s,{type:"null"}]},Ml=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},jl=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},Ll=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);if(s.ref=n.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(n.defaultValue))},Ul=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType;let i;try{i=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},Zl=(e,t,r,o)=>{let n=e._zod.def,s=n.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?n.out:n.in:n.out;oe(i,t,o);let a=t.seen.get(e);a.ref=i},Dl=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType,r.readOnly=!0},xm=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},$a=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},Fl=(e,t,r,o)=>{let n=e._zod.innerType;oe(n,t,o);let s=t.seen.get(e);s.ref=n},pm={string:bl,number:yl,boolean:vl,bigint:hm,symbol:mm,null:zl,undefined:wl,void:fm,never:Rl,any:xl,unknown:Pl,date:gm,enum:Tl,literal:El,nan:Sm,template_literal:_m,file:bm,success:ym,custom:kl,function:vm,transform:$l,map:zm,set:wm,array:Cl,object:Il,union:Ol,intersection:Nl,tuple:Rm,record:ql,nullable:Al,nonoptional:Ml,default:jl,prefault:Ll,catch:Ul,pipe:Zl,readonly:Dl,promise:xm,optional:$a,lazy:Fl};function Ca(e,t){if("_idmap"in e){let o=e,n=Fn({...t,processors:pm}),s={};for(let l of o._idmap.entries()){let[u,d]=l;oe(d,n)}let i={},a={registry:o,uri:t?.uri,defs:s};n.external=a;for(let l of o._idmap.entries()){let[u,d]=l;Hn(n,d),i[u]=Vn(n,d)}if(Object.keys(s).length>0){let l=n.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[l]:s}}return{schemas:i}}let r=Fn({...t,processors:pm});return oe(e,r),Hn(r,e),Vn(r,e)}var S_=_("ZodISODateTime",(e,t)=>{Up.init(e,t),ae.init(e,t)});function uo(e){return Kh(S_,e)}var __=_("ZodISODate",(e,t)=>{Zp.init(e,t),ae.init(e,t)});function Hl(e){return Gh(__,e)}var b_=_("ZodISOTime",(e,t)=>{Dp.init(e,t),ae.init(e,t)});function Pm(e){return Yh(b_,e)}var y_=_("ZodISODuration",(e,t)=>{Fp.init(e,t),ae.init(e,t)});function Tm(e){return Xh(y_,e)}var v_=(e,t)=>{ba.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>Jc(e,r)},flatten:{value:(r)=>Vc(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Nn,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Nn,2)}},isEmpty:{get(){return e.issues.length===0}}})};var Je=_("ZodError",v_,{Parent:Error});var km=ya(Je),$m=va(Je),Oa=An(Je),Cm=Mn(Je),Im=wd(Je),Om=Rd(Je),Nm=xd(Je),qm=Pd(Je),Am=Td(Je),Mm=Ed(Je),jm=kd(Je),Lm=$d(Je);var Um=new WeakMap;function Jn(e,t,r){let o=Object.getPrototypeOf(e),n=Um.get(o);if(!n)n=new Set,Um.set(o,n);if(n.has(t))return;n.add(t);for(let s in r){let i=r[s];Object.defineProperty(o,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var ne=_("ZodType",(e,t)=>(re.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dn(e,"input"),output:Dn(e,"output")}}),e.toJSONSchema=dm(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,o)=>km(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Oa(e,r,o),e.parseAsync=async(r,o)=>$m(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>Cm(e,r,o),e.spa=e.safeParseAsync,e.encode=(r,o)=>Im(e,r,o),e.decode=(r,o)=>Om(e,r,o),e.encodeAsync=async(r,o)=>Nm(e,r,o),e.decodeAsync=async(r,o)=>qm(e,r,o),e.safeEncode=(r,o)=>Am(e,r,o),e.safeDecode=(r,o)=>Mm(e,r,o),e.safeEncodeAsync=async(r,o)=>jm(e,r,o),e.safeDecodeAsync=async(r,o)=>Lm(e,r,o),Jn(e,"ZodType",{check(...r){let o=this.def;return this.clone(Wt(o,{checks:[...o.checks??[],...r.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,o){return rt(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(ub(r,o))},superRefine(r,o){return this.check(db(r,o))},overwrite(r){return this.check(Xt(r))},optional(){return j(this)},exactOptional(){return G_(this)},nullable(){return Hm(this)},nullish(){return j(Hm(this))},nonoptional(r){return rb(this,r)},array(){return g(this)},or(r){return T([this,r])},and(r){return $t(this,r)},transform(r){return Vm(this,ef(r))},default(r){return Q_(this,r)},prefault(r){return tb(this,r)},catch(r){return nb(this,r)},pipe(r){return Vm(this,r)},readonly(){return ab(this)},describe(r){let o=this.clone();return Yt.add(o,{description:r}),o},meta(...r){if(r.length===0)return Yt.get(this);let o=this.clone();return Yt.add(o,r[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return Yt.get(e)?.description},configurable:!0}),e)),Jm=_("_ZodString",(e,t)=>{Ra.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,s)=>bl(e,o,n,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Jn(e,"_ZodString",{regex(...o){return this.check(cl(...o))},includes(...o){return this.check(dl(...o))},startsWith(...o){return this.check(pl(...o))},endsWith(...o){return this.check(hl(...o))},min(...o){return this.check(co(...o))},max(...o){return this.check(Ea(...o))},length(...o){return this.check(ka(...o))},nonempty(...o){return this.check(co(1,...o))},lowercase(o){return this.check(ll(o))},uppercase(o){return this.check(ul(o))},trim(){return this.check(fl())},normalize(...o){return this.check(ml(...o))},toLowerCase(){return this.check(gl())},toUpperCase(){return this.check(Sl())},slugify(){return this.check(_l())}})}),Bm=_("ZodString",(e,t)=>{Ra.init(e,t),Jm.init(e,t),e.email=(r)=>e.check(sl(Wm,r)),e.url=(r)=>e.check(al(Gm,r)),e.jwt=(r)=>e.check(Wh(M_,r)),e.emoji=(r)=>e.check(Nh(w_,r)),e.guid=(r)=>e.check(il(Zm,r)),e.uuid=(r)=>e.check($h(Na,r)),e.uuidv4=(r)=>e.check(Ch(Na,r)),e.uuidv6=(r)=>e.check(Ih(Na,r)),e.uuidv7=(r)=>e.check(Oh(Na,r)),e.nanoid=(r)=>e.check(qh(R_,r)),e.guid=(r)=>e.check(il(Zm,r)),e.cuid=(r)=>e.check(Ah(x_,r)),e.cuid2=(r)=>e.check(Mh(P_,r)),e.ulid=(r)=>e.check(jh(T_,r)),e.base64=(r)=>e.check(Vh(N_,r)),e.base64url=(r)=>e.check(Jh(q_,r)),e.xid=(r)=>e.check(Lh(E_,r)),e.ksuid=(r)=>e.check(Uh(k_,r)),e.ipv4=(r)=>e.check(Zh($_,r)),e.ipv6=(r)=>e.check(Dh(C_,r)),e.cidrv4=(r)=>e.check(Fh(I_,r)),e.cidrv6=(r)=>e.check(Hh(O_,r)),e.e164=(r)=>e.check(Bh(A_,r)),e.datetime=(r)=>e.check(uo(r)),e.date=(r)=>e.check(Hl(r)),e.time=(r)=>e.check(Pm(r)),e.duration=(r)=>e.check(Tm(r))});function c(e){return kh(Bm,e)}var ae=_("ZodStringFormat",(e,t)=>{ie.init(e,t),Jm.init(e,t)}),Wm=_("ZodEmail",(e,t)=>{Cp.init(e,t),ae.init(e,t)});function Km(e){return sl(Wm,e)}var Zm=_("ZodGUID",(e,t)=>{kp.init(e,t),ae.init(e,t)});var Na=_("ZodUUID",(e,t)=>{$p.init(e,t),ae.init(e,t)});var Gm=_("ZodURL",(e,t)=>{Ip.init(e,t),ae.init(e,t)});function qa(e){return al(Gm,e)}var w_=_("ZodEmoji",(e,t)=>{Op.init(e,t),ae.init(e,t)});var R_=_("ZodNanoID",(e,t)=>{Np.init(e,t),ae.init(e,t)});var x_=_("ZodCUID",(e,t)=>{qp.init(e,t),ae.init(e,t)});var P_=_("ZodCUID2",(e,t)=>{Ap.init(e,t),ae.init(e,t)});var T_=_("ZodULID",(e,t)=>{Mp.init(e,t),ae.init(e,t)});var E_=_("ZodXID",(e,t)=>{jp.init(e,t),ae.init(e,t)});var k_=_("ZodKSUID",(e,t)=>{Lp.init(e,t),ae.init(e,t)});var $_=_("ZodIPv4",(e,t)=>{Hp.init(e,t),ae.init(e,t)});var C_=_("ZodIPv6",(e,t)=>{Vp.init(e,t),ae.init(e,t)});var I_=_("ZodCIDRv4",(e,t)=>{Jp.init(e,t),ae.init(e,t)});var O_=_("ZodCIDRv6",(e,t)=>{Bp.init(e,t),ae.init(e,t)});var N_=_("ZodBase64",(e,t)=>{Kp.init(e,t),ae.init(e,t)});var q_=_("ZodBase64URL",(e,t)=>{Gp.init(e,t),ae.init(e,t)});var A_=_("ZodE164",(e,t)=>{Yp.init(e,t),ae.init(e,t)});var M_=_("ZodJWT",(e,t)=>{Xp.init(e,t),ae.init(e,t)});var Aa=_("ZodNumber",(e,t)=>{el.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,s)=>yl(e,o,n,s),Jn(e,"ZodNumber",{gt(o,n){return this.check(Pa(o,n))},gte(o,n){return this.check(Zn(o,n))},min(o,n){return this.check(Zn(o,n))},lt(o,n){return this.check(xa(o,n))},lte(o,n){return this.check(Un(o,n))},max(o,n){return this.check(Un(o,n))},int(o){return this.check(Dm(o))},safe(o){return this.check(Dm(o))},positive(o){return this.check(Pa(0,o))},nonnegative(o){return this.check(Zn(0,o))},negative(o){return this.check(xa(0,o))},nonpositive(o){return this.check(Un(0,o))},multipleOf(o,n){return this.check(Ta(o,n))},step(o,n){return this.check(Ta(o,n))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??0.5),e.isFinite=!0,e.format=r.format??null});function z(e){return Qh(Aa,e)}var j_=_("ZodNumberFormat",(e,t)=>{Qp.init(e,t),Aa.init(e,t)});function Dm(e){return tm(j_,e)}var Ym=_("ZodBoolean",(e,t)=>{eh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vl(e,r,o,n)});function E(e){return rm(Ym,e)}var L_=_("ZodUndefined",(e,t)=>{th.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wl(e,r,o,n)});function Jl(e){return om(L_,e)}var U_=_("ZodNull",(e,t)=>{rh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zl(e,r,o,n)});function Rr(e){return nm(U_,e)}var Z_=_("ZodAny",(e,t)=>{oh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xl(e,r,o,n)});function Ma(){return sm(Z_)}var D_=_("ZodUnknown",(e,t)=>{nh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Pl(e,r,o,n)});function A(){return im(D_)}var F_=_("ZodNever",(e,t)=>{sh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rl(e,r,o,n)});function Bl(e){return am(F_,e)}var H_=_("ZodArray",(e,t)=>{ih.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cl(e,r,o,n),e.element=t.element,Jn(e,"ZodArray",{min(r,o){return this.check(co(r,o))},nonempty(r){return this.check(co(1,r))},max(r,o){return this.check(Ea(r,o))},length(r,o){return this.check(ka(r,o))},unwrap(){return this.element}})});function g(e,t){return cm(H_,e,t)}var Xm=_("ZodObject",(e,t)=>{lh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n),Q(e,"shape",()=>t.shape),Jn(e,"ZodObject",{keyof(){return K(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:A()})},loose(){return this.clone({...this._zod.def,catchall:A()})},strict(){return this.clone({...this._zod.def,catchall:Bl()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return KS(this,r)},safeExtend(r){return GS(this,r)},merge(r){return YS(this,r)},pick(r){return BS(this,r)},omit(r){return WS(this,r)},partial(...r){return XS(tf,this,r[0])},required(...r){return QS(rf,this,r[0])}})});function p(e,t){let r={type:"object",shape:e??{},...M(t)};return new Xm(r)}function F(e,t){return new Xm({type:"object",shape:e,catchall:A(),...M(t)})}var Qm=_("ZodUnion",(e,t)=>{tl.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n),e.options=t.options});function T(e,t){return new Qm({type:"union",options:e,...M(t)})}var V_=_("ZodDiscriminatedUnion",(e,t)=>{Qm.init(e,t),uh.init(e,t)});function po(e,t,r){return new V_({type:"union",options:t,discriminator:e,...M(r)})}var J_=_("ZodIntersection",(e,t)=>{dh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nl(e,r,o,n)});function $t(e,t){return new J_({type:"intersection",left:e,right:t})}var Fm=_("ZodRecord",(e,t)=>{ph.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function P(e,t,r){if(!t||!t._zod)return new Fm({type:"record",keyType:c(),valueType:e,...M(t)});return new Fm({type:"record",keyType:e,valueType:t,...M(r)})}var Vl=_("ZodEnum",(e,t)=>{hh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,s)=>Tl(e,o,n,s),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let s={};for(let i of o)if(r.has(i))s[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new Vl({...t,checks:[],...M(n),entries:s})},e.exclude=(o,n)=>{let s={...t.entries};for(let i of o)if(r.has(i))delete s[i];else throw Error(`Key ${i} not found in enum`);return new Vl({...t,checks:[],...M(n),entries:s})}});function K(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new Vl({type:"enum",entries:r,...M(t)})}var B_=_("ZodLiteral",(e,t)=>{mh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>El(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function h(e,t){return new B_({type:"literal",values:Array.isArray(e)?e:[e],...M(t)})}var W_=_("ZodTransform",(e,t)=>{fh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$l(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new On(e.constructor.name);r.addIssue=(s)=>{if(typeof s==="string")r.issues.push(wr(s,r.value,t));else{let i=s;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(wr(i))}};let n=t.transform(r.value,r);if(n instanceof Promise)return n.then((s)=>(r.value=s,r.fallback=!0,r));return r.value=n,r.fallback=!0,r}});function ef(e){return new W_({type:"transform",transform:e})}var tf=_("ZodOptional",(e,t)=>{rl.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$a(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function j(e){return new tf({type:"optional",innerType:e})}var K_=_("ZodExactOptional",(e,t)=>{gh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$a(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function G_(e){return new K_({type:"optional",innerType:e})}var Y_=_("ZodNullable",(e,t)=>{Sh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Hm(e){return new Y_({type:"nullable",innerType:e})}var X_=_("ZodDefault",(e,t)=>{_h.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Q_(e,t){return new X_({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Dc(t)}})}var eb=_("ZodPrefault",(e,t)=>{bh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function tb(e,t){return new eb({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Dc(t)}})}var rf=_("ZodNonOptional",(e,t)=>{yh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function rb(e,t){return new rf({type:"nonoptional",innerType:e,...M(t)})}var ob=_("ZodCatch",(e,t)=>{vh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function nb(e,t){return new ob({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var of=_("ZodPipe",(e,t)=>{ol.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n),e.in=t.in,e.out=t.out});function Vm(e,t){return new of({type:"pipe",in:e,out:t})}var sb=_("ZodPreprocess",(e,t)=>{of.init(e,t),zh.init(e,t)}),ib=_("ZodReadonly",(e,t)=>{wh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ab(e){return new ib({type:"readonly",innerType:e})}var cb=_("ZodLazy",(e,t)=>{Rh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function Bn(e){return new cb({type:"lazy",getter:e})}var lb=_("ZodCustom",(e,t)=>{xh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kl(e,r,o,n)});function ub(e,t={}){return lm(lb,e,t)}function db(e,t){return um(e,t)}function xr(e,t){return new sb({type:"pipe",in:ef(e),out:t})}var sf={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var nf;(function(e){})(nf||(nf={}));function pb(e){return em(Aa,e)}je(nl());var ho="2025-11-25";var ja=[ho,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],La="io.modelcontextprotocol/related-task",It="io.modelcontextprotocol/protocolVersion",mo="io.modelcontextprotocol/clientInfo",Ot="io.modelcontextprotocol/serverInfo",Pr="io.modelcontextprotocol/clientCapabilities",Wn="io.modelcontextprotocol/subscriptionId",fo="io.modelcontextprotocol/logLevel";var Tr="2.0";var Ct=Bn(()=>T([c(),z(),E(),Rr(),P(c(),Ct),g(Ct)])),le=P(c(),Ct),Ua=g(Ct),go=T([c(),z().int()]),So=c(),Kn=p({ttl:z().optional()}),Gn=p({taskId:c()}),_o=F({progressToken:go.optional(),[La]:Gn.optional()}),ye=p({_meta:_o.optional()}),er=ye.extend({task:Kn.optional()}),ue=p({method:c(),params:ye.loose().optional()}),Te=p({_meta:_o.optional()}),we=p({method:c(),params:Te.loose().optional()}),bo=F({get[Ot](){return _t.optional().catch(void 0)}}),de=F({_meta:bo.optional()}),nt=T([c(),z().int()]),yo=p({jsonrpc:h(Tr),id:nt,...ue.shape}).strict(),vo=p({jsonrpc:h(Tr),...we.shape}).strict(),Er=p({jsonrpc:h(Tr),id:nt,result:de}).strict(),kr=p({jsonrpc:h(Tr),id:nt.optional(),error:p({code:z().int(),message:c(),data:A().optional()})}).strict(),st=T([yo,vo,Er,kr]),Za=T([Er,kr]),tr=de.strict(),Yn=Te.extend({requestId:nt.optional(),reason:c().optional()}),zo=we.extend({method:h("notifications/cancelled"),params:Yn}),Xn=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),Nt=p({icons:g(Xn).optional()}),St=p({name:c(),title:c().optional()}),_t=St.extend({...St.shape,...Nt.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),mb=$t(p({applyDefaults:E().optional()}),le),fb=xr((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)&&Object.keys(e).length===0)return{form:{}};return e},$t(p({form:mb.optional(),url:le.optional()}),le.optional())),Da=F({list:le.optional(),cancel:le.optional(),requests:F({sampling:F({createMessage:le.optional()}).optional(),elicitation:F({create:le.optional()}).optional()}).optional()}),Fa=F({list:le.optional(),cancel:le.optional(),requests:F({tools:F({call:le.optional()}).optional()}).optional()}),Qn=p({experimental:P(c(),le).optional(),sampling:p({context:le.optional(),tools:le.optional()}).optional(),elicitation:fb.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:Da.optional(),extensions:P(c(),le).optional()}),es=ye.extend({protocolVersion:c(),capabilities:Qn,clientInfo:_t}),wo=ue.extend({method:h("initialize"),params:es}),Ro=p({experimental:P(c(),le).optional(),logging:le.optional(),completions:le.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:Fa.optional(),extensions:P(c(),le).optional()}),ts=de.extend({protocolVersion:c(),capabilities:Ro,serverInfo:_t,instructions:c().optional()}),xo=we.extend({method:h("notifications/initialized"),params:Te.optional()}),rs=ue.extend({method:h("server/discover"),params:ye.optional()}),rr=de.extend({supportedVersions:g(c()),capabilities:Ro,instructions:c().optional()}),Po=ue.extend({method:h("ping"),params:ye.optional()}),os=p({progress:z(),total:j(z()),message:j(c())}),ns=p({...Te.shape,...os.shape,progressToken:go}),To=we.extend({method:h("notifications/progress"),params:ns}),ss=ye.extend({cursor:So.optional()}),qt=ue.extend({params:ss.optional()}),At=de.extend({nextCursor:So.optional()}),Eo=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),ko=Eo.extend({text:c()}),Kl=c().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),$o=Eo.extend({blob:Kl}),Mt=K(["user","assistant"]),bt=p({audience:g(Mt).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),Co=p({...St.shape,...Nt.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:bt.optional(),_meta:j(F({}))}),is=p({...St.shape,...Nt.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:bt.optional(),_meta:j(F({}))}),as=qt.extend({method:h("resources/list")}),cs=At.extend({resources:g(Co)}),ls=qt.extend({method:h("resources/templates/list")}),us=At.extend({resourceTemplates:g(is)}),$r=ye.extend({uri:c()}),ds=$r,ps=ue.extend({method:h("resources/read"),params:ds}),hs=de.extend({contents:g(T([ko,$o]))}),ms=we.extend({method:h("notifications/resources/list_changed"),params:Te.optional()}),fs=$r,gs=ue.extend({method:h("resources/subscribe"),params:fs}),Ss=$r,_s=ue.extend({method:h("resources/unsubscribe"),params:Ss}),Io=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:g(c()).optional()}),bs=ye.extend({notifications:Io}),ys=ue.extend({method:h("subscriptions/listen"),params:bs}),vs=Te.extend({notifications:Io}),zs=we.extend({method:h("notifications/subscriptions/acknowledged"),params:vs}),ws=bo.extend({[Wn]:nt}),Rs=de.extend({_meta:ws}),xs=Te.extend({uri:c()}),Ps=we.extend({method:h("notifications/resources/updated"),params:xs}),Ts=p({name:c(),description:j(c()),required:j(E())}),Es=p({...St.shape,...Nt.shape,description:j(c()),arguments:j(g(Ts)),_meta:j(F({}))}),ks=qt.extend({method:h("prompts/list")}),$s=At.extend({prompts:g(Es)}),Cs=ye.extend({name:c(),arguments:P(c(),c()).optional()}),Is=ue.extend({method:h("prompts/get"),params:Cs}),Cr=p({type:h("text"),text:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Ir=p({type:h("image"),data:Kl,mimeType:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Or=p({type:h("audio"),data:Kl,mimeType:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Os=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),Nr=p({type:h("resource"),resource:T([ko,$o]),annotations:bt.optional(),_meta:P(c(),A()).optional()}),qr=Co.extend({type:h("resource_link")}),yt=T([Cr,Ir,Or,qr,Nr]),Ns=p({role:Mt,content:yt}),qs=de.extend({description:c().optional(),messages:g(Ns)}),As=we.extend({method:h("notifications/prompts/list_changed"),params:Te.optional()}),Ms=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),js=p({taskSupport:K(["required","optional","forbidden"]).optional()}),or=p({...St.shape,...Nt.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),Ct).optional(),required:g(c()).optional()}).catchall(A()),outputSchema:F({$schema:c().optional()}).optional(),annotations:Ms.optional(),execution:js.optional(),_meta:P(c(),A()).optional()}),Ls=qt.extend({method:h("tools/list")}),Us=At.extend({tools:g(or)}),nr=de.extend({content:g(yt).default([]),structuredContent:A().optional(),isError:E().optional()}),Ha=nr.or(de.extend({toolResult:A()})),Zs=er.extend({name:c(),arguments:P(c(),A()).optional()}),Ds=ue.extend({method:h("tools/call"),params:Zs}),Fs=we.extend({method:h("notifications/tools/list_changed"),params:Te.optional()}),Hs=p({autoRefresh:E().default(!0),debounceMs:z().int().nonnegative().default(300)}),Oo=K(["debug","info","notice","warning","error","critical","alert","emergency"]),Vs=ye.extend({level:Oo}),Js=ue.extend({method:h("logging/setLevel"),params:Vs}),Bs=Te.extend({level:Oo,logger:c().optional(),data:A()}),Ar=we.extend({method:h("notifications/message"),params:Bs}),Ws=p({name:c().optional()}),Ks=p({hints:g(Ws).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),Gs=p({mode:K(["auto","required","none"]).optional()}),Ys=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:g(yt),structuredContent:A().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),Xs=po("type",[Cr,Ir,Or]),Qt=po("type",[Cr,Ir,Or,Os,Ys]),Qs=p({role:Mt,content:T([Qt,g(Qt)]),_meta:P(c(),A()).optional()}),ei=er.extend({messages:g(Qs),modelPreferences:Ks.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:le.optional(),tools:g(or).optional(),toolChoice:Gs.optional()}),ti=ue.extend({method:h("sampling/createMessage"),params:ei}),ri=de.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Mt,content:Xs}),oi=de.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Mt,content:T([Qt,g(Qt)])}),No=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),Mr=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),jr=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),qo=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),Ao=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),Mo=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),ni=T([qo,Ao]),jo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),Lo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),si=T([jo,Lo]),ii=T([Mo,ni,si]),Uo=T([ii,No,Mr,jr]),Lr=er.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),Uo),required:g(c()).optional()}).catchall(A())}),ai=er.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),ci=T([Lr,ai]),li=ue.extend({method:h("elicitation/create"),params:ci}),ui=Te.extend({elicitationId:c()}),di=we.extend({method:h("notifications/elicitation/complete"),params:ui}),pi=de.extend({action:K(["accept","decline","cancel"]),content:xr((e)=>e===null?void 0:e,P(c(),T([c(),z(),E(),g(c())])).optional())}),hi=p({type:h("ref/resource"),uri:c()}),mi=p({type:h("ref/prompt"),name:c()}),fi=ye.extend({ref:T([mi,hi]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),gi=ue.extend({method:h("completion/complete"),params:fi}),Si=de.extend({completion:F({values:g(c()).max(100),total:j(z().int()),hasMore:j(E())})}),_i=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),bi=ue.extend({method:h("roots/list"),params:ye.optional()}),yi=de.extend({roots:g(_i)}),vi=we.extend({method:h("notifications/roots/list_changed"),params:Te.optional()}),Va=F({ttl:z().optional(),pollInterval:z().optional()}),zi=K(["working","input_required","completed","failed","cancelled"]),jt=p({taskId:c(),status:zi,ttl:T([z(),Rr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:j(z()),statusMessage:j(c())}),Ja=de.extend({task:jt}),wi=Te.merge(jt),Ba=we.extend({method:h("notifications/tasks/status"),params:wi}),Wa=ue.extend({method:h("tasks/get"),params:ye.extend({taskId:c()})}),Ka=de.merge(jt),Ga=ue.extend({method:h("tasks/result"),params:ye.extend({taskId:c()})}),Ya=de.loose(),Xa=qt.extend({method:h("tasks/list")}),Qa=At.extend({tasks:g(jt)}),ec=ue.extend({method:h("tasks/cancel"),params:ye.extend({taskId:c()})}),tc=de.merge(jt),rc=T([Po,wo,rs,gi,Js,Is,ks,as,ls,ps,gs,_s,ys,Ds,Ls]),oc=T([zo,To,xo,vi]),nc=T([tr,ri,oi,pi,yi]),sc=T([Po,ti,li,bi]),ic=T([zo,To,Ar,Ps,ms,Fs,As,zs,di]),ac=T([tr,ts,rr,Si,qs,$s,cs,us,hs,nr,Us,Rs]),be=qa().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:sf.custom,message:"URL must be parseable",fatal:!0}),Mc}).refine((e)=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Zo=F({resource:c().url(),authorization_servers:g(be).optional(),jwks_uri:c().url().optional(),scopes_supported:g(c()).optional(),bearer_methods_supported:g(c()).optional(),resource_signing_alg_values_supported:g(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:E().optional(),authorization_details_types_supported:g(c()).optional(),dpop_signing_alg_values_supported:g(c()).optional(),dpop_bound_access_tokens_required:E().optional()}),Ur=F({issuer:c(),authorization_endpoint:be,token_endpoint:be,registration_endpoint:be.optional(),scopes_supported:g(c()).optional(),response_types_supported:g(c()),response_modes_supported:g(c()).optional(),grant_types_supported:g(c()).optional(),token_endpoint_auth_methods_supported:g(c()).optional(),token_endpoint_auth_signing_alg_values_supported:g(c()).optional(),service_documentation:be.optional(),revocation_endpoint:be.optional(),revocation_endpoint_auth_methods_supported:g(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:g(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:g(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:g(c()).optional(),code_challenge_methods_supported:g(c()).optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0),dpop_signing_alg_values_supported:g(c()).optional()}),Ri=F({issuer:c(),authorization_endpoint:be,token_endpoint:be,userinfo_endpoint:be.optional(),jwks_uri:be,registration_endpoint:be.optional(),scopes_supported:g(c()).optional(),response_types_supported:g(c()),response_modes_supported:g(c()).optional(),grant_types_supported:g(c()).optional(),acr_values_supported:g(c()).optional(),subject_types_supported:g(c()),id_token_signing_alg_values_supported:g(c()),id_token_encryption_alg_values_supported:g(c()).optional(),id_token_encryption_enc_values_supported:g(c()).optional(),userinfo_signing_alg_values_supported:g(c()).optional(),userinfo_encryption_alg_values_supported:g(c()).optional(),userinfo_encryption_enc_values_supported:g(c()).optional(),request_object_signing_alg_values_supported:g(c()).optional(),request_object_encryption_alg_values_supported:g(c()).optional(),request_object_encryption_enc_values_supported:g(c()).optional(),token_endpoint_auth_methods_supported:g(c()).optional(),token_endpoint_auth_signing_alg_values_supported:g(c()).optional(),display_values_supported:g(c()).optional(),claim_types_supported:g(c()).optional(),claims_supported:g(c()).optional(),service_documentation:c().optional(),claims_locales_supported:g(c()).optional(),ui_locales_supported:g(c()).optional(),claims_parameter_supported:E().optional(),request_parameter_supported:E().optional(),request_uri_parameter_supported:E().optional(),require_request_uri_registration:E().optional(),op_policy_uri:be.optional(),op_tos_uri:be.optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0)}),Do=p({...Ri.shape,...Ur.pick({code_challenge_methods_supported:!0}).shape}),Fo=p({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:pb().optional(),scope:c().optional(),refresh_token:c().optional(),issuer:c().optional().catch(void 0)}).strip(),xi=p({issued_token_type:h("urn:ietf:params:oauth:token-type:id-jag"),access_token:c(),token_type:c().optional(),expires_in:z().optional(),scope:c().optional()}).strip(),Ho=p({error:c(),error_description:c().optional(),error_uri:c().optional()}),Wl=be.optional().or(h("").transform(()=>{return})),Pi=p({redirect_uris:g(be),token_endpoint_auth_method:c().optional(),grant_types:g(c()).optional(),response_types:g(c()).optional(),application_type:c().optional(),client_name:c().optional(),client_uri:be.optional(),logo_uri:Wl,scope:c().optional(),contacts:g(c()).optional(),tos_uri:Wl,policy_uri:c().optional(),jwks_uri:be.optional(),jwks:Ma().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Ti=p({client_id:c(),client_secret:c().optional(),client_id_issued_at:z().optional(),client_secret_expires_at:z().optional(),issuer:c().optional().catch(void 0)}).strip(),Vo=Pi.merge(Ti),cc=p({error:c(),error_description:c().optional()}).strip(),lc=p({token:c(),token_type_hint:c().optional()}).strip();var eu=Symbol.for("mcp.sdk.errorBrands");function Zr(e,t){let r=new Set,o=t;while(typeof o==="function"){let n=o.mcpBrand;if(Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof n==="string")r.add(n);o=Object.getPrototypeOf(o)}if(r.size===0)return;Object.defineProperty(e,eu,{value:r,enumerable:!1,configurable:!0})}function Be(e,t){try{if(typeof t==="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand==="string"&&Object.prototype.hasOwnProperty.call(t,eu)){let r=t[eu];if(r&&typeof r.has==="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var Ut=function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e}({}),Dr=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Be(this,t)}static isInstance(t){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,t)}constructor(t,r,o){super(r);this.code=t,this.errorUri=o,this.name="OAuthError",Zr(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};if(this.errorUri)t.error_uri=this.errorUri;return t}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}},O=function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e}({}),N=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e,t,r,o){super(t,o);this.code=e,this.data=r,this.name="SdkError",Zr(this,new.target)}},vt=class extends N{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,o){super(e,t,r,o);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function If(e){let t=typeof e==="string"?new URL(e):new URL(e.href);return t.hash="",t}function su(e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}function Of({requestedResource:e,configuredResource:t}){let r=typeof e==="string"?new URL(e):new URL(e.href),o=typeof t==="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin)return!1;if(r.pathname.length<o.pathname.length)return!1;let n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(s)}var Nf="2026-07-28",iu=[Nf];function Zt(e){return e>=Nf}function au(e){return e.filter((t)=>!Zt(t))}function Oi(e){return e.filter((t)=>Zt(t))}function qf(e){let t=e.structuredContent;if(t===void 0)return e;if(!(typeof t!=="object"||t===null||Array.isArray(t)))return e;if(e.content?.some((r)=>r.type==="text")??!1)return e;return{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}var Af=["task","inputRequests","requestState"];function gb(e){if(e===null||typeof e!=="object"||Array.isArray(e)||e.content!==void 0||Af.some((t)=>(t in e)))return e;return{...e,content:[]}}function Sb(){let e=Bn(()=>T([c(),z(),E(),Rr(),P(c(),e),g(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=p({ttl:z().optional()}),s=p({taskId:c()}),i=F({progressToken:r.optional(),"io.modelcontextprotocol/related-task":s.optional()}),a=p({_meta:i.optional()}),l=a.extend({task:n.optional()}),u=p({method:c(),params:a.loose().optional()}),d=p({_meta:i.optional()}),m=p({method:c(),params:d.loose().optional()}),f=F({_meta:i.optional()}),S=T([c(),z().int()]),b=f.strict(),y=d.extend({requestId:S.optional(),reason:c().optional()}),v=m.extend({method:h("notifications/cancelled"),params:y}),U=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),H=p({icons:g(U).optional()}),x=p({name:c(),title:c().optional()}),Z=x.extend({...x.shape,...H.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),R=$t(p({applyDefaults:E().optional()}),t),w=xr((Pe)=>{if(Pe&&typeof Pe==="object"&&!Array.isArray(Pe)&&Object.keys(Pe).length===0)return{form:{}};return Pe},$t(p({form:R.optional(),url:t.optional()}),t.optional())),D=F({list:t.optional(),cancel:t.optional(),requests:F({sampling:F({createMessage:t.optional()}).optional(),elicitation:F({create:t.optional()}).optional()}).optional()}),X=F({list:t.optional(),cancel:t.optional(),requests:F({tools:F({call:t.optional()}).optional()}).optional()}),Y=p({experimental:P(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:w.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:D.optional(),extensions:P(c(),t).optional()}),ce=a.extend({protocolVersion:c(),capabilities:Y,clientInfo:Z}),Ee=u.extend({method:h("initialize"),params:ce}),te=p({experimental:P(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:X.optional(),extensions:P(c(),t).optional()}),se=f.extend({protocolVersion:c(),capabilities:te,serverInfo:Z,instructions:c().optional()}),ve=m.extend({method:h("notifications/initialized"),params:d.optional()}),ke=u.extend({method:h("ping"),params:a.optional()}),ct=p({progress:z(),total:j(z()),message:j(c())}),qe=p({...d.shape,...ct.shape,progressToken:r}),We=m.extend({method:h("notifications/progress"),params:qe}),lt=a.extend({cursor:o.optional()}),Ze=u.extend({params:lt.optional()}),$e=f.extend({nextCursor:o.optional()}),Tt=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),Et=Tt.extend({text:c()}),ut=c().refine((Pe)=>{try{return atob(Pe),!0}catch{return!1}},{message:"Invalid Base64 string"}),Re=Tt.extend({blob:ut}),Ce=K(["user","assistant"]),Ie=p({audience:g(Ce).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),et=p({...x.shape,...H.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:Ie.optional(),_meta:j(F({}))}),lr=p({...x.shape,...H.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:Ie.optional(),_meta:j(F({}))}),De=Ze.extend({method:h("resources/list")}),Fe=$e.extend({resources:g(et)}),Ae=Ze.extend({method:h("resources/templates/list")}),Ke=$e.extend({resourceTemplates:g(lr)}),Ge=a.extend({uri:c()}),dt=Ge,pt=u.extend({method:h("resources/read"),params:dt}),Ht=f.extend({contents:g(T([Et,Re]))}),ht=m.extend({method:h("notifications/resources/list_changed"),params:d.optional()}),ur=Ge,C=u.extend({method:h("resources/subscribe"),params:ur}),mt=Ge,V=u.extend({method:h("resources/unsubscribe"),params:mt}),q=d.extend({uri:c()}),G=m.extend({method:h("notifications/resources/updated"),params:q}),I=p({name:c(),description:j(c()),required:j(E())}),k=p({...x.shape,...H.shape,description:j(c()),arguments:j(g(I)),_meta:j(F({}))}),B=Ze.extend({method:h("prompts/list")}),J=$e.extend({prompts:g(k)}),ge=a.extend({name:c(),arguments:P(c(),c()).optional()}),dr=u.extend({method:h("prompts/get"),params:ge}),ft=p({type:h("text"),text:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),pr=p({type:h("image"),data:ut,mimeType:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),hr=p({type:h("audio"),data:ut,mimeType:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),nn=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),Vt=p({type:h("resource"),resource:T([Et,Re]),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),sn=et.extend({type:h("resource_link")}),Ye=T([ft,pr,hr,sn,Vt]),Kr=p({role:Ce,content:Ye}),Gr=f.extend({description:c().optional(),messages:g(Kr)}),mr=m.extend({method:h("notifications/prompts/list_changed"),params:d.optional()}),an=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Yr=p({taskSupport:K(["required","optional","forbidden"]).optional()}),fr=p({...x.shape,...H.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:g(c()).optional()}).catchall(A()),outputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:g(c()).optional()}).catchall(A()).optional(),annotations:an.optional(),execution:Yr.optional(),_meta:P(c(),A()).optional()}),Xr=Ze.extend({method:h("tools/list")}),Qr=$e.extend({tools:g(fr)}),eo=f.extend({content:g(Ye),structuredContent:P(c(),A()).optional(),isError:E().optional()}),xe=l.extend({name:c(),arguments:P(c(),A()).optional()}),cn=u.extend({method:h("tools/call"),params:xe}),Gi=m.extend({method:h("notifications/tools/list_changed"),params:d.optional()}),to=K(["debug","info","notice","warning","error","critical","alert","emergency"]),ln=a.extend({level:to}),un=u.extend({method:h("logging/setLevel"),params:ln}),dn=d.extend({level:to,logger:c().optional(),data:A()}),pn=m.extend({method:h("notifications/message"),params:dn}),hn=p({name:c().optional()}),mn=p({hints:g(hn).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),fn=p({mode:K(["auto","required","none"]).optional()}),Yi=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:g(Ye),structuredContent:p({}).loose().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),gn=po("type",[ft,pr,hr]),Jt=po("type",[ft,pr,hr,nn,Yi]),Sn=p({role:Ce,content:T([Jt,g(Jt)]),_meta:P(c(),A()).optional()}),_n=l.extend({messages:g(Sn),modelPreferences:mn.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:t.optional(),tools:g(fr).optional(),toolChoice:fn.optional()}),bn=u.extend({method:h("sampling/createMessage"),params:_n}),yn=f.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Ce,content:gn}),vn=f.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Ce,content:T([Jt,g(Jt)])}),zn=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),wn=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),Rn=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),xn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),Pn=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),Tn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),En=T([xn,Pn]),gr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),Sr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),Xi=T([gr,Sr]),Qi=T([Tn,En,Xi]),He=T([Qi,zn,wn,Rn]),Ve=l.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),He),required:g(c()).optional()}).catchall(A())}),kn=l.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),tt=T([Ve,kn]),ea=u.extend({method:h("elicitation/create"),params:tt}),ta=d.extend({elicitationId:c()}),ra=m.extend({method:h("notifications/elicitation/complete"),params:ta}),oa=f.extend({action:K(["accept","decline","cancel"]),content:xr((Pe)=>Pe===null?void 0:Pe,P(c(),T([c(),z(),E(),g(c())])).optional())}),na=p({type:h("ref/resource"),uri:c()}),sa=p({type:h("ref/prompt"),name:c()}),ia=a.extend({ref:T([sa,na]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),$n=u.extend({method:h("completion/complete"),params:ia}),aa=f.extend({completion:F({values:g(c()).max(100),total:j(z().int()),hasMore:j(E())})}),ca=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),ro=u.extend({method:h("roots/list"),params:a.optional()}),Cn=f.extend({roots:g(ca)}),la=m.extend({method:h("notifications/roots/list_changed"),params:d.optional()}),ua=F({ttl:z().optional(),pollInterval:z().optional()}),In=K(["working","input_required","completed","failed","cancelled"]),Bt=p({taskId:c(),status:In,ttl:T([z(),Rr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:j(z()),statusMessage:j(c())}),Me=f.extend({task:Bt}),da=d.merge(Bt),_r=m.extend({method:h("notifications/tasks/status"),params:da}),oo=u.extend({method:h("tasks/get"),params:a.extend({taskId:c()})}),no=f.merge(Bt),so=u.extend({method:h("tasks/result"),params:a.extend({taskId:c()})}),Ac=f.loose(),Oe=Ze.extend({method:h("tasks/list")}),fe=$e.extend({tasks:g(Bt)}),br=u.extend({method:h("tasks/cancel"),params:a.extend({taskId:c()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:n,RelatedTaskMetadataSchema:s,RequestMetaSchema:i,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:l,RequestSchema:u,NotificationsParamsSchema:d,NotificationSchema:m,ResultSchema:f,RequestIdSchema:S,EmptyResultSchema:b,CancelledNotificationParamsSchema:y,CancelledNotificationSchema:v,IconSchema:U,IconsSchema:H,BaseMetadataSchema:x,ImplementationSchema:Z,ClientTasksCapabilitySchema:D,ServerTasksCapabilitySchema:X,ClientCapabilitiesSchema:Y,InitializeRequestParamsSchema:ce,InitializeRequestSchema:Ee,ServerCapabilitiesSchema:te,InitializeResultSchema:se,InitializedNotificationSchema:ve,PingRequestSchema:ke,ProgressSchema:ct,ProgressNotificationParamsSchema:qe,ProgressNotificationSchema:We,PaginatedRequestParamsSchema:lt,PaginatedRequestSchema:Ze,PaginatedResultSchema:$e,ResourceContentsSchema:Tt,TextResourceContentsSchema:Et,BlobResourceContentsSchema:Re,RoleSchema:Ce,AnnotationsSchema:Ie,ResourceSchema:et,ResourceTemplateSchema:lr,ListResourcesRequestSchema:De,ListResourcesResultSchema:Fe,ListResourceTemplatesRequestSchema:Ae,ListResourceTemplatesResultSchema:Ke,ResourceRequestParamsSchema:Ge,ReadResourceRequestParamsSchema:dt,ReadResourceRequestSchema:pt,ReadResourceResultSchema:Ht,ResourceListChangedNotificationSchema:ht,SubscribeRequestParamsSchema:ur,SubscribeRequestSchema:C,UnsubscribeRequestParamsSchema:mt,UnsubscribeRequestSchema:V,ResourceUpdatedNotificationParamsSchema:q,ResourceUpdatedNotificationSchema:G,PromptArgumentSchema:I,PromptSchema:k,ListPromptsRequestSchema:B,ListPromptsResultSchema:J,GetPromptRequestParamsSchema:ge,GetPromptRequestSchema:dr,TextContentSchema:ft,ImageContentSchema:pr,AudioContentSchema:hr,ToolUseContentSchema:nn,EmbeddedResourceSchema:Vt,ResourceLinkSchema:sn,ContentBlockSchema:Ye,PromptMessageSchema:Kr,GetPromptResultSchema:Gr,PromptListChangedNotificationSchema:mr,ToolAnnotationsSchema:an,ToolExecutionSchema:Yr,ToolSchema:fr,ListToolsRequestSchema:Xr,ListToolsResultSchema:Qr,CallToolResultSchema:eo,CallToolRequestParamsSchema:xe,CallToolRequestSchema:cn,ToolListChangedNotificationSchema:Gi,LoggingLevelSchema:to,SetLevelRequestParamsSchema:ln,SetLevelRequestSchema:un,LoggingMessageNotificationParamsSchema:dn,LoggingMessageNotificationSchema:pn,ModelHintSchema:hn,ModelPreferencesSchema:mn,ToolChoiceSchema:fn,ToolResultContentSchema:Yi,SamplingContentSchema:gn,SamplingMessageContentBlockSchema:Jt,SamplingMessageSchema:Sn,CreateMessageRequestParamsSchema:_n,CreateMessageRequestSchema:bn,CreateMessageResultSchema:yn,CreateMessageResultWithToolsSchema:vn,BooleanSchemaSchema:zn,StringSchemaSchema:wn,NumberSchemaSchema:Rn,UntitledSingleSelectEnumSchemaSchema:xn,TitledSingleSelectEnumSchemaSchema:Pn,LegacyTitledEnumSchemaSchema:Tn,SingleSelectEnumSchemaSchema:En,UntitledMultiSelectEnumSchemaSchema:gr,TitledMultiSelectEnumSchemaSchema:Sr,MultiSelectEnumSchemaSchema:Xi,EnumSchemaSchema:Qi,PrimitiveSchemaDefinitionSchema:He,ElicitRequestFormParamsSchema:Ve,ElicitRequestURLParamsSchema:kn,ElicitRequestParamsSchema:tt,ElicitRequestSchema:ea,ElicitationCompleteNotificationParamsSchema:ta,ElicitationCompleteNotificationSchema:ra,ElicitResultSchema:oa,ResourceTemplateReferenceSchema:na,PromptReferenceSchema:sa,CompleteRequestParamsSchema:ia,CompleteRequestSchema:$n,CompleteResultSchema:aa,RootSchema:ca,ListRootsRequestSchema:ro,ListRootsResultSchema:Cn,RootsListChangedNotificationSchema:la,TaskCreationParamsSchema:ua,TaskStatusSchema:In,TaskSchema:Bt,CreateTaskResultSchema:Me,TaskStatusNotificationParamsSchema:da,TaskStatusNotificationSchema:_r,GetTaskRequestSchema:oo,GetTaskResultSchema:no,GetTaskPayloadRequestSchema:so,GetTaskPayloadResultSchema:Ac,ListTasksRequestSchema:Oe,ListTasksResultSchema:fe,CancelTaskRequestSchema:br,CancelTaskResultSchema:f.merge(Bt),ClientRequestSchema:T([ke,Ee,$n,un,dr,B,De,Ae,pt,C,V,cn,Xr,oo,so,Oe,br]),ClientNotificationSchema:T([v,We,ve,la,_r]),ClientResultSchema:T([b,yn,vn,oa,Cn,no,fe,Me]),ServerRequestSchema:T([ke,bn,ea,ro,oo,so,Oe,br]),ServerNotificationSchema:T([v,We,pn,G,ht,Gi,mr,_r,ra]),ServerResultSchema:T([b,se,aa,Gr,J,Fe,Ke,Ht,eo,Qr,no,fe,Me]),CallToolResultWireSchema:A().superRefine((Pe,AS)=>{if(typeof Pe!=="object"||Pe===null||Array.isArray(Pe)||Pe.content!==void 0)return;for(let rd of Af)if(rd in Pe){AS.addIssue({code:"custom",message:`content is required when the body carries '${rd}' — another result family cannot default into an empty tools/call success`});return}}).transform(gb).pipe(eo)}}var _b;function Mf(){return _b??=Sb()}function jf(e){return e.type!=="object"}var bb=new Set(["const","enum","default","examples"]),yb=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function _f(e){return e!==void 0&&!(typeof e==="string"&&e.startsWith("#"))}function vb(e){let t=typeof e.$schema==="string"?e.$schema:void 0;if(_f(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=cd(e.$schema)&&e.$recursiveAnchor!==!0,o=(n,s)=>{if(Array.isArray(n))return n.map((l)=>o(l,!1));if(n===null||typeof n!=="object")return n;if(!s&&_f(n.$id))return n;let i={},a=!1;for(let[l,u]of Object.entries(n))if(s)i[l]=o(u,!1);else if((l==="$ref"||l==="$dynamicRef")&&typeof u==="string")i[l]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u;else if(l==="$recursiveRef"&&u==="#"&&r)a=!0;else if(bb.has(l))i[l]=u;else if(yb.has(l))i[l]=o(u,!0);else i[l]=o(u,!1);if(a)if("$ref"in i)i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:"#/properties/result"}];else i.$ref="#/properties/result";return i};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}var Lf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Uf={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},zb={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},uc;function cu(){if(uc)return uc;let e=Mf();return uc={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},uc}function Zf(e){return Object.prototype.hasOwnProperty.call(Lf,e)}function Df(e){return Object.prototype.hasOwnProperty.call(Uf,e)}function wb(e){return Object.prototype.hasOwnProperty.call(zb,e)}function Rb(e){return wb(e)?cu().resultSchemas[e]:void 0}function xb(e){return Zf(e)?cu().requestSchemas[e]:void 0}function Pb(e){return Df(e)?cu().notificationSchemas[e]:void 0}var kx=Object.keys(Lf),$x=Object.keys(Uf);function tu(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function dc(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var bf={ok:!1,reason:"not-in-era"};function yf(e){return tu(e)&&tu(e.outputSchema)&&jf(e.outputSchema)}function vf(e){return e}var lu={era:"2025-11-25",hasRequestMethod:Zf,hasNotificationMethod:Df,validateRequest:(e,t)=>dc(xb(e),t),validateResult:(e,t)=>dc(Rb(e),t),validateNotification:(e,t)=>dc(Pb(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>bf,validateInputResponse:()=>bf,samplingResultVariant:(e,t)=>{let r=Mf();return dc(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)},outboundEnvelope:(e)=>{return},validateEnvelopeMeta:(e)=>[],projectCallToolResult(e,t){let r=qf(e),o=r.structuredContent;if(o===void 0)return r;let n=typeof o!=="object"||o===null||Array.isArray(o),s=t!==void 0&&jf(t);if(!n&&!s)return r;return{...r,structuredContent:{result:o}}},decodeResult(e,t){if(tu(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:vf(r)}}return{kind:"complete",result:vf(t)}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;if(!Array.isArray(r)||!r.some((o)=>yf(o)))return t;return{...t,tools:r.map((o)=>yf(o)?{...o,outputSchema:vb(o.outputSchema)}:o)}},encodeErrorCode:(e)=>e===-32002?-32602:e,checkInboundEnvelope:(e)=>{return}};function Tb(){let e=Bn(()=>T([c(),z(),E(),Rr(),P(c(),e),g(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=T([c(),z().int()]),s=K(["user","assistant"]),i=K(["debug","info","notice","warning","error","critical","alert","emergency"]),a=c().refine((fe)=>{try{return atob(fe),!0}catch{return!1}},{message:"Invalid Base64 string"}),l=p({ttl:z().optional()}),u=p({taskId:c()}),d=F({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),m=p({_meta:d.optional()}),f=m.extend({task:l.optional()}),S=p({_meta:d.optional()}),b=p({method:c(),params:S.loose().optional()}),y=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),v=p({icons:g(y).optional()}),U=p({name:c(),title:c().optional()}),H=U.extend({...U.shape,...v.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),x=$t(p({applyDefaults:E().optional()}),t),Z=xr((fe)=>{if(fe&&typeof fe==="object"&&!Array.isArray(fe)&&Object.keys(fe).length===0)return{form:{}};return fe},$t(p({form:x.optional(),url:t.optional()}),t.optional())),R=F({list:t.optional(),cancel:t.optional(),requests:F({sampling:F({createMessage:t.optional()}).optional(),elicitation:F({create:t.optional()}).optional()}).optional()}),w=F({list:t.optional(),cancel:t.optional(),requests:F({tools:F({call:t.optional()}).optional()}).optional()}),D=p({experimental:P(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:Z.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:R.optional(),extensions:P(c(),t).optional()}),X=p({experimental:P(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:w.optional(),extensions:P(c(),t).optional()}),Y=p({progress:z(),total:j(z()),message:j(c())}),ce=p({...S.shape,...Y.shape,progressToken:r}),Ee=b.extend({method:h("notifications/progress"),params:ce}),te=S.extend({level:i,logger:c().optional(),data:A()}),se=b.extend({method:h("notifications/message"),params:te}),ve=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),ke=ve.extend({text:c()}),ct=ve.extend({blob:a}),qe=p({audience:g(s).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),We=p({...U.shape,...v.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:qe.optional(),_meta:j(F({}))}),lt=p({...U.shape,...v.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:qe.optional(),_meta:j(F({}))}),Ze=b.extend({method:h("notifications/resources/list_changed"),params:S.optional()}),$e=S.extend({uri:c()}),Tt=b.extend({method:h("notifications/resources/updated"),params:$e}),Et=p({name:c(),description:j(c()),required:j(E())}),ut=p({...U.shape,...v.shape,description:j(c()),arguments:j(g(Et)),_meta:j(F({}))}),Re=b.extend({method:h("notifications/prompts/list_changed"),params:S.optional()}),Ce=p({type:h("text"),text:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),Ie=p({type:h("image"),data:a,mimeType:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),et=p({type:h("audio"),data:a,mimeType:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),lr=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),De=p({type:h("resource"),resource:T([ke,ct]),annotations:qe.optional(),_meta:P(c(),A()).optional()}),Fe=We.extend({type:h("resource_link")}),Ae=T([Ce,Ie,et,Fe,De]),Ke=p({role:s,content:Ae}),Ge=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),dt=b.extend({method:h("notifications/tools/list_changed"),params:S.optional()}),pt=p({name:c().optional()}),Ht=p({hints:g(pt).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),ht=p({mode:K(["auto","required","none"]).optional()}),ur=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),C=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),mt=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),V=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),q=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),G=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),I=T([V,q]),k=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),B=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),J=T([k,B]),ge=T([G,I,J]),dr=T([ge,ur,C,mt]),ft=f.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),dr),required:g(c()).optional()}).catchall(A())}),pr=p({type:h("ref/resource"),uri:c()}),hr=p({type:h("ref/prompt"),name:c()}),nn=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),Vt=D.shape,sn=p({experimental:Vt.experimental,sampling:Vt.sampling,elicitation:Vt.elicitation,roots:Vt.roots,extensions:Vt.extensions}),Ye=X.shape,Kr=p({experimental:Ye.experimental,logging:Ye.logging,completions:Ye.completions,prompts:Ye.prompts,resources:Ye.resources,tools:Ye.tools,extensions:Ye.extensions}),Gr=F({progressToken:r.optional(),[It]:c(),[mo]:H.optional(),[Pr]:sn,[fo]:i.optional()}),mr=p({...U.shape,...v.shape,description:c().optional(),inputSchema:F({$schema:c().optional(),type:h("object")}),outputSchema:F({$schema:c().optional()}).optional(),annotations:Ge.optional(),_meta:P(c(),A()).optional()}),an=p({type:h("tool_result"),toolUseId:c(),content:g(Ae),structuredContent:A().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),Yr=T([Ce,Ie,et,lr,an]),fr=p({role:s,content:T([Yr,g(Yr)]),_meta:P(c(),A()).optional()}),Xr=c(),Qr=F({[Ot]:H.optional().catch(void 0)}),eo=Qr.optional();function xe(fe){return F({_meta:eo,resultType:Xr.default("complete"),...fe})}let cn=xe({}),Gi=xe({nextCursor:o.optional()}),to=xe({content:g(Ae),structuredContent:A().optional(),isError:E().optional()}),ln=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:g(mr),nextCursor:o.optional()}),un=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:g(ut),nextCursor:o.optional()}),dn=xe({description:c().optional(),messages:g(Ke)}),pn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:g(We),nextCursor:o.optional()}),hn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:g(lt),nextCursor:o.optional()}),mn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:g(T([ke,ct]))}),fn=xe({completion:p({values:g(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),Yi=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"])}),gn=xe({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:g(c()),capabilities:Kr,instructions:c().optional()}),Jt=p({messages:g(fr),modelPreferences:Ht.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:t.optional(),tools:g(mr).optional(),toolChoice:ht.optional()}),Sn=p({method:h("sampling/createMessage"),params:Jt}),_n=p({method:h("roots/list"),params:p({_meta:P(c(),A()).optional()}).optional()}),bn=p({...fr.shape,model:c(),stopReason:c().optional()}),yn=p({roots:g(nn)}),vn=p({action:K(["accept","decline","cancel"]),content:P(c(),T([c(),z(),E(),g(c())])).optional()}),zn=p({mode:h("url"),message:c(),url:c().url()}),wn=T([ft,zn]),Rn=p({method:h("elicitation/create"),params:wn}),xn=T([Sn,_n,Rn]),Pn=T([bn,yn,vn]),Tn=P(c(),xn),En=P(c(),Pn),gr=xe({inputRequests:Tn.optional(),requestState:c().optional()}),Sr={inputResponses:En.optional(),requestState:c().optional()},Xi=p({_meta:Gr,...Sr}),Qi=F({progressToken:r.optional()});function He(fe,br){return p({method:h(fe),params:p({_meta:Gr,...br})})}function Ve(fe,br){return p({method:h(fe),params:p({_meta:Qi.optional(),...br}).optional()})}let kn={name:c(),arguments:P(c(),A()).optional(),...Sr},tt={cursor:o.optional()},ea=He("tools/call",kn),ta=He("tools/list",tt),ra=He("prompts/list",tt),oa=He("prompts/get",{name:c(),arguments:P(c(),c()).optional(),...Sr}),na=He("resources/list",tt),sa=He("resources/templates/list",tt),ia=He("resources/read",{uri:c(),...Sr}),$n={ref:T([hr,pr]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()},aa=He("completion/complete",$n),ca=He("server/discover",{}),ro=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:g(c()).optional()}),Cn={notifications:ro},la=He("subscriptions/listen",Cn),ua=Qr.extend({"io.modelcontextprotocol/subscriptionId":n}),In=F({_meta:ua,resultType:Xr.default("complete")}),Bt={"tools/call":Ve("tools/call",kn),"tools/list":Ve("tools/list",tt),"prompts/get":Ve("prompts/get",{name:c(),arguments:P(c(),c()).optional()}),"prompts/list":Ve("prompts/list",tt),"resources/list":Ve("resources/list",tt),"resources/templates/list":Ve("resources/templates/list",tt),"resources/read":Ve("resources/read",{uri:c()}),"completion/complete":Ve("completion/complete",$n),"server/discover":Ve("server/discover",{}),"subscriptions/listen":Ve("subscriptions/listen",Cn)};function Me(fe){return F({_meta:eo,...fe})}let da={"tools/call":Me({content:g(Ae),structuredContent:A().optional(),isError:E().optional()}),"tools/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:g(mr),nextCursor:o.optional()}),"prompts/get":Me({description:c().optional(),messages:g(Ke)}),"prompts/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:g(ut),nextCursor:o.optional()}),"resources/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:g(We),nextCursor:o.optional()}),"resources/templates/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:g(lt),nextCursor:o.optional()}),"resources/read":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:g(T([ke,ct]))}),"completion/complete":Me({completion:p({values:g(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":Me({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:g(c()),capabilities:Kr,instructions:c().optional()}),"subscriptions/listen":Me({})},_r=F({"io.modelcontextprotocol/subscriptionId":n.optional()}),oo=p({method:h("notifications/subscriptions/acknowledged"),params:p({_meta:_r.optional(),notifications:ro})}),no=p({_meta:_r.optional(),requestId:n,reason:c().optional()}),so=p({method:h("notifications/cancelled"),params:no}),Ac={"notifications/cancelled":so,"notifications/progress":Ee,"notifications/message":se,"notifications/resources/updated":Tt,"notifications/resources/list_changed":Ze,"notifications/tools/list_changed":dt,"notifications/prompts/list_changed":Re,"notifications/subscriptions/acknowledged":oo},Oe=(fe)=>p({jsonrpc:h("2.0"),id:T([c(),z().int()]),result:fe}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:n,RoleSchema:s,LoggingLevelSchema:i,TaskMetadataSchema:l,RelatedTaskMetadataSchema:u,RequestMetaSchema:d,BaseRequestParamsSchema:m,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:S,NotificationSchema:b,IconSchema:y,IconsSchema:v,BaseMetadataSchema:U,ImplementationSchema:H,ClientTasksCapabilitySchema:R,ServerTasksCapabilitySchema:w,ClientCapabilitiesSchema:D,ServerCapabilitiesSchema:X,ProgressSchema:Y,ProgressNotificationParamsSchema:ce,ProgressNotificationSchema:Ee,LoggingMessageNotificationParamsSchema:te,LoggingMessageNotificationSchema:se,ResourceContentsSchema:ve,TextResourceContentsSchema:ke,BlobResourceContentsSchema:ct,AnnotationsSchema:qe,ResourceSchema:We,ResourceTemplateSchema:lt,ResourceListChangedNotificationSchema:Ze,ResourceUpdatedNotificationParamsSchema:$e,ResourceUpdatedNotificationSchema:Tt,PromptArgumentSchema:Et,PromptSchema:ut,PromptListChangedNotificationSchema:Re,TextContentSchema:Ce,ImageContentSchema:Ie,AudioContentSchema:et,ToolUseContentSchema:lr,EmbeddedResourceSchema:De,ResourceLinkSchema:Fe,ContentBlockSchema:Ae,PromptMessageSchema:Ke,ToolAnnotationsSchema:Ge,ToolListChangedNotificationSchema:dt,ModelHintSchema:pt,ModelPreferencesSchema:Ht,ToolChoiceSchema:ht,BooleanSchemaSchema:ur,StringSchemaSchema:C,NumberSchemaSchema:mt,UntitledSingleSelectEnumSchemaSchema:V,TitledSingleSelectEnumSchemaSchema:q,LegacyTitledEnumSchemaSchema:G,SingleSelectEnumSchemaSchema:I,UntitledMultiSelectEnumSchemaSchema:k,TitledMultiSelectEnumSchemaSchema:B,MultiSelectEnumSchemaSchema:J,EnumSchemaSchema:ge,PrimitiveSchemaDefinitionSchema:dr,ElicitRequestFormParamsSchema:ft,ResourceTemplateReferenceSchema:pr,PromptReferenceSchema:hr,RootSchema:nn,ClientCapabilities2026Schema:sn,ServerCapabilities2026Schema:Kr,RequestMetaEnvelopeSchema:Gr,ToolSchema:mr,ToolResultContentSchema:an,SamplingMessageContentBlockSchema:Yr,SamplingMessageSchema:fr,ResultTypeSchema:Xr,ResultMetaSchema:Qr,ResultSchema:cn,PaginatedResultSchema:Gi,CallToolResultSchema:to,ListToolsResultSchema:ln,ListPromptsResultSchema:un,GetPromptResultSchema:dn,ListResourcesResultSchema:pn,ListResourceTemplatesResultSchema:hn,ReadResourceResultSchema:mn,CompleteResultSchema:fn,CacheableResultSchema:Yi,DiscoverResultSchema:gn,CreateMessageRequestParamsSchema:Jt,CreateMessageRequestSchema:Sn,ListRootsRequestSchema:_n,CreateMessageResultSchema:bn,ListRootsResultSchema:yn,ElicitResultSchema:vn,ElicitRequestURLParamsSchema:zn,ElicitRequestParamsSchema:wn,ElicitRequestSchema:Rn,InputRequestSchema:xn,InputResponseSchema:Pn,InputRequestsSchema:Tn,InputResponsesSchema:En,InputRequiredResultSchema:gr,InputResponseRequestParamsSchema:Xi,CallToolRequestSchema:ea,ListToolsRequestSchema:ta,ListPromptsRequestSchema:ra,GetPromptRequestSchema:oa,ListResourcesRequestSchema:na,ListResourceTemplatesRequestSchema:sa,ReadResourceRequestSchema:ia,CompleteRequestSchema:aa,DiscoverRequestSchema:ca,SubscriptionFilterSchema:ro,SubscriptionsListenRequestSchema:la,SubscriptionsListenResultMetaSchema:ua,SubscriptionsListenResultSchema:In,dispatchRequestSchemas:Bt,dispatchResultSchemas:da,NotificationMetaSchema:_r,SubscriptionsAcknowledgedNotificationSchema:oo,CancelledNotificationParamsSchema:no,CancelledNotificationSchema:so,notificationSchemas2026:Ac,JSONRPCResultResponseSchema:Oe(cn),CallToolResultResponseSchema:Oe(T([to,gr])),ListToolsResultResponseSchema:Oe(ln),ListPromptsResultResponseSchema:Oe(un),GetPromptResultResponseSchema:Oe(T([dn,gr])),ListResourcesResultResponseSchema:Oe(pn),ListResourceTemplatesResultResponseSchema:Oe(hn),ReadResourceResultResponseSchema:Oe(T([mn,gr])),CompleteResultResponseSchema:Oe(fn),DiscoverResultResponseSchema:Oe(gn),SubscriptionsListenResultResponseSchema:Oe(In)}}var Eb;function sr(){return Eb??=Tb()}var kb=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function $b(e){return kb.includes(e)}var uu=Symbol("modelcontextprotocol.resultCacheHintFallback");function Cb(e){return e[uu]}function Ff(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function Hf(e){return e==="public"||e==="private"}var W=function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e}({}),ee=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Be(this,t)}static isInstance(t){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,t)}constructor(t,r,o){super(r);this.code=t,this.data=o,this.name="ProtocolError",Zr(this,new.target)}static fromError(t,r,o){if(t===W.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new Jf(n.elicitations,r)}if(t===W.UnsupportedProtocolVersion&&o){let n=o;if(Array.isArray(n.supported)&&typeof n.requested==="string")return new gc({supported:n.supported,requested:n.requested},r)}if(t===W.InvalidParams||t===W.ResourceNotFound){let n=o;if(typeof n?.uri==="string"&&(t===W.ResourceNotFound||Object.keys(n).length===1))return new Vf(n.uri,r)}if(t===W.MissingRequiredClientCapability&&o){let n=o;if(n.requiredCapabilities!==null&&typeof n.requiredCapabilities==="object"&&!Array.isArray(n.requiredCapabilities))return new Bf({requiredCapabilities:n.requiredCapabilities},r)}return new e(t,r,o)}},Vf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(W.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Jf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(W.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},gc=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(W.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Bf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(W.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},Ib=0,Ob="private",Nb=["tools/call","prompts/get","resources/read"];function qb(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete")return t;if(Nb.includes(e))return t;throw new ee(W.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function Ab(e,t){let r=Cb(t);if(t.resultType!=="complete"||!$b(e))return r===void 0?t:Zb(t);let o=t,n=Ff(o.ttlMs)?o.ttlMs:Lb(r),s=Hf(o.cacheScope)?o.cacheScope:Ub(r),i={...o,ttlMs:n,cacheScope:s};return delete i[uu],i}function Mb(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function jb(e,t){if(t===void 0)return e;let r=e._meta;if(r===void 0)return{...e,_meta:{[Ot]:t}};if(!Mb(r))return e;if(r[Ot]!==void 0)return e;return{...e,_meta:{...r,[Ot]:t}}}function Lb(e){return e!==void 0&&Ff(e.ttlMs)?e.ttlMs:Ib}function Ub(e){return e!==void 0&&Hf(e.cacheScope)?e.cacheScope:Ob}function Zb(e){let t={...e};return delete t[uu],t}var Db=["elicitation/create","sampling/createMessage","roots/list"],pc;function Wf(){if(pc)return pc;let e=sr();return pc={request:{"elicitation/create":p({method:h("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":p({method:h("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":p({method:h("roots/list"),params:F({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},pc}function Kf(e){return Db.includes(e)}function Gl(e){return Kf(e)?Wf().request[e]:void 0}function Fb(e){return Kf(e)?Wf().response[e]:void 0}var du={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Gf={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function Yf(e){return Object.prototype.hasOwnProperty.call(du,e)}function Xf(e){return Object.prototype.hasOwnProperty.call(Gf,e)}function Hb(e){return Object.prototype.hasOwnProperty.call(du,e)}function Vb(e){return Yf(e)?sr().dispatchRequestSchemas[e]:void 0}function Jb(e){return Hb(e)?sr().dispatchResultSchemas[e]:void 0}function Bb(e){return Xf(e)?sr().notificationSchemas2026[e]:void 0}var Cx=Object.keys(du),Ix=Object.keys(Gf);function $i(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Ei(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var Wb={ok:!1,reason:"not-in-era"},Kb=[It,Pr];function Gb(e,t){let r=t,o=!1,n=()=>{if(!o)r={...r},o=!0;return r},s=t.tools;if(e==="tools/list"&&Array.isArray(s)&&s.some((a)=>$i(a)&&("execution"in a)))n().tools=s.map((a)=>{if(!$i(a)||!("execution"in a))return a;let l={...a};return delete l.execution,l});let i=t.capabilities;if($i(i)&&"tasks"in i){let a={...i};delete a.tasks,n().capabilities=a}return r}var pu={era:"2026-07-28",hasRequestMethod:Yf,hasNotificationMethod:Xf,hasInputRequestMethod:(e)=>Gl(e)!==void 0,validateRequest:(e,t)=>Ei(Vb(e),t),validateResult:(e,t)=>Ei(Jb(e),t),validateNotification:(e,t)=>Ei(Bb(e),t),validateInputRequest:(e,t)=>Ei(Gl(e),t),validateInputResponse:(e,t)=>Ei(Fb(e),t),samplingResultVariant:()=>Wb,outboundEnvelope(e){return{[It]:e.protocolVersion,[mo]:e.clientInfo,[Pr]:e.clientCapabilities,...e.logLevel!==void 0&&{[fo]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of Kb)if(!(o in e))t.push({key:o,problem:"missing"});let r=sr().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let n=o.path.map(String),s=n.length>0?n.join("."):"_meta";if(n.length===1&&t.some((i)=>i.key===s&&i.problem==="missing"))continue;t.push({key:s,problem:o.message})}return t},projectCallToolResult:(e)=>qf(e),inputRequestSchema:Gl,decodeResult(e,t){if(!$i(t))return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!=="string")return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let i=t.inputRequests,a=$i(i)?i:{},l=t.requestState,u=t._meta===void 0?void 0:sr().ResultMetaSchema.safeParse(t._meta),d=u?.success?u.data:void 0;if(Object.keys(a).length===0&&typeof l!=="string")return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})};return{kind:"input_required",inputRequests:a,...typeof l==="string"&&{requestState:l},...d!==void 0&&{_meta:d}}}if(r!=="complete")return{kind:"invalid",error:new N(O.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=Yb(),n=Object.hasOwn(o,e)?o[e]:void 0;if(n!==void 0){let i=n.safeParse(t);if(!i.success)return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: ${i.error}`,{method:e})}}let s={...t};return delete s.resultType,{kind:"complete",result:s}},encodeResult(e,t,r){return jb(Ab(e,qb(e,Gb(e,t))),r)},encodeErrorCode:(e)=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=sr().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map((r)=>r.message).join("; ")}`}},hc;function Yb(){if(hc)return hc;let e=sr();return hc={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},hc}var Sc="2026-07-28";function Lt(e){return e!==void 0&&Zt(e)?pu:lu}function zf(e){if(e.revision!==void 0)return Lt(e.revision).era;return e.era==="modern"?pu.era:lu.era}function Yl(e){return Qf.some((t)=>t.hasRequestMethod(e))}function Xl(e){return Qf.some((t)=>t.hasNotificationMethod(e))}function wf(e){return e==="tasks/get"||e==="tasks/cancel"}var Qf=[lu,pu],Xb=sd({AnnotationsSchema:()=>bt,AudioContentSchema:()=>Or,BaseMetadataSchema:()=>St,BaseRequestParamsSchema:()=>ye,BlobResourceContentsSchema:()=>$o,BooleanSchemaSchema:()=>No,CallToolRequestParamsSchema:()=>Zs,CallToolRequestSchema:()=>Ds,CallToolResultSchema:()=>nr,CancelTaskRequestSchema:()=>ec,CancelTaskResultSchema:()=>tc,CancelledNotificationParamsSchema:()=>Yn,CancelledNotificationSchema:()=>zo,ClientCapabilitiesSchema:()=>Qn,ClientNotificationSchema:()=>oc,ClientRequestSchema:()=>rc,ClientResultSchema:()=>nc,ClientTasksCapabilitySchema:()=>Da,CompatibilityCallToolResultSchema:()=>Ha,CompleteRequestParamsSchema:()=>fi,CompleteRequestSchema:()=>gi,CompleteResultSchema:()=>Si,ContentBlockSchema:()=>yt,CreateMessageRequestParamsSchema:()=>ei,CreateMessageRequestSchema:()=>ti,CreateMessageResultSchema:()=>ri,CreateMessageResultWithToolsSchema:()=>oi,CreateTaskResultSchema:()=>Ja,CursorSchema:()=>So,DiscoverRequestSchema:()=>rs,DiscoverResultSchema:()=>rr,ElicitRequestFormParamsSchema:()=>Lr,ElicitRequestParamsSchema:()=>ci,ElicitRequestSchema:()=>li,ElicitRequestURLParamsSchema:()=>ai,ElicitResultSchema:()=>pi,ElicitationCompleteNotificationParamsSchema:()=>ui,ElicitationCompleteNotificationSchema:()=>di,EmbeddedResourceSchema:()=>Nr,EmptyResultSchema:()=>tr,EnumSchemaSchema:()=>ii,GetPromptRequestParamsSchema:()=>Cs,GetPromptRequestSchema:()=>Is,GetPromptResultSchema:()=>qs,GetTaskPayloadRequestSchema:()=>Ga,GetTaskPayloadResultSchema:()=>Ya,GetTaskRequestSchema:()=>Wa,GetTaskResultSchema:()=>Ka,IconSchema:()=>Xn,IconsSchema:()=>Nt,ImageContentSchema:()=>Ir,ImplementationSchema:()=>_t,InitializeRequestParamsSchema:()=>es,InitializeRequestSchema:()=>wo,InitializeResultSchema:()=>ts,InitializedNotificationSchema:()=>xo,JSONArraySchema:()=>Ua,JSONObjectSchema:()=>le,JSONRPCErrorResponseSchema:()=>kr,JSONRPCMessageSchema:()=>st,JSONRPCNotificationSchema:()=>vo,JSONRPCRequestSchema:()=>yo,JSONRPCResponseSchema:()=>Za,JSONRPCResultResponseSchema:()=>Er,JSONValueSchema:()=>Ct,LegacyTitledEnumSchemaSchema:()=>Mo,ListChangedOptionsBaseSchema:()=>Hs,ListPromptsRequestSchema:()=>ks,ListPromptsResultSchema:()=>$s,ListResourceTemplatesRequestSchema:()=>ls,ListResourceTemplatesResultSchema:()=>us,ListResourcesRequestSchema:()=>as,ListResourcesResultSchema:()=>cs,ListRootsRequestSchema:()=>bi,ListRootsResultSchema:()=>yi,ListTasksRequestSchema:()=>Xa,ListTasksResultSchema:()=>Qa,ListToolsRequestSchema:()=>Ls,ListToolsResultSchema:()=>Us,LoggingLevelSchema:()=>Oo,LoggingMessageNotificationParamsSchema:()=>Bs,LoggingMessageNotificationSchema:()=>Ar,ModelHintSchema:()=>Ws,ModelPreferencesSchema:()=>Ks,MultiSelectEnumSchemaSchema:()=>si,NotificationSchema:()=>we,NotificationsParamsSchema:()=>Te,NumberSchemaSchema:()=>jr,PaginatedRequestParamsSchema:()=>ss,PaginatedRequestSchema:()=>qt,PaginatedResultSchema:()=>At,PingRequestSchema:()=>Po,PrimitiveSchemaDefinitionSchema:()=>Uo,ProgressNotificationParamsSchema:()=>ns,ProgressNotificationSchema:()=>To,ProgressSchema:()=>os,ProgressTokenSchema:()=>go,PromptArgumentSchema:()=>Ts,PromptListChangedNotificationSchema:()=>As,PromptMessageSchema:()=>Ns,PromptReferenceSchema:()=>mi,PromptSchema:()=>Es,ReadResourceRequestParamsSchema:()=>ds,ReadResourceRequestSchema:()=>ps,ReadResourceResultSchema:()=>hs,RelatedTaskMetadataSchema:()=>Gn,RequestIdSchema:()=>nt,RequestMetaSchema:()=>_o,RequestSchema:()=>ue,ResourceContentsSchema:()=>Eo,ResourceLinkSchema:()=>qr,ResourceListChangedNotificationSchema:()=>ms,ResourceRequestParamsSchema:()=>$r,ResourceSchema:()=>Co,ResourceTemplateReferenceSchema:()=>hi,ResourceTemplateSchema:()=>is,ResourceUpdatedNotificationParamsSchema:()=>xs,ResourceUpdatedNotificationSchema:()=>Ps,ResultMetaObjectSchema:()=>bo,ResultSchema:()=>de,RoleSchema:()=>Mt,RootSchema:()=>_i,RootsListChangedNotificationSchema:()=>vi,SamplingContentSchema:()=>Xs,SamplingMessageContentBlockSchema:()=>Qt,SamplingMessageSchema:()=>Qs,ServerCapabilitiesSchema:()=>Ro,ServerNotificationSchema:()=>ic,ServerRequestSchema:()=>sc,ServerResultSchema:()=>ac,ServerTasksCapabilitySchema:()=>Fa,SetLevelRequestParamsSchema:()=>Vs,SetLevelRequestSchema:()=>Js,SingleSelectEnumSchemaSchema:()=>ni,StringSchemaSchema:()=>Mr,SubscribeRequestParamsSchema:()=>fs,SubscribeRequestSchema:()=>gs,SubscriptionFilterSchema:()=>Io,SubscriptionsAcknowledgedNotificationParamsSchema:()=>vs,SubscriptionsAcknowledgedNotificationSchema:()=>zs,SubscriptionsListenRequestParamsSchema:()=>bs,SubscriptionsListenRequestSchema:()=>ys,SubscriptionsListenResultMetaSchema:()=>ws,SubscriptionsListenResultSchema:()=>Rs,TaskAugmentedRequestParamsSchema:()=>er,TaskCreationParamsSchema:()=>Va,TaskMetadataSchema:()=>Kn,TaskSchema:()=>jt,TaskStatusNotificationParamsSchema:()=>wi,TaskStatusNotificationSchema:()=>Ba,TaskStatusSchema:()=>zi,TextContentSchema:()=>Cr,TextResourceContentsSchema:()=>ko,TitledMultiSelectEnumSchemaSchema:()=>Lo,TitledSingleSelectEnumSchemaSchema:()=>Ao,ToolAnnotationsSchema:()=>Ms,ToolChoiceSchema:()=>Gs,ToolExecutionSchema:()=>js,ToolListChangedNotificationSchema:()=>Fs,ToolResultContentSchema:()=>Ys,ToolSchema:()=>or,ToolUseContentSchema:()=>Os,UnsubscribeRequestParamsSchema:()=>Ss,UnsubscribeRequestSchema:()=>_s,UntitledMultiSelectEnumSchemaSchema:()=>jo,UntitledSingleSelectEnumSchemaSchema:()=>qo});var Fr=(e)=>yo.safeParse(e).success,eg=(e)=>vo.safeParse(e).success,Bo=(e)=>Er.safeParse(e).success,Wo=(e)=>kr.safeParse(e).success;var tg=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var hu=(e)=>wo.safeParse(e).success,rg=(e)=>xo.safeParse(e).success;var Qb="Mcp-Param-",Rf="x-mcp-header",ey=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,ty=new Set(["string","integer","boolean","number"]);function mu(e){let t=[],r=new Map,o=(s,i,a)=>{if(s===null||typeof s!=="object")return;let l=s;if(Rf in l){if(!a||i.length===0)return`${mc(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let d=l[Rf];if(typeof d!=="string"||d.length===0)return`${mc(i)}: x-mcp-header MUST be a non-empty string`;if(!ey.test(d))return`${mc(i)}: x-mcp-header '${d}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let m=typeof l.type==="string"?l.type:void 0;if(m===void 0||!ty.has(m))return`${mc(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${m??"<none>"}`;let f=d.toLowerCase(),S=r.get(f);if(S!==void 0)return`x-mcp-header '${d}' is not case-insensitively unique (also declared as '${S}')`;r.set(f,d),t.push({path:i,headerName:d,type:m})}let u=l.properties;if(u!==null&&typeof u==="object")for(let[d,m]of Object.entries(u)){let f=o(m,[...i,d],a);if(f!==void 0)return f}for(let d of ry){let m=l[d];if(m===void 0)continue;let f=Array.isArray(m)?m:m!==null&&typeof m==="object"&&oy.has(d)?Object.values(m):[m];for(let S of f){let b=o(S,[...i,`<${d}>`],!1);if(b!==void 0)return b}}},n=o(e,[],!0);return n===void 0?{valid:!0,declarations:t}:{valid:!1,reason:n}}var ry=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],oy=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function mc(e){return e.length===0?"<root>":e.join(".")}var og="=?base64?",ng="?=";function ny(e){if(typeof e==="string")return e;if(typeof e==="boolean")return e?"true":"false";if(typeof e==="number"){if(!Number.isFinite(e))return;if(Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}function sy(e){if(e.length===0)return!0;if(e.startsWith(og)&&e.endsWith(ng))return!0;if(e!==e.trim())return!0;for(let t=0;t<e.length;t++){let r=e.codePointAt(t);if(r===9||r>=32&&r<=126)continue;return!0}return!1}function iy(e){let t=new TextEncoder().encode(e),r="";for(let o of t)r+=String.fromCodePoint(o);return btoa(r)}function fu(e){return sy(e)?`${og}${iy(e)}${ng}`:e}function ay(e,t){let r=e;for(let o of t){if(r===null||typeof r!=="object")return;r=r[o]}return r}function sg(e,t){let r={};for(let o of e){let n=ay(t,o.path);if(n===void 0||n===null)continue;let s=ny(n);if(s===void 0)continue;r[`${Qb}${o.headerName}`]=fu(s)}return r}var Jo=-32020,Ox=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32000],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[W.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Jo,W.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[W.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[W.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[W.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Jo],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half — including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[W.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Jo],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],Nx={[W.ParseError]:400,[W.InvalidRequest]:400,[W.MethodNotFound]:404,[W.UnsupportedProtocolVersion]:400,[W.MissingRequiredClientCapability]:400,[Jo]:400},xf={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function ig(e,t){let r=Object.hasOwn(xf,e)?xf[e]:void 0;if(r===void 0)return;let o=cy(t)?t[r]:void 0;return{field:r,value:typeof o==="string"?o:void 0}}function cy(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function _c(e,t){return Oa(e,t)}function ki(e){return new Set(e.flatMap((t)=>Object.keys(t.shape)))}function ru(e){if(e==null)return!1;let t=typeof e;if(t!=="object"&&t!=="function")return!1;if(!("~standard"in e))return!1;return typeof e["~standard"]?.validate==="function"}var Pf=!1,ou="draft-2020-12";function ly(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:ou});else if(r.vendor==="zod"){if(!("_zod"in e))throw Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");if(!Pf)Pf=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.");o=Ca(e,{target:ou,io:t})}else throw Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output"){if(o.type!==void 0)return o;return ag(o)?{type:"object",...o}:o}if(o.type!==void 0&&o.type!=="object")throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}function ag(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every((o)=>o!==null&&typeof o==="object"&&(o.type==="object"||ag(o)))}return!1}function uy(e){if(!e.path?.length)return e.message;return`${e.path.map((t)=>String(typeof t==="object"?t.key:t)).join(".")}: ${e.message}`}async function Ql(e,t){let r=await e["~standard"].validate(t);if(r.issues&&r.issues.length>0)return{success:!1,error:r.issues.map((o)=>uy(o)).join(", ")};return{success:!0,data:r.value}}function dy(e){let t=Ca(e,{target:ou,io:"input"});return typeof t.pattern==="string"?t.pattern:void 0}var py=/\\\.\\d\{(\d+)\}/;function hy(e){let t=py.exec(e),r=[void 0,-1,0];if(t)r.push(Number(t[1]));return[!1,!0].flatMap((o)=>[!1,!0].flatMap((n)=>r.map((s)=>uo({local:o,offset:n,precision:s}))))}function my(e,t){let r;switch(e){case"email":r=[Km()];break;case"uri":r=[qa()];break;case"date":r=[Hl()];break;case"date-time":r=hy(t);break}return new Set(r.map((o)=>dy(o)).filter((o)=>o!==void 0))}function fy(e,t,r){if(r!=="zod")return!0;return my(e,t).has(t)}function Ii(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function gy(e){try{return ly(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new ee(W.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}var Sy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function gu(e){return Sy.has(e)||e.startsWith("x-")}var _y=new Set(["$schema",...Object.keys(Lr.shape.requestedSchema.shape)]),Tf={string:ki([Mr,qo,Ao,Mo]),number:ki([jr]),integer:ki([jr]),boolean:ki([No]),array:ki([jo,Lo])},by=new Set(Mr.shape.format.unwrap().options);function yy(e,t,r,o){if(!Ii(e))return e;let n=typeof e.type==="string"&&Object.hasOwn(Tf,e.type)?Tf[e.type]:void 0;if(n===void 0)return e;let s={};for(let[i,a]of Object.entries(e))if(n.has(i)||gu(i))s[i]=a;else if(i==="pattern"&&e.type==="string"&&typeof e.format==="string"){if(!by.has(e.format))s[i]=a;else if(typeof a!=="string"||!fy(e.format,a,r))o.push(`${t}.${i}`)}else o.push(`${t}.${i}`);return s}function vy(e,t){let r={},o=[];for(let[n,s]of Object.entries(e))if(n==="properties"&&Ii(s))r[n]=Object.fromEntries(Object.entries(s).map(([i,a])=>[i,yy(a,`properties.${i}`,t,o)]));else if(_y.has(n))r[n]=s;else if(!gu(n))o.push(n);if(o.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}function zy(e,t){if(!Ii(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!_c(Uo,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}function nu(e,t,r=""){if(Array.isArray(e)&&Array.isArray(t))return e.flatMap((o,n)=>nu(o,t[n],`${r}[${n}]`));if(!Ii(e)||!Ii(t))return[];return Object.entries(e).flatMap(([o,n])=>{let s=r?`${r}.${o}`:o;if(!Object.prototype.hasOwnProperty.call(t,o))return gu(o)?[]:[s];return nu(n,t[o],s)})}function wy(e){if(!ru(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=vy(gy(e.requestedSchema),t),o=_c(Lr.shape.requestedSchema,r);if(!o.success)throw new ee(W.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${zy(r,o.error.message)}`);let n=nu(r,o.data);if(n.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);let s=(o.data.required??[]).filter((i)=>!Object.prototype.hasOwnProperty.call(o.data.properties,i));if(s.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function Ry(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState==="string";if(!t&&!r)throw TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}var qx=Object.assign(Ry,{elicit(e){try{return{method:"elicitation/create",params:wy(e)}}catch(t){throw t instanceof ee?TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var xy=!0,Py=10,Ty=250;function cg(e){return{autoFulfill:e?.autoFulfill??xy,maxRounds:e?.maxRounds??Py}}function Ey(e,t,r){let o=t!==void 0&&Object.keys(t).length>0;if(!o&&r===void 0)return e;return{...e,...o&&{inputResponses:t},...r!==void 0&&{requestState:r}}}function ky(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function $y(e,t){return new Promise((r,o)=>{if(t?.aborted){o(t.reason instanceof N?t.reason:new N(O.RequestTimeout,String(t.reason)));return}let n=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),s=()=>{clearTimeout(n),o(t?.reason instanceof N?t.reason:new N(O.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",s,{once:!0})})}function Cy(e){let t=new AbortController,r=()=>t.abort(e?.reason);if(e?.addEventListener("abort",r,{once:!0}),e?.aborted)t.abort(e.reason);return{signal:t.signal,abort:(o)=>t.abort(o),dispose:()=>e?.removeEventListener("abort",r)}}async function Iy(e){let{config:t,method:r,originalParams:o,requestOptions:n,hooks:s,signal:i}=e,a=e.flowStartedAt??Date.now(),l=e.firstPayload,u=0;while(!0){if(u+=1,u>t.maxRounds)throw new N(O.InputRequiredRoundsExceeded,ky(r,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:l.inputRequests,...l.requestState!==void 0&&{requestState:l.requestState}}});n.onprogress?.({progress:u,message:`Fulfilling input required by '${r}' (round ${u})`});let d=Object.entries(l.inputRequests??{}),m;if(d.length>0){let b=Cy(i);try{let y=await Promise.all(d.map(async([v,U])=>{try{return[v,await s.dispatchInputRequest(v,U,b.signal)]}catch(H){throw b.abort(H),H}}));m=Object.fromEntries(y)}finally{b.dispose()}}else await $y(Ty,i);let f={...n.timeout!==void 0&&{timeout:n.timeout}};if(n.maxTotalTimeout!==void 0){let b=Date.now()-a,y=n.maxTotalTimeout-b;if(y<=0)throw new N(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:b});f.maxTotalTimeout=y}let S=await s.retry(Ey(o,m,l.requestState),f);if(tg(S)){l={inputRequests:S.inputRequests??{},...S.requestState!==void 0&&{requestState:S.requestState}};continue}return S}}var Oy=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],Ny={IdJagTokenExchangeResponseSchema:xi,OAuthClientInformationFullSchema:Vo,OAuthClientInformationSchema:Ti,OAuthClientMetadataSchema:Pi,OAuthClientRegistrationErrorSchema:cc,OAuthErrorResponseSchema:Ho,OAuthMetadataSchema:Ur,OAuthProtectedResourceMetadataSchema:Zo,OAuthTokenRevocationRequestSchema:lc,OAuthTokensSchema:Fo,OpenIdProviderDiscoveryMetadataSchema:Do,OpenIdProviderMetadataSchema:Ri},lg={},ug={};function dg(e,t){let r=e.slice(0,-6);lg[r]=t,ug[r]=(o)=>t.safeParse(o).success}for(let e of Oy)dg(e,Xb[e]);for(let[e,t]of Object.entries(Ny))dg(e,t);var qy=Object.freeze(lg),pg=Object.freeze(ug);function Ay(e){switch(e){case"initialize":case"notifications/initialized":return Lt(void 0);case"server/discover":return Lt(Sc);default:return}}var bc=60000,My=[It,mo,Pr,fo],jy=["inputResponses","requestState"];function Ef(e,t){let r=e.params;if(!Ci(r))return{message:e,lifted:{}};let o=r._meta,n=Ci(o)?My.filter((l)=>(l in o)):[],s=t==="request"?jy.filter((l)=>(l in r)):[];if(n.length===0&&s.length===0)return{message:e,lifted:{}};let i={},a={...r};if(n.length>0&&Ci(o)){let l={},u={...o};for(let d of n)l[d]=o[d],delete u[d];if(i.envelope=l,Object.keys(u).length>0)a._meta=u;else delete a._meta}for(let l of s){if(l==="inputResponses")i.inputResponses=a[l];if(l==="requestState")i.requestState=a[l];delete a[l]}return{message:{...e,params:a},lifted:i}}function kf(e,t){let r=e.validateResult(t,void 0);if(!r.ok&&r.reason==="not-in-era")return;return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let n=e.validateResult(t,o);if(n.ok)return{value:n.value};return{issues:[{message:n.reason==="invalid"?n.message:`not-in-era: ${t}`}]}}}}}function Su(e){return()=>e}var Ly=Su(void 0),Uy,yc=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{Uy=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??ja,this.setNotificationHandler("notifications/cancelled",(t)=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",(t)=>{this._onprogress(t)}),this.setRequestHandler("ping",(t)=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new N(O.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){if(e.params.requestId===void 0)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new N(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=(n)=>{r?.(n),this._onerror(n)};let o=this._transport?.onmessage;this._transport.onmessage=(n,s)=>{if(o?.(n,s),Bo(n)||Wo(n))this._onresponse(n);else if(Fr(n))this._onrequest(n,s);else if(eg(n))this._onnotification(n,s);else this._onerror(Error(`Unknown message type: ${JSON.stringify(n)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new N(O.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(r);for(let o of t.values())o.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=Ef(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let i=zf(t.classification);if(i!==o.era){this._onerror(Error(`Era mismatch on inbound notification '${r.method}': classified as ${i} but this instance serves ${o.era}`));return}}if(Xl(r.method)&&!o.hasNotificationMethod(r.method))return;let n=this._notificationHandlers.get(r.method),s=this.fallbackNotificationHandler;if(n===void 0&&s===void 0)return;Promise.resolve().then(()=>n===void 0?s(r):n(r,o)).catch((i)=>this._onerror(Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,t){let{message:r,lifted:o}=Ef(e,"request"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let s=this._transport,i=(y,v,U)=>{let H={jsonrpc:"2.0",id:r.id,error:{code:y,message:v,...U!==void 0&&{data:U}}};s?.send(H).catch((x)=>this._onerror(Error(`Failed to send an error response: ${x}`)))};if(t?.classification!==void 0){let y=zf(t.classification);if(y!==n.era){this._onerror(Error(`Era mismatch on inbound request '${r.method}': classified as ${y} but this instance serves ${n.era}`));let v=t.classification.revision??y;i(W.UnsupportedProtocolVersion,`Unsupported protocol version: ${v}`,{supported:this._supportedProtocolVersions,requested:v});return}}if(Yl(r.method)&&!n.hasRequestMethod(r.method)&&!(wf(r.method)&&this._customSchemaRequestMethods.has(r.method))){i(W.MethodNotFound,"Method not found");return}let a=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(a===void 0){i(W.MethodNotFound,"Method not found");return}let l=n.checkInboundEnvelope(o);if(l!==void 0){i(W.InvalidParams,l);return}let u=(y,v)=>this._notificationViaCodec(this._resolveOutboundCodec(y.method),y,{...v,relatedRequestId:r.id}),d=(y,v,U)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(y.method),y,v,{...U,relatedRequestId:r.id}),m=new AbortController;this._requestHandlerAbortControllers.set(r.id,m);let f=o.inputResponses===void 0?void 0:Zy(o.inputResponses),S={sessionId:s?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:o.requestState===void 0?Ly:Su(o.requestState),signal:m.signal,send:(y,v,U)=>{let H=this._resolveOutboundCodec(y.method);if(this._assertOutboundRequestInEra(H,y.method),ru(v))return d(y,v,U);let x=kf(H,y.method);if(x===void 0)throw TypeError(`'${y.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return d(y,x,v)},notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},b=this.buildContext(S,t);Promise.resolve().then(()=>a(r,b)).then(async(y)=>{if(m.signal.aborted)return;let v;try{v=n.encodeResult(r.method,y,this._outboundServerInfo())}catch(H){this._onerror(Error(`Failed to encode result for ${r.method}: ${H}`)),i(W.InternalError,"Internal error");return}let U={result:v,jsonrpc:"2.0",id:r.id};await s?.send(U)},async(y)=>{if(m.signal.aborted)return;let v=Number.isSafeInteger(y.code)?y.code:W.InternalError,U={jsonrpc:"2.0",id:r.id,error:{code:n.encodeErrorCode(v),message:y.message??"Internal error",...y.data!==void 0&&{data:y.data}}};await s?.send(U)}).catch((y)=>this._onerror(Error(`Failed to send response: ${y}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(r.id)===m)this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),n=this._progressHandlers.get(o);if(!n){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(a);return}n(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Bo(e))r(e);else r(ee.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let o=this._resolveOutboundCodec(e.method);if(ru(t)){if(!wf(e.method))this._assertOutboundRequestInEra(o,e.method);return this._requestWithSchemaViaCodec(o,e,t,r)}this._assertOutboundRequestInEra(o,e.method);let n=kf(o,e.method);if(n===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(o,e,n,t)}_negotiatedWireCodec(){return Lt(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Ay(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Yl(t)&&!e.hasRequestMethod(t))throw new N(O.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r)}_requestWithSchemaViaCodec(e,t,r,o){let{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,headers:a}=o??{},l=Date.now(),u,d;return new Promise((m,f)=>{let S=(w)=>{f(w)};if(!this._transport){S(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(w){S(w);return}if(o?.signal?.aborted){let w=o.signal.reason;throw w instanceof N?w:new N(O.RequestTimeout,String(w))}let b=e.era===Sc&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,y=this._requestMessageId++;d=y;let v={...t,jsonrpc:"2.0",id:y};if(o?.onprogress)this._progressHandlers.set(y,o.onprogress),v.params={...t.params,_meta:{...t.params?._meta,progressToken:y}};let U=this._envelopeOutbound(v),H=!1,x=(w)=>{if(H)return;if(this._progressHandlers.delete(y),b===void 0){if(t.method!=="initialize")this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:y,reason:String(w)}}),{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch((D)=>this._onerror(Error(`Failed to send cancellation: ${D}`)))}else b.abort();f(w instanceof N?w:new N(O.RequestTimeout,String(w)))};this._responseHandlers.set(y,(w)=>{if(o?.signal?.aborted)return;if(H=!0,w instanceof Error)return f(w);let D;try{D=e.decodeResult(t.method,w.result)}catch(Y){return f(Y instanceof Error?Y:Error(String(Y)))}if(D.kind==="invalid")return f(D.error);if(D.kind==="input_required"){if(o?.allowInputRequired===!0)return m(Vy(D));let Y={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:l,retry:(ce,Ee)=>this._requestWithSchemaViaCodec(e,ce===void 0?{method:t.method}:{method:t.method,params:ce},r,Ee)};return m(this._resolveNonCompleteResult(D,Y))}let X=D.result;Ql(r,X).then((Y)=>{if(Y.success)m(Y.data);else f(new N(O.InvalidResult,`Invalid result for ${t.method}: ${Y.error}`))},f)}),u=()=>x(o?.signal?.reason),o?.signal?.addEventListener("abort",u,{once:!0});let Z=o?.timeout??bc,R=()=>x(new N(O.RequestTimeout,"Request timed out",{timeout:Z}));this._setupTimeout(y,Z,o?.maxTotalTimeout,R,o?.resetTimeoutOnProgress??!1),this._transport.send(U,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,headers:a,requestSignal:b?.signal}).catch((w)=>{this._progressHandlers.delete(y),f(w)})}).finally(()=>{if(u)o?.signal?.removeEventListener("abort",u);if(d!==void 0)this._responseHandlers.delete(d),this._cleanupTimeout(d)})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new N(O.NotConnected,"Not connected");if(Xl(t.method)&&!e.hasNotificationMethod(t.method))throw new N(O.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;this._transport?.send(o,r).catch((n)=>this._onerror(n))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t==="function"){if(!Yl(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=(n,s)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason==="not-in-era")a=i.validateInputRequest(e,n);if(!a.ok){if(a.reason==="not-in-era")throw new ee(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(a.message)}return Promise.resolve(t(a.value,s))}}else if(r)o=async(n,s)=>{let i=await Ql(t.params,{...n.params});if(!i.success)throw new ee(W.InvalidParams,`Invalid params for ${e}: ${i.error}`);return r(i.data,s)};else throw TypeError("setRequestHandler: handler is required");if(typeof t==="function")this._customSchemaRequestMethods.delete(e);else this._customSchemaRequestMethods.add(e);this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t==="function"){if(!Xl(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,n)=>{let s=n.validateNotification(e,o);if(!s.ok){if(s.reason==="not-in-era")throw new ee(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(s.message)}return Promise.resolve(t(s.value))});return}if(!r)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async(o)=>{let n=await Ql(t.params,{...o.params});if(!n.success)throw new ee(W.InvalidParams,`Invalid params for notification ${e}: ${n.error}`);await r(n.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Ci(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function hg(e,t){let r={...e};for(let o in t){let n=o,s=t[n];if(s===void 0)continue;let i=r[n];r[n]=Ci(i)&&Ci(s)?{...i,...s}:s}return r}function fc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Zy(e){let t={},r=[];if(!fc(e))return{accepted:t,droppedKeys:r};for(let[o,n]of Object.entries(e)){if(!fc(n)||"method"in n||"result"in n){r.push(o);continue}t[o]=n}return{accepted:t,droppedKeys:r}}function $f(e){throw new N(O.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function Dy(e,t,r,o,n){return{sessionId:n,mcpReq:{id:e,method:t,_meta:r?._meta,requestState:Su(void 0),signal:o,send:()=>$f("send"),notify:()=>$f("notify")}}}async function Fy(e,t,r,o,n){if(!fc(o)||typeof o.method!=="string")throw new N(O.InvalidResult,`Invalid input request '${r}': each inputRequests entry must be an embedded request object with a method`,{key:r});let s=o.method;if(!t.hasInputRequestMethod(s))throw new N(O.InvalidResult,`Invalid input request '${r}': '${s}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:r,method:s});let i=e.getRequestHandler(s);if(i===void 0)throw new N(O.CapabilityNotSupported,`Cannot fulfil input request '${r}': no handler is registered for '${s}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:r,method:s});let a=fc(o.params)?o.params:void 0;return await i({jsonrpc:"2.0",id:r,method:s,...a!==void 0&&{params:a}},e.buildContext(Dy(r,s,a,n,e.sessionId)))}function Hy(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function mg(e,t,r,o){let{codec:n,request:s,options:i,flowStartedAt:a}=o,l={inputRequests:r.inputRequests,...r.requestState!==void 0&&{requestState:r.requestState}},u={dispatchInputRequest:(d,m,f)=>Fy(e,n,d,m,f),retry:(d,m)=>o.retry(d,Hy(i,m))};return Iy({config:t,method:s.method,originalParams:s.params,firstPayload:l,flowStartedAt:a,signal:i?.signal,requestOptions:{...i?.timeout!==void 0&&{timeout:i.timeout},...i?.maxTotalTimeout!==void 0&&{maxTotalTimeout:i.maxTotalTimeout},...i?.onprogress!==void 0&&{onprogress:i.onprogress}},hooks:u})}function Vy(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}/*!
65
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){i(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1){if(e.reused==="ref"){i(s);continue}}}}function Vn(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(a)=>{let l=e.seen.get(a);if(l.ref===null)return;let u=l.def??l.schema,d={...u},m=l.ref;if(l.ref=null,m){o(m);let S=e.seen.get(m),b=S.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))u.allOf=u.allOf??[],u.allOf.push(b);else Object.assign(u,b);if(Object.assign(u,d),a._zod.parent===m)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(!(v in d))delete u[v]}if(b.$ref&&S.def)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(v in S.def&&JSON.stringify(u[v])===JSON.stringify(S.def[v]))delete u[v]}}let f=a._zod.parent;if(f&&f!==m){o(f);let S=e.seen.get(f);if(S?.schema.$ref){if(u.$ref=S.schema.$ref,S.def)for(let b in u){if(b==="$ref"||b==="allOf")continue;if(b in S.def&&JSON.stringify(u[b])===JSON.stringify(S.def[b]))delete u[b]}}}e.override({zodSchema:a,jsonSchema:u,path:l.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let n={};if(e.target==="draft-2020-12")n.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")n.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")n.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");n.$id=e.external.uri(a)}Object.assign(n,r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&n.id===i)delete n.id;let s=e.external?.defs??{};for(let a of e.seen.entries()){let l=a[1];if(l.def&&l.defId){if(l.def.id===l.defId)delete l.def.id;s[l.defId]=l.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")n.$defs=s;else n.definitions=s;try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dn(t,"input",e.processors),output:Dn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Ne(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Ne(o.element,r);if(o.type==="set")return Ne(o.valueType,r);if(o.type==="lazy")return Ne(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return Ne(o.innerType,r);if(o.type==="intersection")return Ne(o.left,r)||Ne(o.right,r);if(o.type==="record"||o.type==="map")return Ne(o.keyType,r)||Ne(o.valueType,r);if(o.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Ne(o.in,r)||Ne(o.out,r)}if(o.type==="object"){for(let n in o.shape)if(Ne(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Ne(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Ne(n,r))return!0;if(o.rest&&Ne(o.rest,r))return!0;return!1}return!1}var dm=(e,t={})=>(r)=>{let o=Fn({...r,processors:t});return oe(e,o),Hn(o,e),Vn(o,e)},Dn=(e,t,r={})=>(o)=>{let{libraryOptions:n,target:i}=o??{},s=Fn({...n??{},target:i,io:t,processors:r});return oe(e,s),Hn(s,e),Vn(s,e)};var l_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},yl=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof i==="number")n.minLength=i;if(typeof s==="number")n.maxLength=s;if(a){if(n.format=l_[a]??a,n.format==="")delete n.format;if(a==="time")delete n.format}if(u)n.contentEncoding=u;if(l&&l.size>0){let d=[...l];if(d.length===1)n.pattern=d[0].source;else if(d.length>1)n.allOf=[...d.map((m)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))]}},vl=(e,t,r,o)=>{let n=r,{minimum:i,maximum:s,format:a,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))n.type="integer";else n.type="number";let m=typeof d==="number"&&d>=(i??Number.NEGATIVE_INFINITY),f=typeof u==="number"&&u<=(s??Number.POSITIVE_INFINITY),S=t.target==="draft-04"||t.target==="openapi-3.0";if(m)if(S)n.minimum=d,n.exclusiveMinimum=!0;else n.exclusiveMinimum=d;else if(typeof i==="number")n.minimum=i;if(f)if(S)n.maximum=u,n.exclusiveMaximum=!0;else n.exclusiveMaximum=u;else if(typeof s==="number")n.maximum=s;if(typeof l==="number")n.multipleOf=l},zl=(e,t,r,o)=>{r.type="boolean"},hm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},mm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},wl=(e,t,r,o)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},Rl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},fm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},xl=(e,t,r,o)=>{r.not={}},Pl=(e,t,r,o)=>{},Tl=(e,t,r,o)=>{},gm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},El=(e,t,r,o)=>{let n=e._zod.def,i=fa(n.entries);if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";r.enum=i},kl=(e,t,r,o)=>{let n=e._zod.def,i=[];for(let s of n.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else i.push(Number(s));else i.push(s);if(i.length===0);else if(i.length===1){let s=i[0];if(r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[s];else r.const=s}else{if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";if(i.every((s)=>typeof s==="boolean"))r.type="boolean";if(i.every((s)=>s===null))r.type="null";r.enum=i}},Sm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},_m=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},bm=(e,t,r,o)=>{let n=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:l}=e._zod.bag;if(s!==void 0)i.minLength=s;if(a!==void 0)i.maxLength=a;if(l)if(l.length===1)i.contentMediaType=l[0],Object.assign(n,i);else Object.assign(n,i),n.anyOf=l.map((u)=>({contentMediaType:u}));else Object.assign(n,i)},ym=(e,t,r,o)=>{r.type="boolean"},$l=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},vm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},Cl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},zm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},wm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},Il=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")n.minItems=s;if(typeof a==="number")n.maxItems=a;n.type="array",n.items=oe(i.element,t,{...o,path:[...o.path,"items"]})},Ol=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object",n.properties={};let s=i.shape;for(let u in s)n.properties[u]=oe(s[u],t,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(s)),l=new Set([...a].filter((u)=>{let d=i.shape[u]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(l.size>0)n.required=Array.from(l);if(i.catchall?._zod.def.type==="never")n.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")n.additionalProperties=!1}else if(i.catchall)n.additionalProperties=oe(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Nl=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,s=n.options.map((a,l)=>oe(a,t,{...o,path:[...o.path,i?"oneOf":"anyOf",l]}));if(i)r.oneOf=s;else r.anyOf=s},ql=(e,t,r,o)=>{let n=e._zod.def,i=oe(n.left,t,{...o,path:[...o.path,"allOf",0]}),s=oe(n.right,t,{...o,path:[...o.path,"allOf",1]}),a=(u)=>("allOf"in u)&&Object.keys(u).length===1,l=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=l},Rm=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",l=i.items.map((f,S)=>oe(f,t,{...o,path:[...o.path,s,S]})),u=i.rest?oe(i.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(n.prefixItems=l,u)n.items=u}else if(t.target==="openapi-3.0"){if(n.items={anyOf:l},u)n.items.anyOf.push(u);if(n.minItems=l.length,!u)n.maxItems=l.length}else if(n.items=l,u)n.additionalItems=u;let{minimum:d,maximum:m}=e._zod.bag;if(typeof d==="number")n.minItems=d;if(typeof m==="number")n.maxItems=m},Al=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let s=i.keyType,l=s._zod.bag?.patterns;if(i.mode==="loose"&&l&&l.size>0){let d=oe(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let m of l)n.patternProperties[m.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")n.propertyNames=oe(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});n.additionalProperties=oe(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=s._zod.values;if(u){let d=[...u].filter((m)=>typeof m==="string"||typeof m==="number");if(d.length>0)n.required=d}},Ml=(e,t,r,o)=>{let n=e._zod.def,i=oe(n.innerType,t,o),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=n.innerType,r.nullable=!0;else r.anyOf=[i,{type:"null"}]},jl=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Ll=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},Ul=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(n.defaultValue))},Zl=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},Dl=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?n.out:n.in:n.out;oe(s,t,o);let a=t.seen.get(e);a.ref=s},Fl=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},xm=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},$a=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Hl=(e,t,r,o)=>{let n=e._zod.innerType;oe(n,t,o);let i=t.seen.get(e);i.ref=n},pm={string:yl,number:vl,boolean:zl,bigint:hm,symbol:mm,null:wl,undefined:Rl,void:fm,never:xl,any:Pl,unknown:Tl,date:gm,enum:El,literal:kl,nan:Sm,template_literal:_m,file:bm,success:ym,custom:$l,function:vm,transform:Cl,map:zm,set:wm,array:Il,object:Ol,union:Nl,intersection:ql,tuple:Rm,record:Al,nullable:Ml,nonoptional:jl,default:Ll,prefault:Ul,catch:Zl,pipe:Dl,readonly:Fl,promise:xm,optional:$a,lazy:Hl};function Ca(e,t){if("_idmap"in e){let o=e,n=Fn({...t,processors:pm}),i={};for(let l of o._idmap.entries()){let[u,d]=l;oe(d,n)}let s={},a={registry:o,uri:t?.uri,defs:i};n.external=a;for(let l of o._idmap.entries()){let[u,d]=l;Hn(n,d),s[u]=Vn(n,d)}if(Object.keys(i).length>0){let l=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[l]:i}}return{schemas:s}}let r=Fn({...t,processors:pm});return oe(e,r),Hn(r,e),Vn(r,e)}var S_=_("ZodISODateTime",(e,t)=>{Up.init(e,t),ce.init(e,t)});function uo(e){return Kh(S_,e)}var __=_("ZodISODate",(e,t)=>{Zp.init(e,t),ce.init(e,t)});function Vl(e){return Gh(__,e)}var b_=_("ZodISOTime",(e,t)=>{Dp.init(e,t),ce.init(e,t)});function Pm(e){return Yh(b_,e)}var y_=_("ZodISODuration",(e,t)=>{Fp.init(e,t),ce.init(e,t)});function Tm(e){return Xh(y_,e)}var v_=(e,t)=>{ba.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>Bc(e,r)},flatten:{value:(r)=>Jc(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Nn,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Nn,2)}},isEmpty:{get(){return e.issues.length===0}}})};var Je=_("ZodError",v_,{Parent:Error});var km=ya(Je),$m=va(Je),Oa=An(Je),Cm=Mn(Je),Im=wd(Je),Om=Rd(Je),Nm=xd(Je),qm=Pd(Je),Am=Td(Je),Mm=Ed(Je),jm=kd(Je),Lm=$d(Je);var Um=new WeakMap;function Jn(e,t,r){let o=Object.getPrototypeOf(e),n=Um.get(o);if(!n)n=new Set,Um.set(o,n);if(n.has(t))return;n.add(t);for(let i in r){let s=r[i];Object.defineProperty(o,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var ne=_("ZodType",(e,t)=>(re.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dn(e,"input"),output:Dn(e,"output")}}),e.toJSONSchema=dm(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,o)=>km(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Oa(e,r,o),e.parseAsync=async(r,o)=>$m(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>Cm(e,r,o),e.spa=e.safeParseAsync,e.encode=(r,o)=>Im(e,r,o),e.decode=(r,o)=>Om(e,r,o),e.encodeAsync=async(r,o)=>Nm(e,r,o),e.decodeAsync=async(r,o)=>qm(e,r,o),e.safeEncode=(r,o)=>Am(e,r,o),e.safeDecode=(r,o)=>Mm(e,r,o),e.safeEncodeAsync=async(r,o)=>jm(e,r,o),e.safeDecodeAsync=async(r,o)=>Lm(e,r,o),Jn(e,"ZodType",{check(...r){let o=this.def;return this.clone(Wt(o,{checks:[...o.checks??[],...r.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,o){return rt(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(ub(r,o))},superRefine(r,o){return this.check(db(r,o))},overwrite(r){return this.check(Xt(r))},optional(){return j(this)},exactOptional(){return G_(this)},nullable(){return Hm(this)},nullish(){return j(Hm(this))},nonoptional(r){return rb(this,r)},array(){return g(this)},or(r){return T([this,r])},and(r){return $t(this,r)},transform(r){return Vm(this,ef(r))},default(r){return Q_(this,r)},prefault(r){return tb(this,r)},catch(r){return nb(this,r)},pipe(r){return Vm(this,r)},readonly(){return ab(this)},describe(r){let o=this.clone();return Yt.add(o,{description:r}),o},meta(...r){if(r.length===0)return Yt.get(this);let o=this.clone();return Yt.add(o,r[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return Yt.get(e)?.description},configurable:!0}),e)),Jm=_("_ZodString",(e,t)=>{Ra.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,i)=>yl(e,o,n,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Jn(e,"_ZodString",{regex(...o){return this.check(ll(...o))},includes(...o){return this.check(pl(...o))},startsWith(...o){return this.check(hl(...o))},endsWith(...o){return this.check(ml(...o))},min(...o){return this.check(co(...o))},max(...o){return this.check(Ea(...o))},length(...o){return this.check(ka(...o))},nonempty(...o){return this.check(co(1,...o))},lowercase(o){return this.check(ul(o))},uppercase(o){return this.check(dl(o))},trim(){return this.check(gl())},normalize(...o){return this.check(fl(...o))},toLowerCase(){return this.check(Sl())},toUpperCase(){return this.check(_l())},slugify(){return this.check(bl())}})}),Bm=_("ZodString",(e,t)=>{Ra.init(e,t),Jm.init(e,t),e.email=(r)=>e.check(il(Wm,r)),e.url=(r)=>e.check(cl(Gm,r)),e.jwt=(r)=>e.check(Wh(M_,r)),e.emoji=(r)=>e.check(Nh(w_,r)),e.guid=(r)=>e.check(al(Zm,r)),e.uuid=(r)=>e.check($h(Na,r)),e.uuidv4=(r)=>e.check(Ch(Na,r)),e.uuidv6=(r)=>e.check(Ih(Na,r)),e.uuidv7=(r)=>e.check(Oh(Na,r)),e.nanoid=(r)=>e.check(qh(R_,r)),e.guid=(r)=>e.check(al(Zm,r)),e.cuid=(r)=>e.check(Ah(x_,r)),e.cuid2=(r)=>e.check(Mh(P_,r)),e.ulid=(r)=>e.check(jh(T_,r)),e.base64=(r)=>e.check(Vh(N_,r)),e.base64url=(r)=>e.check(Jh(q_,r)),e.xid=(r)=>e.check(Lh(E_,r)),e.ksuid=(r)=>e.check(Uh(k_,r)),e.ipv4=(r)=>e.check(Zh($_,r)),e.ipv6=(r)=>e.check(Dh(C_,r)),e.cidrv4=(r)=>e.check(Fh(I_,r)),e.cidrv6=(r)=>e.check(Hh(O_,r)),e.e164=(r)=>e.check(Bh(A_,r)),e.datetime=(r)=>e.check(uo(r)),e.date=(r)=>e.check(Vl(r)),e.time=(r)=>e.check(Pm(r)),e.duration=(r)=>e.check(Tm(r))});function c(e){return kh(Bm,e)}var ce=_("ZodStringFormat",(e,t)=>{ae.init(e,t),Jm.init(e,t)}),Wm=_("ZodEmail",(e,t)=>{Cp.init(e,t),ce.init(e,t)});function Km(e){return il(Wm,e)}var Zm=_("ZodGUID",(e,t)=>{kp.init(e,t),ce.init(e,t)});var Na=_("ZodUUID",(e,t)=>{$p.init(e,t),ce.init(e,t)});var Gm=_("ZodURL",(e,t)=>{Ip.init(e,t),ce.init(e,t)});function qa(e){return cl(Gm,e)}var w_=_("ZodEmoji",(e,t)=>{Op.init(e,t),ce.init(e,t)});var R_=_("ZodNanoID",(e,t)=>{Np.init(e,t),ce.init(e,t)});var x_=_("ZodCUID",(e,t)=>{qp.init(e,t),ce.init(e,t)});var P_=_("ZodCUID2",(e,t)=>{Ap.init(e,t),ce.init(e,t)});var T_=_("ZodULID",(e,t)=>{Mp.init(e,t),ce.init(e,t)});var E_=_("ZodXID",(e,t)=>{jp.init(e,t),ce.init(e,t)});var k_=_("ZodKSUID",(e,t)=>{Lp.init(e,t),ce.init(e,t)});var $_=_("ZodIPv4",(e,t)=>{Hp.init(e,t),ce.init(e,t)});var C_=_("ZodIPv6",(e,t)=>{Vp.init(e,t),ce.init(e,t)});var I_=_("ZodCIDRv4",(e,t)=>{Jp.init(e,t),ce.init(e,t)});var O_=_("ZodCIDRv6",(e,t)=>{Bp.init(e,t),ce.init(e,t)});var N_=_("ZodBase64",(e,t)=>{Kp.init(e,t),ce.init(e,t)});var q_=_("ZodBase64URL",(e,t)=>{Gp.init(e,t),ce.init(e,t)});var A_=_("ZodE164",(e,t)=>{Yp.init(e,t),ce.init(e,t)});var M_=_("ZodJWT",(e,t)=>{Xp.init(e,t),ce.init(e,t)});var Aa=_("ZodNumber",(e,t)=>{tl.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,i)=>vl(e,o,n,i),Jn(e,"ZodNumber",{gt(o,n){return this.check(Pa(o,n))},gte(o,n){return this.check(Zn(o,n))},min(o,n){return this.check(Zn(o,n))},lt(o,n){return this.check(xa(o,n))},lte(o,n){return this.check(Un(o,n))},max(o,n){return this.check(Un(o,n))},int(o){return this.check(Dm(o))},safe(o){return this.check(Dm(o))},positive(o){return this.check(Pa(0,o))},nonnegative(o){return this.check(Zn(0,o))},negative(o){return this.check(xa(0,o))},nonpositive(o){return this.check(Un(0,o))},multipleOf(o,n){return this.check(Ta(o,n))},step(o,n){return this.check(Ta(o,n))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??0.5),e.isFinite=!0,e.format=r.format??null});function z(e){return Qh(Aa,e)}var j_=_("ZodNumberFormat",(e,t)=>{Qp.init(e,t),Aa.init(e,t)});function Dm(e){return tm(j_,e)}var Ym=_("ZodBoolean",(e,t)=>{eh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zl(e,r,o,n)});function E(e){return rm(Ym,e)}var L_=_("ZodUndefined",(e,t)=>{th.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rl(e,r,o,n)});function Bl(e){return om(L_,e)}var U_=_("ZodNull",(e,t)=>{rh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wl(e,r,o,n)});function Rr(e){return nm(U_,e)}var Z_=_("ZodAny",(e,t)=>{oh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Pl(e,r,o,n)});function Ma(){return sm(Z_)}var D_=_("ZodUnknown",(e,t)=>{nh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Tl(e,r,o,n)});function A(){return im(D_)}var F_=_("ZodNever",(e,t)=>{sh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xl(e,r,o,n)});function Wl(e){return am(F_,e)}var H_=_("ZodArray",(e,t)=>{ih.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n),e.element=t.element,Jn(e,"ZodArray",{min(r,o){return this.check(co(r,o))},nonempty(r){return this.check(co(1,r))},max(r,o){return this.check(Ea(r,o))},length(r,o){return this.check(ka(r,o))},unwrap(){return this.element}})});function g(e,t){return cm(H_,e,t)}var Xm=_("ZodObject",(e,t)=>{lh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n),Q(e,"shape",()=>t.shape),Jn(e,"ZodObject",{keyof(){return K(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:A()})},loose(){return this.clone({...this._zod.def,catchall:A()})},strict(){return this.clone({...this._zod.def,catchall:Wl()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return KS(this,r)},safeExtend(r){return GS(this,r)},merge(r){return YS(this,r)},pick(r){return BS(this,r)},omit(r){return WS(this,r)},partial(...r){return XS(tf,this,r[0])},required(...r){return QS(rf,this,r[0])}})});function p(e,t){let r={type:"object",shape:e??{},...M(t)};return new Xm(r)}function F(e,t){return new Xm({type:"object",shape:e,catchall:A(),...M(t)})}var Qm=_("ZodUnion",(e,t)=>{rl.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nl(e,r,o,n),e.options=t.options});function T(e,t){return new Qm({type:"union",options:e,...M(t)})}var V_=_("ZodDiscriminatedUnion",(e,t)=>{Qm.init(e,t),uh.init(e,t)});function po(e,t,r){return new V_({type:"union",options:t,discriminator:e,...M(r)})}var J_=_("ZodIntersection",(e,t)=>{dh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n)});function $t(e,t){return new J_({type:"intersection",left:e,right:t})}var Fm=_("ZodRecord",(e,t)=>{ph.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function P(e,t,r){if(!t||!t._zod)return new Fm({type:"record",keyType:c(),valueType:e,...M(t)});return new Fm({type:"record",keyType:e,valueType:t,...M(r)})}var Jl=_("ZodEnum",(e,t)=>{hh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,i)=>El(e,o,n,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new Jl({...t,checks:[],...M(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let s of o)if(r.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new Jl({...t,checks:[],...M(n),entries:i})}});function K(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new Jl({type:"enum",entries:r,...M(t)})}var B_=_("ZodLiteral",(e,t)=>{mh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kl(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function h(e,t){return new B_({type:"literal",values:Array.isArray(e)?e:[e],...M(t)})}var W_=_("ZodTransform",(e,t)=>{fh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cl(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new On(e.constructor.name);r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(wr(i,r.value,t));else{let s=i;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),r.issues.push(wr(s))}};let n=t.transform(r.value,r);if(n instanceof Promise)return n.then((i)=>(r.value=i,r.fallback=!0,r));return r.value=n,r.fallback=!0,r}});function ef(e){return new W_({type:"transform",transform:e})}var tf=_("ZodOptional",(e,t)=>{ol.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$a(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function j(e){return new tf({type:"optional",innerType:e})}var K_=_("ZodExactOptional",(e,t)=>{gh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$a(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function G_(e){return new K_({type:"optional",innerType:e})}var Y_=_("ZodNullable",(e,t)=>{Sh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Hm(e){return new Y_({type:"nullable",innerType:e})}var X_=_("ZodDefault",(e,t)=>{_h.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Q_(e,t){return new X_({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Fc(t)}})}var eb=_("ZodPrefault",(e,t)=>{bh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function tb(e,t){return new eb({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Fc(t)}})}var rf=_("ZodNonOptional",(e,t)=>{yh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function rb(e,t){return new rf({type:"nonoptional",innerType:e,...M(t)})}var ob=_("ZodCatch",(e,t)=>{vh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function nb(e,t){return new ob({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var of=_("ZodPipe",(e,t)=>{nl.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dl(e,r,o,n),e.in=t.in,e.out=t.out});function Vm(e,t){return new of({type:"pipe",in:e,out:t})}var sb=_("ZodPreprocess",(e,t)=>{of.init(e,t),zh.init(e,t)}),ib=_("ZodReadonly",(e,t)=>{wh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ab(e){return new ib({type:"readonly",innerType:e})}var cb=_("ZodLazy",(e,t)=>{Rh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hl(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function Bn(e){return new cb({type:"lazy",getter:e})}var lb=_("ZodCustom",(e,t)=>{xh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$l(e,r,o,n)});function ub(e,t={}){return lm(lb,e,t)}function db(e,t){return um(e,t)}function xr(e,t){return new sb({type:"pipe",in:ef(e),out:t})}var sf={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var nf;(function(e){})(nf||(nf={}));function pb(e){return em(Aa,e)}je(sl());var ho="2025-11-25";var ja=[ho,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],La="io.modelcontextprotocol/related-task",It="io.modelcontextprotocol/protocolVersion",mo="io.modelcontextprotocol/clientInfo",Ot="io.modelcontextprotocol/serverInfo",Pr="io.modelcontextprotocol/clientCapabilities",Wn="io.modelcontextprotocol/subscriptionId",fo="io.modelcontextprotocol/logLevel";var Tr="2.0";var Ct=Bn(()=>T([c(),z(),E(),Rr(),P(c(),Ct),g(Ct)])),ue=P(c(),Ct),Ua=g(Ct),go=T([c(),z().int()]),So=c(),Kn=p({ttl:z().optional()}),Gn=p({taskId:c()}),_o=F({progressToken:go.optional(),[La]:Gn.optional()}),ye=p({_meta:_o.optional()}),er=ye.extend({task:Kn.optional()}),de=p({method:c(),params:ye.loose().optional()}),Te=p({_meta:_o.optional()}),we=p({method:c(),params:Te.loose().optional()}),bo=F({get[Ot](){return _t.optional().catch(void 0)}}),pe=F({_meta:bo.optional()}),nt=T([c(),z().int()]),yo=p({jsonrpc:h(Tr),id:nt,...de.shape}).strict(),vo=p({jsonrpc:h(Tr),...we.shape}).strict(),Er=p({jsonrpc:h(Tr),id:nt,result:pe}).strict(),kr=p({jsonrpc:h(Tr),id:nt.optional(),error:p({code:z().int(),message:c(),data:A().optional()})}).strict(),st=T([yo,vo,Er,kr]),Za=T([Er,kr]),tr=pe.strict(),Yn=Te.extend({requestId:nt.optional(),reason:c().optional()}),zo=we.extend({method:h("notifications/cancelled"),params:Yn}),Xn=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),Nt=p({icons:g(Xn).optional()}),St=p({name:c(),title:c().optional()}),_t=St.extend({...St.shape,...Nt.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),mb=$t(p({applyDefaults:E().optional()}),ue),fb=xr((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)&&Object.keys(e).length===0)return{form:{}};return e},$t(p({form:mb.optional(),url:ue.optional()}),ue.optional())),Da=F({list:ue.optional(),cancel:ue.optional(),requests:F({sampling:F({createMessage:ue.optional()}).optional(),elicitation:F({create:ue.optional()}).optional()}).optional()}),Fa=F({list:ue.optional(),cancel:ue.optional(),requests:F({tools:F({call:ue.optional()}).optional()}).optional()}),Qn=p({experimental:P(c(),ue).optional(),sampling:p({context:ue.optional(),tools:ue.optional()}).optional(),elicitation:fb.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:Da.optional(),extensions:P(c(),ue).optional()}),es=ye.extend({protocolVersion:c(),capabilities:Qn,clientInfo:_t}),wo=de.extend({method:h("initialize"),params:es}),Ro=p({experimental:P(c(),ue).optional(),logging:ue.optional(),completions:ue.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:Fa.optional(),extensions:P(c(),ue).optional()}),ts=pe.extend({protocolVersion:c(),capabilities:Ro,serverInfo:_t,instructions:c().optional()}),xo=we.extend({method:h("notifications/initialized"),params:Te.optional()}),rs=de.extend({method:h("server/discover"),params:ye.optional()}),rr=pe.extend({supportedVersions:g(c()),capabilities:Ro,instructions:c().optional()}),Po=de.extend({method:h("ping"),params:ye.optional()}),os=p({progress:z(),total:j(z()),message:j(c())}),ns=p({...Te.shape,...os.shape,progressToken:go}),To=we.extend({method:h("notifications/progress"),params:ns}),ss=ye.extend({cursor:So.optional()}),qt=de.extend({params:ss.optional()}),At=pe.extend({nextCursor:So.optional()}),Eo=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),ko=Eo.extend({text:c()}),Gl=c().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),$o=Eo.extend({blob:Gl}),Mt=K(["user","assistant"]),bt=p({audience:g(Mt).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),Co=p({...St.shape,...Nt.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:bt.optional(),_meta:j(F({}))}),is=p({...St.shape,...Nt.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:bt.optional(),_meta:j(F({}))}),as=qt.extend({method:h("resources/list")}),cs=At.extend({resources:g(Co)}),ls=qt.extend({method:h("resources/templates/list")}),us=At.extend({resourceTemplates:g(is)}),$r=ye.extend({uri:c()}),ds=$r,ps=de.extend({method:h("resources/read"),params:ds}),hs=pe.extend({contents:g(T([ko,$o]))}),ms=we.extend({method:h("notifications/resources/list_changed"),params:Te.optional()}),fs=$r,gs=de.extend({method:h("resources/subscribe"),params:fs}),Ss=$r,_s=de.extend({method:h("resources/unsubscribe"),params:Ss}),Io=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:g(c()).optional()}),bs=ye.extend({notifications:Io}),ys=de.extend({method:h("subscriptions/listen"),params:bs}),vs=Te.extend({notifications:Io}),zs=we.extend({method:h("notifications/subscriptions/acknowledged"),params:vs}),ws=bo.extend({[Wn]:nt}),Rs=pe.extend({_meta:ws}),xs=Te.extend({uri:c()}),Ps=we.extend({method:h("notifications/resources/updated"),params:xs}),Ts=p({name:c(),description:j(c()),required:j(E())}),Es=p({...St.shape,...Nt.shape,description:j(c()),arguments:j(g(Ts)),_meta:j(F({}))}),ks=qt.extend({method:h("prompts/list")}),$s=At.extend({prompts:g(Es)}),Cs=ye.extend({name:c(),arguments:P(c(),c()).optional()}),Is=de.extend({method:h("prompts/get"),params:Cs}),Cr=p({type:h("text"),text:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Ir=p({type:h("image"),data:Gl,mimeType:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Or=p({type:h("audio"),data:Gl,mimeType:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Os=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),Nr=p({type:h("resource"),resource:T([ko,$o]),annotations:bt.optional(),_meta:P(c(),A()).optional()}),qr=Co.extend({type:h("resource_link")}),yt=T([Cr,Ir,Or,qr,Nr]),Ns=p({role:Mt,content:yt}),qs=pe.extend({description:c().optional(),messages:g(Ns)}),As=we.extend({method:h("notifications/prompts/list_changed"),params:Te.optional()}),Ms=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),js=p({taskSupport:K(["required","optional","forbidden"]).optional()}),or=p({...St.shape,...Nt.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),Ct).optional(),required:g(c()).optional()}).catchall(A()),outputSchema:F({$schema:c().optional()}).optional(),annotations:Ms.optional(),execution:js.optional(),_meta:P(c(),A()).optional()}),Ls=qt.extend({method:h("tools/list")}),Us=At.extend({tools:g(or)}),nr=pe.extend({content:g(yt).default([]),structuredContent:A().optional(),isError:E().optional()}),Ha=nr.or(pe.extend({toolResult:A()})),Zs=er.extend({name:c(),arguments:P(c(),A()).optional()}),Ds=de.extend({method:h("tools/call"),params:Zs}),Fs=we.extend({method:h("notifications/tools/list_changed"),params:Te.optional()}),Hs=p({autoRefresh:E().default(!0),debounceMs:z().int().nonnegative().default(300)}),Oo=K(["debug","info","notice","warning","error","critical","alert","emergency"]),Vs=ye.extend({level:Oo}),Js=de.extend({method:h("logging/setLevel"),params:Vs}),Bs=Te.extend({level:Oo,logger:c().optional(),data:A()}),Ar=we.extend({method:h("notifications/message"),params:Bs}),Ws=p({name:c().optional()}),Ks=p({hints:g(Ws).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),Gs=p({mode:K(["auto","required","none"]).optional()}),Ys=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:g(yt),structuredContent:A().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),Xs=po("type",[Cr,Ir,Or]),Qt=po("type",[Cr,Ir,Or,Os,Ys]),Qs=p({role:Mt,content:T([Qt,g(Qt)]),_meta:P(c(),A()).optional()}),ei=er.extend({messages:g(Qs),modelPreferences:Ks.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:ue.optional(),tools:g(or).optional(),toolChoice:Gs.optional()}),ti=de.extend({method:h("sampling/createMessage"),params:ei}),ri=pe.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Mt,content:Xs}),oi=pe.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Mt,content:T([Qt,g(Qt)])}),No=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),Mr=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),jr=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),qo=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),Ao=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),Mo=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),ni=T([qo,Ao]),jo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),Lo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),si=T([jo,Lo]),ii=T([Mo,ni,si]),Uo=T([ii,No,Mr,jr]),Lr=er.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),Uo),required:g(c()).optional()}).catchall(A())}),ai=er.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),ci=T([Lr,ai]),li=de.extend({method:h("elicitation/create"),params:ci}),ui=Te.extend({elicitationId:c()}),di=we.extend({method:h("notifications/elicitation/complete"),params:ui}),pi=pe.extend({action:K(["accept","decline","cancel"]),content:xr((e)=>e===null?void 0:e,P(c(),T([c(),z(),E(),g(c())])).optional())}),hi=p({type:h("ref/resource"),uri:c()}),mi=p({type:h("ref/prompt"),name:c()}),fi=ye.extend({ref:T([mi,hi]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),gi=de.extend({method:h("completion/complete"),params:fi}),Si=pe.extend({completion:F({values:g(c()).max(100),total:j(z().int()),hasMore:j(E())})}),_i=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),bi=de.extend({method:h("roots/list"),params:ye.optional()}),yi=pe.extend({roots:g(_i)}),vi=we.extend({method:h("notifications/roots/list_changed"),params:Te.optional()}),Va=F({ttl:z().optional(),pollInterval:z().optional()}),zi=K(["working","input_required","completed","failed","cancelled"]),jt=p({taskId:c(),status:zi,ttl:T([z(),Rr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:j(z()),statusMessage:j(c())}),Ja=pe.extend({task:jt}),wi=Te.merge(jt),Ba=we.extend({method:h("notifications/tasks/status"),params:wi}),Wa=de.extend({method:h("tasks/get"),params:ye.extend({taskId:c()})}),Ka=pe.merge(jt),Ga=de.extend({method:h("tasks/result"),params:ye.extend({taskId:c()})}),Ya=pe.loose(),Xa=qt.extend({method:h("tasks/list")}),Qa=At.extend({tasks:g(jt)}),ec=de.extend({method:h("tasks/cancel"),params:ye.extend({taskId:c()})}),tc=pe.merge(jt),rc=T([Po,wo,rs,gi,Js,Is,ks,as,ls,ps,gs,_s,ys,Ds,Ls]),oc=T([zo,To,xo,vi]),nc=T([tr,ri,oi,pi,yi]),sc=T([Po,ti,li,bi]),ic=T([zo,To,Ar,Ps,ms,Fs,As,zs,di]),ac=T([tr,ts,rr,Si,qs,$s,cs,us,hs,nr,Us,Rs]),be=qa().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:sf.custom,message:"URL must be parseable",fatal:!0}),jc}).refine((e)=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Zo=F({resource:c().url(),authorization_servers:g(be).optional(),jwks_uri:c().url().optional(),scopes_supported:g(c()).optional(),bearer_methods_supported:g(c()).optional(),resource_signing_alg_values_supported:g(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:E().optional(),authorization_details_types_supported:g(c()).optional(),dpop_signing_alg_values_supported:g(c()).optional(),dpop_bound_access_tokens_required:E().optional()}),Ur=F({issuer:c(),authorization_endpoint:be,token_endpoint:be,registration_endpoint:be.optional(),scopes_supported:g(c()).optional(),response_types_supported:g(c()),response_modes_supported:g(c()).optional(),grant_types_supported:g(c()).optional(),token_endpoint_auth_methods_supported:g(c()).optional(),token_endpoint_auth_signing_alg_values_supported:g(c()).optional(),service_documentation:be.optional(),revocation_endpoint:be.optional(),revocation_endpoint_auth_methods_supported:g(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:g(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:g(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:g(c()).optional(),code_challenge_methods_supported:g(c()).optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0),dpop_signing_alg_values_supported:g(c()).optional()}),Ri=F({issuer:c(),authorization_endpoint:be,token_endpoint:be,userinfo_endpoint:be.optional(),jwks_uri:be,registration_endpoint:be.optional(),scopes_supported:g(c()).optional(),response_types_supported:g(c()),response_modes_supported:g(c()).optional(),grant_types_supported:g(c()).optional(),acr_values_supported:g(c()).optional(),subject_types_supported:g(c()),id_token_signing_alg_values_supported:g(c()),id_token_encryption_alg_values_supported:g(c()).optional(),id_token_encryption_enc_values_supported:g(c()).optional(),userinfo_signing_alg_values_supported:g(c()).optional(),userinfo_encryption_alg_values_supported:g(c()).optional(),userinfo_encryption_enc_values_supported:g(c()).optional(),request_object_signing_alg_values_supported:g(c()).optional(),request_object_encryption_alg_values_supported:g(c()).optional(),request_object_encryption_enc_values_supported:g(c()).optional(),token_endpoint_auth_methods_supported:g(c()).optional(),token_endpoint_auth_signing_alg_values_supported:g(c()).optional(),display_values_supported:g(c()).optional(),claim_types_supported:g(c()).optional(),claims_supported:g(c()).optional(),service_documentation:c().optional(),claims_locales_supported:g(c()).optional(),ui_locales_supported:g(c()).optional(),claims_parameter_supported:E().optional(),request_parameter_supported:E().optional(),request_uri_parameter_supported:E().optional(),require_request_uri_registration:E().optional(),op_policy_uri:be.optional(),op_tos_uri:be.optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0)}),Do=p({...Ri.shape,...Ur.pick({code_challenge_methods_supported:!0}).shape}),Fo=p({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:pb().optional(),scope:c().optional(),refresh_token:c().optional(),issuer:c().optional().catch(void 0)}).strip(),xi=p({issued_token_type:h("urn:ietf:params:oauth:token-type:id-jag"),access_token:c(),token_type:c().optional(),expires_in:z().optional(),scope:c().optional()}).strip(),Ho=p({error:c(),error_description:c().optional(),error_uri:c().optional()}),Kl=be.optional().or(h("").transform(()=>{return})),Pi=p({redirect_uris:g(be),token_endpoint_auth_method:c().optional(),grant_types:g(c()).optional(),response_types:g(c()).optional(),application_type:c().optional(),client_name:c().optional(),client_uri:be.optional(),logo_uri:Kl,scope:c().optional(),contacts:g(c()).optional(),tos_uri:Kl,policy_uri:c().optional(),jwks_uri:be.optional(),jwks:Ma().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Ti=p({client_id:c(),client_secret:c().optional(),client_id_issued_at:z().optional(),client_secret_expires_at:z().optional(),issuer:c().optional().catch(void 0)}).strip(),Vo=Pi.merge(Ti),cc=p({error:c(),error_description:c().optional()}).strip(),lc=p({token:c(),token_type_hint:c().optional()}).strip();var tu=Symbol.for("mcp.sdk.errorBrands");function Zr(e,t){let r=new Set,o=t;while(typeof o==="function"){let n=o.mcpBrand;if(Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof n==="string")r.add(n);o=Object.getPrototypeOf(o)}if(r.size===0)return;Object.defineProperty(e,tu,{value:r,enumerable:!1,configurable:!0})}function Be(e,t){try{if(typeof t==="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand==="string"&&Object.prototype.hasOwnProperty.call(t,tu)){let r=t[tu];if(r&&typeof r.has==="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var Ut=function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e}({}),Dr=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Be(this,t)}static isInstance(t){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,t)}constructor(t,r,o){super(r);this.code=t,this.errorUri=o,this.name="OAuthError",Zr(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};if(this.errorUri)t.error_uri=this.errorUri;return t}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}},O=function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e}({}),N=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e,t,r,o){super(t,o);this.code=e,this.data=r,this.name="SdkError",Zr(this,new.target)}},vt=class extends N{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,o){super(e,t,r,o);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function If(e){let t=typeof e==="string"?new URL(e):new URL(e.href);return t.hash="",t}function iu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}function Of({requestedResource:e,configuredResource:t}){let r=typeof e==="string"?new URL(e):new URL(e.href),o=typeof t==="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin)return!1;if(r.pathname.length<o.pathname.length)return!1;let n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(i)}var Nf="2026-07-28",au=[Nf];function Zt(e){return e>=Nf}function cu(e){return e.filter((t)=>!Zt(t))}function Oi(e){return e.filter((t)=>Zt(t))}function qf(e){let t=e.structuredContent;if(t===void 0)return e;if(!(typeof t!=="object"||t===null||Array.isArray(t)))return e;if(e.content?.some((r)=>r.type==="text")??!1)return e;return{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}var Af=["task","inputRequests","requestState"];function gb(e){if(e===null||typeof e!=="object"||Array.isArray(e)||e.content!==void 0||Af.some((t)=>(t in e)))return e;return{...e,content:[]}}function Sb(){let e=Bn(()=>T([c(),z(),E(),Rr(),P(c(),e),g(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=p({ttl:z().optional()}),i=p({taskId:c()}),s=F({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),a=p({_meta:s.optional()}),l=a.extend({task:n.optional()}),u=p({method:c(),params:a.loose().optional()}),d=p({_meta:s.optional()}),m=p({method:c(),params:d.loose().optional()}),f=F({_meta:s.optional()}),S=T([c(),z().int()]),b=f.strict(),y=d.extend({requestId:S.optional(),reason:c().optional()}),v=m.extend({method:h("notifications/cancelled"),params:y}),U=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),H=p({icons:g(U).optional()}),x=p({name:c(),title:c().optional()}),Z=x.extend({...x.shape,...H.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),R=$t(p({applyDefaults:E().optional()}),t),w=xr((Pe)=>{if(Pe&&typeof Pe==="object"&&!Array.isArray(Pe)&&Object.keys(Pe).length===0)return{form:{}};return Pe},$t(p({form:R.optional(),url:t.optional()}),t.optional())),D=F({list:t.optional(),cancel:t.optional(),requests:F({sampling:F({createMessage:t.optional()}).optional(),elicitation:F({create:t.optional()}).optional()}).optional()}),X=F({list:t.optional(),cancel:t.optional(),requests:F({tools:F({call:t.optional()}).optional()}).optional()}),Y=p({experimental:P(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:w.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:D.optional(),extensions:P(c(),t).optional()}),le=a.extend({protocolVersion:c(),capabilities:Y,clientInfo:Z}),Ee=u.extend({method:h("initialize"),params:le}),te=p({experimental:P(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:X.optional(),extensions:P(c(),t).optional()}),ie=f.extend({protocolVersion:c(),capabilities:te,serverInfo:Z,instructions:c().optional()}),ve=m.extend({method:h("notifications/initialized"),params:d.optional()}),ke=u.extend({method:h("ping"),params:a.optional()}),ct=p({progress:z(),total:j(z()),message:j(c())}),qe=p({...d.shape,...ct.shape,progressToken:r}),We=m.extend({method:h("notifications/progress"),params:qe}),lt=a.extend({cursor:o.optional()}),Ze=u.extend({params:lt.optional()}),$e=f.extend({nextCursor:o.optional()}),Tt=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),Et=Tt.extend({text:c()}),ut=c().refine((Pe)=>{try{return atob(Pe),!0}catch{return!1}},{message:"Invalid Base64 string"}),Re=Tt.extend({blob:ut}),Ce=K(["user","assistant"]),Ie=p({audience:g(Ce).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),et=p({...x.shape,...H.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:Ie.optional(),_meta:j(F({}))}),lr=p({...x.shape,...H.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:Ie.optional(),_meta:j(F({}))}),De=Ze.extend({method:h("resources/list")}),Fe=$e.extend({resources:g(et)}),Ae=Ze.extend({method:h("resources/templates/list")}),Ke=$e.extend({resourceTemplates:g(lr)}),Ge=a.extend({uri:c()}),dt=Ge,pt=u.extend({method:h("resources/read"),params:dt}),Ht=f.extend({contents:g(T([Et,Re]))}),ht=m.extend({method:h("notifications/resources/list_changed"),params:d.optional()}),ur=Ge,C=u.extend({method:h("resources/subscribe"),params:ur}),mt=Ge,V=u.extend({method:h("resources/unsubscribe"),params:mt}),q=d.extend({uri:c()}),G=m.extend({method:h("notifications/resources/updated"),params:q}),I=p({name:c(),description:j(c()),required:j(E())}),k=p({...x.shape,...H.shape,description:j(c()),arguments:j(g(I)),_meta:j(F({}))}),B=Ze.extend({method:h("prompts/list")}),J=$e.extend({prompts:g(k)}),ge=a.extend({name:c(),arguments:P(c(),c()).optional()}),dr=u.extend({method:h("prompts/get"),params:ge}),ft=p({type:h("text"),text:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),pr=p({type:h("image"),data:ut,mimeType:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),hr=p({type:h("audio"),data:ut,mimeType:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),nn=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),Vt=p({type:h("resource"),resource:T([Et,Re]),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),sn=et.extend({type:h("resource_link")}),Ye=T([ft,pr,hr,sn,Vt]),Kr=p({role:Ce,content:Ye}),Gr=f.extend({description:c().optional(),messages:g(Kr)}),mr=m.extend({method:h("notifications/prompts/list_changed"),params:d.optional()}),an=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Yr=p({taskSupport:K(["required","optional","forbidden"]).optional()}),fr=p({...x.shape,...H.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:g(c()).optional()}).catchall(A()),outputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:g(c()).optional()}).catchall(A()).optional(),annotations:an.optional(),execution:Yr.optional(),_meta:P(c(),A()).optional()}),Xr=Ze.extend({method:h("tools/list")}),Qr=$e.extend({tools:g(fr)}),eo=f.extend({content:g(Ye),structuredContent:P(c(),A()).optional(),isError:E().optional()}),xe=l.extend({name:c(),arguments:P(c(),A()).optional()}),cn=u.extend({method:h("tools/call"),params:xe}),Gi=m.extend({method:h("notifications/tools/list_changed"),params:d.optional()}),to=K(["debug","info","notice","warning","error","critical","alert","emergency"]),ln=a.extend({level:to}),un=u.extend({method:h("logging/setLevel"),params:ln}),dn=d.extend({level:to,logger:c().optional(),data:A()}),pn=m.extend({method:h("notifications/message"),params:dn}),hn=p({name:c().optional()}),mn=p({hints:g(hn).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),fn=p({mode:K(["auto","required","none"]).optional()}),Yi=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:g(Ye),structuredContent:p({}).loose().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),gn=po("type",[ft,pr,hr]),Jt=po("type",[ft,pr,hr,nn,Yi]),Sn=p({role:Ce,content:T([Jt,g(Jt)]),_meta:P(c(),A()).optional()}),_n=l.extend({messages:g(Sn),modelPreferences:mn.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:t.optional(),tools:g(fr).optional(),toolChoice:fn.optional()}),bn=u.extend({method:h("sampling/createMessage"),params:_n}),yn=f.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Ce,content:gn}),vn=f.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Ce,content:T([Jt,g(Jt)])}),zn=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),wn=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),Rn=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),xn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),Pn=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),Tn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),En=T([xn,Pn]),gr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),Sr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),Xi=T([gr,Sr]),Qi=T([Tn,En,Xi]),He=T([Qi,zn,wn,Rn]),Ve=l.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),He),required:g(c()).optional()}).catchall(A())}),kn=l.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),tt=T([Ve,kn]),ea=u.extend({method:h("elicitation/create"),params:tt}),ta=d.extend({elicitationId:c()}),ra=m.extend({method:h("notifications/elicitation/complete"),params:ta}),oa=f.extend({action:K(["accept","decline","cancel"]),content:xr((Pe)=>Pe===null?void 0:Pe,P(c(),T([c(),z(),E(),g(c())])).optional())}),na=p({type:h("ref/resource"),uri:c()}),sa=p({type:h("ref/prompt"),name:c()}),ia=a.extend({ref:T([sa,na]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),$n=u.extend({method:h("completion/complete"),params:ia}),aa=f.extend({completion:F({values:g(c()).max(100),total:j(z().int()),hasMore:j(E())})}),ca=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),ro=u.extend({method:h("roots/list"),params:a.optional()}),Cn=f.extend({roots:g(ca)}),la=m.extend({method:h("notifications/roots/list_changed"),params:d.optional()}),ua=F({ttl:z().optional(),pollInterval:z().optional()}),In=K(["working","input_required","completed","failed","cancelled"]),Bt=p({taskId:c(),status:In,ttl:T([z(),Rr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:j(z()),statusMessage:j(c())}),Me=f.extend({task:Bt}),da=d.merge(Bt),_r=m.extend({method:h("notifications/tasks/status"),params:da}),oo=u.extend({method:h("tasks/get"),params:a.extend({taskId:c()})}),no=f.merge(Bt),so=u.extend({method:h("tasks/result"),params:a.extend({taskId:c()})}),Mc=f.loose(),Oe=Ze.extend({method:h("tasks/list")}),fe=$e.extend({tasks:g(Bt)}),br=u.extend({method:h("tasks/cancel"),params:a.extend({taskId:c()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:n,RelatedTaskMetadataSchema:i,RequestMetaSchema:s,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:l,RequestSchema:u,NotificationsParamsSchema:d,NotificationSchema:m,ResultSchema:f,RequestIdSchema:S,EmptyResultSchema:b,CancelledNotificationParamsSchema:y,CancelledNotificationSchema:v,IconSchema:U,IconsSchema:H,BaseMetadataSchema:x,ImplementationSchema:Z,ClientTasksCapabilitySchema:D,ServerTasksCapabilitySchema:X,ClientCapabilitiesSchema:Y,InitializeRequestParamsSchema:le,InitializeRequestSchema:Ee,ServerCapabilitiesSchema:te,InitializeResultSchema:ie,InitializedNotificationSchema:ve,PingRequestSchema:ke,ProgressSchema:ct,ProgressNotificationParamsSchema:qe,ProgressNotificationSchema:We,PaginatedRequestParamsSchema:lt,PaginatedRequestSchema:Ze,PaginatedResultSchema:$e,ResourceContentsSchema:Tt,TextResourceContentsSchema:Et,BlobResourceContentsSchema:Re,RoleSchema:Ce,AnnotationsSchema:Ie,ResourceSchema:et,ResourceTemplateSchema:lr,ListResourcesRequestSchema:De,ListResourcesResultSchema:Fe,ListResourceTemplatesRequestSchema:Ae,ListResourceTemplatesResultSchema:Ke,ResourceRequestParamsSchema:Ge,ReadResourceRequestParamsSchema:dt,ReadResourceRequestSchema:pt,ReadResourceResultSchema:Ht,ResourceListChangedNotificationSchema:ht,SubscribeRequestParamsSchema:ur,SubscribeRequestSchema:C,UnsubscribeRequestParamsSchema:mt,UnsubscribeRequestSchema:V,ResourceUpdatedNotificationParamsSchema:q,ResourceUpdatedNotificationSchema:G,PromptArgumentSchema:I,PromptSchema:k,ListPromptsRequestSchema:B,ListPromptsResultSchema:J,GetPromptRequestParamsSchema:ge,GetPromptRequestSchema:dr,TextContentSchema:ft,ImageContentSchema:pr,AudioContentSchema:hr,ToolUseContentSchema:nn,EmbeddedResourceSchema:Vt,ResourceLinkSchema:sn,ContentBlockSchema:Ye,PromptMessageSchema:Kr,GetPromptResultSchema:Gr,PromptListChangedNotificationSchema:mr,ToolAnnotationsSchema:an,ToolExecutionSchema:Yr,ToolSchema:fr,ListToolsRequestSchema:Xr,ListToolsResultSchema:Qr,CallToolResultSchema:eo,CallToolRequestParamsSchema:xe,CallToolRequestSchema:cn,ToolListChangedNotificationSchema:Gi,LoggingLevelSchema:to,SetLevelRequestParamsSchema:ln,SetLevelRequestSchema:un,LoggingMessageNotificationParamsSchema:dn,LoggingMessageNotificationSchema:pn,ModelHintSchema:hn,ModelPreferencesSchema:mn,ToolChoiceSchema:fn,ToolResultContentSchema:Yi,SamplingContentSchema:gn,SamplingMessageContentBlockSchema:Jt,SamplingMessageSchema:Sn,CreateMessageRequestParamsSchema:_n,CreateMessageRequestSchema:bn,CreateMessageResultSchema:yn,CreateMessageResultWithToolsSchema:vn,BooleanSchemaSchema:zn,StringSchemaSchema:wn,NumberSchemaSchema:Rn,UntitledSingleSelectEnumSchemaSchema:xn,TitledSingleSelectEnumSchemaSchema:Pn,LegacyTitledEnumSchemaSchema:Tn,SingleSelectEnumSchemaSchema:En,UntitledMultiSelectEnumSchemaSchema:gr,TitledMultiSelectEnumSchemaSchema:Sr,MultiSelectEnumSchemaSchema:Xi,EnumSchemaSchema:Qi,PrimitiveSchemaDefinitionSchema:He,ElicitRequestFormParamsSchema:Ve,ElicitRequestURLParamsSchema:kn,ElicitRequestParamsSchema:tt,ElicitRequestSchema:ea,ElicitationCompleteNotificationParamsSchema:ta,ElicitationCompleteNotificationSchema:ra,ElicitResultSchema:oa,ResourceTemplateReferenceSchema:na,PromptReferenceSchema:sa,CompleteRequestParamsSchema:ia,CompleteRequestSchema:$n,CompleteResultSchema:aa,RootSchema:ca,ListRootsRequestSchema:ro,ListRootsResultSchema:Cn,RootsListChangedNotificationSchema:la,TaskCreationParamsSchema:ua,TaskStatusSchema:In,TaskSchema:Bt,CreateTaskResultSchema:Me,TaskStatusNotificationParamsSchema:da,TaskStatusNotificationSchema:_r,GetTaskRequestSchema:oo,GetTaskResultSchema:no,GetTaskPayloadRequestSchema:so,GetTaskPayloadResultSchema:Mc,ListTasksRequestSchema:Oe,ListTasksResultSchema:fe,CancelTaskRequestSchema:br,CancelTaskResultSchema:f.merge(Bt),ClientRequestSchema:T([ke,Ee,$n,un,dr,B,De,Ae,pt,C,V,cn,Xr,oo,so,Oe,br]),ClientNotificationSchema:T([v,We,ve,la,_r]),ClientResultSchema:T([b,yn,vn,oa,Cn,no,fe,Me]),ServerRequestSchema:T([ke,bn,ea,ro,oo,so,Oe,br]),ServerNotificationSchema:T([v,We,pn,G,ht,Gi,mr,_r,ra]),ServerResultSchema:T([b,ie,aa,Gr,J,Fe,Ke,Ht,eo,Qr,no,fe,Me]),CallToolResultWireSchema:A().superRefine((Pe,AS)=>{if(typeof Pe!=="object"||Pe===null||Array.isArray(Pe)||Pe.content!==void 0)return;for(let rd of Af)if(rd in Pe){AS.addIssue({code:"custom",message:`content is required when the body carries '${rd}' — another result family cannot default into an empty tools/call success`});return}}).transform(gb).pipe(eo)}}var _b;function Mf(){return _b??=Sb()}function jf(e){return e.type!=="object"}var bb=new Set(["const","enum","default","examples"]),yb=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function _f(e){return e!==void 0&&!(typeof e==="string"&&e.startsWith("#"))}function vb(e){let t=typeof e.$schema==="string"?e.$schema:void 0;if(_f(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=cd(e.$schema)&&e.$recursiveAnchor!==!0,o=(n,i)=>{if(Array.isArray(n))return n.map((l)=>o(l,!1));if(n===null||typeof n!=="object")return n;if(!i&&_f(n.$id))return n;let s={},a=!1;for(let[l,u]of Object.entries(n))if(i)s[l]=o(u,!1);else if((l==="$ref"||l==="$dynamicRef")&&typeof u==="string")s[l]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u;else if(l==="$recursiveRef"&&u==="#"&&r)a=!0;else if(bb.has(l))s[l]=u;else if(yb.has(l))s[l]=o(u,!0);else s[l]=o(u,!1);if(a)if("$ref"in s)s.allOf=[...Array.isArray(s.allOf)?s.allOf:[],{$ref:"#/properties/result"}];else s.$ref="#/properties/result";return s};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}var Lf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Uf={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},zb={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},uc;function lu(){if(uc)return uc;let e=Mf();return uc={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},uc}function Zf(e){return Object.prototype.hasOwnProperty.call(Lf,e)}function Df(e){return Object.prototype.hasOwnProperty.call(Uf,e)}function wb(e){return Object.prototype.hasOwnProperty.call(zb,e)}function Rb(e){return wb(e)?lu().resultSchemas[e]:void 0}function xb(e){return Zf(e)?lu().requestSchemas[e]:void 0}function Pb(e){return Df(e)?lu().notificationSchemas[e]:void 0}var kx=Object.keys(Lf),$x=Object.keys(Uf);function ru(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function dc(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var bf={ok:!1,reason:"not-in-era"};function yf(e){return ru(e)&&ru(e.outputSchema)&&jf(e.outputSchema)}function vf(e){return e}var uu={era:"2025-11-25",hasRequestMethod:Zf,hasNotificationMethod:Df,validateRequest:(e,t)=>dc(xb(e),t),validateResult:(e,t)=>dc(Rb(e),t),validateNotification:(e,t)=>dc(Pb(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>bf,validateInputResponse:()=>bf,samplingResultVariant:(e,t)=>{let r=Mf();return dc(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)},outboundEnvelope:(e)=>{return},validateEnvelopeMeta:(e)=>[],projectCallToolResult(e,t){let r=qf(e),o=r.structuredContent;if(o===void 0)return r;let n=typeof o!=="object"||o===null||Array.isArray(o),i=t!==void 0&&jf(t);if(!n&&!i)return r;return{...r,structuredContent:{result:o}}},decodeResult(e,t){if(ru(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:vf(r)}}return{kind:"complete",result:vf(t)}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;if(!Array.isArray(r)||!r.some((o)=>yf(o)))return t;return{...t,tools:r.map((o)=>yf(o)?{...o,outputSchema:vb(o.outputSchema)}:o)}},encodeErrorCode:(e)=>e===-32002?-32602:e,checkInboundEnvelope:(e)=>{return}};function Tb(){let e=Bn(()=>T([c(),z(),E(),Rr(),P(c(),e),g(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=T([c(),z().int()]),i=K(["user","assistant"]),s=K(["debug","info","notice","warning","error","critical","alert","emergency"]),a=c().refine((fe)=>{try{return atob(fe),!0}catch{return!1}},{message:"Invalid Base64 string"}),l=p({ttl:z().optional()}),u=p({taskId:c()}),d=F({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),m=p({_meta:d.optional()}),f=m.extend({task:l.optional()}),S=p({_meta:d.optional()}),b=p({method:c(),params:S.loose().optional()}),y=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),v=p({icons:g(y).optional()}),U=p({name:c(),title:c().optional()}),H=U.extend({...U.shape,...v.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),x=$t(p({applyDefaults:E().optional()}),t),Z=xr((fe)=>{if(fe&&typeof fe==="object"&&!Array.isArray(fe)&&Object.keys(fe).length===0)return{form:{}};return fe},$t(p({form:x.optional(),url:t.optional()}),t.optional())),R=F({list:t.optional(),cancel:t.optional(),requests:F({sampling:F({createMessage:t.optional()}).optional(),elicitation:F({create:t.optional()}).optional()}).optional()}),w=F({list:t.optional(),cancel:t.optional(),requests:F({tools:F({call:t.optional()}).optional()}).optional()}),D=p({experimental:P(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:Z.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:R.optional(),extensions:P(c(),t).optional()}),X=p({experimental:P(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:w.optional(),extensions:P(c(),t).optional()}),Y=p({progress:z(),total:j(z()),message:j(c())}),le=p({...S.shape,...Y.shape,progressToken:r}),Ee=b.extend({method:h("notifications/progress"),params:le}),te=S.extend({level:s,logger:c().optional(),data:A()}),ie=b.extend({method:h("notifications/message"),params:te}),ve=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),ke=ve.extend({text:c()}),ct=ve.extend({blob:a}),qe=p({audience:g(i).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),We=p({...U.shape,...v.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:qe.optional(),_meta:j(F({}))}),lt=p({...U.shape,...v.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:qe.optional(),_meta:j(F({}))}),Ze=b.extend({method:h("notifications/resources/list_changed"),params:S.optional()}),$e=S.extend({uri:c()}),Tt=b.extend({method:h("notifications/resources/updated"),params:$e}),Et=p({name:c(),description:j(c()),required:j(E())}),ut=p({...U.shape,...v.shape,description:j(c()),arguments:j(g(Et)),_meta:j(F({}))}),Re=b.extend({method:h("notifications/prompts/list_changed"),params:S.optional()}),Ce=p({type:h("text"),text:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),Ie=p({type:h("image"),data:a,mimeType:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),et=p({type:h("audio"),data:a,mimeType:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),lr=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),De=p({type:h("resource"),resource:T([ke,ct]),annotations:qe.optional(),_meta:P(c(),A()).optional()}),Fe=We.extend({type:h("resource_link")}),Ae=T([Ce,Ie,et,Fe,De]),Ke=p({role:i,content:Ae}),Ge=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),dt=b.extend({method:h("notifications/tools/list_changed"),params:S.optional()}),pt=p({name:c().optional()}),Ht=p({hints:g(pt).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),ht=p({mode:K(["auto","required","none"]).optional()}),ur=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),C=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),mt=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),V=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),q=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),G=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),I=T([V,q]),k=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),B=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),J=T([k,B]),ge=T([G,I,J]),dr=T([ge,ur,C,mt]),ft=f.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),dr),required:g(c()).optional()}).catchall(A())}),pr=p({type:h("ref/resource"),uri:c()}),hr=p({type:h("ref/prompt"),name:c()}),nn=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),Vt=D.shape,sn=p({experimental:Vt.experimental,sampling:Vt.sampling,elicitation:Vt.elicitation,roots:Vt.roots,extensions:Vt.extensions}),Ye=X.shape,Kr=p({experimental:Ye.experimental,logging:Ye.logging,completions:Ye.completions,prompts:Ye.prompts,resources:Ye.resources,tools:Ye.tools,extensions:Ye.extensions}),Gr=F({progressToken:r.optional(),[It]:c(),[mo]:H.optional(),[Pr]:sn,[fo]:s.optional()}),mr=p({...U.shape,...v.shape,description:c().optional(),inputSchema:F({$schema:c().optional(),type:h("object")}),outputSchema:F({$schema:c().optional()}).optional(),annotations:Ge.optional(),_meta:P(c(),A()).optional()}),an=p({type:h("tool_result"),toolUseId:c(),content:g(Ae),structuredContent:A().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),Yr=T([Ce,Ie,et,lr,an]),fr=p({role:i,content:T([Yr,g(Yr)]),_meta:P(c(),A()).optional()}),Xr=c(),Qr=F({[Ot]:H.optional().catch(void 0)}),eo=Qr.optional();function xe(fe){return F({_meta:eo,resultType:Xr.default("complete"),...fe})}let cn=xe({}),Gi=xe({nextCursor:o.optional()}),to=xe({content:g(Ae),structuredContent:A().optional(),isError:E().optional()}),ln=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:g(mr),nextCursor:o.optional()}),un=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:g(ut),nextCursor:o.optional()}),dn=xe({description:c().optional(),messages:g(Ke)}),pn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:g(We),nextCursor:o.optional()}),hn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:g(lt),nextCursor:o.optional()}),mn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:g(T([ke,ct]))}),fn=xe({completion:p({values:g(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),Yi=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"])}),gn=xe({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:g(c()),capabilities:Kr,instructions:c().optional()}),Jt=p({messages:g(fr),modelPreferences:Ht.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:t.optional(),tools:g(mr).optional(),toolChoice:ht.optional()}),Sn=p({method:h("sampling/createMessage"),params:Jt}),_n=p({method:h("roots/list"),params:p({_meta:P(c(),A()).optional()}).optional()}),bn=p({...fr.shape,model:c(),stopReason:c().optional()}),yn=p({roots:g(nn)}),vn=p({action:K(["accept","decline","cancel"]),content:P(c(),T([c(),z(),E(),g(c())])).optional()}),zn=p({mode:h("url"),message:c(),url:c().url()}),wn=T([ft,zn]),Rn=p({method:h("elicitation/create"),params:wn}),xn=T([Sn,_n,Rn]),Pn=T([bn,yn,vn]),Tn=P(c(),xn),En=P(c(),Pn),gr=xe({inputRequests:Tn.optional(),requestState:c().optional()}),Sr={inputResponses:En.optional(),requestState:c().optional()},Xi=p({_meta:Gr,...Sr}),Qi=F({progressToken:r.optional()});function He(fe,br){return p({method:h(fe),params:p({_meta:Gr,...br})})}function Ve(fe,br){return p({method:h(fe),params:p({_meta:Qi.optional(),...br}).optional()})}let kn={name:c(),arguments:P(c(),A()).optional(),...Sr},tt={cursor:o.optional()},ea=He("tools/call",kn),ta=He("tools/list",tt),ra=He("prompts/list",tt),oa=He("prompts/get",{name:c(),arguments:P(c(),c()).optional(),...Sr}),na=He("resources/list",tt),sa=He("resources/templates/list",tt),ia=He("resources/read",{uri:c(),...Sr}),$n={ref:T([hr,pr]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()},aa=He("completion/complete",$n),ca=He("server/discover",{}),ro=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:g(c()).optional()}),Cn={notifications:ro},la=He("subscriptions/listen",Cn),ua=Qr.extend({"io.modelcontextprotocol/subscriptionId":n}),In=F({_meta:ua,resultType:Xr.default("complete")}),Bt={"tools/call":Ve("tools/call",kn),"tools/list":Ve("tools/list",tt),"prompts/get":Ve("prompts/get",{name:c(),arguments:P(c(),c()).optional()}),"prompts/list":Ve("prompts/list",tt),"resources/list":Ve("resources/list",tt),"resources/templates/list":Ve("resources/templates/list",tt),"resources/read":Ve("resources/read",{uri:c()}),"completion/complete":Ve("completion/complete",$n),"server/discover":Ve("server/discover",{}),"subscriptions/listen":Ve("subscriptions/listen",Cn)};function Me(fe){return F({_meta:eo,...fe})}let da={"tools/call":Me({content:g(Ae),structuredContent:A().optional(),isError:E().optional()}),"tools/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:g(mr),nextCursor:o.optional()}),"prompts/get":Me({description:c().optional(),messages:g(Ke)}),"prompts/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:g(ut),nextCursor:o.optional()}),"resources/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:g(We),nextCursor:o.optional()}),"resources/templates/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:g(lt),nextCursor:o.optional()}),"resources/read":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:g(T([ke,ct]))}),"completion/complete":Me({completion:p({values:g(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":Me({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:g(c()),capabilities:Kr,instructions:c().optional()}),"subscriptions/listen":Me({})},_r=F({"io.modelcontextprotocol/subscriptionId":n.optional()}),oo=p({method:h("notifications/subscriptions/acknowledged"),params:p({_meta:_r.optional(),notifications:ro})}),no=p({_meta:_r.optional(),requestId:n,reason:c().optional()}),so=p({method:h("notifications/cancelled"),params:no}),Mc={"notifications/cancelled":so,"notifications/progress":Ee,"notifications/message":ie,"notifications/resources/updated":Tt,"notifications/resources/list_changed":Ze,"notifications/tools/list_changed":dt,"notifications/prompts/list_changed":Re,"notifications/subscriptions/acknowledged":oo},Oe=(fe)=>p({jsonrpc:h("2.0"),id:T([c(),z().int()]),result:fe}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:n,RoleSchema:i,LoggingLevelSchema:s,TaskMetadataSchema:l,RelatedTaskMetadataSchema:u,RequestMetaSchema:d,BaseRequestParamsSchema:m,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:S,NotificationSchema:b,IconSchema:y,IconsSchema:v,BaseMetadataSchema:U,ImplementationSchema:H,ClientTasksCapabilitySchema:R,ServerTasksCapabilitySchema:w,ClientCapabilitiesSchema:D,ServerCapabilitiesSchema:X,ProgressSchema:Y,ProgressNotificationParamsSchema:le,ProgressNotificationSchema:Ee,LoggingMessageNotificationParamsSchema:te,LoggingMessageNotificationSchema:ie,ResourceContentsSchema:ve,TextResourceContentsSchema:ke,BlobResourceContentsSchema:ct,AnnotationsSchema:qe,ResourceSchema:We,ResourceTemplateSchema:lt,ResourceListChangedNotificationSchema:Ze,ResourceUpdatedNotificationParamsSchema:$e,ResourceUpdatedNotificationSchema:Tt,PromptArgumentSchema:Et,PromptSchema:ut,PromptListChangedNotificationSchema:Re,TextContentSchema:Ce,ImageContentSchema:Ie,AudioContentSchema:et,ToolUseContentSchema:lr,EmbeddedResourceSchema:De,ResourceLinkSchema:Fe,ContentBlockSchema:Ae,PromptMessageSchema:Ke,ToolAnnotationsSchema:Ge,ToolListChangedNotificationSchema:dt,ModelHintSchema:pt,ModelPreferencesSchema:Ht,ToolChoiceSchema:ht,BooleanSchemaSchema:ur,StringSchemaSchema:C,NumberSchemaSchema:mt,UntitledSingleSelectEnumSchemaSchema:V,TitledSingleSelectEnumSchemaSchema:q,LegacyTitledEnumSchemaSchema:G,SingleSelectEnumSchemaSchema:I,UntitledMultiSelectEnumSchemaSchema:k,TitledMultiSelectEnumSchemaSchema:B,MultiSelectEnumSchemaSchema:J,EnumSchemaSchema:ge,PrimitiveSchemaDefinitionSchema:dr,ElicitRequestFormParamsSchema:ft,ResourceTemplateReferenceSchema:pr,PromptReferenceSchema:hr,RootSchema:nn,ClientCapabilities2026Schema:sn,ServerCapabilities2026Schema:Kr,RequestMetaEnvelopeSchema:Gr,ToolSchema:mr,ToolResultContentSchema:an,SamplingMessageContentBlockSchema:Yr,SamplingMessageSchema:fr,ResultTypeSchema:Xr,ResultMetaSchema:Qr,ResultSchema:cn,PaginatedResultSchema:Gi,CallToolResultSchema:to,ListToolsResultSchema:ln,ListPromptsResultSchema:un,GetPromptResultSchema:dn,ListResourcesResultSchema:pn,ListResourceTemplatesResultSchema:hn,ReadResourceResultSchema:mn,CompleteResultSchema:fn,CacheableResultSchema:Yi,DiscoverResultSchema:gn,CreateMessageRequestParamsSchema:Jt,CreateMessageRequestSchema:Sn,ListRootsRequestSchema:_n,CreateMessageResultSchema:bn,ListRootsResultSchema:yn,ElicitResultSchema:vn,ElicitRequestURLParamsSchema:zn,ElicitRequestParamsSchema:wn,ElicitRequestSchema:Rn,InputRequestSchema:xn,InputResponseSchema:Pn,InputRequestsSchema:Tn,InputResponsesSchema:En,InputRequiredResultSchema:gr,InputResponseRequestParamsSchema:Xi,CallToolRequestSchema:ea,ListToolsRequestSchema:ta,ListPromptsRequestSchema:ra,GetPromptRequestSchema:oa,ListResourcesRequestSchema:na,ListResourceTemplatesRequestSchema:sa,ReadResourceRequestSchema:ia,CompleteRequestSchema:aa,DiscoverRequestSchema:ca,SubscriptionFilterSchema:ro,SubscriptionsListenRequestSchema:la,SubscriptionsListenResultMetaSchema:ua,SubscriptionsListenResultSchema:In,dispatchRequestSchemas:Bt,dispatchResultSchemas:da,NotificationMetaSchema:_r,SubscriptionsAcknowledgedNotificationSchema:oo,CancelledNotificationParamsSchema:no,CancelledNotificationSchema:so,notificationSchemas2026:Mc,JSONRPCResultResponseSchema:Oe(cn),CallToolResultResponseSchema:Oe(T([to,gr])),ListToolsResultResponseSchema:Oe(ln),ListPromptsResultResponseSchema:Oe(un),GetPromptResultResponseSchema:Oe(T([dn,gr])),ListResourcesResultResponseSchema:Oe(pn),ListResourceTemplatesResultResponseSchema:Oe(hn),ReadResourceResultResponseSchema:Oe(T([mn,gr])),CompleteResultResponseSchema:Oe(fn),DiscoverResultResponseSchema:Oe(gn),SubscriptionsListenResultResponseSchema:Oe(In)}}var Eb;function sr(){return Eb??=Tb()}var kb=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function $b(e){return kb.includes(e)}var du=Symbol("modelcontextprotocol.resultCacheHintFallback");function Cb(e){return e[du]}function Ff(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function Hf(e){return e==="public"||e==="private"}var W=function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e}({}),ee=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Be(this,t)}static isInstance(t){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,t)}constructor(t,r,o){super(r);this.code=t,this.data=o,this.name="ProtocolError",Zr(this,new.target)}static fromError(t,r,o){if(t===W.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new Jf(n.elicitations,r)}if(t===W.UnsupportedProtocolVersion&&o){let n=o;if(Array.isArray(n.supported)&&typeof n.requested==="string")return new gc({supported:n.supported,requested:n.requested},r)}if(t===W.InvalidParams||t===W.ResourceNotFound){let n=o;if(typeof n?.uri==="string"&&(t===W.ResourceNotFound||Object.keys(n).length===1))return new Vf(n.uri,r)}if(t===W.MissingRequiredClientCapability&&o){let n=o;if(n.requiredCapabilities!==null&&typeof n.requiredCapabilities==="object"&&!Array.isArray(n.requiredCapabilities))return new Bf({requiredCapabilities:n.requiredCapabilities},r)}return new e(t,r,o)}},Vf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(W.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Jf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(W.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},gc=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(W.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Bf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(W.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},Ib=0,Ob="private",Nb=["tools/call","prompts/get","resources/read"];function qb(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete")return t;if(Nb.includes(e))return t;throw new ee(W.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function Ab(e,t){let r=Cb(t);if(t.resultType!=="complete"||!$b(e))return r===void 0?t:Zb(t);let o=t,n=Ff(o.ttlMs)?o.ttlMs:Lb(r),i=Hf(o.cacheScope)?o.cacheScope:Ub(r),s={...o,ttlMs:n,cacheScope:i};return delete s[du],s}function Mb(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function jb(e,t){if(t===void 0)return e;let r=e._meta;if(r===void 0)return{...e,_meta:{[Ot]:t}};if(!Mb(r))return e;if(r[Ot]!==void 0)return e;return{...e,_meta:{...r,[Ot]:t}}}function Lb(e){return e!==void 0&&Ff(e.ttlMs)?e.ttlMs:Ib}function Ub(e){return e!==void 0&&Hf(e.cacheScope)?e.cacheScope:Ob}function Zb(e){let t={...e};return delete t[du],t}var Db=["elicitation/create","sampling/createMessage","roots/list"],pc;function Wf(){if(pc)return pc;let e=sr();return pc={request:{"elicitation/create":p({method:h("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":p({method:h("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":p({method:h("roots/list"),params:F({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},pc}function Kf(e){return Db.includes(e)}function Yl(e){return Kf(e)?Wf().request[e]:void 0}function Fb(e){return Kf(e)?Wf().response[e]:void 0}var pu={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Gf={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function Yf(e){return Object.prototype.hasOwnProperty.call(pu,e)}function Xf(e){return Object.prototype.hasOwnProperty.call(Gf,e)}function Hb(e){return Object.prototype.hasOwnProperty.call(pu,e)}function Vb(e){return Yf(e)?sr().dispatchRequestSchemas[e]:void 0}function Jb(e){return Hb(e)?sr().dispatchResultSchemas[e]:void 0}function Bb(e){return Xf(e)?sr().notificationSchemas2026[e]:void 0}var Cx=Object.keys(pu),Ix=Object.keys(Gf);function $i(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Ei(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var Wb={ok:!1,reason:"not-in-era"},Kb=[It,Pr];function Gb(e,t){let r=t,o=!1,n=()=>{if(!o)r={...r},o=!0;return r},i=t.tools;if(e==="tools/list"&&Array.isArray(i)&&i.some((a)=>$i(a)&&("execution"in a)))n().tools=i.map((a)=>{if(!$i(a)||!("execution"in a))return a;let l={...a};return delete l.execution,l});let s=t.capabilities;if($i(s)&&"tasks"in s){let a={...s};delete a.tasks,n().capabilities=a}return r}var hu={era:"2026-07-28",hasRequestMethod:Yf,hasNotificationMethod:Xf,hasInputRequestMethod:(e)=>Yl(e)!==void 0,validateRequest:(e,t)=>Ei(Vb(e),t),validateResult:(e,t)=>Ei(Jb(e),t),validateNotification:(e,t)=>Ei(Bb(e),t),validateInputRequest:(e,t)=>Ei(Yl(e),t),validateInputResponse:(e,t)=>Ei(Fb(e),t),samplingResultVariant:()=>Wb,outboundEnvelope(e){return{[It]:e.protocolVersion,[mo]:e.clientInfo,[Pr]:e.clientCapabilities,...e.logLevel!==void 0&&{[fo]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of Kb)if(!(o in e))t.push({key:o,problem:"missing"});let r=sr().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let n=o.path.map(String),i=n.length>0?n.join("."):"_meta";if(n.length===1&&t.some((s)=>s.key===i&&s.problem==="missing"))continue;t.push({key:i,problem:o.message})}return t},projectCallToolResult:(e)=>qf(e),inputRequestSchema:Yl,decodeResult(e,t){if(!$i(t))return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!=="string")return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let s=t.inputRequests,a=$i(s)?s:{},l=t.requestState,u=t._meta===void 0?void 0:sr().ResultMetaSchema.safeParse(t._meta),d=u?.success?u.data:void 0;if(Object.keys(a).length===0&&typeof l!=="string")return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})};return{kind:"input_required",inputRequests:a,...typeof l==="string"&&{requestState:l},...d!==void 0&&{_meta:d}}}if(r!=="complete")return{kind:"invalid",error:new N(O.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=Yb(),n=Object.hasOwn(o,e)?o[e]:void 0;if(n!==void 0){let s=n.safeParse(t);if(!s.success)return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: ${s.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return jb(Ab(e,qb(e,Gb(e,t))),r)},encodeErrorCode:(e)=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=sr().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map((r)=>r.message).join("; ")}`}},hc;function Yb(){if(hc)return hc;let e=sr();return hc={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},hc}var Sc="2026-07-28";function Lt(e){return e!==void 0&&Zt(e)?hu:uu}function zf(e){if(e.revision!==void 0)return Lt(e.revision).era;return e.era==="modern"?hu.era:uu.era}function Xl(e){return Qf.some((t)=>t.hasRequestMethod(e))}function Ql(e){return Qf.some((t)=>t.hasNotificationMethod(e))}function wf(e){return e==="tasks/get"||e==="tasks/cancel"}var Qf=[uu,hu],Xb=sd({AnnotationsSchema:()=>bt,AudioContentSchema:()=>Or,BaseMetadataSchema:()=>St,BaseRequestParamsSchema:()=>ye,BlobResourceContentsSchema:()=>$o,BooleanSchemaSchema:()=>No,CallToolRequestParamsSchema:()=>Zs,CallToolRequestSchema:()=>Ds,CallToolResultSchema:()=>nr,CancelTaskRequestSchema:()=>ec,CancelTaskResultSchema:()=>tc,CancelledNotificationParamsSchema:()=>Yn,CancelledNotificationSchema:()=>zo,ClientCapabilitiesSchema:()=>Qn,ClientNotificationSchema:()=>oc,ClientRequestSchema:()=>rc,ClientResultSchema:()=>nc,ClientTasksCapabilitySchema:()=>Da,CompatibilityCallToolResultSchema:()=>Ha,CompleteRequestParamsSchema:()=>fi,CompleteRequestSchema:()=>gi,CompleteResultSchema:()=>Si,ContentBlockSchema:()=>yt,CreateMessageRequestParamsSchema:()=>ei,CreateMessageRequestSchema:()=>ti,CreateMessageResultSchema:()=>ri,CreateMessageResultWithToolsSchema:()=>oi,CreateTaskResultSchema:()=>Ja,CursorSchema:()=>So,DiscoverRequestSchema:()=>rs,DiscoverResultSchema:()=>rr,ElicitRequestFormParamsSchema:()=>Lr,ElicitRequestParamsSchema:()=>ci,ElicitRequestSchema:()=>li,ElicitRequestURLParamsSchema:()=>ai,ElicitResultSchema:()=>pi,ElicitationCompleteNotificationParamsSchema:()=>ui,ElicitationCompleteNotificationSchema:()=>di,EmbeddedResourceSchema:()=>Nr,EmptyResultSchema:()=>tr,EnumSchemaSchema:()=>ii,GetPromptRequestParamsSchema:()=>Cs,GetPromptRequestSchema:()=>Is,GetPromptResultSchema:()=>qs,GetTaskPayloadRequestSchema:()=>Ga,GetTaskPayloadResultSchema:()=>Ya,GetTaskRequestSchema:()=>Wa,GetTaskResultSchema:()=>Ka,IconSchema:()=>Xn,IconsSchema:()=>Nt,ImageContentSchema:()=>Ir,ImplementationSchema:()=>_t,InitializeRequestParamsSchema:()=>es,InitializeRequestSchema:()=>wo,InitializeResultSchema:()=>ts,InitializedNotificationSchema:()=>xo,JSONArraySchema:()=>Ua,JSONObjectSchema:()=>ue,JSONRPCErrorResponseSchema:()=>kr,JSONRPCMessageSchema:()=>st,JSONRPCNotificationSchema:()=>vo,JSONRPCRequestSchema:()=>yo,JSONRPCResponseSchema:()=>Za,JSONRPCResultResponseSchema:()=>Er,JSONValueSchema:()=>Ct,LegacyTitledEnumSchemaSchema:()=>Mo,ListChangedOptionsBaseSchema:()=>Hs,ListPromptsRequestSchema:()=>ks,ListPromptsResultSchema:()=>$s,ListResourceTemplatesRequestSchema:()=>ls,ListResourceTemplatesResultSchema:()=>us,ListResourcesRequestSchema:()=>as,ListResourcesResultSchema:()=>cs,ListRootsRequestSchema:()=>bi,ListRootsResultSchema:()=>yi,ListTasksRequestSchema:()=>Xa,ListTasksResultSchema:()=>Qa,ListToolsRequestSchema:()=>Ls,ListToolsResultSchema:()=>Us,LoggingLevelSchema:()=>Oo,LoggingMessageNotificationParamsSchema:()=>Bs,LoggingMessageNotificationSchema:()=>Ar,ModelHintSchema:()=>Ws,ModelPreferencesSchema:()=>Ks,MultiSelectEnumSchemaSchema:()=>si,NotificationSchema:()=>we,NotificationsParamsSchema:()=>Te,NumberSchemaSchema:()=>jr,PaginatedRequestParamsSchema:()=>ss,PaginatedRequestSchema:()=>qt,PaginatedResultSchema:()=>At,PingRequestSchema:()=>Po,PrimitiveSchemaDefinitionSchema:()=>Uo,ProgressNotificationParamsSchema:()=>ns,ProgressNotificationSchema:()=>To,ProgressSchema:()=>os,ProgressTokenSchema:()=>go,PromptArgumentSchema:()=>Ts,PromptListChangedNotificationSchema:()=>As,PromptMessageSchema:()=>Ns,PromptReferenceSchema:()=>mi,PromptSchema:()=>Es,ReadResourceRequestParamsSchema:()=>ds,ReadResourceRequestSchema:()=>ps,ReadResourceResultSchema:()=>hs,RelatedTaskMetadataSchema:()=>Gn,RequestIdSchema:()=>nt,RequestMetaSchema:()=>_o,RequestSchema:()=>de,ResourceContentsSchema:()=>Eo,ResourceLinkSchema:()=>qr,ResourceListChangedNotificationSchema:()=>ms,ResourceRequestParamsSchema:()=>$r,ResourceSchema:()=>Co,ResourceTemplateReferenceSchema:()=>hi,ResourceTemplateSchema:()=>is,ResourceUpdatedNotificationParamsSchema:()=>xs,ResourceUpdatedNotificationSchema:()=>Ps,ResultMetaObjectSchema:()=>bo,ResultSchema:()=>pe,RoleSchema:()=>Mt,RootSchema:()=>_i,RootsListChangedNotificationSchema:()=>vi,SamplingContentSchema:()=>Xs,SamplingMessageContentBlockSchema:()=>Qt,SamplingMessageSchema:()=>Qs,ServerCapabilitiesSchema:()=>Ro,ServerNotificationSchema:()=>ic,ServerRequestSchema:()=>sc,ServerResultSchema:()=>ac,ServerTasksCapabilitySchema:()=>Fa,SetLevelRequestParamsSchema:()=>Vs,SetLevelRequestSchema:()=>Js,SingleSelectEnumSchemaSchema:()=>ni,StringSchemaSchema:()=>Mr,SubscribeRequestParamsSchema:()=>fs,SubscribeRequestSchema:()=>gs,SubscriptionFilterSchema:()=>Io,SubscriptionsAcknowledgedNotificationParamsSchema:()=>vs,SubscriptionsAcknowledgedNotificationSchema:()=>zs,SubscriptionsListenRequestParamsSchema:()=>bs,SubscriptionsListenRequestSchema:()=>ys,SubscriptionsListenResultMetaSchema:()=>ws,SubscriptionsListenResultSchema:()=>Rs,TaskAugmentedRequestParamsSchema:()=>er,TaskCreationParamsSchema:()=>Va,TaskMetadataSchema:()=>Kn,TaskSchema:()=>jt,TaskStatusNotificationParamsSchema:()=>wi,TaskStatusNotificationSchema:()=>Ba,TaskStatusSchema:()=>zi,TextContentSchema:()=>Cr,TextResourceContentsSchema:()=>ko,TitledMultiSelectEnumSchemaSchema:()=>Lo,TitledSingleSelectEnumSchemaSchema:()=>Ao,ToolAnnotationsSchema:()=>Ms,ToolChoiceSchema:()=>Gs,ToolExecutionSchema:()=>js,ToolListChangedNotificationSchema:()=>Fs,ToolResultContentSchema:()=>Ys,ToolSchema:()=>or,ToolUseContentSchema:()=>Os,UnsubscribeRequestParamsSchema:()=>Ss,UnsubscribeRequestSchema:()=>_s,UntitledMultiSelectEnumSchemaSchema:()=>jo,UntitledSingleSelectEnumSchemaSchema:()=>qo});var Fr=(e)=>yo.safeParse(e).success,eg=(e)=>vo.safeParse(e).success,Bo=(e)=>Er.safeParse(e).success,Wo=(e)=>kr.safeParse(e).success;var tg=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var mu=(e)=>wo.safeParse(e).success,rg=(e)=>xo.safeParse(e).success;var Qb="Mcp-Param-",Rf="x-mcp-header",ey=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,ty=new Set(["string","integer","boolean","number"]);function fu(e){let t=[],r=new Map,o=(i,s,a)=>{if(i===null||typeof i!=="object")return;let l=i;if(Rf in l){if(!a||s.length===0)return`${mc(s)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let d=l[Rf];if(typeof d!=="string"||d.length===0)return`${mc(s)}: x-mcp-header MUST be a non-empty string`;if(!ey.test(d))return`${mc(s)}: x-mcp-header '${d}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let m=typeof l.type==="string"?l.type:void 0;if(m===void 0||!ty.has(m))return`${mc(s)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${m??"<none>"}`;let f=d.toLowerCase(),S=r.get(f);if(S!==void 0)return`x-mcp-header '${d}' is not case-insensitively unique (also declared as '${S}')`;r.set(f,d),t.push({path:s,headerName:d,type:m})}let u=l.properties;if(u!==null&&typeof u==="object")for(let[d,m]of Object.entries(u)){let f=o(m,[...s,d],a);if(f!==void 0)return f}for(let d of ry){let m=l[d];if(m===void 0)continue;let f=Array.isArray(m)?m:m!==null&&typeof m==="object"&&oy.has(d)?Object.values(m):[m];for(let S of f){let b=o(S,[...s,`<${d}>`],!1);if(b!==void 0)return b}}},n=o(e,[],!0);return n===void 0?{valid:!0,declarations:t}:{valid:!1,reason:n}}var ry=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],oy=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function mc(e){return e.length===0?"<root>":e.join(".")}var og="=?base64?",ng="?=";function ny(e){if(typeof e==="string")return e;if(typeof e==="boolean")return e?"true":"false";if(typeof e==="number"){if(!Number.isFinite(e))return;if(Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}function sy(e){if(e.length===0)return!0;if(e.startsWith(og)&&e.endsWith(ng))return!0;if(e!==e.trim())return!0;for(let t=0;t<e.length;t++){let r=e.codePointAt(t);if(r===9||r>=32&&r<=126)continue;return!0}return!1}function iy(e){let t=new TextEncoder().encode(e),r="";for(let o of t)r+=String.fromCodePoint(o);return btoa(r)}function gu(e){return sy(e)?`${og}${iy(e)}${ng}`:e}function ay(e,t){let r=e;for(let o of t){if(r===null||typeof r!=="object")return;r=r[o]}return r}function sg(e,t){let r={};for(let o of e){let n=ay(t,o.path);if(n===void 0||n===null)continue;let i=ny(n);if(i===void 0)continue;r[`${Qb}${o.headerName}`]=gu(i)}return r}var Jo=-32020,Ox=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32000],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[W.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Jo,W.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[W.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[W.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[W.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Jo],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half — including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[W.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Jo],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],Nx={[W.ParseError]:400,[W.InvalidRequest]:400,[W.MethodNotFound]:404,[W.UnsupportedProtocolVersion]:400,[W.MissingRequiredClientCapability]:400,[Jo]:400},xf={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function ig(e,t){let r=Object.hasOwn(xf,e)?xf[e]:void 0;if(r===void 0)return;let o=cy(t)?t[r]:void 0;return{field:r,value:typeof o==="string"?o:void 0}}function cy(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function _c(e,t){return Oa(e,t)}function ki(e){return new Set(e.flatMap((t)=>Object.keys(t.shape)))}function ou(e){if(e==null)return!1;let t=typeof e;if(t!=="object"&&t!=="function")return!1;if(!("~standard"in e))return!1;return typeof e["~standard"]?.validate==="function"}var Pf=!1,nu="draft-2020-12";function ly(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:nu});else if(r.vendor==="zod"){if(!("_zod"in e))throw Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");if(!Pf)Pf=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.");o=Ca(e,{target:nu,io:t})}else throw Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output"){if(o.type!==void 0)return o;return ag(o)?{type:"object",...o}:o}if(o.type!==void 0&&o.type!=="object")throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}function ag(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every((o)=>o!==null&&typeof o==="object"&&(o.type==="object"||ag(o)))}return!1}function uy(e){if(!e.path?.length)return e.message;return`${e.path.map((t)=>String(typeof t==="object"?t.key:t)).join(".")}: ${e.message}`}async function eu(e,t){let r=await e["~standard"].validate(t);if(r.issues&&r.issues.length>0)return{success:!1,error:r.issues.map((o)=>uy(o)).join(", ")};return{success:!0,data:r.value}}function dy(e){let t=Ca(e,{target:nu,io:"input"});return typeof t.pattern==="string"?t.pattern:void 0}var py=/\\\.\\d\{(\d+)\}/;function hy(e){let t=py.exec(e),r=[void 0,-1,0];if(t)r.push(Number(t[1]));return[!1,!0].flatMap((o)=>[!1,!0].flatMap((n)=>r.map((i)=>uo({local:o,offset:n,precision:i}))))}function my(e,t){let r;switch(e){case"email":r=[Km()];break;case"uri":r=[qa()];break;case"date":r=[Vl()];break;case"date-time":r=hy(t);break}return new Set(r.map((o)=>dy(o)).filter((o)=>o!==void 0))}function fy(e,t,r){if(r!=="zod")return!0;return my(e,t).has(t)}function Ii(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function gy(e){try{return ly(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new ee(W.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}var Sy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function Su(e){return Sy.has(e)||e.startsWith("x-")}var _y=new Set(["$schema",...Object.keys(Lr.shape.requestedSchema.shape)]),Tf={string:ki([Mr,qo,Ao,Mo]),number:ki([jr]),integer:ki([jr]),boolean:ki([No]),array:ki([jo,Lo])},by=new Set(Mr.shape.format.unwrap().options);function yy(e,t,r,o){if(!Ii(e))return e;let n=typeof e.type==="string"&&Object.hasOwn(Tf,e.type)?Tf[e.type]:void 0;if(n===void 0)return e;let i={};for(let[s,a]of Object.entries(e))if(n.has(s)||Su(s))i[s]=a;else if(s==="pattern"&&e.type==="string"&&typeof e.format==="string"){if(!by.has(e.format))i[s]=a;else if(typeof a!=="string"||!fy(e.format,a,r))o.push(`${t}.${s}`)}else o.push(`${t}.${s}`);return i}function vy(e,t){let r={},o=[];for(let[n,i]of Object.entries(e))if(n==="properties"&&Ii(i))r[n]=Object.fromEntries(Object.entries(i).map(([s,a])=>[s,yy(a,`properties.${s}`,t,o)]));else if(_y.has(n))r[n]=i;else if(!Su(n))o.push(n);if(o.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}function zy(e,t){if(!Ii(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!_c(Uo,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}function su(e,t,r=""){if(Array.isArray(e)&&Array.isArray(t))return e.flatMap((o,n)=>su(o,t[n],`${r}[${n}]`));if(!Ii(e)||!Ii(t))return[];return Object.entries(e).flatMap(([o,n])=>{let i=r?`${r}.${o}`:o;if(!Object.prototype.hasOwnProperty.call(t,o))return Su(o)?[]:[i];return su(n,t[o],i)})}function wy(e){if(!ou(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=vy(gy(e.requestedSchema),t),o=_c(Lr.shape.requestedSchema,r);if(!o.success)throw new ee(W.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${zy(r,o.error.message)}`);let n=su(r,o.data);if(n.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);let i=(o.data.required??[]).filter((s)=>!Object.prototype.hasOwnProperty.call(o.data.properties,s));if(i.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function Ry(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState==="string";if(!t&&!r)throw TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}var qx=Object.assign(Ry,{elicit(e){try{return{method:"elicitation/create",params:wy(e)}}catch(t){throw t instanceof ee?TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var xy=!0,Py=10,Ty=250;function cg(e){return{autoFulfill:e?.autoFulfill??xy,maxRounds:e?.maxRounds??Py}}function Ey(e,t,r){let o=t!==void 0&&Object.keys(t).length>0;if(!o&&r===void 0)return e;return{...e,...o&&{inputResponses:t},...r!==void 0&&{requestState:r}}}function ky(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function $y(e,t){return new Promise((r,o)=>{if(t?.aborted){o(t.reason instanceof N?t.reason:new N(O.RequestTimeout,String(t.reason)));return}let n=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(n),o(t?.reason instanceof N?t.reason:new N(O.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",i,{once:!0})})}function Cy(e){let t=new AbortController,r=()=>t.abort(e?.reason);if(e?.addEventListener("abort",r,{once:!0}),e?.aborted)t.abort(e.reason);return{signal:t.signal,abort:(o)=>t.abort(o),dispose:()=>e?.removeEventListener("abort",r)}}async function Iy(e){let{config:t,method:r,originalParams:o,requestOptions:n,hooks:i,signal:s}=e,a=e.flowStartedAt??Date.now(),l=e.firstPayload,u=0;while(!0){if(u+=1,u>t.maxRounds)throw new N(O.InputRequiredRoundsExceeded,ky(r,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:l.inputRequests,...l.requestState!==void 0&&{requestState:l.requestState}}});n.onprogress?.({progress:u,message:`Fulfilling input required by '${r}' (round ${u})`});let d=Object.entries(l.inputRequests??{}),m;if(d.length>0){let b=Cy(s);try{let y=await Promise.all(d.map(async([v,U])=>{try{return[v,await i.dispatchInputRequest(v,U,b.signal)]}catch(H){throw b.abort(H),H}}));m=Object.fromEntries(y)}finally{b.dispose()}}else await $y(Ty,s);let f={...n.timeout!==void 0&&{timeout:n.timeout}};if(n.maxTotalTimeout!==void 0){let b=Date.now()-a,y=n.maxTotalTimeout-b;if(y<=0)throw new N(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:b});f.maxTotalTimeout=y}let S=await i.retry(Ey(o,m,l.requestState),f);if(tg(S)){l={inputRequests:S.inputRequests??{},...S.requestState!==void 0&&{requestState:S.requestState}};continue}return S}}var Oy=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],Ny={IdJagTokenExchangeResponseSchema:xi,OAuthClientInformationFullSchema:Vo,OAuthClientInformationSchema:Ti,OAuthClientMetadataSchema:Pi,OAuthClientRegistrationErrorSchema:cc,OAuthErrorResponseSchema:Ho,OAuthMetadataSchema:Ur,OAuthProtectedResourceMetadataSchema:Zo,OAuthTokenRevocationRequestSchema:lc,OAuthTokensSchema:Fo,OpenIdProviderDiscoveryMetadataSchema:Do,OpenIdProviderMetadataSchema:Ri},lg={},ug={};function dg(e,t){let r=e.slice(0,-6);lg[r]=t,ug[r]=(o)=>t.safeParse(o).success}for(let e of Oy)dg(e,Xb[e]);for(let[e,t]of Object.entries(Ny))dg(e,t);var qy=Object.freeze(lg),pg=Object.freeze(ug);function Ay(e){switch(e){case"initialize":case"notifications/initialized":return Lt(void 0);case"server/discover":return Lt(Sc);default:return}}var bc=60000,My=[It,mo,Pr,fo],jy=["inputResponses","requestState"];function Ef(e,t){let r=e.params;if(!Ci(r))return{message:e,lifted:{}};let o=r._meta,n=Ci(o)?My.filter((l)=>(l in o)):[],i=t==="request"?jy.filter((l)=>(l in r)):[];if(n.length===0&&i.length===0)return{message:e,lifted:{}};let s={},a={...r};if(n.length>0&&Ci(o)){let l={},u={...o};for(let d of n)l[d]=o[d],delete u[d];if(s.envelope=l,Object.keys(u).length>0)a._meta=u;else delete a._meta}for(let l of i){if(l==="inputResponses")s.inputResponses=a[l];if(l==="requestState")s.requestState=a[l];delete a[l]}return{message:{...e,params:a},lifted:s}}function kf(e,t){let r=e.validateResult(t,void 0);if(!r.ok&&r.reason==="not-in-era")return;return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let n=e.validateResult(t,o);if(n.ok)return{value:n.value};return{issues:[{message:n.reason==="invalid"?n.message:`not-in-era: ${t}`}]}}}}}function _u(e){return()=>e}var Ly=_u(void 0),Uy,yc=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{Uy=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??ja,this.setNotificationHandler("notifications/cancelled",(t)=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",(t)=>{this._onprogress(t)}),this.setRequestHandler("ping",(t)=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new N(O.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){if(e.params.requestId===void 0)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new N(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=(n)=>{r?.(n),this._onerror(n)};let o=this._transport?.onmessage;this._transport.onmessage=(n,i)=>{if(o?.(n,i),Bo(n)||Wo(n))this._onresponse(n);else if(Fr(n))this._onrequest(n,i);else if(eg(n))this._onnotification(n,i);else this._onerror(Error(`Unknown message type: ${JSON.stringify(n)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new N(O.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(r);for(let o of t.values())o.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=Ef(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let s=zf(t.classification);if(s!==o.era){this._onerror(Error(`Era mismatch on inbound notification '${r.method}': classified as ${s} but this instance serves ${o.era}`));return}}if(Ql(r.method)&&!o.hasNotificationMethod(r.method))return;let n=this._notificationHandlers.get(r.method),i=this.fallbackNotificationHandler;if(n===void 0&&i===void 0)return;Promise.resolve().then(()=>n===void 0?i(r):n(r,o)).catch((s)=>this._onerror(Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){let{message:r,lifted:o}=Ef(e,"request"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let i=this._transport,s=(y,v,U)=>{let H={jsonrpc:"2.0",id:r.id,error:{code:y,message:v,...U!==void 0&&{data:U}}};i?.send(H).catch((x)=>this._onerror(Error(`Failed to send an error response: ${x}`)))};if(t?.classification!==void 0){let y=zf(t.classification);if(y!==n.era){this._onerror(Error(`Era mismatch on inbound request '${r.method}': classified as ${y} but this instance serves ${n.era}`));let v=t.classification.revision??y;s(W.UnsupportedProtocolVersion,`Unsupported protocol version: ${v}`,{supported:this._supportedProtocolVersions,requested:v});return}}if(Xl(r.method)&&!n.hasRequestMethod(r.method)&&!(wf(r.method)&&this._customSchemaRequestMethods.has(r.method))){s(W.MethodNotFound,"Method not found");return}let a=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(a===void 0){s(W.MethodNotFound,"Method not found");return}let l=n.checkInboundEnvelope(o);if(l!==void 0){s(W.InvalidParams,l);return}let u=(y,v)=>this._notificationViaCodec(this._resolveOutboundCodec(y.method),y,{...v,relatedRequestId:r.id}),d=(y,v,U)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(y.method),y,v,{...U,relatedRequestId:r.id}),m=new AbortController;this._requestHandlerAbortControllers.set(r.id,m);let f=o.inputResponses===void 0?void 0:Zy(o.inputResponses),S={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:o.requestState===void 0?Ly:_u(o.requestState),signal:m.signal,send:(y,v,U)=>{let H=this._resolveOutboundCodec(y.method);if(this._assertOutboundRequestInEra(H,y.method),ou(v))return d(y,v,U);let x=kf(H,y.method);if(x===void 0)throw TypeError(`'${y.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return d(y,x,v)},notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},b=this.buildContext(S,t);Promise.resolve().then(()=>a(r,b)).then(async(y)=>{if(m.signal.aborted)return;let v;try{v=n.encodeResult(r.method,y,this._outboundServerInfo())}catch(H){this._onerror(Error(`Failed to encode result for ${r.method}: ${H}`)),s(W.InternalError,"Internal error");return}let U={result:v,jsonrpc:"2.0",id:r.id};await i?.send(U)},async(y)=>{if(m.signal.aborted)return;let v=Number.isSafeInteger(y.code)?y.code:W.InternalError,U={jsonrpc:"2.0",id:r.id,error:{code:n.encodeErrorCode(v),message:y.message??"Internal error",...y.data!==void 0&&{data:y.data}}};await i?.send(U)}).catch((y)=>this._onerror(Error(`Failed to send response: ${y}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(r.id)===m)this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),n=this._progressHandlers.get(o);if(!n){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(a);return}n(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Bo(e))r(e);else r(ee.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let o=this._resolveOutboundCodec(e.method);if(ou(t)){if(!wf(e.method))this._assertOutboundRequestInEra(o,e.method);return this._requestWithSchemaViaCodec(o,e,t,r)}this._assertOutboundRequestInEra(o,e.method);let n=kf(o,e.method);if(n===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(o,e,n,t)}_negotiatedWireCodec(){return Lt(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Ay(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Xl(t)&&!e.hasRequestMethod(t))throw new N(O.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r)}_requestWithSchemaViaCodec(e,t,r,o){let{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s,headers:a}=o??{},l=Date.now(),u,d;return new Promise((m,f)=>{let S=(w)=>{f(w)};if(!this._transport){S(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(w){S(w);return}if(o?.signal?.aborted){let w=o.signal.reason;throw w instanceof N?w:new N(O.RequestTimeout,String(w))}let b=e.era===Sc&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,y=this._requestMessageId++;d=y;let v={...t,jsonrpc:"2.0",id:y};if(o?.onprogress)this._progressHandlers.set(y,o.onprogress),v.params={...t.params,_meta:{...t.params?._meta,progressToken:y}};let U=this._envelopeOutbound(v),H=!1,x=(w)=>{if(H)return;if(this._progressHandlers.delete(y),b===void 0){if(t.method!=="initialize")this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:y,reason:String(w)}}),{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s}).catch((D)=>this._onerror(Error(`Failed to send cancellation: ${D}`)))}else b.abort();f(w instanceof N?w:new N(O.RequestTimeout,String(w)))};this._responseHandlers.set(y,(w)=>{if(o?.signal?.aborted)return;if(H=!0,w instanceof Error)return f(w);let D;try{D=e.decodeResult(t.method,w.result)}catch(Y){return f(Y instanceof Error?Y:Error(String(Y)))}if(D.kind==="invalid")return f(D.error);if(D.kind==="input_required"){if(o?.allowInputRequired===!0)return m(Vy(D));let Y={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:l,retry:(le,Ee)=>this._requestWithSchemaViaCodec(e,le===void 0?{method:t.method}:{method:t.method,params:le},r,Ee)};return m(this._resolveNonCompleteResult(D,Y))}let X=D.result;eu(r,X).then((Y)=>{if(Y.success)m(Y.data);else f(new N(O.InvalidResult,`Invalid result for ${t.method}: ${Y.error}`))},f)}),u=()=>x(o?.signal?.reason),o?.signal?.addEventListener("abort",u,{once:!0});let Z=o?.timeout??bc,R=()=>x(new N(O.RequestTimeout,"Request timed out",{timeout:Z}));this._setupTimeout(y,Z,o?.maxTotalTimeout,R,o?.resetTimeoutOnProgress??!1),this._transport.send(U,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s,headers:a,requestSignal:b?.signal}).catch((w)=>{this._progressHandlers.delete(y),f(w)})}).finally(()=>{if(u)o?.signal?.removeEventListener("abort",u);if(d!==void 0)this._responseHandlers.delete(d),this._cleanupTimeout(d)})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new N(O.NotConnected,"Not connected");if(Ql(t.method)&&!e.hasNotificationMethod(t.method))throw new N(O.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;this._transport?.send(o,r).catch((n)=>this._onerror(n))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t==="function"){if(!Xl(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=(n,i)=>{let s=this._negotiatedWireCodec(),a=s.validateRequest(e,n);if(!a.ok&&a.reason==="not-in-era")a=s.validateInputRequest(e,n);if(!a.ok){if(a.reason==="not-in-era")throw new ee(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(a.message)}return Promise.resolve(t(a.value,i))}}else if(r)o=async(n,i)=>{let s=await eu(t.params,{...n.params});if(!s.success)throw new ee(W.InvalidParams,`Invalid params for ${e}: ${s.error}`);return r(s.data,i)};else throw TypeError("setRequestHandler: handler is required");if(typeof t==="function")this._customSchemaRequestMethods.delete(e);else this._customSchemaRequestMethods.add(e);this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t==="function"){if(!Ql(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,n)=>{let i=n.validateNotification(e,o);if(!i.ok){if(i.reason==="not-in-era")throw new ee(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(i.message)}return Promise.resolve(t(i.value))});return}if(!r)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async(o)=>{let n=await eu(t.params,{...o.params});if(!n.success)throw new ee(W.InvalidParams,`Invalid params for notification ${e}: ${n.error}`);await r(n.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Ci(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function hg(e,t){let r={...e};for(let o in t){let n=o,i=t[n];if(i===void 0)continue;let s=r[n];r[n]=Ci(s)&&Ci(i)?{...s,...i}:i}return r}function fc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Zy(e){let t={},r=[];if(!fc(e))return{accepted:t,droppedKeys:r};for(let[o,n]of Object.entries(e)){if(!fc(n)||"method"in n||"result"in n){r.push(o);continue}t[o]=n}return{accepted:t,droppedKeys:r}}function $f(e){throw new N(O.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function Dy(e,t,r,o,n){return{sessionId:n,mcpReq:{id:e,method:t,_meta:r?._meta,requestState:_u(void 0),signal:o,send:()=>$f("send"),notify:()=>$f("notify")}}}async function Fy(e,t,r,o,n){if(!fc(o)||typeof o.method!=="string")throw new N(O.InvalidResult,`Invalid input request '${r}': each inputRequests entry must be an embedded request object with a method`,{key:r});let i=o.method;if(!t.hasInputRequestMethod(i))throw new N(O.InvalidResult,`Invalid input request '${r}': '${i}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:r,method:i});let s=e.getRequestHandler(i);if(s===void 0)throw new N(O.CapabilityNotSupported,`Cannot fulfil input request '${r}': no handler is registered for '${i}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:r,method:i});let a=fc(o.params)?o.params:void 0;return await s({jsonrpc:"2.0",id:r,method:i,...a!==void 0&&{params:a}},e.buildContext(Dy(r,i,a,n,e.sessionId)))}function Hy(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function mg(e,t,r,o){let{codec:n,request:i,options:s,flowStartedAt:a}=o,l={inputRequests:r.inputRequests,...r.requestState!==void 0&&{requestState:r.requestState}},u={dispatchInputRequest:(d,m,f)=>Fy(e,n,d,m,f),retry:(d,m)=>o.retry(d,Hy(s,m))};return Iy({config:t,method:i.method,originalParams:i.params,firstPayload:l,flowStartedAt:a,signal:s?.signal,requestOptions:{...s?.timeout!==void 0&&{timeout:s.timeout},...s?.maxTotalTimeout!==void 0&&{maxTotalTimeout:s.maxTotalTimeout},...s?.onprogress!==void 0&&{onprogress:s.onprogress}},hooks:u})}function Vy(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}/*!
66
66
  * content-type
67
67
  * Copyright(c) 2015 Douglas Christopher Wilson
68
68
  * MIT Licensed
69
- */var Jy=nd((e)=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=n;function n(a){if(!a)throw TypeError("argument string is required");var l=typeof a==="object"?s(a):a;if(typeof l!=="string")throw TypeError("argument string is required to be a string");var u=l.indexOf(";"),d=u!==-1?l.slice(0,u).trim():l.trim();if(!o.test(d))throw TypeError("invalid media type");var m=new i(d.toLowerCase());if(u!==-1){var f,S,b;t.lastIndex=u;while(S=t.exec(l)){if(S.index!==u)throw TypeError("invalid parameter format");if(u+=S[0].length,f=S[1].toLowerCase(),b=S[2],b.charCodeAt(0)===34){if(b=b.slice(1,-1),b.indexOf("\\")!==-1)b=b.replace(r,"$1")}m.parameters[f]=b}if(u!==l.length)throw TypeError("invalid parameter format")}return m}function s(a){var l;if(typeof a.getHeader==="function")l=a.getHeader("content-type");else if(typeof a.headers==="object")l=a.headers&&a.headers["content-type"];if(typeof l!=="string")throw TypeError("content-type header is missing from object");return l}function i(a){this.parameters=Object.create(null),this.type=a}}),By=id(Jy(),1);function fg(e){if(!e)return;try{return By.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();if(t===""||e.slice(t.length).includes(","))return;return t}}function Cf(e){if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Array.isArray(e))return Object.fromEntries(e);return{...e}}function gg(e=fetch,t){if(!t)return e;return async(r,o)=>e(r,{...t,...o,headers:o?.headers?{...Cf(t.headers),...Cf(o.headers)}:t.headers})}var Wy=new Set([301,302,303,307,308]),Ky=5;function Gy(e,t){if(e.protocol===t.protocol&&e.host===t.host)return!0;return e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}function Sg(e,t){let r=Wy.has(t.status)?t.headers?.get("location"):void 0;if(!r)return;try{return new URL(r,e)}catch{return}}var _g=new WeakSet;function bg(e){let t=(r,o)=>e(r,o);return _g.add(t),t}function Ni(e){if(_g.has(e))return e;return async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let o=(r?.method??"GET").toUpperCase(),n=t;for(let s=0;;s++){let i=await e(n,{...r,redirect:"manual"}),a=Sg(n,i);if(!a||s===Ky)return i;let l=new URL(n),u=o==="GET"||i.status===307||i.status===308,d=!(a.username||a.password)||a.username===l.username&&a.password===l.password;if(!u||!d||!Gy(l,a))return i;await i.text?.().catch(()=>{}),n=a}}}function yg(e,t){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";let r=Sg(t.url||e,t);if(!r)return;if(r.username=r.password=r.search=r.hash="",r.protocol==="http:"&&new URL(t.url||e).protocol==="https:")return r.protocol="https:",`Redirect from https to plain http not followed; try ${r.href} as the endpoint`;return`Redirect to ${r.href} not followed; use that URL as the endpoint if it is the intended server`}function qi(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let o=e.length;if(o!==t.length)return!1;for(let n=0;n<o;n++)if(!qi(e[n],t[n]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)return!1;for(let s of o)if(!qi(e[s],t[s]))return!1;return!0}return e===t}function it(e){return encodeURI(Yy(e))}function Yy(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Xy={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Qy={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},ev={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},tv=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 Hr(e,t=Object.create(null),r=tv,o=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e.$id||e.id;if(s){let i=new URL(s,r.href);if(i.hash.length>1)t[i.href]=e;else if(i.hash="",o==="")r=i;else Hr(e,t,r)}}else if(e!==!0&&e!==!1)return t;let n=r.href+(o?"#"+o:"");if(t[n]!==void 0)throw Error(`Duplicate schema URI "${n}".`);if(t[n]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:n});if(e.$ref&&e.__absolute_ref__===void 0){let s=new URL(e.$ref,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let s=new URL(e.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){let s=new URL("#"+e.$anchor,r.href);t[s.href]=e}for(let s in e){if(ev[s])continue;let i=`${o}/${it(s)}`,a=e[s];if(Array.isArray(a)){if(Xy[s]){let l=a.length;for(let u=0;u<l;u++)Hr(a[u],t,r,`${i}/${u}`)}}else if(Qy[s])for(let l in a)Hr(a[l],t,r,`${i}/${it(l)}`);else Hr(a,t,r,i)}return t}var rv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ov=[0,31,28,31,30,31,30,31,31,30,31,30,31],nv=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,sv=/^(?=.{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,iv=/^(?:[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,av=/^(?:(?:[^\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,cv=/^(?:(?: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,lv=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,uv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,dv=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,pv=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,hv=(e)=>{if(e[0]==='"')return!1;let[t,r,...o]=e.split("@");if(!t||!r||o.length!==0||t.length>64||r.length>253)return!1;if(t[0]==="."||t.endsWith(".")||t.includes(".."))return!1;if(!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))return!1;return r.split(".").every((n)=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(n))},mv=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,fv=/^((([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,gv=(e)=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function zt(e){return e.test.bind(e)}var vg={date:zg,time:wg.bind(void 0,!1),"date-time":bv,duration:gv,uri:zv,"uri-reference":zt(iv),"uri-template":zt(av),url:zt(cv),email:hv,hostname:zt(sv),ipv4:zt(mv),ipv6:zt(fv),regex:Rv,uuid:zt(lv),"json-pointer":zt(uv),"json-pointer-uri-fragment":zt(dv),"relative-json-pointer":zt(pv)};function Sv(e){return e%4===0&&(e%100!==0||e%400===0)}function zg(e){let t=e.match(rv);if(!t)return!1;let r=+t[1],o=+t[2],n=+t[3];return o>=1&&o<=12&&n>=1&&n<=(o==2&&Sv(r)?29:ov[o])}function wg(e,t){let r=t.match(nv);if(!r)return!1;let o=+r[1],n=+r[2],s=+r[3],i=!!r[5];return(o<=23&&n<=59&&s<=59||o==23&&n==59&&s==60)&&(!e||i)}var _v=/t|\s/i;function bv(e){let t=e.split(_v);return t.length==2&&zg(t[0])&&wg(!0,t[1])}var yv=/\/|:/,vv=/^(?:[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 zv(e){return yv.test(e)&&vv.test(e)}var wv=/[^\\]\\Z/;function Rv(e){if(wv.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function xv(e){let t=0,r=e.length,o=0,n;while(o<r)if(t++,n=e.charCodeAt(o++),n>=55296&&n<=56319&&o<r){if(n=e.charCodeAt(o),(n&64512)==56320)o++}return t}function pe(e,t,r="2019-09",o=Hr(t),n=!0,s=null,i="#",a="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};let u=typeof e,d;switch(u){case"boolean":case"number":case"string":d=u;break;case"object":if(e===null)d="null";else if(Array.isArray(e))d="array";else d="object";break;default:throw Error(`Instances of "${u}" type are not supported.`)}let{$ref:m,$recursiveRef:f,$recursiveAnchor:S,type:b,const:y,enum:v,required:U,not:H,anyOf:x,allOf:Z,oneOf:R,if:w,then:D,else:X,format:Y,properties:ce,patternProperties:Ee,additionalProperties:te,unevaluatedProperties:se,minProperties:ve,maxProperties:ke,propertyNames:ct,dependentRequired:qe,dependentSchemas:We,dependencies:lt,prefixItems:Ze,items:$e,additionalItems:Tt,unevaluatedItems:Et,contains:ut,minContains:Re,maxContains:Ce,minItems:Ie,maxItems:et,uniqueItems:lr,minimum:De,maximum:Fe,exclusiveMinimum:Ae,exclusiveMaximum:Ke,multipleOf:Ge,minLength:dt,maxLength:pt,pattern:Ht,__absolute_ref__:ht,__absolute_recursive_ref__:ur}=t,C=[];if(S===!0&&s===null)s=t;if(f==="#"){let V=s===null?o[ur]:s,q=`${a}/$recursiveRef`,G=pe(e,s===null?t:s,r,o,n,V,i,q,l);if(!G.valid)C.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:q,error:"A subschema had errors."},...G.errors)}if(m!==void 0){let V=o[ht||m];if(V===void 0){let I=`Unresolved $ref "${m}".`;if(ht&&ht!==m)I+=` Absolute URI "${ht}".`;throw I+=`
69
+ */var Jy=nd((e)=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=n;function n(a){if(!a)throw TypeError("argument string is required");var l=typeof a==="object"?i(a):a;if(typeof l!=="string")throw TypeError("argument string is required to be a string");var u=l.indexOf(";"),d=u!==-1?l.slice(0,u).trim():l.trim();if(!o.test(d))throw TypeError("invalid media type");var m=new s(d.toLowerCase());if(u!==-1){var f,S,b;t.lastIndex=u;while(S=t.exec(l)){if(S.index!==u)throw TypeError("invalid parameter format");if(u+=S[0].length,f=S[1].toLowerCase(),b=S[2],b.charCodeAt(0)===34){if(b=b.slice(1,-1),b.indexOf("\\")!==-1)b=b.replace(r,"$1")}m.parameters[f]=b}if(u!==l.length)throw TypeError("invalid parameter format")}return m}function i(a){var l;if(typeof a.getHeader==="function")l=a.getHeader("content-type");else if(typeof a.headers==="object")l=a.headers&&a.headers["content-type"];if(typeof l!=="string")throw TypeError("content-type header is missing from object");return l}function s(a){this.parameters=Object.create(null),this.type=a}}),By=id(Jy(),1);function fg(e){if(!e)return;try{return By.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();if(t===""||e.slice(t.length).includes(","))return;return t}}function Cf(e){if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Array.isArray(e))return Object.fromEntries(e);return{...e}}function gg(e=fetch,t){if(!t)return e;return async(r,o)=>e(r,{...t,...o,headers:o?.headers?{...Cf(t.headers),...Cf(o.headers)}:t.headers})}var Wy=new Set([301,302,303,307,308]),Ky=5;function Gy(e,t){if(e.protocol===t.protocol&&e.host===t.host)return!0;return e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}function Sg(e,t){let r=Wy.has(t.status)?t.headers?.get("location"):void 0;if(!r)return;try{return new URL(r,e)}catch{return}}var _g=new WeakSet;function bg(e){let t=(r,o)=>e(r,o);return _g.add(t),t}function Ni(e){if(_g.has(e))return e;return async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let o=(r?.method??"GET").toUpperCase(),n=t;for(let i=0;;i++){let s=await e(n,{...r,redirect:"manual"}),a=Sg(n,s);if(!a||i===Ky)return s;let l=new URL(n),u=o==="GET"||s.status===307||s.status===308,d=!(a.username||a.password)||a.username===l.username&&a.password===l.password;if(!u||!d||!Gy(l,a))return s;await s.text?.().catch(()=>{}),n=a}}}function yg(e,t){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";let r=Sg(t.url||e,t);if(!r)return;if(r.username=r.password=r.search=r.hash="",r.protocol==="http:"&&new URL(t.url||e).protocol==="https:")return r.protocol="https:",`Redirect from https to plain http not followed; try ${r.href} as the endpoint`;return`Redirect to ${r.href} not followed; use that URL as the endpoint if it is the intended server`}function qi(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let o=e.length;if(o!==t.length)return!1;for(let n=0;n<o;n++)if(!qi(e[n],t[n]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)return!1;for(let i of o)if(!qi(e[i],t[i]))return!1;return!0}return e===t}function it(e){return encodeURI(Yy(e))}function Yy(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Xy={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Qy={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},ev={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},tv=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 Hr(e,t=Object.create(null),r=tv,o=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let s=new URL(i,r.href);if(s.hash.length>1)t[s.href]=e;else if(s.hash="",o==="")r=s;else Hr(e,t,r)}}else if(e!==!0&&e!==!1)return t;let n=r.href+(o?"#"+o:"");if(t[n]!==void 0)throw Error(`Duplicate schema URI "${n}".`);if(t[n]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:n});if(e.$ref&&e.__absolute_ref__===void 0){let i=new URL(e.$ref,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=new URL(e.$recursiveRef,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=new URL("#"+e.$anchor,r.href);t[i.href]=e}for(let i in e){if(ev[i])continue;let s=`${o}/${it(i)}`,a=e[i];if(Array.isArray(a)){if(Xy[i]){let l=a.length;for(let u=0;u<l;u++)Hr(a[u],t,r,`${s}/${u}`)}}else if(Qy[i])for(let l in a)Hr(a[l],t,r,`${s}/${it(l)}`);else Hr(a,t,r,s)}return t}var rv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ov=[0,31,28,31,30,31,30,31,31,30,31,30,31],nv=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,sv=/^(?=.{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,iv=/^(?:[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,av=/^(?:(?:[^\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,cv=/^(?:(?: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,lv=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,uv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,dv=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,pv=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,hv=(e)=>{if(e[0]==='"')return!1;let[t,r,...o]=e.split("@");if(!t||!r||o.length!==0||t.length>64||r.length>253)return!1;if(t[0]==="."||t.endsWith(".")||t.includes(".."))return!1;if(!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))return!1;return r.split(".").every((n)=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(n))},mv=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,fv=/^((([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,gv=(e)=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function zt(e){return e.test.bind(e)}var vg={date:zg,time:wg.bind(void 0,!1),"date-time":bv,duration:gv,uri:zv,"uri-reference":zt(iv),"uri-template":zt(av),url:zt(cv),email:hv,hostname:zt(sv),ipv4:zt(mv),ipv6:zt(fv),regex:Rv,uuid:zt(lv),"json-pointer":zt(uv),"json-pointer-uri-fragment":zt(dv),"relative-json-pointer":zt(pv)};function Sv(e){return e%4===0&&(e%100!==0||e%400===0)}function zg(e){let t=e.match(rv);if(!t)return!1;let r=+t[1],o=+t[2],n=+t[3];return o>=1&&o<=12&&n>=1&&n<=(o==2&&Sv(r)?29:ov[o])}function wg(e,t){let r=t.match(nv);if(!r)return!1;let o=+r[1],n=+r[2],i=+r[3],s=!!r[5];return(o<=23&&n<=59&&i<=59||o==23&&n==59&&i==60)&&(!e||s)}var _v=/t|\s/i;function bv(e){let t=e.split(_v);return t.length==2&&zg(t[0])&&wg(!0,t[1])}var yv=/\/|:/,vv=/^(?:[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 zv(e){return yv.test(e)&&vv.test(e)}var wv=/[^\\]\\Z/;function Rv(e){if(wv.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function xv(e){let t=0,r=e.length,o=0,n;while(o<r)if(t++,n=e.charCodeAt(o++),n>=55296&&n<=56319&&o<r){if(n=e.charCodeAt(o),(n&64512)==56320)o++}return t}function he(e,t,r="2019-09",o=Hr(t),n=!0,i=null,s="#",a="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let u=typeof e,d;switch(u){case"boolean":case"number":case"string":d=u;break;case"object":if(e===null)d="null";else if(Array.isArray(e))d="array";else d="object";break;default:throw Error(`Instances of "${u}" type are not supported.`)}let{$ref:m,$recursiveRef:f,$recursiveAnchor:S,type:b,const:y,enum:v,required:U,not:H,anyOf:x,allOf:Z,oneOf:R,if:w,then:D,else:X,format:Y,properties:le,patternProperties:Ee,additionalProperties:te,unevaluatedProperties:ie,minProperties:ve,maxProperties:ke,propertyNames:ct,dependentRequired:qe,dependentSchemas:We,dependencies:lt,prefixItems:Ze,items:$e,additionalItems:Tt,unevaluatedItems:Et,contains:ut,minContains:Re,maxContains:Ce,minItems:Ie,maxItems:et,uniqueItems:lr,minimum:De,maximum:Fe,exclusiveMinimum:Ae,exclusiveMaximum:Ke,multipleOf:Ge,minLength:dt,maxLength:pt,pattern:Ht,__absolute_ref__:ht,__absolute_recursive_ref__:ur}=t,C=[];if(S===!0&&i===null)i=t;if(f==="#"){let V=i===null?o[ur]:i,q=`${a}/$recursiveRef`,G=he(e,i===null?t:i,r,o,n,V,s,q,l);if(!G.valid)C.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:q,error:"A subschema had errors."},...G.errors)}if(m!==void 0){let V=o[ht||m];if(V===void 0){let I=`Unresolved $ref "${m}".`;if(ht&&ht!==m)I+=` Absolute URI "${ht}".`;throw I+=`
70
70
  Known schemas:
71
71
  - ${Object.keys(o).join(`
72
- - `)}`,Error(I)}let q=`${a}/$ref`,G=pe(e,V,r,o,n,s,i,q,l);if(!G.valid)C.push({instanceLocation:i,keyword:"$ref",keywordLocation:q,error:"A subschema had errors."},...G.errors);if(r==="4"||r==="7")return{valid:C.length===0,errors:C}}if(Array.isArray(b)){let V=b.length,q=!1;for(let G=0;G<V;G++)if(d===b[G]||b[G]==="integer"&&d==="number"&&e%1===0&&e===e){q=!0;break}if(!q)C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b.join('", "')}".`})}else if(b==="integer"){if(d!=="number"||e%1||e!==e)C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`})}else if(b!==void 0&&d!==b)C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`});if(y!==void 0){if(d==="object"||d==="array"){if(!qi(e,y))C.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}else if(e!==y)C.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}if(v!==void 0){if(d==="object"||d==="array"){if(!v.some((V)=>qi(e,V)))C.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}else if(!v.some((V)=>e===V))C.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}if(H!==void 0){let V=`${a}/not`;if(pe(e,H,r,o,n,s,i,V).valid)C.push({instanceLocation:i,keyword:"not",keywordLocation:V,error:'Instance matched "not" schema.'})}let mt=[];if(x!==void 0){let V=`${a}/anyOf`,q=C.length,G=!1;for(let I=0;I<x.length;I++){let k=x[I],B=Object.create(l),J=pe(e,k,r,o,n,S===!0?s:null,i,`${V}/${I}`,B);if(C.push(...J.errors),G=G||J.valid,J.valid)mt.push(B)}if(G)C.length=q;else C.splice(q,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:V,error:"Instance does not match any subschemas."})}if(Z!==void 0){let V=`${a}/allOf`,q=C.length,G=!0;for(let I=0;I<Z.length;I++){let k=Z[I],B=Object.create(l),J=pe(e,k,r,o,n,S===!0?s:null,i,`${V}/${I}`,B);if(C.push(...J.errors),G=G&&J.valid,J.valid)mt.push(B)}if(G)C.length=q;else C.splice(q,0,{instanceLocation:i,keyword:"allOf",keywordLocation:V,error:"Instance does not match every subschema."})}if(R!==void 0){let V=`${a}/oneOf`,q=C.length,G=R.filter((I,k)=>{let B=Object.create(l),J=pe(e,I,r,o,n,S===!0?s:null,i,`${V}/${k}`,B);if(C.push(...J.errors),J.valid)mt.push(B);return J.valid}).length;if(G===1)C.length=q;else C.splice(q,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:V,error:`Instance does not match exactly one subschema (${G} matches).`})}if(d==="object"||d==="array")Object.assign(l,...mt);if(w!==void 0){let V=`${a}/if`;if(pe(e,w,r,o,n,s,i,V,l).valid){if(D!==void 0){let q=pe(e,D,r,o,n,s,i,`${a}/then`,l);if(!q.valid)C.push({instanceLocation:i,keyword:"if",keywordLocation:V,error:'Instance does not match "then" schema.'},...q.errors)}}else if(X!==void 0){let q=pe(e,X,r,o,n,s,i,`${a}/else`,l);if(!q.valid)C.push({instanceLocation:i,keyword:"if",keywordLocation:V,error:'Instance does not match "else" schema.'},...q.errors)}}if(d==="object"){if(U!==void 0){for(let I of U)if(!(I in e))C.push({instanceLocation:i,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${I}".`})}let V=Object.keys(e);if(ve!==void 0&&V.length<ve)C.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${ve} properties.`});if(ke!==void 0&&V.length>ke)C.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${ke} properties.`});if(ct!==void 0){let I=`${a}/propertyNames`;for(let k in e){let B=`${i}/${it(k)}`,J=pe(k,ct,r,o,n,s,B,I);if(!J.valid)C.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:I,error:`Property name "${k}" does not match schema.`},...J.errors)}}if(qe!==void 0){let I=`${a}/dependantRequired`;for(let k in qe)if(k in e){let B=qe[k];for(let J of B)if(!(J in e))C.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:I,error:`Instance has "${k}" but does not have "${J}".`})}}if(We!==void 0)for(let I in We){let k=`${a}/dependentSchemas`;if(I in e){let B=pe(e,We[I],r,o,n,s,i,`${k}/${it(I)}`,l);if(!B.valid)C.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:k,error:`Instance has "${I}" but does not match dependant schema.`},...B.errors)}}if(lt!==void 0){let I=`${a}/dependencies`;for(let k in lt)if(k in e){let B=lt[k];if(Array.isArray(B)){for(let J of B)if(!(J in e))C.push({instanceLocation:i,keyword:"dependencies",keywordLocation:I,error:`Instance has "${k}" but does not have "${J}".`})}else{let J=pe(e,B,r,o,n,s,i,`${I}/${it(k)}`);if(!J.valid)C.push({instanceLocation:i,keyword:"dependencies",keywordLocation:I,error:`Instance has "${k}" but does not match dependant schema.`},...J.errors)}}}let q=Object.create(null),G=!1;if(ce!==void 0){let I=`${a}/properties`;for(let k in ce){if(!(k in e))continue;let B=`${i}/${it(k)}`,J=pe(e[k],ce[k],r,o,n,s,B,`${I}/${it(k)}`);if(J.valid)l[k]=q[k]=!0;else if(G=n,C.push({instanceLocation:i,keyword:"properties",keywordLocation:I,error:`Property "${k}" does not match schema.`},...J.errors),G)break}}if(!G&&Ee!==void 0){let I=`${a}/patternProperties`;for(let k in Ee){let B=new RegExp(k,"u"),J=Ee[k];for(let ge in e){if(!B.test(ge))continue;let dr=`${i}/${it(ge)}`,ft=pe(e[ge],J,r,o,n,s,dr,`${I}/${it(k)}`);if(ft.valid)l[ge]=q[ge]=!0;else G=n,C.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:I,error:`Property "${ge}" matches pattern "${k}" but does not match associated schema.`},...ft.errors)}}}if(!G&&te!==void 0){let I=`${a}/additionalProperties`;for(let k in e){if(q[k])continue;let B=`${i}/${it(k)}`,J=pe(e[k],te,r,o,n,s,B,I);if(J.valid)l[k]=!0;else G=n,C.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:I,error:`Property "${k}" does not match additional properties schema.`},...J.errors)}}else if(!G&&se!==void 0){let I=`${a}/unevaluatedProperties`;for(let k in e)if(!l[k]){let B=`${i}/${it(k)}`,J=pe(e[k],se,r,o,n,s,B,I);if(J.valid)l[k]=!0;else C.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:I,error:`Property "${k}" does not match unevaluated properties schema.`},...J.errors)}}}else if(d==="array"){if(et!==void 0&&e.length>et)C.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${et}).`});if(Ie!==void 0&&e.length<Ie)C.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Ie}).`});let V=e.length,q=0,G=!1;if(Ze!==void 0){let I=`${a}/prefixItems`,k=Math.min(Ze.length,V);for(;q<k;q++){let B=pe(e[q],Ze[q],r,o,n,s,`${i}/${q}`,`${I}/${q}`);if(l[q]=!0,!B.valid){if(G=n,C.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:I,error:"Items did not match schema."},...B.errors),G)break}}}if($e!==void 0){let I=`${a}/items`;if(Array.isArray($e)){let k=Math.min($e.length,V);for(;q<k;q++){let B=pe(e[q],$e[q],r,o,n,s,`${i}/${q}`,`${I}/${q}`);if(l[q]=!0,!B.valid){if(G=n,C.push({instanceLocation:i,keyword:"items",keywordLocation:I,error:"Items did not match schema."},...B.errors),G)break}}}else for(;q<V;q++){let k=pe(e[q],$e,r,o,n,s,`${i}/${q}`,I);if(l[q]=!0,!k.valid){if(G=n,C.push({instanceLocation:i,keyword:"items",keywordLocation:I,error:"Items did not match schema."},...k.errors),G)break}}if(!G&&Tt!==void 0){let k=`${a}/additionalItems`;for(;q<V;q++){let B=pe(e[q],Tt,r,o,n,s,`${i}/${q}`,k);if(l[q]=!0,!B.valid)G=n,C.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:k,error:"Items did not match additional items schema."},...B.errors)}}}if(ut!==void 0)if(V===0&&Re===void 0)C.push({instanceLocation:i,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Re!==void 0&&V<Re)C.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${V}) than minContains (${Re}).`});else{let I=`${a}/contains`,k=C.length,B=0;for(let J=0;J<V;J++){let ge=pe(e[J],ut,r,o,n,s,`${i}/${J}`,I);if(ge.valid)l[J]=!0,B++;else C.push(...ge.errors)}if(B>=(Re||0))C.length=k;if(Re===void 0&&Ce===void 0&&B===0)C.splice(k,0,{instanceLocation:i,keyword:"contains",keywordLocation:I,error:"Array does not contain item matching schema."});else if(Re!==void 0&&B<Re)C.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Re} items matching schema. Only ${B} items were found.`});else if(Ce!==void 0&&B>Ce)C.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Ce} items matching schema. ${B} items were found.`})}if(!G&&Et!==void 0){let I=`${a}/unevaluatedItems`;for(;q<V;q++){if(l[q])continue;let k=pe(e[q],Et,r,o,n,s,`${i}/${q}`,I);if(l[q]=!0,!k.valid)C.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:I,error:"Items did not match unevaluated items schema."},...k.errors)}}if(lr)for(let I=0;I<V;I++){let k=e[I],B=typeof k==="object"&&k!==null;for(let J=0;J<V;J++){if(I===J)continue;let ge=e[J];if(k===ge||B&&typeof ge==="object"&&ge!==null&&qi(k,ge))C.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${I} and ${J}.`}),I=Number.MAX_SAFE_INTEGER,J=Number.MAX_SAFE_INTEGER}}}else if(d==="number"){if(r==="4"){if(De!==void 0&&(Ae===!0&&e<=De||e<De))C.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Ae?"or equal to ":""} ${De}.`});if(Fe!==void 0&&(Ke===!0&&e>=Fe||e>Fe))C.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Ke?"or equal to ":""} ${Fe}.`})}else{if(De!==void 0&&e<De)C.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${De}.`});if(Fe!==void 0&&e>Fe)C.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Fe}.`});if(Ae!==void 0&&e<=Ae)C.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${Ae}.`});if(Ke!==void 0&&e>=Ke)C.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ke}.`})}if(Ge!==void 0){let V=e%Ge;if(Math.abs(0-V)>=0.00000011920929&&Math.abs(Ge-V)>=0.00000011920929)C.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Ge}.`})}}else if(d==="string"){let V=dt===void 0&&pt===void 0?0:xv(e);if(dt!==void 0&&V<dt)C.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${V} < ${dt}).`});if(pt!==void 0&&V>pt)C.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${V} > ${pt}).`});if(Ht!==void 0&&!new RegExp(Ht,"u").test(e))C.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(Y!==void 0&&vg[Y]&&!vg[Y](e))C.push({instanceLocation:i,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${Y}".`})}return{valid:C.length===0,errors:C}}var Pv=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=Hr(e)}validate(e){return pe(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){if(t)e={...e,$id:t};Hr(e,this.lookup)}},_u=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=ld(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){let t=new Pv(e,this.draft??this._draftFor(e),this.shortcircuit);return(r)=>{let o=t.validate(r);return o.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:o.errors.map((n)=>`${n.instanceLocation}: ${n.error}`).join("; ")}}}};var Rg=!0;var bu;bu=globalThis.crypto;async function Tv(e){return(await bu).getRandomValues(new Uint8Array(e))}async function Ev(e){let r=Math.pow(2,8)-Math.pow(2,8)%66,o="";while(o.length<e){let n=await Tv(e-o.length);for(let s of n)if(s<r)o+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[s%66]}return o}async function kv(e){return await Ev(e)}async function $v(e){let t=await(await bu).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function yu(e){if(!e)e=43;if(e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await kv(e),r=await $v(t);return{code_verifier:t,code_challenge:r}}class vc extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}var xg=10,Cv=13,Vr=32;function vu(e){}function Eg(e){if(typeof e=="function")throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=vu,onError:r=vu,onRetry:o=vu,onComment:n,maxBufferSize:s}=e,i=[],a=0,l=!0,u,d="",m=0,f,S=!1;function b(R){if(S)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,R.charCodeAt(0)===239&&R.charCodeAt(1)===187&&R.charCodeAt(2)===191&&(R=R.slice(3))),i.length===0){let X=v(R);X!==""&&(i.push(X),a=X.length),y();return}if(R.indexOf(`
73
- `)===-1&&R.indexOf("\r")===-1){i.push(R),a+=R.length,y();return}i.push(R);let w=i.join("");i.length=0,a=0;let D=v(w);D!==""&&(i.push(D),a=D.length),y()}function y(){s!==void 0&&(a+d.length<=s||(S=!0,i.length=0,a=0,u=void 0,d="",m=0,f=void 0,r(new vc(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function v(R){let w=0;if(R.indexOf("\r")===-1){let D=R.indexOf(`
72
+ - `)}`,Error(I)}let q=`${a}/$ref`,G=he(e,V,r,o,n,i,s,q,l);if(!G.valid)C.push({instanceLocation:s,keyword:"$ref",keywordLocation:q,error:"A subschema had errors."},...G.errors);if(r==="4"||r==="7")return{valid:C.length===0,errors:C}}if(Array.isArray(b)){let V=b.length,q=!1;for(let G=0;G<V;G++)if(d===b[G]||b[G]==="integer"&&d==="number"&&e%1===0&&e===e){q=!0;break}if(!q)C.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b.join('", "')}".`})}else if(b==="integer"){if(d!=="number"||e%1||e!==e)C.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`})}else if(b!==void 0&&d!==b)C.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`});if(y!==void 0){if(d==="object"||d==="array"){if(!qi(e,y))C.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}else if(e!==y)C.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}if(v!==void 0){if(d==="object"||d==="array"){if(!v.some((V)=>qi(e,V)))C.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}else if(!v.some((V)=>e===V))C.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}if(H!==void 0){let V=`${a}/not`;if(he(e,H,r,o,n,i,s,V).valid)C.push({instanceLocation:s,keyword:"not",keywordLocation:V,error:'Instance matched "not" schema.'})}let mt=[];if(x!==void 0){let V=`${a}/anyOf`,q=C.length,G=!1;for(let I=0;I<x.length;I++){let k=x[I],B=Object.create(l),J=he(e,k,r,o,n,S===!0?i:null,s,`${V}/${I}`,B);if(C.push(...J.errors),G=G||J.valid,J.valid)mt.push(B)}if(G)C.length=q;else C.splice(q,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:V,error:"Instance does not match any subschemas."})}if(Z!==void 0){let V=`${a}/allOf`,q=C.length,G=!0;for(let I=0;I<Z.length;I++){let k=Z[I],B=Object.create(l),J=he(e,k,r,o,n,S===!0?i:null,s,`${V}/${I}`,B);if(C.push(...J.errors),G=G&&J.valid,J.valid)mt.push(B)}if(G)C.length=q;else C.splice(q,0,{instanceLocation:s,keyword:"allOf",keywordLocation:V,error:"Instance does not match every subschema."})}if(R!==void 0){let V=`${a}/oneOf`,q=C.length,G=R.filter((I,k)=>{let B=Object.create(l),J=he(e,I,r,o,n,S===!0?i:null,s,`${V}/${k}`,B);if(C.push(...J.errors),J.valid)mt.push(B);return J.valid}).length;if(G===1)C.length=q;else C.splice(q,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:V,error:`Instance does not match exactly one subschema (${G} matches).`})}if(d==="object"||d==="array")Object.assign(l,...mt);if(w!==void 0){let V=`${a}/if`;if(he(e,w,r,o,n,i,s,V,l).valid){if(D!==void 0){let q=he(e,D,r,o,n,i,s,`${a}/then`,l);if(!q.valid)C.push({instanceLocation:s,keyword:"if",keywordLocation:V,error:'Instance does not match "then" schema.'},...q.errors)}}else if(X!==void 0){let q=he(e,X,r,o,n,i,s,`${a}/else`,l);if(!q.valid)C.push({instanceLocation:s,keyword:"if",keywordLocation:V,error:'Instance does not match "else" schema.'},...q.errors)}}if(d==="object"){if(U!==void 0){for(let I of U)if(!(I in e))C.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${I}".`})}let V=Object.keys(e);if(ve!==void 0&&V.length<ve)C.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${ve} properties.`});if(ke!==void 0&&V.length>ke)C.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${ke} properties.`});if(ct!==void 0){let I=`${a}/propertyNames`;for(let k in e){let B=`${s}/${it(k)}`,J=he(k,ct,r,o,n,i,B,I);if(!J.valid)C.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:I,error:`Property name "${k}" does not match schema.`},...J.errors)}}if(qe!==void 0){let I=`${a}/dependantRequired`;for(let k in qe)if(k in e){let B=qe[k];for(let J of B)if(!(J in e))C.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:I,error:`Instance has "${k}" but does not have "${J}".`})}}if(We!==void 0)for(let I in We){let k=`${a}/dependentSchemas`;if(I in e){let B=he(e,We[I],r,o,n,i,s,`${k}/${it(I)}`,l);if(!B.valid)C.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:k,error:`Instance has "${I}" but does not match dependant schema.`},...B.errors)}}if(lt!==void 0){let I=`${a}/dependencies`;for(let k in lt)if(k in e){let B=lt[k];if(Array.isArray(B)){for(let J of B)if(!(J in e))C.push({instanceLocation:s,keyword:"dependencies",keywordLocation:I,error:`Instance has "${k}" but does not have "${J}".`})}else{let J=he(e,B,r,o,n,i,s,`${I}/${it(k)}`);if(!J.valid)C.push({instanceLocation:s,keyword:"dependencies",keywordLocation:I,error:`Instance has "${k}" but does not match dependant schema.`},...J.errors)}}}let q=Object.create(null),G=!1;if(le!==void 0){let I=`${a}/properties`;for(let k in le){if(!(k in e))continue;let B=`${s}/${it(k)}`,J=he(e[k],le[k],r,o,n,i,B,`${I}/${it(k)}`);if(J.valid)l[k]=q[k]=!0;else if(G=n,C.push({instanceLocation:s,keyword:"properties",keywordLocation:I,error:`Property "${k}" does not match schema.`},...J.errors),G)break}}if(!G&&Ee!==void 0){let I=`${a}/patternProperties`;for(let k in Ee){let B=new RegExp(k,"u"),J=Ee[k];for(let ge in e){if(!B.test(ge))continue;let dr=`${s}/${it(ge)}`,ft=he(e[ge],J,r,o,n,i,dr,`${I}/${it(k)}`);if(ft.valid)l[ge]=q[ge]=!0;else G=n,C.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:I,error:`Property "${ge}" matches pattern "${k}" but does not match associated schema.`},...ft.errors)}}}if(!G&&te!==void 0){let I=`${a}/additionalProperties`;for(let k in e){if(q[k])continue;let B=`${s}/${it(k)}`,J=he(e[k],te,r,o,n,i,B,I);if(J.valid)l[k]=!0;else G=n,C.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:I,error:`Property "${k}" does not match additional properties schema.`},...J.errors)}}else if(!G&&ie!==void 0){let I=`${a}/unevaluatedProperties`;for(let k in e)if(!l[k]){let B=`${s}/${it(k)}`,J=he(e[k],ie,r,o,n,i,B,I);if(J.valid)l[k]=!0;else C.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:I,error:`Property "${k}" does not match unevaluated properties schema.`},...J.errors)}}}else if(d==="array"){if(et!==void 0&&e.length>et)C.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${et}).`});if(Ie!==void 0&&e.length<Ie)C.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Ie}).`});let V=e.length,q=0,G=!1;if(Ze!==void 0){let I=`${a}/prefixItems`,k=Math.min(Ze.length,V);for(;q<k;q++){let B=he(e[q],Ze[q],r,o,n,i,`${s}/${q}`,`${I}/${q}`);if(l[q]=!0,!B.valid){if(G=n,C.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:I,error:"Items did not match schema."},...B.errors),G)break}}}if($e!==void 0){let I=`${a}/items`;if(Array.isArray($e)){let k=Math.min($e.length,V);for(;q<k;q++){let B=he(e[q],$e[q],r,o,n,i,`${s}/${q}`,`${I}/${q}`);if(l[q]=!0,!B.valid){if(G=n,C.push({instanceLocation:s,keyword:"items",keywordLocation:I,error:"Items did not match schema."},...B.errors),G)break}}}else for(;q<V;q++){let k=he(e[q],$e,r,o,n,i,`${s}/${q}`,I);if(l[q]=!0,!k.valid){if(G=n,C.push({instanceLocation:s,keyword:"items",keywordLocation:I,error:"Items did not match schema."},...k.errors),G)break}}if(!G&&Tt!==void 0){let k=`${a}/additionalItems`;for(;q<V;q++){let B=he(e[q],Tt,r,o,n,i,`${s}/${q}`,k);if(l[q]=!0,!B.valid)G=n,C.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:k,error:"Items did not match additional items schema."},...B.errors)}}}if(ut!==void 0)if(V===0&&Re===void 0)C.push({instanceLocation:s,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Re!==void 0&&V<Re)C.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${V}) than minContains (${Re}).`});else{let I=`${a}/contains`,k=C.length,B=0;for(let J=0;J<V;J++){let ge=he(e[J],ut,r,o,n,i,`${s}/${J}`,I);if(ge.valid)l[J]=!0,B++;else C.push(...ge.errors)}if(B>=(Re||0))C.length=k;if(Re===void 0&&Ce===void 0&&B===0)C.splice(k,0,{instanceLocation:s,keyword:"contains",keywordLocation:I,error:"Array does not contain item matching schema."});else if(Re!==void 0&&B<Re)C.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Re} items matching schema. Only ${B} items were found.`});else if(Ce!==void 0&&B>Ce)C.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Ce} items matching schema. ${B} items were found.`})}if(!G&&Et!==void 0){let I=`${a}/unevaluatedItems`;for(;q<V;q++){if(l[q])continue;let k=he(e[q],Et,r,o,n,i,`${s}/${q}`,I);if(l[q]=!0,!k.valid)C.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:I,error:"Items did not match unevaluated items schema."},...k.errors)}}if(lr)for(let I=0;I<V;I++){let k=e[I],B=typeof k==="object"&&k!==null;for(let J=0;J<V;J++){if(I===J)continue;let ge=e[J];if(k===ge||B&&typeof ge==="object"&&ge!==null&&qi(k,ge))C.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${I} and ${J}.`}),I=Number.MAX_SAFE_INTEGER,J=Number.MAX_SAFE_INTEGER}}}else if(d==="number"){if(r==="4"){if(De!==void 0&&(Ae===!0&&e<=De||e<De))C.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Ae?"or equal to ":""} ${De}.`});if(Fe!==void 0&&(Ke===!0&&e>=Fe||e>Fe))C.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Ke?"or equal to ":""} ${Fe}.`})}else{if(De!==void 0&&e<De)C.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${De}.`});if(Fe!==void 0&&e>Fe)C.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Fe}.`});if(Ae!==void 0&&e<=Ae)C.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${Ae}.`});if(Ke!==void 0&&e>=Ke)C.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ke}.`})}if(Ge!==void 0){let V=e%Ge;if(Math.abs(0-V)>=0.00000011920929&&Math.abs(Ge-V)>=0.00000011920929)C.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Ge}.`})}}else if(d==="string"){let V=dt===void 0&&pt===void 0?0:xv(e);if(dt!==void 0&&V<dt)C.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${V} < ${dt}).`});if(pt!==void 0&&V>pt)C.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${V} > ${pt}).`});if(Ht!==void 0&&!new RegExp(Ht,"u").test(e))C.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(Y!==void 0&&vg[Y]&&!vg[Y](e))C.push({instanceLocation:s,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${Y}".`})}return{valid:C.length===0,errors:C}}var Pv=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=Hr(e)}validate(e){return he(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){if(t)e={...e,$id:t};Hr(e,this.lookup)}},bu=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=ld(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){let t=new Pv(e,this.draft??this._draftFor(e),this.shortcircuit);return(r)=>{let o=t.validate(r);return o.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:o.errors.map((n)=>`${n.instanceLocation}: ${n.error}`).join("; ")}}}};var Rg=!0;var yu;yu=globalThis.crypto;async function Tv(e){return(await yu).getRandomValues(new Uint8Array(e))}async function Ev(e){let r=Math.pow(2,8)-Math.pow(2,8)%66,o="";while(o.length<e){let n=await Tv(e-o.length);for(let i of n)if(i<r)o+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[i%66]}return o}async function kv(e){return await Ev(e)}async function $v(e){let t=await(await yu).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function vu(e){if(!e)e=43;if(e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await kv(e),r=await $v(t);return{code_verifier:t,code_challenge:r}}class vc extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}var xg=10,Cv=13,Vr=32;function zu(e){}function Eg(e){if(typeof e=="function")throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=zu,onError:r=zu,onRetry:o=zu,onComment:n,maxBufferSize:i}=e,s=[],a=0,l=!0,u,d="",m=0,f,S=!1;function b(R){if(S)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,R.charCodeAt(0)===239&&R.charCodeAt(1)===187&&R.charCodeAt(2)===191&&(R=R.slice(3))),s.length===0){let X=v(R);X!==""&&(s.push(X),a=X.length),y();return}if(R.indexOf(`
73
+ `)===-1&&R.indexOf("\r")===-1){s.push(R),a+=R.length,y();return}s.push(R);let w=s.join("");s.length=0,a=0;let D=v(w);D!==""&&(s.push(D),a=D.length),y()}function y(){i!==void 0&&(a+d.length<=i||(S=!0,s.length=0,a=0,u=void 0,d="",m=0,f=void 0,r(new vc(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function v(R){let w=0;if(R.indexOf("\r")===-1){let D=R.indexOf(`
74
74
  `,w);for(;D!==-1;){if(w===D){m>0&&t({id:u,event:f,data:d}),u=void 0,d="",m=0,f=void 0,w=D+1,D=R.indexOf(`
75
- `,w);continue}let X=R.charCodeAt(w);if(Pg(R,w,X)){let Y=R.charCodeAt(w+5)===Vr?w+6:w+5,ce=R.slice(Y,D);if(m===0&&R.charCodeAt(D+1)===xg){t({id:u,event:f,data:ce}),u=void 0,d="",f=void 0,w=D+2,D=R.indexOf(`
76
- `,w);continue}d=m===0?ce:`${d}
77
- ${ce}`,m++}else Tg(R,w,X)?f=R.slice(R.charCodeAt(w+6)===Vr?w+7:w+6,D)||void 0:U(R,w,D);w=D+1,D=R.indexOf(`
75
+ `,w);continue}let X=R.charCodeAt(w);if(Pg(R,w,X)){let Y=R.charCodeAt(w+5)===Vr?w+6:w+5,le=R.slice(Y,D);if(m===0&&R.charCodeAt(D+1)===xg){t({id:u,event:f,data:le}),u=void 0,d="",f=void 0,w=D+2,D=R.indexOf(`
76
+ `,w);continue}d=m===0?le:`${d}
77
+ ${le}`,m++}else Tg(R,w,X)?f=R.slice(R.charCodeAt(w+6)===Vr?w+7:w+6,D)||void 0:U(R,w,D);w=D+1,D=R.indexOf(`
78
78
  `,w)}return R.slice(w)}for(;w<R.length;){let D=R.indexOf("\r",w),X=R.indexOf(`
79
79
  `,w),Y=-1;if(D!==-1&&X!==-1?Y=D<X?D:X:D!==-1?D===R.length-1?Y=-1:Y=D:X!==-1&&(Y=X),Y===-1)break;U(R,w,Y),w=Y+1,R.charCodeAt(w-1)===Cv&&R.charCodeAt(w)===xg&&w++}return R.slice(w)}function U(R,w,D){if(w===D){x();return}let X=R.charCodeAt(w);if(Pg(R,w,X)){let ve=R.charCodeAt(w+5)===Vr?w+6:w+5,ke=R.slice(ve,D);d=m===0?ke:`${d}
80
- ${ke}`,m++;return}if(Tg(R,w,X)){f=R.slice(R.charCodeAt(w+6)===Vr?w+7:w+6,D)||void 0;return}if(X===105&&R.charCodeAt(w+1)===100&&R.charCodeAt(w+2)===58){let ve=R.slice(R.charCodeAt(w+3)===Vr?w+4:w+3,D);ve.includes("\x00")||(u=ve);return}if(X===58){if(n){let ve=R.slice(w,D);n(ve.slice(R.charCodeAt(w+1)===Vr?2:1))}return}let Y=R.slice(w,D),ce=Y.indexOf(":");if(ce===-1){H(Y,"",Y);return}let Ee=Y.slice(0,ce),te=Y.charCodeAt(ce+1)===Vr?2:1,se=Y.slice(ce+te);H(Ee,se,Y)}function H(R,w,D){switch(R){case"event":f=w||void 0;break;case"data":d=m===0?w:`${d}
81
- ${w}`,m++;break;case"id":w.includes("\x00")||(u=w);break;case"retry":/^\d+$/.test(w)?o(parseInt(w,10)):r(new vc(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:D}));break;default:r(new vc(`Unknown field "${R.length>20?`${R.slice(0,20)}…`:R}"`,{type:"unknown-field",field:R,value:w,line:D}));break}}function x(){m>0&&t({id:u,event:f,data:d}),u=void 0,d="",m=0,f=void 0}function Z(R={}){if(R.consume&&i.length>0){let w=i.join("");U(w,0,w.length)}l=!0,u=void 0,d="",m=0,f=void 0,i.length=0,a=0,S=!1}return{feed:b,reset:Z}}function Pg(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Tg(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}class zu extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:o}={}){let n;super({start(s){n=Eg({onEvent:(i)=>{s.enqueue(i)},onError(i){typeof e=="function"&&e(i),(e==="terminate"||i.type==="max-buffer-size-exceeded")&&s.error(i)},onRetry:t,onComment:r,maxBufferSize:o})},transform(s){n.feed(s)}})}}var Mi=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e){super(e);this.name=new.target.name,Zr(this,new.target)}},ku=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 §3.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`);this.kind=e,this.expected=t,this.received=r}},Iv=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`);this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},Zg=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`);this.tokenEndpoint=e}},Rc=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`);this.recordedIssuer=e,this.currentIssuer=t}},kg=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`);this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function $u(e,t,r){if(!e)return;if(typeof e.issuer!=="string"){if(r?.canPersistStamp!==!1)console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field.");return e.issuer===void 0?e:{...e,issuer:void 0}}return Dg(e.issuer,t)?e:void 0}function Dg(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function Ov(e){if(e==null)return!1;let t=e;return typeof t.tokens==="function"&&typeof t.clientInformation==="function"}async function Nv(e,t,r){let{resourceMetadataUrl:o,scope:n}=Ai(t.response);if(await Cu(e,{serverUrl:t.serverUrl,resourceMetadataUrl:o,scope:n,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new wt}function qv(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async(r)=>Nv(e,r,t)}}var wt=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e){super(e??"Unauthorized");this.name="UnauthorizedError",Zr(this,new.target)}};function Ou(e){return e?.authorization_response_iss_parameter_supported===!0}function Nu({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t===void 0)return;if(e===void 0){if(r)throw new ku("authorization_response",t,void 0);return}if(e!==t)throw new ku("authorization_response",t,e)}function wu(...e){let t=new Set;for(let r of e){if(!r)continue;for(let o of r.split(/\s+/))if(o)t.add(o)}return t.size>0?[...t].join(" "):void 0}function Av(e,t){if(!e)return!1;let r=new Set((t??"").split(/\s+/).filter(Boolean));for(let o of e.split(/\s+/))if(o&&!r.has(o))return!0;return!1}async function Mv(e,t,r,o,n){if(typeof e==="string")return{authorizationCode:e,iss:t};let s=e.get("iss")??void 0,i=e.get("code");if(i)return{authorizationCode:i,iss:s};let a=(await r.discoveryState?.())?.authorizationServerMetadata;if(!a)try{a=(await Bg(o,n)).authorizationServerMetadata}catch{a=void 0}if(!a)throw new wt("Authorization callback failed and the issuer could not be verified");Nu({iss:s,expectedIssuer:a.issuer,issParameterSupported:Ou(a)});let l=e.get("error");if(l)throw new Dr(l,e.get("error_description")??l,e.get("error_uri")??void 0);throw new wt("Authorization callback contained neither `code` nor `error`")}function jv(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var Ru="code",xu="S256";function Lv(e,t){let r=e.client_secret!==void 0;if("token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&jv(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method)))return e.token_endpoint_auth_method;if(t.length===0)return r?"client_secret_basic":"none";if(r&&t.includes("client_secret_basic"))return"client_secret_basic";if(r&&t.includes("client_secret_post"))return"client_secret_post";if(t.includes("none"))return"none";return r?"client_secret_post":"none"}function Uv(e,t,r,o){let{client_id:n,client_secret:s}=t;switch(e){case"client_secret_basic":Zv(n,s,r);return;case"client_secret_post":Dv(n,s,o);return;case"none":Fv(n,o);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Zv(e,t,r){if(!t)throw Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}function Dv(e,t,r){if(r.set("client_id",e),t)r.set("client_secret",t)}function Fv(e,t){t.set("client_id",e)}function Fg(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function Hv(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!Fg(t.hostname))throw new Zg(t.href);return t}function Vv(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:")return"native";if(Fg(r.hostname))return"native"}return"web"}function Jv(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??Vv(t.redirect_uris)}}async function $g(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Ho.parse(JSON.parse(r));return Dr.fromResponse(o)}catch(o){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Dr(Ut.ServerError,n)}}function Cg(e,t,r){let o=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} — ${o}. Cause: ${JSON.stringify(t.message)}`)}async function Cu(e,t){try{return await Pu(e,t)}catch(r){if(r instanceof Dr){if(r.code===Ut.InvalidClient||r.code===Ut.UnauthorizedClient)return Cg(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Pu(e,t);else if(r.code===Ut.InvalidGrant||r.code===Ut.InvalidDpopProof)return Cg(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await Pu(e,t)}throw r}}function Bv(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:n}=e,s=t||r?.scopes_supported?.join(" ")||n.scope;if(s&&o?.scopes_supported?.includes("offline_access")&&!s.split(" ").includes("offline_access")&&n.grant_types?.includes("refresh_token"))s=`${s} offline_access`;return s}async function Pu(e,{serverUrl:t,authorizationCode:r,iss:o,scope:n,resourceMetadataUrl:s,fetchFn:i,skipIssuerMetadataValidation:a,forceReauthorization:l}){let u=Jv(e),d=await e.discoveryState?.(),m,f,S,b,y=s;if(!y&&d?.resourceMetadataUrl)y=new URL(d.resourceMetadataUrl);if(d?.authorizationServerUrl){if(f=d.authorizationServerUrl,m=d.resourceMetadata,S=d.authorizationServerMetadata??await Jg(f,{fetchFn:i,skipIssuerValidation:a}),!m)try{m=await Hg(t,{resourceMetadataUrl:y},i)}catch(te){if(te instanceof TypeError)throw te}if(S!==d.authorizationServerMetadata||m!==d.resourceMetadata)await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:S})}else{let te=await Bg(t,{resourceMetadataUrl:y,fetchFn:i,skipIssuerMetadataValidation:a});f=te.authorizationServerUrl,S=te.authorizationServerMetadata,m=te.resourceMetadata,b={authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:S}}let v=S?.issuer??String(f),U={issuer:v};if(await e.saveAuthorizationServerUrl?.(v),r!==void 0){let te=d?.authorizationServerMetadata?.issuer??d?.authorizationServerUrl;if(te===void 0){if(e.saveDiscoveryState!==void 0)throw new Rc("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",v);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.")}else if(!Dg(te,v))throw new Rc(te,v)}if(b)await e.saveDiscoveryState?.(b);let H=await Kv(t,e,m),x=H&&m&&!e.validateResourceURL?m.resource:H;if(x)await e.saveResourceUrl?.(qu(x));let Z=Bv({requestedScope:n,resourceMetadata:m,authServerMetadata:S,clientMetadata:e.clientMetadata}),R=await Promise.resolve(e.clientInformation(U)),w=$u(R,v,{canPersistStamp:e.saveClientInformation!==void 0});if(w===void 0&&R?.issuer&&e.saveClientInformation===void 0)throw new Rc(R.issuer,v);if(w&&w.issuer===void 0)w={...w,issuer:v},await e.saveClientInformation?.(w,U);if(!w){if(r!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let te=S?.client_id_metadata_document_supported===!0,se=e.clientMetadataUrl;if(se&&!Wv(se))throw new Dr(Ut.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${se}`);if(te&&se)w={client_id:se,issuer:v},await e.saveClientInformation?.(w,U);else{if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");w={...await sz(f,{metadata:S,clientMetadata:u,scope:Z,fetchFn:i}),issuer:v},await e.saveClientInformation(w,U)}}let D=!e.redirectUrl;if(r!==void 0||D){if(r!==void 0)Nu({iss:o,expectedIssuer:S?.issuer,issParameterSupported:Ou(S)});let te=await nz(e,f,{metadata:S,resource:x,authorizationCode:r,iss:o,scope:Z,fetchFn:i});return await e.saveTokens({...te,issuer:v},U),"AUTHORIZED"}let X=$u(await e.tokens(U),v);if(X&&X.issuer===void 0)X={...X,issuer:v},await e.saveTokens(X,U);if(X?.refresh_token&&!l){let te;try{te=await oz(f,{metadata:S,clientInformation:w,refreshToken:X.refresh_token,resource:x,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:i})}catch(se){if(se instanceof Zg)throw se;if(!(se instanceof Dr)||se.code===Ut.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(se instanceof Error?se.message:String(se))}`);else throw se}if(te)return await e.saveTokens({...te,issuer:v},U),"AUTHORIZED"}let Y=e.state?await e.state():void 0,{authorizationUrl:ce,codeVerifier:Ee}=await tz(f,{metadata:S,clientInformation:w,state:Y,redirectUrl:e.redirectUrl,scope:Z,resource:x});return await e.saveCodeVerifier(Ee),await e.redirectToAuthorization(ce),"REDIRECT"}function Wv(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Kv(e,t,r){let o=If(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(!r)return;if(!Of({requestedResource:o,configuredResource:r.resource}))throw Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}var Gv=new Set(["bearer","dpop"]);function Ai(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!Gv.has(r.toLowerCase())||!o)return{};let n=zc(e,"resource_metadata")||void 0,s;if(n)try{s=new URL(n)}catch{}let i=zc(e,"scope")||void 0,a=zc(e,"error")||void 0,l=zc(e,"error_description")||void 0;return{resourceMetadataUrl:s,scope:i,error:a,errorDescription:l}}function zc(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),n=r.match(o);if(n){let s=n[1]||n[2];if(s)return s}return null}async function Hg(e,t,r=fetch){let o=await Qv(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.text?.().catch(()=>{}),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.text?.().catch(()=>{}),Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Zo.parse(await o.json())}async function Vg(e,t,r=fetch){let o=Ni(r);try{return await o(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!Rg)throw n;if(t)try{return await o(e,{})}catch(s){if(!(s instanceof TypeError))throw s;return}return}}function Yv(e,t="",r={}){if(t.endsWith("/"))t=t.slice(0,-1);return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Ig(e,t,r=fetch){return await Vg(e,{"MCP-Protocol-Version":t},r)}function Xv(e,t){if(!e)return!0;if(t==="/")return!1;return!e.ok&&e.status<500||e.status===502}async function Qv(e,t,r,o){let n=new URL(e),s=o?.protocolVersion??ho,i;if(o?.metadataUrl)i=new URL(o.metadataUrl);else{let l=Yv(t,n.pathname);i=new URL(l,o?.metadataServerUrl??n),i.search=n.search}let a=await Ig(i,s,r);if(!o?.metadataUrl&&Xv(a,n.pathname))a=await Ig(new URL(`/.well-known/${t}`,n),s,r);return a}function ez(e){let t=typeof e==="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;if(n.endsWith("/"))n=n.slice(0,-1);return o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"},{url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function Jg(e,{fetchFn:t=fetch,protocolVersion:r=ho,skipIssuerValidation:o=!1}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},s=ez(e);for(let{url:i,type:a}of s){let l=await Vg(i,n,t);if(!l)continue;if(!l.ok){if(await l.text?.().catch(()=>{}),l.status<500||l.status===502)continue;throw Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}let u=a==="oauth"?Ur.parse(await l.json()):Do.parse(await l.json());if(!o){let d=typeof e==="string"?e:e.href;if(!(u.issuer===d||d.endsWith("/")&&u.issuer===d.slice(0,-1)))throw new ku("metadata",d,u.issuer)}return u}}async function Bg(e,t){let r,o;try{if(r=await Hg(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0)o=r.authorization_servers[0]}catch(s){if(s instanceof TypeError)throw s}if(!o)o=String(new URL("/",e));let n=await Jg(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function qu(e){return typeof e==="string"?e:e.href}async function tz(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Ru))throw Error(`Incompatible auth server: does not support response type ${Ru}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(xu))throw Error(`Incompatible auth server: does not support code challenge method ${xu}`)}else a=new URL("/authorize",e);let l=await yu(),{code_verifier:u,code_challenge:d}=l;if(a.searchParams.set("response_type",Ru),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",xu),a.searchParams.set("redirect_uri",String(o)),s)a.searchParams.set("state",s);if(n)a.searchParams.set("scope",n);if(n?.split(" ").includes("offline_access"))a.searchParams.append("prompt","consent");if(i)a.searchParams.set("resource",qu(i));return{authorizationUrl:a,codeVerifier:u}}function rz(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function Wg(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:s,dpop:i,fetchFn:a}){let l=Hv(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s)r.set("resource",qu(s));if(!n&&o)Uv(Lv(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let d=async()=>{let S=new Headers(u);if(n)await n(S,r,l,t);if(i)S.set("DPoP",await i.buildProof({htm:"POST",htu:l}));return Ni(a??fetch)(l,{method:"POST",headers:S,body:r})},m=await d();if(i&&m.status===400){if((await m.clone().json().catch(()=>{}))?.error===Ut.UseDpopNonce)i.observeNonce(m,l),m=await d()}if(i?.observeNonce(m,l),!m.ok)throw await $g(m);let f=await m.json();try{return Fo.parse(su(f))}catch(S){if(typeof f==="object"&&f!==null&&"error"in f)throw await $g(JSON.stringify(f));throw S}}async function oz(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:s,dpop:i,fetchFn:a}){return{refresh_token:o,...await Wg(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:s,resource:n,dpop:i,fetchFn:a})}}async function nz(e,t,{metadata:r,resource:o,authorizationCode:n,iss:s,scope:i,fetchFn:a}={}){if(n!==void 0)Nu({iss:s,expectedIssuer:r?.issuer,issParameterSupported:Ou(r)});let l=r?.issuer??String(t),u=async()=>{let S=await e.clientInformation({issuer:l}),b=$u(S,l,{canPersistStamp:!1});if(S&&b===void 0)throw new Rc(String(S.issuer),l);return b},d=await u(),m=i??e.clientMetadata.scope,f;if(e.prepareTokenRequest)f=await e.prepareTokenRequest(m);if(!f){if(!n)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");f=rz(n,await e.codeVerifier(),e.redirectUrl)}return d??=await u(),Wg(t,{metadata:r,tokenRequestParams:f,clientInformation:d,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:a})}async function sz(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:n}){let s;if(t){if(!t.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);let i={...r,...o===void 0?{}:{scope:o}},a=await Ni(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!a.ok)throw new Iv({status:a.status,body:await a.text(),submittedMetadata:i});return Vo.parse(su(await a.json()))}var wc=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),iz=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(Tu(e))}set(e,t){let r=Tu(e),o=wc.has(e.method),n=!this._entries.has(r);if(!o&&n&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let i of this._entries.keys())if(!wc.has(i.slice(0,i.indexOf("\x00")))){this._entries.delete(i),this._cappedSize--;break}}let s=++this._stamp;if(this._entries.set(r,{...t,stamp:s}),n&&!o)this._cappedSize++;return s}delete(e){if(this._entries.delete(Tu(e))&&!wc.has(e.method))this._cappedSize--}evict(e){let t=`${e}\x00`,r=wc.has(e);for(let o of this._entries.keys())if(o.startsWith(t)){if(this._entries.delete(o),!r)this._cappedSize--}}clear(){this._entries.clear(),this._cappedSize=0}};function Tu(e){return`${e.method}\x00${JSON.stringify([e.partition??"",e.params??""])}`}function Eu(e,t){return t===void 0?e:`${e}\x00${t}`}var az=86400000,cz=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,r=()=>{},o="",n=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=r,this._cachePartition=o,this._now=n}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){let r={method:e,params:t??""},o=this._partitionFor("private"),n=await this._store.get({...r,partition:o});if(n!==void 0)return n;let s=this._partitionFor("public");if(s===o)return;let i=await this._store.get({...r,partition:s});return i?.scope==="public"?i:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){let r=this._partitionFor("private"),o=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:r})}catch(n){this._reportError(n)}if(o!==r)try{await this._store.delete({method:e,params:t,partition:o})}catch(n){this._reportError(n)}}async evictKey(e,t){let r=Eu(e,t),o=this._evictionGeneration.get(r);if(o!==void 0)this._evictionGeneration.set(r,o+1);await this._deleteBoth(e,t)}captureGeneration(e,t){let r=Eu(e,t),o=this._evictionGeneration.get(r)??0;return this._evictionGeneration.set(r,o),o}async write(e,t,r,o){if((this._evictionGeneration.get(Eu(e,o?.params))??0)!==r)return;let n=o?.params??"",s=this._partitionFor("private"),i=this._partitionFor("public"),a=(o?.scope??"private")==="public"?i:s;try{await this._store.set({method:e,params:n,partition:a},{value:lz(t),expiresAt:o?.expiresAt,scope:o?.scope})}catch(l){this._reportError(l)}if(i!==s)try{await this._store.delete({method:e,params:n,partition:a===s?i:s})}catch(l){this._reportError(l)}}async read(e,t){let r=await this._probe(e,t);if(r?.expiresAt===void 0||!(r.expiresAt>this.now()))return;try{let o=JSON.parse(r.value);if(typeof o!=="object"||o===null||Array.isArray(o))throw TypeError("cached document is not an object");return{value:o}}catch(o){this._reportError(o),await this._deleteBoth(e,t??"");return}}resetForReconnect(){if(!this._isUserSupplied)this._store.clear();this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){let t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let r=this._decodeListTools(t),o=new Map;if(r!==void 0)for(let n of r.tools)o.set(n.name,n);this._toolIndex={stamp:t.stamp,byName:o}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let r=await this._probe("tools/list");if(r===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==r.stamp){let o=this._decodeListTools(r)??{tools:[]},n=new Map;for(let s of o.tools){let i=t(s);if(i!==void 0)n.set(s.name,i)}this._toolOutputValidatorIndex={stamp:r.stamp,byName:n}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every((r)=>r!==null&&typeof r==="object"))throw TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};function lz(e){let t;try{t=JSON.stringify(e)}catch(r){throw TypeError(`cache value is not JSON-serializable: ${r instanceof Error?r.message:String(r)}`)}if(typeof t!=="string")throw TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}var Kg=Symbol.for("mcp.authSeamEscape");function Xe(e){if(typeof e==="object"&&e!==null||typeof e==="function")try{Object.defineProperty(e,Kg,{value:!0,configurable:!0})}catch{}return e}function uz(e){return(typeof e==="object"&&e!==null||typeof e==="function")&&e[Kg]===!0}var dz=-32022,pz=new Set([-32001,-32020,-32021]);function hz(e,t){switch(e.kind){case"result":return mz(e.result,t);case"rpc-error":return Gg(e,t);case"http-error":return fz(e,t);case"network-error":return Og(e.error,t);case"unusable-reply":return{kind:"error",error:new N(O.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${Yg(e.error)})`,{cause:e.error},{cause:e.error})};case"auth-required":return{kind:"error",error:e.error};case"closed":if(t.transportKind==="stdio")return{kind:"legacy"};return Og(Error("Connection closed during the version negotiation probe"),t);case"timeout":if(t.transportKind==="stdio")return{kind:"legacy"};return{kind:"error",error:new N(O.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function mz(e,t){let r=Lt(Sc).validateResult("server/discover",e);if(!r.ok)return{kind:"legacy"};let o=r.value.supportedVersions,n=t.clientModernVersions.find((s)=>o.includes(s));if(n!==void 0)return{kind:"modern",version:n,discover:r.value};if(t.fallbackAvailable)return{kind:"legacy"};return{kind:"error",error:new gc({supported:[...o],requested:t.requestedVersion})}}function Gg(e,t){let{code:r,message:o,data:n}=e;if(r===dz){let s=Sz(n);if(s===void 0)return{kind:"legacy"};let i=new gc({supported:s,requested:_z(n)??t.requestedVersion},o),a=Oi(s),l=t.clientModernVersions.find((u)=>a.includes(u));if(l!==void 0)return{kind:"corrective",version:l,error:i};if(a.length>0)return{kind:"error",error:i};return t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:i}}if(pz.has(r))return{kind:"legacy"};return{kind:"legacy"}}function fz(e,t){if(e.status===401||e.status===403){let o=e.status===403;return{kind:"error",error:new vt(o?O.ClientHttpForbidden:O.ClientHttpAuthentication,`Version negotiation failed: ${o?"the server denied access (HTTP 403)":"the server requires authorization (HTTP 401)"}`,{status:e.status,statusText:e.statusText,text:e.body})}}if(e.status>=500)return{kind:"error",error:new vt(O.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let r=bz(e.body);if(r!==void 0)return Gg(r,t);return{kind:"legacy"}}function Og(e,t){if(t.environment==="browser"&&gz(e))return{kind:"legacy"};return{kind:"error",error:new N(O.EraNegotiationFailed,`Version negotiation probe failed: ${Yg(e)}`,{cause:e},{cause:e})}}function gz(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function Yg(e){return e instanceof Error?e.message:String(e)}function Sz(e){if(typeof e!=="object"||e===null)return;let t=e.supported;if(!Array.isArray(t)||t.length===0||!t.every((r)=>typeof r==="string"))return;return t}function _z(e){if(typeof e!=="object"||e===null)return;let t=e.requested;return typeof t==="string"?t:void 0}function bz(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=="object"||t===null)return;let r=t.error;if(typeof r!=="object"||r===null)return;let{code:o,message:n,data:s}=r;if(typeof o!=="number")return;return{code:o,message:typeof n==="string"?n:"",data:s}}var yz="legacy";function vz(e,t){let r=e?.mode??yz;if(r==="legacy")return{kind:"legacy"};let o=e?.probe??{};if(typeof r==="object"){if(!Zt(r.pin))throw TypeError(`versionNegotiation: { pin: '${r.pin}' } is not a modern protocol revision — pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:r.pin,probe:o}}let n=t?Oi(t):[];return{kind:"auto",modernVersions:n.length>0?n:[...iu],fallbackAvailable:t?au(t).length>0:!0,probe:o}}function Ng(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function qg(e){return"stderr"in e&&"pid"in e?"stdio":"http"}var zz=class e{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(t){this._transport=t,this._savedOnMessage=t.onmessage,this._savedOnError=t.onerror,this._savedOnClose=t.onclose}static async open(t){let r=new e(t);t.onmessage=(o)=>{let n=r._pending;if(n!==void 0&&(Bo(o)||Wo(o))&&o.id===n.id){if(r._pending=void 0,Bo(o))n.resolve({kind:"response",result:o.result});else n.resolve({kind:"response",error:o.error});return}},t.onerror=(o)=>{r._savedOnError?.(o)},t.onclose=()=>{let o=r._pending;if(o!==void 0)r._pending=void 0,o.resolve({kind:"closed"});r._closeDelivered=!0,r._savedOnClose?.()};try{await t.start()}catch(o){throw r.detach(),o}return r}async exchange(t,r){let o=`server-discover-probe-${++this._probeCounter}`;return new Promise((n)=>{let s=!1,i=(l)=>{if(s)return;if(s=!0,clearTimeout(a),this._pending?.id===o)this._pending=void 0;n(l)},a=setTimeout(()=>i({kind:"timeout"}),r);this._pending={id:o,resolve:i},this._transport.send(t(o)).catch((l)=>i({kind:"send-error",error:l}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let t=this._savedOnClose,r=this._transport,o=!1,n=()=>{if(!o){o=!0;return}t()};r.onclose=n,Iu.set(r,()=>{if(r.onclose===n)r.onclose=t})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let t=this._transport,r=t.start,o=!0;t.start=async function(){if(o){o=!1,t.start=r;return}return r.call(t)}}},Iu=new WeakMap;function Ag(e){let t=Iu.get(e);Iu.delete(e),t?.()}function wz(e,t,r,o){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:Lt(t).outboundEnvelope({protocolVersion:t,clientInfo:r,clientCapabilities:o})}}}function Rz(e){if(e instanceof N&&e.code===O.ClientHttpUnexpectedContent)return!0;return e instanceof Error&&e.name==="SyntaxError"}function xz(e,t){switch(e.kind){case"response":return e.error===void 0?{kind:"result",result:e.result}:{kind:"rpc-error",...e.error};case"send-error":{let r=e.error;if(uz(r)||r instanceof wt||r instanceof Error&&r.name==="UnauthorizedError")return{kind:"auth-required",error:r};if(r instanceof vt){let o=r.data?.text;return{kind:"http-error",status:r.data.status,body:typeof o==="string"?o:void 0,statusText:r.data.statusText}}if(Rz(r))return{kind:"unusable-reply",error:r};return{kind:"network-error",error:r}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function Xg(e,t){let r=e.probe.timeoutMs??t.defaultTimeoutMs,o=Math.max(0,e.probe.maxRetries??0),n=e.kind==="pin"?[e.version]:e.modernVersions,s=e.kind==="auto"&&e.fallbackAvailable,i=await zz.open(t.transport),a=async()=>{let u=n[0],d=!1,m=o;for(;;){let f=await i.exchange((y)=>wz(y,u,t.clientInfo,t.capabilities),r);if(f.kind==="timeout"&&m>0){m--;continue}let S=xz(f,r),b=hz(S,{clientModernVersions:n,requestedVersion:u,fallbackAvailable:s,environment:t.environment,transportKind:t.transportKind});switch(b.kind){case"modern":return{era:"modern",version:b.version,discover:b.discover};case"corrective":if(d)throw b.error;d=!0,u=b.version;continue;case"legacy":{let y=S.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new N(O.EraNegotiationFailed,y===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${y} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new N(O.EraNegotiationFailed,y===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${y} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(y!==void 0&&t.disposableProbe!==!0)throw new N(O.EraNegotiationFailed,`Version negotiation failed: ${y} (this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw b.error}}},l;try{l=await a()}catch(u){throw i.detach(),u}return i.release(),l}function Pz(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;let r=e._serverParams;return typeof r==="object"&&r!==null&&typeof r.command==="string"?r:void 0}async function Tz(e,t,r,o){let s=new t.constructor({...r,stderr:"ignore"}),i=t.close,a=!1,l,u=new Promise((m,f)=>{l=()=>f(Mg())});t.close=async function(){return a=!0,l?.(),i.call(t)};let d;try{let m=Xg(e,{...o,transport:s,transportKind:"stdio",disposableProbe:!0});m.catch(()=>{}),d=await Promise.race([m,u])}finally{await Ez(s),t.close=i}if(a)throw Mg();return d}function Mg(){return new N(O.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function Ez(e){try{let t=e._dispose;await(typeof t==="function"?t.call(e):e.close())}catch{}}function jg(e){let t=e._meta?.[Ot];return pg.Implementation(t)?t:void 0}function xc(e,t){if(!e||t===null||typeof t!=="object")return;if(e.type==="object"&&e.properties&&typeof e.properties==="object"){let r=t,o=e.properties;for(let n of Object.keys(o)){let s=o[n];if(r[n]===void 0&&Object.prototype.hasOwnProperty.call(s,"default"))r[n]=s.default;if(r[n]!==void 0)xc(s,r[n])}}if(Array.isArray(e.anyOf)){for(let r of e.anyOf)if(typeof r!=="boolean")xc(r,t)}if(Array.isArray(e.oneOf)){for(let r of e.oneOf)if(typeof r!=="boolean")xc(r,t)}}function kz(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}function $z(e){if(typeof e==="object"&&e!==null){if(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e))return e;if(e.kind==="modern"&&rr.safeParse(e.discover).success)return e}throw new N(O.EraNegotiationFailed,"connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }")}var Lg={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},Cz=64,Qg=class extends yc{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new N(O.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t);if(this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new _u,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=cg(t?.inputRequired),this._cache=new cz(t?.responseCacheStore??new iz,t?.responseCacheStore!==void 0,(r)=>this._reportStoreError(r),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??Cz,t?.listChanged)this._listChangedConfig=t.listChanged}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&Zt(this._negotiatedProtocolVersion)&&Fr(e))return"drop"}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){if(!this._inputRequiredDriverConfig.autoFulfill)return Promise.reject(new N(O.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance — pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:t.request.method}));return mg({getRequestHandler:(r)=>this._getRequestHandler(r),buildContext:(r)=>this.buildContext(r,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t)}_setupListChangedHandlers(e){if(e.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools);if(e.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts);if(e.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources","notifications/resources/list_changed",e.resources,async()=>(await this.listResources(void 0,{cacheMode:"refresh"})).resources)}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=hg(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){if(e==="elicitation/create")return async(r,o)=>{let n=Lt(this._negotiatedProtocolVersion),s=n.validateRequest("elicitation/create",r);if(!s.ok&&s.reason==="not-in-era")s=n.validateInputRequest("elicitation/create",r);if(!s.ok)throw new ee(s.reason==="not-in-era"?W.InternalError:W.InvalidParams,s.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${s.message}`);let{params:i}=s.value;i.mode=i.mode??"form";let{supportsFormMode:a,supportsUrlMode:l}=kz(this._capabilities.elicitation);if(i.mode==="form"&&!a)throw new ee(W.InvalidParams,"Client does not support form-mode elicitation requests");if(i.mode==="url"&&!l)throw new ee(W.InvalidParams,"Client does not support URL-mode elicitation requests");let u=await t(r,o),d=n.validateResult("elicitation/create",u);if(!d.ok&&d.reason==="not-in-era")d=n.validateInputResponse("elicitation/create",u);if(!d.ok)throw new ee(d.reason==="not-in-era"?W.InternalError:W.InvalidParams,d.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${d.message}`);let m=d.value,f=i.mode==="form"?i.requestedSchema:void 0;if(i.mode==="form"&&m.action==="accept"&&m.content&&f&&this._capabilities.elicitation?.form?.applyDefaults)try{xc(f,m.content)}catch{}return m};if(e==="sampling/createMessage")return async(r,o)=>{let n=Lt(this._negotiatedProtocolVersion),s=n.validateRequest("sampling/createMessage",r);if(!s.ok&&s.reason==="not-in-era")s=n.validateInputRequest("sampling/createMessage",r);if(!s.ok)throw new ee(s.reason==="not-in-era"?W.InternalError:W.InvalidParams,s.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${s.message}`);let{params:i}=s.value,a=await t(r,o),l=Boolean(i.tools||i.toolChoice),u=n.samplingResultVariant(l,a);if(!u.ok&&u.reason==="not-in-era")u=n.validateInputResponse("sampling/createMessage",a);if(!u.ok)throw new ee(u.reason==="not-in-era"?W.InternalError:W.InvalidParams,u.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${u.message}`);return u.value};return t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new N(O.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,$z(t.prior),t);let r=vz(this._versionNegotiation,this._supportedProtocolVersionsOption);if(r.kind!=="legacy")return this._connectNegotiated(e,r,t);return this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let r=this._negotiatedProtocolVersion;if(r!==void 0)e.setProtocolVersion?.(r);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let r=au(this._supportedProtocolVersions);try{let o=r[0];if(o===void 0)throw new N(O.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let n=await this.request({method:"initialize",params:{protocolVersion:o,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!r.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);if(this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion)e.setProtocolVersion(n.protocolVersion);if(this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=n.protocolVersion,this._listChangedConfig)this._setupListChangedHandlers(this._listChangedConfig)}catch(o){throw this.close(),o}}async _connectNegotiated(e,t,r){if(e.sessionId!==void 0){await super.connect(e);let n=this._negotiatedProtocolVersion;if(n!==void 0&&e.setProtocolVersion)e.setProtocolVersion(n);return}this._resetConnectionState();let o;try{let n=qg(e),s={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:Ng(),defaultTimeoutMs:r?.timeout??bc},i=n==="stdio"?Pz(e):void 0;o=i===void 0?await Xg(t,{...s,transport:e,transportKind:n}):await Tz(t,e,i,s)}catch(n){throw await e.close().catch(()=>{}),Ag(e),n}if(Ag(e),await super.connect(e),o.era==="legacy"){await this._legacyHandshake(e,r);return}if(this._serverCapabilities=o.discover.capabilities,this._serverVersion=jg(o.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.discover.instructions,this._discoverResult=o.discover,this._negotiatedProtocolVersion=o.version,e.setProtocolVersion)e.setProtocolVersion(o.version);if(this._listChangedConfig){let n=this._listChangedConfig,s=this._serverCapabilities,i={...n.tools&&s?.tools?.listChanged&&{tools:n.tools},...n.prompts&&s?.prompts?.listChanged&&{prompts:n.prompts},...n.resources&&s?.resources?.listChanged&&{resources:n.resources}},a=!0;try{this._setupListChangedHandlers(i)}catch(u){a=!1,this.onerror?.(u instanceof Error?u:Error(String(u)))}let l=a?{...i.tools&&{toolsListChanged:!0},...i.prompts&&{promptsListChanged:!0},...i.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(l).length>0){let u=new AbortController,d=()=>u.abort(r?.signal?.reason);if(r?.signal?.aborted)d();r?.signal?.addEventListener("abort",d);try{this._autoOpenedSubscription=await this.listen(l,{timeout:r?.timeout,signal:u.signal})}catch(m){if(r?.signal?.aborted)throw await this.close().catch(()=>{}),m;this.onerror?.(m instanceof Error?m:Error(String(m)))}finally{r?.signal?.removeEventListener("abort",d)}}}}async _connectFromPrior(e,t,r){if(t.kind==="legacy")return this._connectPlainLegacy(e,r);let o=t.discover;this._resetConnectionState();let n=this._supportedProtocolVersionsOption,s=(n&&Oi(n).length>0?Oi(n):iu).find((i)=>o.supportedVersions.includes(i));if(s===void 0)throw new N(O.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(e),this._discoverResult=o,this._serverCapabilities=o.capabilities,this._serverVersion=jg(o),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.instructions,this._negotiatedProtocolVersion=s,e.setProtocolVersion?.(s),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(i){this.onerror?.(i instanceof Error?i:Error(String(i)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;if(t!==void 0)return`${t.name}@${t.version}`;return e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return Zt(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new N(O.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new N(O.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new N(O.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new N(O.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new N(O.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new N(O.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new N(O.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new N(O.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new N(O.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new N(O.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){let t=await this._requestWithSchema({method:"server/discover"},rr,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:"completion/complete",params:e},t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:"prompts/list",params:e},t);let r=await this._serveFromCache("prompts/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("prompts/list",e,t,(o)=>o.prompts)}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(e?.cursor!==void 0)return this.request({method:"resources/list",params:e},t);let r=await this._serveFromCache("resources/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("resources/list",e,t,(o)=>o.resources)}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:"resources/templates/list",params:e},t);let r=await this._serveFromCache("resources/templates/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("resources/templates/list",e,t,(o)=>o.resourceTemplates)}async _listAllPages(e,t,r,o,n){let s=r?.cacheMode==="bypass",i=this._cache.captureGeneration(e),a=await this.request({method:e,...t&&{params:{...t}}},r),l=a.nextCursor,u=a,d=1;while(l!==void 0){if(this._listMaxPages!==0&&d>=this._listMaxPages)throw new N(O.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});let m=await this.request({method:e,params:{...t,cursor:l}},r);if(m.nextCursor===l&&JSON.stringify(o(m))===JSON.stringify(o(u)))break;o(a).push(...o(m)),u=m,l=m.nextCursor,d++}if(delete a.nextCursor,n?.(a),s)return a;return await this._cache.write(e,a,i,this._freshness(a)),a}_freshness(e,t){let r=e,o=typeof r.ttlMs==="number"?r.ttlMs:this._defaultCacheTtlMs,n=r.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,o),az),scope:n,params:t}}async _serveFromCache(e,t,r){if(r?.cacheMode==="bypass"||r?.cacheMode==="refresh")return;let o=await this._cache.read(e,t).catch((n)=>void this._reportStoreError(n));if(o!==void 0){if(r?.signal?.aborted){let n=r.signal.reason;throw n instanceof N?n:new N(O.RequestTimeout,String(n))}return o.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}_compileOutputValidator(e){if(!e.outputSchema)return;try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){let r=t??await this._cache.toolDefinition(e);return r===void 0?void 0:mu(r.inputSchema)}async readResource(e,t){let r=await this._serveFromCache("resources/read",e.uri,t);if(r!==void 0)return r;let o=this._cache.captureGeneration("resources/read",e.uri),n=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){let s=this._freshness(n,e.uri);if(s.expiresAt>this._cache.now())await this._cache.write("resources/read",n,o,s);else if(t?.cacheMode==="refresh")await this._cache.evictKey("resources/read",e.uri)}return n}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},t)}async listen(e,t){if(this.transport===void 0)throw new N(O.NotConnected,"Not connected");let r=this._negotiatedProtocolVersion;if(r===void 0||!Zt(r))throw new N(O.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${r??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:r});if(t?.signal?.aborted){let x=t.signal.reason;throw x instanceof N?x:new N(O.RequestTimeout,String(x))}let o=new AbortController,n=`listen:${this._nextListenId++}`,s="opening",i,a,l,u,d=new Promise((x,Z)=>{l=x,u=Z}),m,f=new Promise((x)=>{m=x}),S=(x)=>{if(s==="closed")return;let Z=s==="opening";if(i!==void 0)clearTimeout(i),i=void 0;if("ack"in x){s="open",l(x.ack);return}if(s="closed",a!==void 0)t?.signal?.removeEventListener("abort",a);if(this._listenState.delete(n),o.abort(),m(x.cause),Z)u(x.error??new N(O.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},b=async()=>{o.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:n}}).catch(()=>{})},y=async()=>{if(s==="closed")return;S({cause:"local"}),await b()};this._listenState.set(n,{settle:S});let v=t?.timeout??bc;if(i=setTimeout(()=>{S({cause:"remote",error:new N(O.RequestTimeout,"subscriptions/listen ack timed out",{timeout:v})}),b().catch(()=>{})},v),t?.signal){let x=t.signal;a=()=>{if(s==="closed")return;let Z=x.reason;S({cause:"local",error:Z instanceof Error?Z:Error(String(Z??"Aborted"))}),b().catch(()=>{})},x.addEventListener("abort",a,{once:!0})}let U={jsonrpc:"2.0",id:n,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}},H=(x)=>{S({cause:"remote",error:x instanceof Error?x:Error(String(x))})};try{this.transport.send(U,{requestSignal:o.signal,onRequestStreamEnd:()=>S({cause:"remote",error:Error("subscriptions/listen: stream ended")})}).catch(H)}catch(x){H(x)}return{honoredFilter:await d,close:y,closed:f}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let r=Object.hasOwn(Lg,e.method)?Lg[e.method]:void 0;if(e.method==="notifications/resources/updated"){let o=e.params?.uri;if(typeof o==="string")this._cache.evictKey("resources/read",o)}else if(r!==void 0)for(let o of r)this._cache.evict(o);if(e.method==="notifications/subscriptions/acknowledged"){let o=e.params?._meta?.[Wn],n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){let s=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);n.settle({ack:s.ok?s.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){let o=e.params?.requestId,n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){n.settle({cause:"remote",error:Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,r=typeof t==="string"?this._listenState.get(t):void 0;if(r!==void 0){if(Wo(e))r.settle({cause:"remote",error:ee.fromError(e.error.code,e.error.message,e.error.data)});else r.settle({cause:"graceful",error:new N(O.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new N(O.ConnectionClosed,"Connection closed");for(let t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let r=this.getProtocolEra()==="modern"&&Ng()!=="browser",o=async()=>{if(!r)return t;let l;try{l=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(d){this._reportStoreError(d)}if(!l?.valid||l.declarations.length===0)return t;let u=sg(l.declarations,e.arguments);return Object.keys(u).length===0?t:{...t,headers:{...t?.headers,...u}}},n=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,(l)=>this._compileOutputValidator(l)).catch((l)=>void this._reportStoreError(l)):this._compileOutputValidator(t.toolDefinition),s=()=>{if(n===void 0||n.ok)return;let l=n.compileError,u=(l instanceof Error?l.message:String(l)).slice(0,200);throw new ee(W.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${u}`)};s();let i;try{i=await this.request({method:"tools/call",params:e},await o())}catch(l){let u=l instanceof ee&&l.code===Jo;if(!r||!u||t?.toolDefinition!==void 0)throw l;let d={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,d).catch((m)=>this._reportStoreError(m)),n=await this._cache.outputValidator(e.name,(m)=>this._compileOutputValidator(m)).catch((m)=>void this._reportStoreError(m)),s(),i=await this.request({method:"tools/call",params:e},await o())}let a=n!==void 0&&n.ok?n.validator:void 0;if(a){if(i.structuredContent===void 0&&!i.isError)throw new ee(W.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent!==void 0&&!i.isError)try{let l=a(i.structuredContent);if(!l.valid)throw new ee(W.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)}catch(l){if(l instanceof ee)throw l;throw new ee(W.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)}}return i}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){let o=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(o),o}let r=await this._serveFromCache("tools/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("tools/list",e,t,(o)=>o.tools,(o)=>this._excludeInvalidXMcpHeaderTools(o))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||qg(this.transport)==="stdio")return;let t=e.tools.filter((r)=>{let o=mu(r.inputSchema);if(!o.valid)return console.warn(`[mcp-sdk] excluding tool '${r.name}' from tools/list: invalid x-mcp-header declaration — ${o.reason}`),!1;return!0});if(t.length!==e.tools.length)e.tools=t}_setupListChangedHandler(e,t,r,o){let n=_c(Hs,r);if(!n.success)throw Error(`Invalid ${e} listChanged options: ${n.error.message}`);if(typeof r.onChanged!=="function")throw TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:i}=n.data,{onChanged:a}=r,l=async()=>{if(!s){a(null,null);return}try{a(null,await o())}catch(d){a(d instanceof Error?d:Error(String(d)),null)}},u=()=>{if(i){let d=this._listChangedDebounceTimers.get(e);if(d)clearTimeout(d);let m=setTimeout(l,i);this._listChangedDebounceTimers.set(e,m)}else l()};this.setNotificationHandler(t,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function Iz(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function Oz(e){if(e.status!==401)return!1;let t=e.headers.get("www-authenticate")??"";return Iz(t)&&/use_dpop_nonce/i.test(t)}var Nz=(e,t)=>(r)=>{let o=typeof e==="function"?e:()=>e;return async(n,s)=>{let i=(s?.method??"GET").toUpperCase(),a=new URL(n.toString()),l=await o();if(!l)return r(n,s);let u=async()=>{let m=await t();if(!m)return r(n,s);let f=new Headers(s?.headers),S=await l.buildProof({htm:i,htu:a,accessToken:m});return f.set("Authorization",`DPoP ${m}`),f.set("DPoP",S),r(n,{...s,headers:f})},d=await u();if(Oz(d)&&d.headers.has("dpop-nonce"))l.observeNonce(d,a),await d.text?.().catch(()=>{}),d=await u();return l.observeNonce(d,a),d}},qz=(e)=>Nz(async()=>{try{return await e.dpop?.()}catch(t){throw Xe(t)}},async()=>{let t;try{t=await e.tokens()}catch(r){throw Xe(r)}return t?.token_type?.toLowerCase()==="dpop"?t.access_token:void 0});var vP=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e,t,r){super(`SSE error: ${t}`);this.code=e,this.event=r,Zr(this,new.target)}};var Az=1,Mz={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2},jz=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function Ug(e,t){if(typeof AbortSignal.any==="function")return AbortSignal.any([e,t]);let r=new AbortController;if(e.aborted)return r.abort(e.reason),r.signal;if(t.aborted)return r.abort(t.reason),r.signal;let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",s)};function n(){o(),r.abort(e.reason)}function s(){o(),r.abort(t.reason)}return e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",s,{once:!0}),r.signal}var eS=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){if(this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,Ov(t?.authProvider)){if(this._oauthProvider=t.authProvider,this._authProvider=qv(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop)this._fetch=qz(t.authProvider)(t.fetch??fetch)}else this._authProvider=t?.authProvider;if(this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=gg(t?.fetch,t?.requestInit),this._redirectPolicy==="follow")this._fetchWithInit=bg(this._fetchWithInit);this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??Mz,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??Az)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(r){throw Xe(r)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new kg({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new kg({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new vt(O.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});if(e.resourceMetadataUrl)this._resourceMetadataUrl=e.resourceMetadataUrl;let r=await this._oauthProvider.tokens(),o=wu(this._scope,r?.scope,e.scope);this._scope=o;let n=Av(o,r?.scope);return Cu(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:o,forceReauthorization:n,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return this._redirectPolicy==="follow"?e:Ni(e)}_unfollowedRedirect(e,t){let r=this._redirectPolicy==="follow"?void 0:yg(e,t);return r&&`${r} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let e=new Headers(this._requestInit?.headers||void 0),t;try{t=await this._authProvider?.token()}catch(r){throw Xe(r)}if(t)e.set("Authorization",`Bearer ${t}`);if(this._sessionId)e.set("mcp-session-id",this._sessionId);if(this._protocolVersion)e.set("mcp-protocol-version",this._protocolVersion);return e}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!Fr(t))return;let r=t.params?._meta?.[It];if(typeof r!=="string")return;e.set("mcp-protocol-version",r),e.set("mcp-method",t.method);let o=ig(t.method,t.params);if(o?.value!==void 0)e.set("mcp-name",fu(o.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Fr(e))return!1;let t=e.params?._meta?.[It];return typeof t==="string"&&Zt(t)}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:o,requestSignal:n}=e,s=()=>this._abortController?.signal.aborted===!0||n?.aborted===!0;try{let i=await this._commonHeaders(),a=[...i.get("accept")?.split(",").map((m)=>m.trim().toLowerCase())??[],"text/event-stream"];if(i.set("accept",[...new Set(a)].join(", ")),o)i.set("last-event-id",o);let l=this._abortController?.signal,u=n!==void 0&&l!==void 0?Ug(l,n):n??l,d=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:i,signal:u});if(!d.ok){if(d.status===401&&this._authProvider){if(d.headers.has("www-authenticate")){let{resourceMetadataUrl:f,scope:S}=Ai(d);this._resourceMetadataUrl=f,this._scope=wu(this._scope,S)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:d,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(f){throw Xe(f)}return await d.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r)}if(await d.text?.().catch(()=>{}),t)throw Xe(new vt(O.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:d.statusText}));throw Xe(new wt)}if(d.status===403){let{resourceMetadataUrl:f,scope:S,error:b,errorDescription:y}=Ai(d);if(b==="insufficient_scope"){let v=await d.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:S,resourceMetadataUrl:f,errorDescription:y,statusText:d.statusText,text:v},r)!=="AUTHORIZED")throw Xe(new wt);return this._startOrAuthSse(e,t,r+1)}}if(await d.text?.().catch(()=>{}),d.status===405){e.onRequestStreamEnd?.();return}let m=this._unfollowedRedirect(this._url,d)??d.statusText;throw new vt(O.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${m}`,{status:d.status,statusText:d.statusText})}this._handleSseStream(d.body,e,!0)}catch(i){if(!s())this.onerror?.(i);throw i}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(Error(`Maximum reconnection attempts (${r}) exceeded.`)),e.onRequestStreamEnd?.();return}let o=this._getNextReconnectionDelay(t),n=()=>{if(this._cancelReconnection=void 0,this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this._startOrAuthSse(e).catch((s)=>{if(this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this.onerror?.(Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`));try{this._scheduleReconnection(e,t+1)}catch(i){this.onerror?.(i instanceof Error?i:Error(String(i)))}})};if(this._reconnectionScheduler){let s=this._reconnectionScheduler(n,o,t);this._cancelReconnection=typeof s==="function"?s:void 0}else{let s=setTimeout(n,o);this._cancelReconnection=()=>clearTimeout(s)}}_handleSseStream(e,t,r){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i}=t,a=()=>this._abortController?.signal.aborted===!0||s?.aborted===!0,l,u=!1,d=!1;(async()=>{try{let f=e.pipeThrough(new TextDecoderStream).pipeThrough(new zu({onRetry:(S)=>{this._serverRetryMs=S}})).getReader();while(!0){let{value:S,done:b}=await f.read();if(b)break;if(S.id)l=S.id,u=!0,o?.(S.id);if(!S.data)continue;if(!S.event||S.event==="message")try{let y=st.parse(JSON.parse(S.data));if(Bo(y)||Wo(y)){if(d=!0,n!==void 0)y.id=n}this.onmessage?.(y)}catch(y){this.onerror?.(y)}}if((r||u)&&!d&&this._abortController&&!a())this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i},0);else if(!a())i?.()}catch(f){if(a())return;if(this.onerror?.(Error(`SSE stream disconnected: ${f}`)),(r||u)&&!d&&this._abortController&&!a())try{this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i},0)}catch(S){this.onerror?.(Error(`Failed to reconnect: ${S instanceof Error?S.message:String(S)}`)),i?.()}else i?.()}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new wt("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:o}=await Mv(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await Cu(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:o,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new wt("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,r,o=0){try{let{resumptionToken:n,onresumptiontoken:s}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Fr(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch((v)=>this.onerror?.(v));return}let i=await this._commonHeaders();this._applyBodyDerivedHeaders(i,e);let a=Array.isArray(e)?e.some((v)=>hu(v)):hu(e);if(a)i.delete("mcp-session-id");if(t?.headers!==void 0)for(let[v,U]of Object.entries(t.headers)){if(jz.has(v.toLowerCase()))continue;i.set(v,U)}i.set("content-type","application/json");let l=[...i.get("accept")?.split(",").map((v)=>v.trim().toLowerCase())??[],"application/json","text/event-stream"];i.set("accept",[...new Set(l)].join(", "));let u=this._abortController?.signal,d=t?.requestSignal!==void 0&&u!==void 0?Ug(u,t.requestSignal):t?.requestSignal??u,m={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(e),signal:d},f=await this._redirects(this._fetch??fetch)(this._url,m);if(a&&f.ok)this._sessionId=f.headers.get("mcp-session-id")||void 0;if(!f.ok){if(f.status===401&&this._authProvider){if(f.headers.has("www-authenticate")){let{resourceMetadataUrl:H,scope:x}=Ai(f);this._resourceMetadataUrl=H,this._scope=wu(this._scope,x)}if(this._authProvider.onUnauthorized&&!r){try{await this._authProvider.onUnauthorized({response:f,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(H){throw Xe(H)}return await f.text?.().catch(()=>{}),this._send(e,t,!0,o)}if(await f.text?.().catch(()=>{}),r)throw Xe(new vt(O.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:f.statusText}));throw Xe(new wt)}let v=await f.text?.().catch(()=>null);if(f.status===403){let{resourceMetadataUrl:H,scope:x,error:Z,errorDescription:R}=Ai(f);if(Z==="insufficient_scope"){if(await this._stepUpAuthorize({scope:x,resourceMetadataUrl:H,errorDescription:R,statusText:f.statusText,text:v},o)!=="AUTHORIZED")throw Xe(new wt);return this._send(e,t,r,o+1)}}if(f.status===400&&typeof v==="string"&&this._isModernEnvelopedRequest(e))try{let H=st.parse(JSON.parse(v)),x=(Array.isArray(e)?e:[e]).filter((Z)=>Fr(Z));if(Wo(H)&&x.some((Z)=>Z.id===H.id)){this.onmessage?.(H);return}}catch{}let U=this._unfollowedRedirect(this._url,f)??v;throw new vt(O.ClientHttpNotImplemented,`Error POSTing to endpoint: ${U}`,{status:f.status,statusText:f.statusText,text:v})}if(f.status===202){if(await f.text?.().catch(()=>{}),rg(e))this._startOrAuthSse({resumptionToken:void 0}).catch((v)=>this.onerror?.(v));return}let S=(Array.isArray(e)?e:[e]).some((v)=>("method"in v)&&("id"in v)&&v.id!==void 0),b=f.headers.get("content-type"),y=fg(b);if(S)if(y==="text/event-stream")this._handleSseStream(f.body,{onresumptiontoken:s,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(y==="application/json"){let v=await f.json(),U=Array.isArray(v)?v.map((H)=>st.parse(H)):[st.parse(v)];for(let H of U)this.onmessage?.(H)}else throw await f.text?.().catch(()=>{}),new N(O.ClientHttpUnexpectedContent,`Unexpected content type: ${b}`,{contentType:b});else await f.text?.().catch(()=>{})}catch(n){if(t?.requestSignal?.aborted!==!0)this.onerror?.(n);throw n}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await this._redirects(this._fetch??fetch)(this._url,t);if(await r.text?.().catch(()=>{}),!r.ok&&r.status!==405)throw new vt(O.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,r)??r.statusText}`,{status:r.status,statusText:r.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};class iS{_eventSlots=new Map;setHandler(e,t){let r=this._ensureEventSlot(e);if(r.onHandler&&t)console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`);r.onHandler=t}getHandler(e){return this._eventSlots.get(e)?.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let r=this._eventSlots.get(e);if(!r)return;let o=r.listeners.indexOf(t);if(o!==-1)r.listeners.splice(o,1)}dispatch(e,t){let r=this._eventSlots.get(e);if(!r)return;r.onHandler?.(t);for(let o of[...r.listeners])o(t)}_ensureEventSlot(e){let t=this._eventSlots.get(e);if(!t)t={listeners:[]},this._eventSlots.set(e,t);return t}}class aS{_methods=new Set;claim(e,t){if(this._methods.has(e))throw Error(`Handler for "${e}" already registered (via ${t}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._methods.add(e)}replace(e){this._methods.add(e)}release(e){this._methods.delete(e)}has(e){return this._methods.has(e)}}var tS=new Set;function rS(e,t){let[r,o]=t,n=r?.shape;if(typeof n?.method?.value!=="string")return;let s=n.method.value,i=e==="request"?"setRequestHandler":"setNotificationHandler";if(!tS.has(i))tS.add(i),console.warn(`[ext-apps] ${i}(Schema, handler) is deprecated; use ${i}("${s}", { params: Schema.shape.params }, handler).`);let a=o;return[s,{params:n.params},e==="request"?(l,u)=>a({method:s,params:l},Lz(u)):(l)=>a({method:s,params:l})]}function Lz(e){return{signal:e.mcpReq.signal,requestId:e.mcpReq.id,sessionId:e.sessionId,_meta:e.mcpReq._meta,sendRequest:e.mcpReq.send,sendNotification:e.mcpReq.notify,authInfo:e.http?.authInfo}}var cS="2026-01-26";var Uz="ui/notifications/tool-input-partial";var Zz=T([h("light"),h("dark")]).describe("Color theme preference for the host environment."),ji=T([h("inline"),h("fullscreen"),h("pip")]).describe("Display mode for UI presentation."),Dz=T([h("--color-background-primary"),h("--color-background-secondary"),h("--color-background-tertiary"),h("--color-background-inverse"),h("--color-background-ghost"),h("--color-background-info"),h("--color-background-danger"),h("--color-background-success"),h("--color-background-warning"),h("--color-background-disabled"),h("--color-text-primary"),h("--color-text-secondary"),h("--color-text-tertiary"),h("--color-text-inverse"),h("--color-text-ghost"),h("--color-text-info"),h("--color-text-danger"),h("--color-text-success"),h("--color-text-warning"),h("--color-text-disabled"),h("--color-border-primary"),h("--color-border-secondary"),h("--color-border-tertiary"),h("--color-border-inverse"),h("--color-border-ghost"),h("--color-border-info"),h("--color-border-danger"),h("--color-border-success"),h("--color-border-warning"),h("--color-border-disabled"),h("--color-ring-primary"),h("--color-ring-secondary"),h("--color-ring-inverse"),h("--color-ring-info"),h("--color-ring-danger"),h("--color-ring-success"),h("--color-ring-warning"),h("--font-sans"),h("--font-mono"),h("--font-weight-normal"),h("--font-weight-medium"),h("--font-weight-semibold"),h("--font-weight-bold"),h("--font-text-xs-size"),h("--font-text-sm-size"),h("--font-text-md-size"),h("--font-text-lg-size"),h("--font-heading-xs-size"),h("--font-heading-sm-size"),h("--font-heading-md-size"),h("--font-heading-lg-size"),h("--font-heading-xl-size"),h("--font-heading-2xl-size"),h("--font-heading-3xl-size"),h("--font-text-xs-line-height"),h("--font-text-sm-line-height"),h("--font-text-md-line-height"),h("--font-text-lg-line-height"),h("--font-heading-xs-line-height"),h("--font-heading-sm-line-height"),h("--font-heading-md-line-height"),h("--font-heading-lg-line-height"),h("--font-heading-xl-line-height"),h("--font-heading-2xl-line-height"),h("--font-heading-3xl-line-height"),h("--border-radius-xs"),h("--border-radius-sm"),h("--border-radius-md"),h("--border-radius-lg"),h("--border-radius-xl"),h("--border-radius-full"),h("--border-width-regular"),h("--shadow-hairline"),h("--shadow-sm"),h("--shadow-md"),h("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),Fz=P(Dz.describe(`Style variables for theming MCP apps.
80
+ ${ke}`,m++;return}if(Tg(R,w,X)){f=R.slice(R.charCodeAt(w+6)===Vr?w+7:w+6,D)||void 0;return}if(X===105&&R.charCodeAt(w+1)===100&&R.charCodeAt(w+2)===58){let ve=R.slice(R.charCodeAt(w+3)===Vr?w+4:w+3,D);ve.includes("\x00")||(u=ve);return}if(X===58){if(n){let ve=R.slice(w,D);n(ve.slice(R.charCodeAt(w+1)===Vr?2:1))}return}let Y=R.slice(w,D),le=Y.indexOf(":");if(le===-1){H(Y,"",Y);return}let Ee=Y.slice(0,le),te=Y.charCodeAt(le+1)===Vr?2:1,ie=Y.slice(le+te);H(Ee,ie,Y)}function H(R,w,D){switch(R){case"event":f=w||void 0;break;case"data":d=m===0?w:`${d}
81
+ ${w}`,m++;break;case"id":w.includes("\x00")||(u=w);break;case"retry":/^\d+$/.test(w)?o(parseInt(w,10)):r(new vc(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:D}));break;default:r(new vc(`Unknown field "${R.length>20?`${R.slice(0,20)}…`:R}"`,{type:"unknown-field",field:R,value:w,line:D}));break}}function x(){m>0&&t({id:u,event:f,data:d}),u=void 0,d="",m=0,f=void 0}function Z(R={}){if(R.consume&&s.length>0){let w=s.join("");U(w,0,w.length)}l=!0,u=void 0,d="",m=0,f=void 0,s.length=0,a=0,S=!1}return{feed:b,reset:Z}}function Pg(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Tg(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}class wu extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:o}={}){let n;super({start(i){n=Eg({onEvent:(s)=>{i.enqueue(s)},onError(s){typeof e=="function"&&e(s),(e==="terminate"||s.type==="max-buffer-size-exceeded")&&i.error(s)},onRetry:t,onComment:r,maxBufferSize:o})},transform(i){n.feed(i)}})}}var Mi=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e){super(e);this.name=new.target.name,Zr(this,new.target)}},$u=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 §3.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`);this.kind=e,this.expected=t,this.received=r}},Iv=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`);this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},Zg=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`);this.tokenEndpoint=e}},Rc=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`);this.recordedIssuer=e,this.currentIssuer=t}},kg=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`);this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function Cu(e,t,r){if(!e)return;if(typeof e.issuer!=="string"){if(r?.canPersistStamp!==!1)console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field.");return e.issuer===void 0?e:{...e,issuer:void 0}}return Dg(e.issuer,t)?e:void 0}function Dg(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function Ov(e){if(e==null)return!1;let t=e;return typeof t.tokens==="function"&&typeof t.clientInformation==="function"}async function Nv(e,t,r){let{resourceMetadataUrl:o,scope:n}=Ai(t.response);if(await Iu(e,{serverUrl:t.serverUrl,resourceMetadataUrl:o,scope:n,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new wt}function qv(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async(r)=>Nv(e,r,t)}}var wt=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e){super(e??"Unauthorized");this.name="UnauthorizedError",Zr(this,new.target)}};function Nu(e){return e?.authorization_response_iss_parameter_supported===!0}function qu({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t===void 0)return;if(e===void 0){if(r)throw new $u("authorization_response",t,void 0);return}if(e!==t)throw new $u("authorization_response",t,e)}function Ru(...e){let t=new Set;for(let r of e){if(!r)continue;for(let o of r.split(/\s+/))if(o)t.add(o)}return t.size>0?[...t].join(" "):void 0}function Av(e,t){if(!e)return!1;let r=new Set((t??"").split(/\s+/).filter(Boolean));for(let o of e.split(/\s+/))if(o&&!r.has(o))return!0;return!1}async function Mv(e,t,r,o,n){if(typeof e==="string")return{authorizationCode:e,iss:t};let i=e.get("iss")??void 0,s=e.get("code");if(s)return{authorizationCode:s,iss:i};let a=(await r.discoveryState?.())?.authorizationServerMetadata;if(!a)try{a=(await Bg(o,n)).authorizationServerMetadata}catch{a=void 0}if(!a)throw new wt("Authorization callback failed and the issuer could not be verified");qu({iss:i,expectedIssuer:a.issuer,issParameterSupported:Nu(a)});let l=e.get("error");if(l)throw new Dr(l,e.get("error_description")??l,e.get("error_uri")??void 0);throw new wt("Authorization callback contained neither `code` nor `error`")}function jv(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var xu="code",Pu="S256";function Lv(e,t){let r=e.client_secret!==void 0;if("token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&jv(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method)))return e.token_endpoint_auth_method;if(t.length===0)return r?"client_secret_basic":"none";if(r&&t.includes("client_secret_basic"))return"client_secret_basic";if(r&&t.includes("client_secret_post"))return"client_secret_post";if(t.includes("none"))return"none";return r?"client_secret_post":"none"}function Uv(e,t,r,o){let{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":Zv(n,i,r);return;case"client_secret_post":Dv(n,i,o);return;case"none":Fv(n,o);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Zv(e,t,r){if(!t)throw Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}function Dv(e,t,r){if(r.set("client_id",e),t)r.set("client_secret",t)}function Fv(e,t){t.set("client_id",e)}function Fg(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function Hv(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!Fg(t.hostname))throw new Zg(t.href);return t}function Vv(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:")return"native";if(Fg(r.hostname))return"native"}return"web"}function Jv(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??Vv(t.redirect_uris)}}async function $g(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Ho.parse(JSON.parse(r));return Dr.fromResponse(o)}catch(o){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Dr(Ut.ServerError,n)}}function Cg(e,t,r){let o=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} — ${o}. Cause: ${JSON.stringify(t.message)}`)}async function Iu(e,t){try{return await Tu(e,t)}catch(r){if(r instanceof Dr){if(r.code===Ut.InvalidClient||r.code===Ut.UnauthorizedClient)return Cg(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Tu(e,t);else if(r.code===Ut.InvalidGrant||r.code===Ut.InvalidDpopProof)return Cg(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await Tu(e,t)}throw r}}function Bv(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:n}=e,i=t||r?.scopes_supported?.join(" ")||n.scope;if(i&&o?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&n.grant_types?.includes("refresh_token"))i=`${i} offline_access`;return i}async function Tu(e,{serverUrl:t,authorizationCode:r,iss:o,scope:n,resourceMetadataUrl:i,fetchFn:s,skipIssuerMetadataValidation:a,forceReauthorization:l}){let u=Jv(e),d=await e.discoveryState?.(),m,f,S,b,y=i;if(!y&&d?.resourceMetadataUrl)y=new URL(d.resourceMetadataUrl);if(d?.authorizationServerUrl){if(f=d.authorizationServerUrl,m=d.resourceMetadata,S=d.authorizationServerMetadata??await Jg(f,{fetchFn:s,skipIssuerValidation:a}),!m)try{m=await Hg(t,{resourceMetadataUrl:y},s)}catch(te){if(te instanceof TypeError)throw te}if(S!==d.authorizationServerMetadata||m!==d.resourceMetadata)await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:S})}else{let te=await Bg(t,{resourceMetadataUrl:y,fetchFn:s,skipIssuerMetadataValidation:a});f=te.authorizationServerUrl,S=te.authorizationServerMetadata,m=te.resourceMetadata,b={authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:S}}let v=S?.issuer??String(f),U={issuer:v};if(await e.saveAuthorizationServerUrl?.(v),r!==void 0){let te=d?.authorizationServerMetadata?.issuer??d?.authorizationServerUrl;if(te===void 0){if(e.saveDiscoveryState!==void 0)throw new Rc("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",v);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.")}else if(!Dg(te,v))throw new Rc(te,v)}if(b)await e.saveDiscoveryState?.(b);let H=await Kv(t,e,m),x=H&&m&&!e.validateResourceURL?m.resource:H;if(x)await e.saveResourceUrl?.(Au(x));let Z=Bv({requestedScope:n,resourceMetadata:m,authServerMetadata:S,clientMetadata:e.clientMetadata}),R=await Promise.resolve(e.clientInformation(U)),w=Cu(R,v,{canPersistStamp:e.saveClientInformation!==void 0});if(w===void 0&&R?.issuer&&e.saveClientInformation===void 0)throw new Rc(R.issuer,v);if(w&&w.issuer===void 0)w={...w,issuer:v},await e.saveClientInformation?.(w,U);if(!w){if(r!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let te=S?.client_id_metadata_document_supported===!0,ie=e.clientMetadataUrl;if(ie&&!Wv(ie))throw new Dr(Ut.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ie}`);if(te&&ie)w={client_id:ie,issuer:v},await e.saveClientInformation?.(w,U);else{if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");w={...await sz(f,{metadata:S,clientMetadata:u,scope:Z,fetchFn:s}),issuer:v},await e.saveClientInformation(w,U)}}let D=!e.redirectUrl;if(r!==void 0||D){if(r!==void 0)qu({iss:o,expectedIssuer:S?.issuer,issParameterSupported:Nu(S)});let te=await nz(e,f,{metadata:S,resource:x,authorizationCode:r,iss:o,scope:Z,fetchFn:s});return await e.saveTokens({...te,issuer:v},U),"AUTHORIZED"}let X=Cu(await e.tokens(U),v);if(X&&X.issuer===void 0)X={...X,issuer:v},await e.saveTokens(X,U);if(X?.refresh_token&&!l){let te;try{te=await oz(f,{metadata:S,clientInformation:w,refreshToken:X.refresh_token,resource:x,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:s})}catch(ie){if(ie instanceof Zg)throw ie;if(!(ie instanceof Dr)||ie.code===Ut.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(ie instanceof Error?ie.message:String(ie))}`);else throw ie}if(te)return await e.saveTokens({...te,issuer:v},U),"AUTHORIZED"}let Y=e.state?await e.state():void 0,{authorizationUrl:le,codeVerifier:Ee}=await tz(f,{metadata:S,clientInformation:w,state:Y,redirectUrl:e.redirectUrl,scope:Z,resource:x});return await e.saveCodeVerifier(Ee),await e.redirectToAuthorization(le),"REDIRECT"}function Wv(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Kv(e,t,r){let o=If(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(!r)return;if(!Of({requestedResource:o,configuredResource:r.resource}))throw Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}var Gv=new Set(["bearer","dpop"]);function Ai(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!Gv.has(r.toLowerCase())||!o)return{};let n=zc(e,"resource_metadata")||void 0,i;if(n)try{i=new URL(n)}catch{}let s=zc(e,"scope")||void 0,a=zc(e,"error")||void 0,l=zc(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:s,error:a,errorDescription:l}}function zc(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),n=r.match(o);if(n){let i=n[1]||n[2];if(i)return i}return null}async function Hg(e,t,r=fetch){let o=await Qv(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.text?.().catch(()=>{}),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.text?.().catch(()=>{}),Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Zo.parse(await o.json())}async function Vg(e,t,r=fetch){let o=Ni(r);try{return await o(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!Rg)throw n;if(t)try{return await o(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}function Yv(e,t="",r={}){if(t.endsWith("/"))t=t.slice(0,-1);return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Ig(e,t,r=fetch){return await Vg(e,{"MCP-Protocol-Version":t},r)}function Xv(e,t){if(!e)return!0;if(t==="/")return!1;return!e.ok&&e.status<500||e.status===502}async function Qv(e,t,r,o){let n=new URL(e),i=o?.protocolVersion??ho,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let l=Yv(t,n.pathname);s=new URL(l,o?.metadataServerUrl??n),s.search=n.search}let a=await Ig(s,i,r);if(!o?.metadataUrl&&Xv(a,n.pathname))a=await Ig(new URL(`/.well-known/${t}`,n),i,r);return a}function ez(e){let t=typeof e==="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;if(n.endsWith("/"))n=n.slice(0,-1);return o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"},{url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function Jg(e,{fetchFn:t=fetch,protocolVersion:r=ho,skipIssuerValidation:o=!1}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},i=ez(e);for(let{url:s,type:a}of i){let l=await Vg(s,n,t);if(!l)continue;if(!l.ok){if(await l.text?.().catch(()=>{}),l.status<500||l.status===502)continue;throw Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}let u=a==="oauth"?Ur.parse(await l.json()):Do.parse(await l.json());if(!o){let d=typeof e==="string"?e:e.href;if(!(u.issuer===d||d.endsWith("/")&&u.issuer===d.slice(0,-1)))throw new $u("metadata",d,u.issuer)}return u}}async function Bg(e,t){let r,o;try{if(r=await Hg(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0)o=r.authorization_servers[0]}catch(i){if(i instanceof TypeError)throw i}if(!o)o=String(new URL("/",e));let n=await Jg(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function Au(e){return typeof e==="string"?e:e.href}async function tz(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:i,resource:s}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(xu))throw Error(`Incompatible auth server: does not support response type ${xu}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Pu))throw Error(`Incompatible auth server: does not support code challenge method ${Pu}`)}else a=new URL("/authorize",e);let l=await vu(),{code_verifier:u,code_challenge:d}=l;if(a.searchParams.set("response_type",xu),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Pu),a.searchParams.set("redirect_uri",String(o)),i)a.searchParams.set("state",i);if(n)a.searchParams.set("scope",n);if(n?.split(" ").includes("offline_access"))a.searchParams.append("prompt","consent");if(s)a.searchParams.set("resource",Au(s));return{authorizationUrl:a,codeVerifier:u}}function rz(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function Wg(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:i,dpop:s,fetchFn:a}){let l=Hv(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i)r.set("resource",Au(i));if(!n&&o)Uv(Lv(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let d=async()=>{let S=new Headers(u);if(n)await n(S,r,l,t);if(s)S.set("DPoP",await s.buildProof({htm:"POST",htu:l}));return Ni(a??fetch)(l,{method:"POST",headers:S,body:r})},m=await d();if(s&&m.status===400){if((await m.clone().json().catch(()=>{}))?.error===Ut.UseDpopNonce)s.observeNonce(m,l),m=await d()}if(s?.observeNonce(m,l),!m.ok)throw await $g(m);let f=await m.json();try{return Fo.parse(iu(f))}catch(S){if(typeof f==="object"&&f!==null&&"error"in f)throw await $g(JSON.stringify(f));throw S}}async function oz(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:i,dpop:s,fetchFn:a}){return{refresh_token:o,...await Wg(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:i,resource:n,dpop:s,fetchFn:a})}}async function nz(e,t,{metadata:r,resource:o,authorizationCode:n,iss:i,scope:s,fetchFn:a}={}){if(n!==void 0)qu({iss:i,expectedIssuer:r?.issuer,issParameterSupported:Nu(r)});let l=r?.issuer??String(t),u=async()=>{let S=await e.clientInformation({issuer:l}),b=Cu(S,l,{canPersistStamp:!1});if(S&&b===void 0)throw new Rc(String(S.issuer),l);return b},d=await u(),m=s??e.clientMetadata.scope,f;if(e.prepareTokenRequest)f=await e.prepareTokenRequest(m);if(!f){if(!n)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");f=rz(n,await e.codeVerifier(),e.redirectUrl)}return d??=await u(),Wg(t,{metadata:r,tokenRequestParams:f,clientInformation:d,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:a})}async function sz(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:n}){let i;if(t){if(!t.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let s={...r,...o===void 0?{}:{scope:o}},a=await Ni(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok)throw new Iv({status:a.status,body:await a.text(),submittedMetadata:s});return Vo.parse(iu(await a.json()))}var wc=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),iz=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(Eu(e))}set(e,t){let r=Eu(e),o=wc.has(e.method),n=!this._entries.has(r);if(!o&&n&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let s of this._entries.keys())if(!wc.has(s.slice(0,s.indexOf("\x00")))){this._entries.delete(s),this._cappedSize--;break}}let i=++this._stamp;if(this._entries.set(r,{...t,stamp:i}),n&&!o)this._cappedSize++;return i}delete(e){if(this._entries.delete(Eu(e))&&!wc.has(e.method))this._cappedSize--}evict(e){let t=`${e}\x00`,r=wc.has(e);for(let o of this._entries.keys())if(o.startsWith(t)){if(this._entries.delete(o),!r)this._cappedSize--}}clear(){this._entries.clear(),this._cappedSize=0}};function Eu(e){return`${e.method}\x00${JSON.stringify([e.partition??"",e.params??""])}`}function ku(e,t){return t===void 0?e:`${e}\x00${t}`}var az=86400000,cz=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,r=()=>{},o="",n=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=r,this._cachePartition=o,this._now=n}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){let r={method:e,params:t??""},o=this._partitionFor("private"),n=await this._store.get({...r,partition:o});if(n!==void 0)return n;let i=this._partitionFor("public");if(i===o)return;let s=await this._store.get({...r,partition:i});return s?.scope==="public"?s:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){let r=this._partitionFor("private"),o=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:r})}catch(n){this._reportError(n)}if(o!==r)try{await this._store.delete({method:e,params:t,partition:o})}catch(n){this._reportError(n)}}async evictKey(e,t){let r=ku(e,t),o=this._evictionGeneration.get(r);if(o!==void 0)this._evictionGeneration.set(r,o+1);await this._deleteBoth(e,t)}captureGeneration(e,t){let r=ku(e,t),o=this._evictionGeneration.get(r)??0;return this._evictionGeneration.set(r,o),o}async write(e,t,r,o){if((this._evictionGeneration.get(ku(e,o?.params))??0)!==r)return;let n=o?.params??"",i=this._partitionFor("private"),s=this._partitionFor("public"),a=(o?.scope??"private")==="public"?s:i;try{await this._store.set({method:e,params:n,partition:a},{value:lz(t),expiresAt:o?.expiresAt,scope:o?.scope})}catch(l){this._reportError(l)}if(s!==i)try{await this._store.delete({method:e,params:n,partition:a===i?s:i})}catch(l){this._reportError(l)}}async read(e,t){let r=await this._probe(e,t);if(r?.expiresAt===void 0||!(r.expiresAt>this.now()))return;try{let o=JSON.parse(r.value);if(typeof o!=="object"||o===null||Array.isArray(o))throw TypeError("cached document is not an object");return{value:o}}catch(o){this._reportError(o),await this._deleteBoth(e,t??"");return}}resetForReconnect(){if(!this._isUserSupplied)this._store.clear();this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){let t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let r=this._decodeListTools(t),o=new Map;if(r!==void 0)for(let n of r.tools)o.set(n.name,n);this._toolIndex={stamp:t.stamp,byName:o}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let r=await this._probe("tools/list");if(r===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==r.stamp){let o=this._decodeListTools(r)??{tools:[]},n=new Map;for(let i of o.tools){let s=t(i);if(s!==void 0)n.set(i.name,s)}this._toolOutputValidatorIndex={stamp:r.stamp,byName:n}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every((r)=>r!==null&&typeof r==="object"))throw TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};function lz(e){let t;try{t=JSON.stringify(e)}catch(r){throw TypeError(`cache value is not JSON-serializable: ${r instanceof Error?r.message:String(r)}`)}if(typeof t!=="string")throw TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}var Kg=Symbol.for("mcp.authSeamEscape");function Xe(e){if(typeof e==="object"&&e!==null||typeof e==="function")try{Object.defineProperty(e,Kg,{value:!0,configurable:!0})}catch{}return e}function uz(e){return(typeof e==="object"&&e!==null||typeof e==="function")&&e[Kg]===!0}var dz=-32022,pz=new Set([-32001,-32020,-32021]);function hz(e,t){switch(e.kind){case"result":return mz(e.result,t);case"rpc-error":return Gg(e,t);case"http-error":return fz(e,t);case"network-error":return Og(e.error,t);case"unusable-reply":return{kind:"error",error:new N(O.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${Yg(e.error)})`,{cause:e.error},{cause:e.error})};case"auth-required":return{kind:"error",error:e.error};case"closed":if(t.transportKind==="stdio")return{kind:"legacy"};return Og(Error("Connection closed during the version negotiation probe"),t);case"timeout":if(t.transportKind==="stdio")return{kind:"legacy"};return{kind:"error",error:new N(O.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function mz(e,t){let r=Lt(Sc).validateResult("server/discover",e);if(!r.ok)return{kind:"legacy"};let o=r.value.supportedVersions,n=t.clientModernVersions.find((i)=>o.includes(i));if(n!==void 0)return{kind:"modern",version:n,discover:r.value};if(t.fallbackAvailable)return{kind:"legacy"};return{kind:"error",error:new gc({supported:[...o],requested:t.requestedVersion})}}function Gg(e,t){let{code:r,message:o,data:n}=e;if(r===dz){let i=Sz(n);if(i===void 0)return{kind:"legacy"};let s=new gc({supported:i,requested:_z(n)??t.requestedVersion},o),a=Oi(i),l=t.clientModernVersions.find((u)=>a.includes(u));if(l!==void 0)return{kind:"corrective",version:l,error:s};if(a.length>0)return{kind:"error",error:s};return t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:s}}if(pz.has(r))return{kind:"legacy"};return{kind:"legacy"}}function fz(e,t){if(e.status===401||e.status===403){let o=e.status===403;return{kind:"error",error:new vt(o?O.ClientHttpForbidden:O.ClientHttpAuthentication,`Version negotiation failed: ${o?"the server denied access (HTTP 403)":"the server requires authorization (HTTP 401)"}`,{status:e.status,statusText:e.statusText,text:e.body})}}if(e.status>=500)return{kind:"error",error:new vt(O.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let r=bz(e.body);if(r!==void 0)return Gg(r,t);return{kind:"legacy"}}function Og(e,t){if(t.environment==="browser"&&gz(e))return{kind:"legacy"};return{kind:"error",error:new N(O.EraNegotiationFailed,`Version negotiation probe failed: ${Yg(e)}`,{cause:e},{cause:e})}}function gz(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function Yg(e){return e instanceof Error?e.message:String(e)}function Sz(e){if(typeof e!=="object"||e===null)return;let t=e.supported;if(!Array.isArray(t)||t.length===0||!t.every((r)=>typeof r==="string"))return;return t}function _z(e){if(typeof e!=="object"||e===null)return;let t=e.requested;return typeof t==="string"?t:void 0}function bz(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=="object"||t===null)return;let r=t.error;if(typeof r!=="object"||r===null)return;let{code:o,message:n,data:i}=r;if(typeof o!=="number")return;return{code:o,message:typeof n==="string"?n:"",data:i}}var yz="legacy";function vz(e,t){let r=e?.mode??yz;if(r==="legacy")return{kind:"legacy"};let o=e?.probe??{};if(typeof r==="object"){if(!Zt(r.pin))throw TypeError(`versionNegotiation: { pin: '${r.pin}' } is not a modern protocol revision — pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:r.pin,probe:o}}let n=t?Oi(t):[];return{kind:"auto",modernVersions:n.length>0?n:[...au],fallbackAvailable:t?cu(t).length>0:!0,probe:o}}function Ng(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function qg(e){return"stderr"in e&&"pid"in e?"stdio":"http"}var zz=class e{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(t){this._transport=t,this._savedOnMessage=t.onmessage,this._savedOnError=t.onerror,this._savedOnClose=t.onclose}static async open(t){let r=new e(t);t.onmessage=(o)=>{let n=r._pending;if(n!==void 0&&(Bo(o)||Wo(o))&&o.id===n.id){if(r._pending=void 0,Bo(o))n.resolve({kind:"response",result:o.result});else n.resolve({kind:"response",error:o.error});return}},t.onerror=(o)=>{r._savedOnError?.(o)},t.onclose=()=>{let o=r._pending;if(o!==void 0)r._pending=void 0,o.resolve({kind:"closed"});r._closeDelivered=!0,r._savedOnClose?.()};try{await t.start()}catch(o){throw r.detach(),o}return r}async exchange(t,r){let o=`server-discover-probe-${++this._probeCounter}`;return new Promise((n)=>{let i=!1,s=(l)=>{if(i)return;if(i=!0,clearTimeout(a),this._pending?.id===o)this._pending=void 0;n(l)},a=setTimeout(()=>s({kind:"timeout"}),r);this._pending={id:o,resolve:s},this._transport.send(t(o)).catch((l)=>s({kind:"send-error",error:l}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let t=this._savedOnClose,r=this._transport,o=!1,n=()=>{if(!o){o=!0;return}t()};r.onclose=n,Ou.set(r,()=>{if(r.onclose===n)r.onclose=t})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let t=this._transport,r=t.start,o=!0;t.start=async function(){if(o){o=!1,t.start=r;return}return r.call(t)}}},Ou=new WeakMap;function Ag(e){let t=Ou.get(e);Ou.delete(e),t?.()}function wz(e,t,r,o){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:Lt(t).outboundEnvelope({protocolVersion:t,clientInfo:r,clientCapabilities:o})}}}function Rz(e){if(e instanceof N&&e.code===O.ClientHttpUnexpectedContent)return!0;return e instanceof Error&&e.name==="SyntaxError"}function xz(e,t){switch(e.kind){case"response":return e.error===void 0?{kind:"result",result:e.result}:{kind:"rpc-error",...e.error};case"send-error":{let r=e.error;if(uz(r)||r instanceof wt||r instanceof Error&&r.name==="UnauthorizedError")return{kind:"auth-required",error:r};if(r instanceof vt){let o=r.data?.text;return{kind:"http-error",status:r.data.status,body:typeof o==="string"?o:void 0,statusText:r.data.statusText}}if(Rz(r))return{kind:"unusable-reply",error:r};return{kind:"network-error",error:r}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function Xg(e,t){let r=e.probe.timeoutMs??t.defaultTimeoutMs,o=Math.max(0,e.probe.maxRetries??0),n=e.kind==="pin"?[e.version]:e.modernVersions,i=e.kind==="auto"&&e.fallbackAvailable,s=await zz.open(t.transport),a=async()=>{let u=n[0],d=!1,m=o;for(;;){let f=await s.exchange((y)=>wz(y,u,t.clientInfo,t.capabilities),r);if(f.kind==="timeout"&&m>0){m--;continue}let S=xz(f,r),b=hz(S,{clientModernVersions:n,requestedVersion:u,fallbackAvailable:i,environment:t.environment,transportKind:t.transportKind});switch(b.kind){case"modern":return{era:"modern",version:b.version,discover:b.discover};case"corrective":if(d)throw b.error;d=!0,u=b.version;continue;case"legacy":{let y=S.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new N(O.EraNegotiationFailed,y===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${y} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new N(O.EraNegotiationFailed,y===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${y} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(y!==void 0&&t.disposableProbe!==!0)throw new N(O.EraNegotiationFailed,`Version negotiation failed: ${y} (this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw b.error}}},l;try{l=await a()}catch(u){throw s.detach(),u}return s.release(),l}function Pz(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;let r=e._serverParams;return typeof r==="object"&&r!==null&&typeof r.command==="string"?r:void 0}async function Tz(e,t,r,o){let i=new t.constructor({...r,stderr:"ignore"}),s=t.close,a=!1,l,u=new Promise((m,f)=>{l=()=>f(Mg())});t.close=async function(){return a=!0,l?.(),s.call(t)};let d;try{let m=Xg(e,{...o,transport:i,transportKind:"stdio",disposableProbe:!0});m.catch(()=>{}),d=await Promise.race([m,u])}finally{await Ez(i),t.close=s}if(a)throw Mg();return d}function Mg(){return new N(O.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function Ez(e){try{let t=e._dispose;await(typeof t==="function"?t.call(e):e.close())}catch{}}function jg(e){let t=e._meta?.[Ot];return pg.Implementation(t)?t:void 0}function xc(e,t){if(!e||t===null||typeof t!=="object")return;if(e.type==="object"&&e.properties&&typeof e.properties==="object"){let r=t,o=e.properties;for(let n of Object.keys(o)){let i=o[n];if(r[n]===void 0&&Object.prototype.hasOwnProperty.call(i,"default"))r[n]=i.default;if(r[n]!==void 0)xc(i,r[n])}}if(Array.isArray(e.anyOf)){for(let r of e.anyOf)if(typeof r!=="boolean")xc(r,t)}if(Array.isArray(e.oneOf)){for(let r of e.oneOf)if(typeof r!=="boolean")xc(r,t)}}function kz(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}function $z(e){if(typeof e==="object"&&e!==null){if(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e))return e;if(e.kind==="modern"&&rr.safeParse(e.discover).success)return e}throw new N(O.EraNegotiationFailed,"connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }")}var Lg={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},Cz=64,Qg=class extends yc{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new N(O.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t);if(this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new bu,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=cg(t?.inputRequired),this._cache=new cz(t?.responseCacheStore??new iz,t?.responseCacheStore!==void 0,(r)=>this._reportStoreError(r),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??Cz,t?.listChanged)this._listChangedConfig=t.listChanged}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&Zt(this._negotiatedProtocolVersion)&&Fr(e))return"drop"}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){if(!this._inputRequiredDriverConfig.autoFulfill)return Promise.reject(new N(O.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance — pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:t.request.method}));return mg({getRequestHandler:(r)=>this._getRequestHandler(r),buildContext:(r)=>this.buildContext(r,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t)}_setupListChangedHandlers(e){if(e.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools);if(e.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts);if(e.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources","notifications/resources/list_changed",e.resources,async()=>(await this.listResources(void 0,{cacheMode:"refresh"})).resources)}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=hg(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){if(e==="elicitation/create")return async(r,o)=>{let n=Lt(this._negotiatedProtocolVersion),i=n.validateRequest("elicitation/create",r);if(!i.ok&&i.reason==="not-in-era")i=n.validateInputRequest("elicitation/create",r);if(!i.ok)throw new ee(i.reason==="not-in-era"?W.InternalError:W.InvalidParams,i.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${i.message}`);let{params:s}=i.value;s.mode=s.mode??"form";let{supportsFormMode:a,supportsUrlMode:l}=kz(this._capabilities.elicitation);if(s.mode==="form"&&!a)throw new ee(W.InvalidParams,"Client does not support form-mode elicitation requests");if(s.mode==="url"&&!l)throw new ee(W.InvalidParams,"Client does not support URL-mode elicitation requests");let u=await t(r,o),d=n.validateResult("elicitation/create",u);if(!d.ok&&d.reason==="not-in-era")d=n.validateInputResponse("elicitation/create",u);if(!d.ok)throw new ee(d.reason==="not-in-era"?W.InternalError:W.InvalidParams,d.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${d.message}`);let m=d.value,f=s.mode==="form"?s.requestedSchema:void 0;if(s.mode==="form"&&m.action==="accept"&&m.content&&f&&this._capabilities.elicitation?.form?.applyDefaults)try{xc(f,m.content)}catch{}return m};if(e==="sampling/createMessage")return async(r,o)=>{let n=Lt(this._negotiatedProtocolVersion),i=n.validateRequest("sampling/createMessage",r);if(!i.ok&&i.reason==="not-in-era")i=n.validateInputRequest("sampling/createMessage",r);if(!i.ok)throw new ee(i.reason==="not-in-era"?W.InternalError:W.InvalidParams,i.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${i.message}`);let{params:s}=i.value,a=await t(r,o),l=Boolean(s.tools||s.toolChoice),u=n.samplingResultVariant(l,a);if(!u.ok&&u.reason==="not-in-era")u=n.validateInputResponse("sampling/createMessage",a);if(!u.ok)throw new ee(u.reason==="not-in-era"?W.InternalError:W.InvalidParams,u.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${u.message}`);return u.value};return t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new N(O.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,$z(t.prior),t);let r=vz(this._versionNegotiation,this._supportedProtocolVersionsOption);if(r.kind!=="legacy")return this._connectNegotiated(e,r,t);return this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let r=this._negotiatedProtocolVersion;if(r!==void 0)e.setProtocolVersion?.(r);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let r=cu(this._supportedProtocolVersions);try{let o=r[0];if(o===void 0)throw new N(O.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let n=await this.request({method:"initialize",params:{protocolVersion:o,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!r.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);if(this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion)e.setProtocolVersion(n.protocolVersion);if(this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=n.protocolVersion,this._listChangedConfig)this._setupListChangedHandlers(this._listChangedConfig)}catch(o){throw this.close(),o}}async _connectNegotiated(e,t,r){if(e.sessionId!==void 0){await super.connect(e);let n=this._negotiatedProtocolVersion;if(n!==void 0&&e.setProtocolVersion)e.setProtocolVersion(n);return}this._resetConnectionState();let o;try{let n=qg(e),i={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:Ng(),defaultTimeoutMs:r?.timeout??bc},s=n==="stdio"?Pz(e):void 0;o=s===void 0?await Xg(t,{...i,transport:e,transportKind:n}):await Tz(t,e,s,i)}catch(n){throw await e.close().catch(()=>{}),Ag(e),n}if(Ag(e),await super.connect(e),o.era==="legacy"){await this._legacyHandshake(e,r);return}if(this._serverCapabilities=o.discover.capabilities,this._serverVersion=jg(o.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.discover.instructions,this._discoverResult=o.discover,this._negotiatedProtocolVersion=o.version,e.setProtocolVersion)e.setProtocolVersion(o.version);if(this._listChangedConfig){let n=this._listChangedConfig,i=this._serverCapabilities,s={...n.tools&&i?.tools?.listChanged&&{tools:n.tools},...n.prompts&&i?.prompts?.listChanged&&{prompts:n.prompts},...n.resources&&i?.resources?.listChanged&&{resources:n.resources}},a=!0;try{this._setupListChangedHandlers(s)}catch(u){a=!1,this.onerror?.(u instanceof Error?u:Error(String(u)))}let l=a?{...s.tools&&{toolsListChanged:!0},...s.prompts&&{promptsListChanged:!0},...s.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(l).length>0){let u=new AbortController,d=()=>u.abort(r?.signal?.reason);if(r?.signal?.aborted)d();r?.signal?.addEventListener("abort",d);try{this._autoOpenedSubscription=await this.listen(l,{timeout:r?.timeout,signal:u.signal})}catch(m){if(r?.signal?.aborted)throw await this.close().catch(()=>{}),m;this.onerror?.(m instanceof Error?m:Error(String(m)))}finally{r?.signal?.removeEventListener("abort",d)}}}}async _connectFromPrior(e,t,r){if(t.kind==="legacy")return this._connectPlainLegacy(e,r);let o=t.discover;this._resetConnectionState();let n=this._supportedProtocolVersionsOption,i=(n&&Oi(n).length>0?Oi(n):au).find((s)=>o.supportedVersions.includes(s));if(i===void 0)throw new N(O.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(e),this._discoverResult=o,this._serverCapabilities=o.capabilities,this._serverVersion=jg(o),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.instructions,this._negotiatedProtocolVersion=i,e.setProtocolVersion?.(i),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(s){this.onerror?.(s instanceof Error?s:Error(String(s)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;if(t!==void 0)return`${t.name}@${t.version}`;return e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return Zt(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new N(O.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new N(O.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new N(O.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new N(O.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new N(O.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new N(O.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new N(O.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new N(O.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new N(O.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new N(O.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){let t=await this._requestWithSchema({method:"server/discover"},rr,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:"completion/complete",params:e},t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:"prompts/list",params:e},t);let r=await this._serveFromCache("prompts/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("prompts/list",e,t,(o)=>o.prompts)}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(e?.cursor!==void 0)return this.request({method:"resources/list",params:e},t);let r=await this._serveFromCache("resources/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("resources/list",e,t,(o)=>o.resources)}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:"resources/templates/list",params:e},t);let r=await this._serveFromCache("resources/templates/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("resources/templates/list",e,t,(o)=>o.resourceTemplates)}async _listAllPages(e,t,r,o,n){let i=r?.cacheMode==="bypass",s=this._cache.captureGeneration(e),a=await this.request({method:e,...t&&{params:{...t}}},r),l=a.nextCursor,u=a,d=1;while(l!==void 0){if(this._listMaxPages!==0&&d>=this._listMaxPages)throw new N(O.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});let m=await this.request({method:e,params:{...t,cursor:l}},r);if(m.nextCursor===l&&JSON.stringify(o(m))===JSON.stringify(o(u)))break;o(a).push(...o(m)),u=m,l=m.nextCursor,d++}if(delete a.nextCursor,n?.(a),i)return a;return await this._cache.write(e,a,s,this._freshness(a)),a}_freshness(e,t){let r=e,o=typeof r.ttlMs==="number"?r.ttlMs:this._defaultCacheTtlMs,n=r.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,o),az),scope:n,params:t}}async _serveFromCache(e,t,r){if(r?.cacheMode==="bypass"||r?.cacheMode==="refresh")return;let o=await this._cache.read(e,t).catch((n)=>void this._reportStoreError(n));if(o!==void 0){if(r?.signal?.aborted){let n=r.signal.reason;throw n instanceof N?n:new N(O.RequestTimeout,String(n))}return o.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}_compileOutputValidator(e){if(!e.outputSchema)return;try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){let r=t??await this._cache.toolDefinition(e);return r===void 0?void 0:fu(r.inputSchema)}async readResource(e,t){let r=await this._serveFromCache("resources/read",e.uri,t);if(r!==void 0)return r;let o=this._cache.captureGeneration("resources/read",e.uri),n=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){let i=this._freshness(n,e.uri);if(i.expiresAt>this._cache.now())await this._cache.write("resources/read",n,o,i);else if(t?.cacheMode==="refresh")await this._cache.evictKey("resources/read",e.uri)}return n}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},t)}async listen(e,t){if(this.transport===void 0)throw new N(O.NotConnected,"Not connected");let r=this._negotiatedProtocolVersion;if(r===void 0||!Zt(r))throw new N(O.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${r??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:r});if(t?.signal?.aborted){let x=t.signal.reason;throw x instanceof N?x:new N(O.RequestTimeout,String(x))}let o=new AbortController,n=`listen:${this._nextListenId++}`,i="opening",s,a,l,u,d=new Promise((x,Z)=>{l=x,u=Z}),m,f=new Promise((x)=>{m=x}),S=(x)=>{if(i==="closed")return;let Z=i==="opening";if(s!==void 0)clearTimeout(s),s=void 0;if("ack"in x){i="open",l(x.ack);return}if(i="closed",a!==void 0)t?.signal?.removeEventListener("abort",a);if(this._listenState.delete(n),o.abort(),m(x.cause),Z)u(x.error??new N(O.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},b=async()=>{o.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:n}}).catch(()=>{})},y=async()=>{if(i==="closed")return;S({cause:"local"}),await b()};this._listenState.set(n,{settle:S});let v=t?.timeout??bc;if(s=setTimeout(()=>{S({cause:"remote",error:new N(O.RequestTimeout,"subscriptions/listen ack timed out",{timeout:v})}),b().catch(()=>{})},v),t?.signal){let x=t.signal;a=()=>{if(i==="closed")return;let Z=x.reason;S({cause:"local",error:Z instanceof Error?Z:Error(String(Z??"Aborted"))}),b().catch(()=>{})},x.addEventListener("abort",a,{once:!0})}let U={jsonrpc:"2.0",id:n,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}},H=(x)=>{S({cause:"remote",error:x instanceof Error?x:Error(String(x))})};try{this.transport.send(U,{requestSignal:o.signal,onRequestStreamEnd:()=>S({cause:"remote",error:Error("subscriptions/listen: stream ended")})}).catch(H)}catch(x){H(x)}return{honoredFilter:await d,close:y,closed:f}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let r=Object.hasOwn(Lg,e.method)?Lg[e.method]:void 0;if(e.method==="notifications/resources/updated"){let o=e.params?.uri;if(typeof o==="string")this._cache.evictKey("resources/read",o)}else if(r!==void 0)for(let o of r)this._cache.evict(o);if(e.method==="notifications/subscriptions/acknowledged"){let o=e.params?._meta?.[Wn],n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){let i=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);n.settle({ack:i.ok?i.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){let o=e.params?.requestId,n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){n.settle({cause:"remote",error:Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,r=typeof t==="string"?this._listenState.get(t):void 0;if(r!==void 0){if(Wo(e))r.settle({cause:"remote",error:ee.fromError(e.error.code,e.error.message,e.error.data)});else r.settle({cause:"graceful",error:new N(O.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new N(O.ConnectionClosed,"Connection closed");for(let t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let r=this.getProtocolEra()==="modern"&&Ng()!=="browser",o=async()=>{if(!r)return t;let l;try{l=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(d){this._reportStoreError(d)}if(!l?.valid||l.declarations.length===0)return t;let u=sg(l.declarations,e.arguments);return Object.keys(u).length===0?t:{...t,headers:{...t?.headers,...u}}},n=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,(l)=>this._compileOutputValidator(l)).catch((l)=>void this._reportStoreError(l)):this._compileOutputValidator(t.toolDefinition),i=()=>{if(n===void 0||n.ok)return;let l=n.compileError,u=(l instanceof Error?l.message:String(l)).slice(0,200);throw new ee(W.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${u}`)};i();let s;try{s=await this.request({method:"tools/call",params:e},await o())}catch(l){let u=l instanceof ee&&l.code===Jo;if(!r||!u||t?.toolDefinition!==void 0)throw l;let d={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,d).catch((m)=>this._reportStoreError(m)),n=await this._cache.outputValidator(e.name,(m)=>this._compileOutputValidator(m)).catch((m)=>void this._reportStoreError(m)),i(),s=await this.request({method:"tools/call",params:e},await o())}let a=n!==void 0&&n.ok?n.validator:void 0;if(a){if(s.structuredContent===void 0&&!s.isError)throw new ee(W.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent!==void 0&&!s.isError)try{let l=a(s.structuredContent);if(!l.valid)throw new ee(W.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)}catch(l){if(l instanceof ee)throw l;throw new ee(W.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)}}return s}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){let o=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(o),o}let r=await this._serveFromCache("tools/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("tools/list",e,t,(o)=>o.tools,(o)=>this._excludeInvalidXMcpHeaderTools(o))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||qg(this.transport)==="stdio")return;let t=e.tools.filter((r)=>{let o=fu(r.inputSchema);if(!o.valid)return console.warn(`[mcp-sdk] excluding tool '${r.name}' from tools/list: invalid x-mcp-header declaration — ${o.reason}`),!1;return!0});if(t.length!==e.tools.length)e.tools=t}_setupListChangedHandler(e,t,r,o){let n=_c(Hs,r);if(!n.success)throw Error(`Invalid ${e} listChanged options: ${n.error.message}`);if(typeof r.onChanged!=="function")throw TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:s}=n.data,{onChanged:a}=r,l=async()=>{if(!i){a(null,null);return}try{a(null,await o())}catch(d){a(d instanceof Error?d:Error(String(d)),null)}},u=()=>{if(s){let d=this._listChangedDebounceTimers.get(e);if(d)clearTimeout(d);let m=setTimeout(l,s);this._listChangedDebounceTimers.set(e,m)}else l()};this.setNotificationHandler(t,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function Iz(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function Oz(e){if(e.status!==401)return!1;let t=e.headers.get("www-authenticate")??"";return Iz(t)&&/use_dpop_nonce/i.test(t)}var Nz=(e,t)=>(r)=>{let o=typeof e==="function"?e:()=>e;return async(n,i)=>{let s=(i?.method??"GET").toUpperCase(),a=new URL(n.toString()),l=await o();if(!l)return r(n,i);let u=async()=>{let m=await t();if(!m)return r(n,i);let f=new Headers(i?.headers),S=await l.buildProof({htm:s,htu:a,accessToken:m});return f.set("Authorization",`DPoP ${m}`),f.set("DPoP",S),r(n,{...i,headers:f})},d=await u();if(Oz(d)&&d.headers.has("dpop-nonce"))l.observeNonce(d,a),await d.text?.().catch(()=>{}),d=await u();return l.observeNonce(d,a),d}},qz=(e)=>Nz(async()=>{try{return await e.dpop?.()}catch(t){throw Xe(t)}},async()=>{let t;try{t=await e.tokens()}catch(r){throw Xe(r)}return t?.token_type?.toLowerCase()==="dpop"?t.access_token:void 0});var vP=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e,t,r){super(`SSE error: ${t}`);this.code=e,this.event=r,Zr(this,new.target)}};var Az=1,Mz={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2},jz=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function Ug(e,t){if(typeof AbortSignal.any==="function")return AbortSignal.any([e,t]);let r=new AbortController;if(e.aborted)return r.abort(e.reason),r.signal;if(t.aborted)return r.abort(t.reason),r.signal;let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",i)};function n(){o(),r.abort(e.reason)}function i(){o(),r.abort(t.reason)}return e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",i,{once:!0}),r.signal}var eS=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){if(this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,Ov(t?.authProvider)){if(this._oauthProvider=t.authProvider,this._authProvider=qv(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop)this._fetch=qz(t.authProvider)(t.fetch??fetch)}else this._authProvider=t?.authProvider;if(this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=gg(t?.fetch,t?.requestInit),this._redirectPolicy==="follow")this._fetchWithInit=bg(this._fetchWithInit);this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??Mz,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??Az)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(r){throw Xe(r)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new kg({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new kg({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new vt(O.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});if(e.resourceMetadataUrl)this._resourceMetadataUrl=e.resourceMetadataUrl;let r=await this._oauthProvider.tokens(),o=Ru(this._scope,r?.scope,e.scope);this._scope=o;let n=Av(o,r?.scope);return Iu(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:o,forceReauthorization:n,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return this._redirectPolicy==="follow"?e:Ni(e)}_unfollowedRedirect(e,t){let r=this._redirectPolicy==="follow"?void 0:yg(e,t);return r&&`${r} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let e=new Headers(this._requestInit?.headers||void 0),t;try{t=await this._authProvider?.token()}catch(r){throw Xe(r)}if(t)e.set("Authorization",`Bearer ${t}`);if(this._sessionId)e.set("mcp-session-id",this._sessionId);if(this._protocolVersion)e.set("mcp-protocol-version",this._protocolVersion);return e}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!Fr(t))return;let r=t.params?._meta?.[It];if(typeof r!=="string")return;e.set("mcp-protocol-version",r),e.set("mcp-method",t.method);let o=ig(t.method,t.params);if(o?.value!==void 0)e.set("mcp-name",gu(o.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Fr(e))return!1;let t=e.params?._meta?.[It];return typeof t==="string"&&Zt(t)}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:o,requestSignal:n}=e,i=()=>this._abortController?.signal.aborted===!0||n?.aborted===!0;try{let s=await this._commonHeaders(),a=[...s.get("accept")?.split(",").map((m)=>m.trim().toLowerCase())??[],"text/event-stream"];if(s.set("accept",[...new Set(a)].join(", ")),o)s.set("last-event-id",o);let l=this._abortController?.signal,u=n!==void 0&&l!==void 0?Ug(l,n):n??l,d=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:s,signal:u});if(!d.ok){if(d.status===401&&this._authProvider){if(d.headers.has("www-authenticate")){let{resourceMetadataUrl:f,scope:S}=Ai(d);this._resourceMetadataUrl=f,this._scope=Ru(this._scope,S)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:d,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(f){throw Xe(f)}return await d.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r)}if(await d.text?.().catch(()=>{}),t)throw Xe(new vt(O.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:d.statusText}));throw Xe(new wt)}if(d.status===403){let{resourceMetadataUrl:f,scope:S,error:b,errorDescription:y}=Ai(d);if(b==="insufficient_scope"){let v=await d.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:S,resourceMetadataUrl:f,errorDescription:y,statusText:d.statusText,text:v},r)!=="AUTHORIZED")throw Xe(new wt);return this._startOrAuthSse(e,t,r+1)}}if(await d.text?.().catch(()=>{}),d.status===405){e.onRequestStreamEnd?.();return}let m=this._unfollowedRedirect(this._url,d)??d.statusText;throw new vt(O.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${m}`,{status:d.status,statusText:d.statusText})}this._handleSseStream(d.body,e,!0)}catch(s){if(!i())this.onerror?.(s);throw s}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(Error(`Maximum reconnection attempts (${r}) exceeded.`)),e.onRequestStreamEnd?.();return}let o=this._getNextReconnectionDelay(t),n=()=>{if(this._cancelReconnection=void 0,this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this._startOrAuthSse(e).catch((i)=>{if(this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this.onerror?.(Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`));try{this._scheduleReconnection(e,t+1)}catch(s){this.onerror?.(s instanceof Error?s:Error(String(s)))}})};if(this._reconnectionScheduler){let i=this._reconnectionScheduler(n,o,t);this._cancelReconnection=typeof i==="function"?i:void 0}else{let i=setTimeout(n,o);this._cancelReconnection=()=>clearTimeout(i)}}_handleSseStream(e,t,r){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:o,replayMessageId:n,requestSignal:i,onRequestStreamEnd:s}=t,a=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0,l,u=!1,d=!1;(async()=>{try{let f=e.pipeThrough(new TextDecoderStream).pipeThrough(new wu({onRetry:(S)=>{this._serverRetryMs=S}})).getReader();while(!0){let{value:S,done:b}=await f.read();if(b)break;if(S.id)l=S.id,u=!0,o?.(S.id);if(!S.data)continue;if(!S.event||S.event==="message")try{let y=st.parse(JSON.parse(S.data));if(Bo(y)||Wo(y)){if(d=!0,n!==void 0)y.id=n}this.onmessage?.(y)}catch(y){this.onerror?.(y)}}if((r||u)&&!d&&this._abortController&&!a())this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:i,onRequestStreamEnd:s},0);else if(!a())s?.()}catch(f){if(a())return;if(this.onerror?.(Error(`SSE stream disconnected: ${f}`)),(r||u)&&!d&&this._abortController&&!a())try{this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:i,onRequestStreamEnd:s},0)}catch(S){this.onerror?.(Error(`Failed to reconnect: ${S instanceof Error?S.message:String(S)}`)),s?.()}else s?.()}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new wt("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:o}=await Mv(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await Iu(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:o,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new wt("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,r,o=0){try{let{resumptionToken:n,onresumptiontoken:i}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Fr(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch((v)=>this.onerror?.(v));return}let s=await this._commonHeaders();this._applyBodyDerivedHeaders(s,e);let a=Array.isArray(e)?e.some((v)=>mu(v)):mu(e);if(a)s.delete("mcp-session-id");if(t?.headers!==void 0)for(let[v,U]of Object.entries(t.headers)){if(jz.has(v.toLowerCase()))continue;s.set(v,U)}s.set("content-type","application/json");let l=[...s.get("accept")?.split(",").map((v)=>v.trim().toLowerCase())??[],"application/json","text/event-stream"];s.set("accept",[...new Set(l)].join(", "));let u=this._abortController?.signal,d=t?.requestSignal!==void 0&&u!==void 0?Ug(u,t.requestSignal):t?.requestSignal??u,m={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:d},f=await this._redirects(this._fetch??fetch)(this._url,m);if(a&&f.ok)this._sessionId=f.headers.get("mcp-session-id")||void 0;if(!f.ok){if(f.status===401&&this._authProvider){if(f.headers.has("www-authenticate")){let{resourceMetadataUrl:H,scope:x}=Ai(f);this._resourceMetadataUrl=H,this._scope=Ru(this._scope,x)}if(this._authProvider.onUnauthorized&&!r){try{await this._authProvider.onUnauthorized({response:f,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(H){throw Xe(H)}return await f.text?.().catch(()=>{}),this._send(e,t,!0,o)}if(await f.text?.().catch(()=>{}),r)throw Xe(new vt(O.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:f.statusText}));throw Xe(new wt)}let v=await f.text?.().catch(()=>null);if(f.status===403){let{resourceMetadataUrl:H,scope:x,error:Z,errorDescription:R}=Ai(f);if(Z==="insufficient_scope"){if(await this._stepUpAuthorize({scope:x,resourceMetadataUrl:H,errorDescription:R,statusText:f.statusText,text:v},o)!=="AUTHORIZED")throw Xe(new wt);return this._send(e,t,r,o+1)}}if(f.status===400&&typeof v==="string"&&this._isModernEnvelopedRequest(e))try{let H=st.parse(JSON.parse(v)),x=(Array.isArray(e)?e:[e]).filter((Z)=>Fr(Z));if(Wo(H)&&x.some((Z)=>Z.id===H.id)){this.onmessage?.(H);return}}catch{}let U=this._unfollowedRedirect(this._url,f)??v;throw new vt(O.ClientHttpNotImplemented,`Error POSTing to endpoint: ${U}`,{status:f.status,statusText:f.statusText,text:v})}if(f.status===202){if(await f.text?.().catch(()=>{}),rg(e))this._startOrAuthSse({resumptionToken:void 0}).catch((v)=>this.onerror?.(v));return}let S=(Array.isArray(e)?e:[e]).some((v)=>("method"in v)&&("id"in v)&&v.id!==void 0),b=f.headers.get("content-type"),y=fg(b);if(S)if(y==="text/event-stream")this._handleSseStream(f.body,{onresumptiontoken:i,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(y==="application/json"){let v=await f.json(),U=Array.isArray(v)?v.map((H)=>st.parse(H)):[st.parse(v)];for(let H of U)this.onmessage?.(H)}else throw await f.text?.().catch(()=>{}),new N(O.ClientHttpUnexpectedContent,`Unexpected content type: ${b}`,{contentType:b});else await f.text?.().catch(()=>{})}catch(n){if(t?.requestSignal?.aborted!==!0)this.onerror?.(n);throw n}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await this._redirects(this._fetch??fetch)(this._url,t);if(await r.text?.().catch(()=>{}),!r.ok&&r.status!==405)throw new vt(O.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,r)??r.statusText}`,{status:r.status,statusText:r.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};class iS{_eventSlots=new Map;setHandler(e,t){let r=this._ensureEventSlot(e);if(r.onHandler&&t)console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`);r.onHandler=t}getHandler(e){return this._eventSlots.get(e)?.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let r=this._eventSlots.get(e);if(!r)return;let o=r.listeners.indexOf(t);if(o!==-1)r.listeners.splice(o,1)}dispatch(e,t){let r=this._eventSlots.get(e);if(!r)return;r.onHandler?.(t);for(let o of[...r.listeners])o(t)}_ensureEventSlot(e){let t=this._eventSlots.get(e);if(!t)t={listeners:[]},this._eventSlots.set(e,t);return t}}class aS{_methods=new Set;claim(e,t){if(this._methods.has(e))throw Error(`Handler for "${e}" already registered (via ${t}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._methods.add(e)}replace(e){this._methods.add(e)}release(e){this._methods.delete(e)}has(e){return this._methods.has(e)}}var tS=new Set;function rS(e,t){let[r,o]=t,n=r?.shape;if(typeof n?.method?.value!=="string")return;let i=n.method.value,s=e==="request"?"setRequestHandler":"setNotificationHandler";if(!tS.has(s))tS.add(s),console.warn(`[ext-apps] ${s}(Schema, handler) is deprecated; use ${s}("${i}", { params: Schema.shape.params }, handler).`);let a=o;return[i,{params:n.params},e==="request"?(l,u)=>a({method:i,params:l},Lz(u)):(l)=>a({method:i,params:l})]}function Lz(e){return{signal:e.mcpReq.signal,requestId:e.mcpReq.id,sessionId:e.sessionId,_meta:e.mcpReq._meta,sendRequest:e.mcpReq.send,sendNotification:e.mcpReq.notify,authInfo:e.http?.authInfo}}var cS="2026-01-26";var Uz="ui/notifications/tool-input-partial";var Zz=T([h("light"),h("dark")]).describe("Color theme preference for the host environment."),ji=T([h("inline"),h("fullscreen"),h("pip")]).describe("Display mode for UI presentation."),Dz=T([h("--color-background-primary"),h("--color-background-secondary"),h("--color-background-tertiary"),h("--color-background-inverse"),h("--color-background-ghost"),h("--color-background-info"),h("--color-background-danger"),h("--color-background-success"),h("--color-background-warning"),h("--color-background-disabled"),h("--color-text-primary"),h("--color-text-secondary"),h("--color-text-tertiary"),h("--color-text-inverse"),h("--color-text-ghost"),h("--color-text-info"),h("--color-text-danger"),h("--color-text-success"),h("--color-text-warning"),h("--color-text-disabled"),h("--color-border-primary"),h("--color-border-secondary"),h("--color-border-tertiary"),h("--color-border-inverse"),h("--color-border-ghost"),h("--color-border-info"),h("--color-border-danger"),h("--color-border-success"),h("--color-border-warning"),h("--color-border-disabled"),h("--color-ring-primary"),h("--color-ring-secondary"),h("--color-ring-inverse"),h("--color-ring-info"),h("--color-ring-danger"),h("--color-ring-success"),h("--color-ring-warning"),h("--font-sans"),h("--font-mono"),h("--font-weight-normal"),h("--font-weight-medium"),h("--font-weight-semibold"),h("--font-weight-bold"),h("--font-text-xs-size"),h("--font-text-sm-size"),h("--font-text-md-size"),h("--font-text-lg-size"),h("--font-heading-xs-size"),h("--font-heading-sm-size"),h("--font-heading-md-size"),h("--font-heading-lg-size"),h("--font-heading-xl-size"),h("--font-heading-2xl-size"),h("--font-heading-3xl-size"),h("--font-text-xs-line-height"),h("--font-text-sm-line-height"),h("--font-text-md-line-height"),h("--font-text-lg-line-height"),h("--font-heading-xs-line-height"),h("--font-heading-sm-line-height"),h("--font-heading-md-line-height"),h("--font-heading-lg-line-height"),h("--font-heading-xl-line-height"),h("--font-heading-2xl-line-height"),h("--font-heading-3xl-line-height"),h("--border-radius-xs"),h("--border-radius-sm"),h("--border-radius-md"),h("--border-radius-lg"),h("--border-radius-xl"),h("--border-radius-full"),h("--border-width-regular"),h("--shadow-hairline"),h("--shadow-sm"),h("--shadow-md"),h("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),Fz=P(Dz.describe(`Style variables for theming MCP apps.
82
82
 
83
83
  Individual style keys are optional - hosts may provide any subset of these values.
84
84
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
85
85
 
86
86
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
87
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),T([c(),Jl()]).describe(`Style variables for theming MCP apps.
87
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),T([c(),Bl()]).describe(`Style variables for theming MCP apps.
88
88
 
89
89
  Individual style keys are optional - hosts may provide any subset of these values.
90
90
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
@@ -96,10 +96,10 @@ Individual style keys are optional - hosts may provide any subset of these value
96
96
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
97
97
 
98
98
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
99
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Hz=p({method:h("ui/open-link"),params:p({url:c().describe("URL to open in the host's browser")})}),Vz=p({isError:E().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),Jz=p({isError:E().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),Bz=p({isError:E().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),Wz=p({method:h("ui/notifications/sandbox-proxy-ready"),params:p({})}),Au=p({connectDomains:g(c()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
99
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Hz=p({method:h("ui/open-link"),params:p({url:c().describe("URL to open in the host's browser")})}),Vz=p({isError:E().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),Jz=p({isError:E().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),Bz=p({isError:E().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),Wz=p({method:h("ui/notifications/sandbox-proxy-ready"),params:p({})}),Mu=p({connectDomains:g(c()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
100
100
 
101
101
  - Maps to CSP \`connect-src\` directive
102
- - Empty or omitted → no network connections (secure default)`),resourceDomains:g(c()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:g(c()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:g(c()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),Mu=p({camera:p({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:p({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:p({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:p({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),Kz=p({method:h("ui/notifications/size-changed"),params:p({width:z().optional().describe("New width in pixels."),height:z().optional().describe("New height in pixels.")})}),ZP=p({method:h("ui/notifications/tool-input"),params:p({arguments:P(c(),A().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),DP=p({method:h("ui/notifications/tool-input-partial"),params:p({arguments:P(c(),A().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),FP=p({method:h("ui/notifications/tool-cancelled"),params:p({reason:c().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),Gz=p({fonts:c().optional()}),Yz=p({variables:Fz.optional().describe("CSS variables for theming the app."),css:Gz.optional().describe("CSS blocks that apps can inject.")}),HP=p({method:h("ui/resource-teardown"),params:p({})}),Xz=P(c(),A()),oS=p({text:p({}).optional().describe("Host supports text content blocks."),image:p({}).optional().describe("Host supports image content blocks."),audio:p({}).optional().describe("Host supports audio content blocks."),resource:p({}).optional().describe("Host supports resource content blocks."),resourceLink:p({}).optional().describe("Host supports resource link content blocks."),structuredContent:p({}).optional().describe("Host supports structured content.")}),Qz=p({method:h("ui/notifications/request-teardown"),params:p({}).optional()}),ew=p({experimental:P(c(),P(c(),Ma()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:p({}).optional().describe("Host supports opening external URLs."),downloadFile:p({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:p({listChanged:E().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:p({listChanged:E().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:p({}).optional().describe("Host accepts log messages."),sandbox:p({permissions:Mu.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:Au.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:oS.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:oS.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:p({tools:p({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),tw=p({experimental:P(c(),P(c(),Ma()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:p({listChanged:E().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:g(ji).optional().describe("Display modes the app supports.")}),rw=p({method:h("ui/notifications/initialized"),params:p({}).optional()}),VP=p({csp:Au.optional().describe("Content Security Policy configuration for UI resources."),permissions:Mu.optional().describe("Sandbox permissions requested by the UI resource."),domain:c().optional().describe(`Dedicated origin for view sandbox.
102
+ - Empty or omitted → no network connections (secure default)`),resourceDomains:g(c()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:g(c()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:g(c()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),ju=p({camera:p({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:p({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:p({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:p({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),Kz=p({method:h("ui/notifications/size-changed"),params:p({width:z().optional().describe("New width in pixels."),height:z().optional().describe("New height in pixels.")})}),ZP=p({method:h("ui/notifications/tool-input"),params:p({arguments:P(c(),A().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),DP=p({method:h("ui/notifications/tool-input-partial"),params:p({arguments:P(c(),A().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),FP=p({method:h("ui/notifications/tool-cancelled"),params:p({reason:c().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),Gz=p({fonts:c().optional()}),Yz=p({variables:Fz.optional().describe("CSS variables for theming the app."),css:Gz.optional().describe("CSS blocks that apps can inject.")}),HP=p({method:h("ui/resource-teardown"),params:p({})}),Xz=P(c(),A()),oS=p({text:p({}).optional().describe("Host supports text content blocks."),image:p({}).optional().describe("Host supports image content blocks."),audio:p({}).optional().describe("Host supports audio content blocks."),resource:p({}).optional().describe("Host supports resource content blocks."),resourceLink:p({}).optional().describe("Host supports resource link content blocks."),structuredContent:p({}).optional().describe("Host supports structured content.")}),Qz=p({method:h("ui/notifications/request-teardown"),params:p({}).optional()}),ew=p({experimental:P(c(),P(c(),Ma()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:p({}).optional().describe("Host supports opening external URLs."),downloadFile:p({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:p({listChanged:E().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:p({listChanged:E().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:p({}).optional().describe("Host accepts log messages."),sandbox:p({permissions:ju.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:Mu.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:oS.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:oS.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:p({tools:p({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),tw=p({experimental:P(c(),P(c(),Ma()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:p({listChanged:E().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:g(ji).optional().describe("Display modes the app supports.")}),rw=p({method:h("ui/notifications/initialized"),params:p({}).optional()}),VP=p({csp:Mu.optional().describe("Content Security Policy configuration for UI resources."),permissions:ju.optional().describe("Sandbox permissions requested by the UI resource."),domain:c().optional().describe(`Dedicated origin for view sandbox.
103
103
 
104
104
  Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
105
105
 
@@ -115,11 +115,11 @@ Boolean requesting whether a visible border and background is provided by the ho
115
115
  - \`false\`: request no visible border + background
116
116
  - omitted: host decides border`)}),nS=p({method:h("ui/request-display-mode"),params:p({mode:ji.describe("The display mode being requested.")})}),sS=p({mode:ji.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),ow=T([h("model"),h("app")]).describe("Tool visibility scope - who can access the tool."),JP=p({resourceUri:c().optional(),visibility:g(ow).optional().describe(`Who can access this tool. Default: ["model", "app"]
117
117
  - "model": Tool visible to and callable by the agent
118
- - "app": Tool callable by the app from this server only`),csp:Bl().optional(),permissions:Bl().optional()}),BP=p({mimeTypes:g(c()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),nw=p({method:h("ui/download-file"),params:p({contents:g(T([Nr,qr])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),sw=p({method:h("ui/message"),params:p({role:h("user").describe('Message role, currently only "user" is supported.'),content:g(yt).describe("Message content blocks (text, image, etc.).")})}),WP=p({method:h("ui/notifications/sandbox-resource-ready"),params:p({html:c().describe("HTML content to load into the inner iframe."),sandbox:c().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Au.optional().describe("CSP configuration from resource metadata."),permissions:Mu.optional().describe("Sandbox permissions from resource metadata.")})}),KP=p({method:h("ui/notifications/tool-result"),params:nr.describe("Standard MCP tool execution result.")}),lS=p({toolInfo:p({id:nt.optional().describe("JSON-RPC id of the tools/call request."),tool:or.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:Zz.optional().describe("Current color theme preference."),styles:Yz.optional().describe("Style configuration for theming the app."),displayMode:ji.optional().describe("How the UI is currently displayed."),availableDisplayModes:g(ji).optional().describe("Display modes the host supports."),containerDimensions:T([p({height:z().describe("Fixed container height in pixels.")}),p({maxHeight:T([z(),Jl()]).optional().describe("Maximum container height in pixels.")})]).and(T([p({width:z().describe("Fixed container width in pixels.")}),p({maxWidth:T([z(),Jl()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
119
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:c().optional().describe("User's language and region preference in BCP 47 format."),timeZone:c().optional().describe("User's timezone in IANA format."),userAgent:c().optional().describe("Host application identifier."),platform:T([h("web"),h("desktop"),h("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p({touch:E().optional().describe("Whether the device supports touch input."),hover:E().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p({top:z().describe("Top safe area inset in pixels."),right:z().describe("Right safe area inset in pixels."),bottom:z().describe("Bottom safe area inset in pixels."),left:z().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),GP=p({method:h("ui/notifications/host-context-changed"),params:lS.describe("Partial context update containing only changed fields.")}),iw=p({method:h("ui/update-model-context"),params:p({content:g(yt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:P(c(),A().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),aw=p({method:h("ui/initialize"),params:p({appInfo:_t.describe("App identification (name and version)."),appCapabilities:tw.describe("Features and capabilities this app provides."),protocolVersion:c().describe("Protocol version this app supports.")})}),cw=p({protocolVersion:c().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:_t.describe("Host application identification and version."),hostCapabilities:ew.describe("Features and capabilities provided by the host."),hostContext:lS.describe("Rich context about the host environment.")}).passthrough();class Li{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=(r)=>{if(t&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let o=st.safeParse(r.data);if(o.success)console.debug("Parsed message",o.data),this.onmessage?.(o.data);else if(r.data?.jsonrpc!=="2.0")console.debug("Ignoring non-JSON-RPC message",o.error.message,r);else console.error("Failed to parse message",o.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+o.error.message))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,t){if(e.method!==Uz)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var lw=[cS];class Ui extends yc{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new iS;_methods=new aS;setRequestHandler=(...e)=>{let[t,...r]=rS("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...r)};setNotificationHandler=(...e)=>{let[t,...r]=rS("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...r)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_wrapHandler(e,t){let r=super._wrapHandler(e,t);if(e==="ui/initialize"||e==="ping")return r;return async(o,n)=>{if(!this._initializedReceived)console.warn(`[ext-apps] AppBridge received '${e}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`);return r(o,n)}}eventSchemas={sizechange:Kz,sandboxready:Wz,initialized:rw,requestteardown:Qz,loggingmessage:Ar};setEventHandler(e,t){this._ensureEventSlot(e),this._events.setHandler(e,t)}getEventHandler(e){return this._events.getHandler(e)}addEventListener(e,t){this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);let r=(o)=>{if(e==="initialized")this._initializedReceived=!0;this._events.dispatch(e,o)};if(e==="loggingmessage")this.setNotificationHandler("notifications/message",(o)=>{r(o.params)});else this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(o)=>r(o));this._registeredEvents.add(e)}warnIfRequestHandlerReplaced(e,t,r){if(t&&r)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t,r,o){super(o);this._client=e,this._hostInfo=t,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=o?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:aw.shape.params,result:cw},(n)=>this._onAppsInitialize(n)),this.replaceRequestHandler("ping",(n,s)=>(this.onping?.(n.params,s),{})),this.replaceRequestHandler("ui/request-display-mode",{params:nS.shape.params,result:sS},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(e){return e}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(e){this.setEventHandler("sizechange",e)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(e){this.setEventHandler("sandboxready",e)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(e){this.setEventHandler("initialized",e)}_onmessage;get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,e),this._onmessage=e,this.replaceRequestHandler("ui/message",{params:sw.shape.params,result:Bz},async(t,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(t,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler("ui/open-link",{params:Hz.shape.params,result:Vz},async(t,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(t,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler("ui/download-file",{params:nw.shape.params,result:Jz},async(t,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(t,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(e){this.setEventHandler("requestteardown",e)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler("ui/request-display-mode",{params:nS.shape.params,result:sS},async(t,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(t,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(e){this.setEventHandler("loggingmessage",e)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler("ui/update-model-context",{params:iw.shape.params,result:tr},async(t,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(t,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",async(t,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(e){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,e),this._oncreatesamplingmessage=e,this.replaceRequestHandler("sampling/createMessage",async(t,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(t.params,r)})}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler("resources/list",async(t,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(t.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler("resources/templates/list",async(t,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(t.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler("resources/read",async(t,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(t.params,r)})}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler("prompts/list",async(t,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(t.params,r)})}sendPromptListChanged(e={}){return this.notification({method:"notifications/prompts/list_changed",params:e})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(e){let t=e.protocolVersion;if(this._appInfo!==void 0)console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values.");return this._appCapabilities=e.appCapabilities,this._appInfo=e.appInfo,{protocolVersion:lw.includes(t)?t:cS,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},r=!1;for(let o of Object.keys(e)){let n=this._hostContext[o],s=e[o];if(uw(n,s))continue;t[o]=s,r=!0}if(r)this._hostContext=e,this.sendHostContextChange(t)}sendHostContextChange(e){return this.notification({method:"ui/notifications/host-context-changed",params:e})}sendToolInput(e){return this.notification({method:"ui/notifications/tool-input",params:e})}sendToolInputPartial(e){return this.notification({method:"ui/notifications/tool-input-partial",params:e})}sendToolResult(e){return this.notification({method:"ui/notifications/tool-result",params:e})}sendToolCancelled(e){return this.notification({method:"ui/notifications/tool-cancelled",params:e})}sendSandboxResourceReady(e){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:e})}teardownResource(e,t){return this.request({method:"ui/resource-teardown",params:e},Xz,t)}sendResourceTeardown=this.teardownResource;callTool(e,t){return this.request({method:"tools/call",params:e},t)}listTools(e,t){return this.request({method:"tools/list",params:e},t)}async connect(e){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let t=this._client.getServerCapabilities();if(!t)throw Error("Client server capabilities not available");if(t.tools){if(this.oncalltool=async(r,o)=>this._client.request({method:"tools/call",params:r},{signal:o.mcpReq.signal}),t.tools.listChanged)this._client.setNotificationHandler("notifications/tools/list_changed",(r)=>this.sendToolListChanged(r.params))}if(t.resources){if(this.onlistresources=async(r,o)=>this._client.request({method:"resources/list",params:r},{signal:o.mcpReq.signal}),this.onlistresourcetemplates=async(r,o)=>this._client.request({method:"resources/templates/list",params:r},{signal:o.mcpReq.signal}),this.onreadresource=async(r,o)=>this._client.request({method:"resources/read",params:r},{signal:o.mcpReq.signal}),t.resources.listChanged)this._client.setNotificationHandler("notifications/resources/list_changed",(r)=>this.sendResourceListChanged(r.params))}if(t.prompts){if(this.onlistprompts=async(r,o)=>this._client.request({method:"prompts/list",params:r},{signal:o.mcpReq.signal}),t.prompts.listChanged)this._client.setNotificationHandler("notifications/prompts/list_changed",(r)=>this.sendPromptListChanged(r.params))}}return super.connect(e)}}function uw(e,t){return JSON.stringify(e)===JSON.stringify(t)}var uS=[200,800],dw=(e)=>e?.name==="TypeError"&&/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.)$/.test(e.message);function pw(e,t){return new Promise((r,o)=>{t?.throwIfAborted();let s=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(s),t.removeEventListener("abort",i),o(t.reason)};t?.addEventListener("abort",i,{once:!0})})}function dS(e,{signal:t,onDiagnostic:r,wait:o=pw}={}){return async(n)=>{for(let s=1;;s++){t?.throwIfAborted();try{let i=await e(n);if(t?.throwIfAborted(),s>1)r?.({state:"recovered",uri:n.uri,attempt:s});return i}catch(i){if(t?.throwIfAborted(),!dw(i))throw i;if(s>uS.length)throw r?.({state:"exhausted",uri:n.uri,attempt:s,message:i.message}),Object.assign(Error(`MCP resource transport failed for ${n.uri} after ${s} attempts: ${i.message}. Inspect the host connection and browser network diagnostics; this resource-loading error does not establish a component assertion failure.`,{cause:i}),{code:"ADS_RESOURCE_TRANSPORT"});let a=uS[s-1];r?.({state:"retry",uri:n.uri,attempt:s,nextAttempt:s+1,delayMs:a,message:i.message}),await o(a,t)}}}}function pS(e){let t=[],r=new Map;for(let o of e){if(!o.group){t.push(o);continue}if(!r.has(o.group))r.set(o.group,[]);r.get(o.group).push(o)}return[...t.length?[{label:null,entries:t}]:[],...[...r].sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>({label:o,entries:n}))]}async function mS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:s,callTool:i,context:a,onError:l,onState:u}){let d={slot:e,title:t,sandboxUrl:r,resourceUri:o,readResource:s,callTool:i,context:a,onError:l,onState:u},m=n,f,S,b,y=!1;function v(){if(y||b)return;u?.({state:"loading"}),b=Promise.resolve().then(async()=>{if(await S,await f?.close(),y)return;S=hS({...d,result:m,onReopen:v});try{f=await S}finally{S=void 0}}).catch((U)=>{if(!y)l(U)}).finally(()=>{b=void 0})}S=hS({...d,result:m,onReopen:v});try{f=await S}finally{S=void 0}return{async updateResult(U){if(m=U,await b,!y)await f.updateResult(m)},refreshContext(){if(!y&&!b)f.refreshContext()},async close(){y=!0,await b,await f?.close()}}}async function hS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:s,callTool:i,context:a,onError:l,onState:u,onReopen:d}){let m=!1,S=(await s({uri:o})).contents.find((x)=>x.mimeType==="text/html;profile=mcp-app"&&typeof x.text==="string");if(!S)throw Error("Comparison preview App is unavailable.");let b=document.createElement("iframe");b.title=t,b.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),b.src=r,e.append(b);let y=new Ui(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:a(b)});y.onreadresource=s,y.oncalltool=i,y.onerror=(x)=>{if(!m)l(x)},y.onloggingmessage=(x)=>{if(m||x.logger!=="ads-preview")return;if(x.data?.code==="ADS_PREVIEW_REOPEN"){d();return}if(u?.(x.data),x.data?.state==="error")l(Error(x.data.message))};let v,U=new Promise((x,Z)=>{v=setTimeout(()=>Z(Error("Comparison App initialization timed out.")),15000),y.oninitialized=()=>{clearTimeout(v),x()}});y.onsandboxready=()=>y.sendSandboxResourceReady({html:S.text,csp:S._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});let H=new ResizeObserver(()=>y.setHostContext(a(b)));try{await Promise.all([y.connect(new Li(b.contentWindow,b.contentWindow)),U]),H.observe(b),await y.sendToolInput({arguments:{}}),await y.sendToolResult(n)}catch(x){throw H.disconnect(),b.remove(),await y.close(),x}finally{clearTimeout(v)}return{updateResult:(x)=>y.sendToolResult(x),refreshContext:()=>y.setHostContext(a(b)),async close(){m=!0,H.disconnect();try{await y.teardownResource({},{timeout:500})}catch{}await y.close(),b.remove()}}}function ju(e,t){return t===e||t.startsWith(e+"/")||t.startsWith(e+".")}function fS(e,t,r,o=new Map){let n=new Map(r.map(({id:l,title:u,revision:d,state:m,preview:f})=>[l,{id:l,title:u,revision:d,state:m,...f?{preview:f}:{}}])),s=new Map(e.map((l)=>[l.id,{...l,drafts:(l.drafts??[]).flatMap((u)=>n.has(u.id)?[n.get(u.id)]:[])}]));for(let l of t){let u=s.get(l.id);s.set(l.id,{...u,...l,kind:"tokens",drafts:u?.drafts??[]})}let i=(l,u)=>l==="tokens"&&u.kind==="tokens"||(u.unit?u.unit===l:ju(l,u.id)),a=(l,u)=>{if(!l.drafts.some((d)=>d.id===u.id))l.drafts.push(n.get(u.id))};for(let l of r){let u=o.get(l.id);for(let d of u?.scenarios??[]){if(!l.units.some((f)=>i(f,d)))continue;let m=s.get(d.id);if(!m)m={...d,draftOnly:!0,drafts:[]},s.set(d.id,m);a(m,l)}}for(let l of r)for(let u of l.units){let d=u.split("/")[0];if(!["tokens","components","patterns","composition"].includes(d))continue;let m=[...s.values()].filter((f)=>i(u,f));if(m.length)for(let f of m)a(f,l);else s.set(u,{id:u,unit:u,title:u.split("/").at(-1),kind:d,draftOnly:!0,pendingDraftScenario:!0,drafts:[n.get(l.id)]})}return{scenarios:[...s.values()],categories:[...s.values()].filter((l)=>l.kind==="tokens")}}function gS(e,t,r){let o=e.drafts?.find((l)=>l.id===r)??e.drafts?.[0],n=o&&(t?.drafts?.find((l)=>l.id===o.id)??o.preview),s=o?n?.scenarios?.find((l)=>l.id===e.id)??n:t?.previews?.find((l)=>l.id===e.id)??e.build,i=s?.state==="error"?"error":s?.state==="checking"||s?.live?"checking":s?.building||["queued","building"].includes(s?.state)?"building":s?.current?"ready":s?.stale?"stale":"unreported",a={error:pa(s),checking:"Preview compiled; checking changes",building:"Preview build in progress",ready:"Preview build complete",stale:"Previous preview; current source not built",unreported:"Preview not built"};return{state:i,label:`${o?"Draft · ":""}${a[i]}${o&&i==="ready"?" · unaccepted":""}`}}var SS={unreported:'<circle cx="8" cy="8" r="3"/>',building:'<circle cx="8" cy="8" r="5" stroke-dasharray="22 10"/>',checking:'<circle cx="8" cy="8" r="5" stroke-dasharray="3 3"/><path d="m6 8 1.5 1.5L10 6"/>',ready:'<circle cx="8" cy="8" r="5"/><path d="m5.5 8 1.7 1.7 3.3-3.4"/>',stale:'<circle cx="8" cy="8" r="5" stroke-dasharray="2 3"/>',error:'<circle cx="8" cy="8" r="5"/><path d="M8 5.5v3M8 10.5h.01"/>'};var L=(e)=>document.getElementById(e),at=new URLSearchParams(location.search),_S=at.get("scenario")??at.get("category"),hw=["tokens","components","patterns","composition"],Yo=[],_e,kc=at.get("draft"),Ju=[],vS=[],Bu=new Map,en=at.get("split")==="1",Zu,tn=[],Dt=0,Ic;async function Oc(){let e=tn;tn=[],await Promise.allSettled(e.map((t)=>t.close()))}var Qe=document.createElement("button");Qe.id="split-view";Qe.setAttribute("aria-label","Split view");Qe.setAttribute("aria-pressed","false");Qe.disabled=!0;Qe.title="Select a draft with an accepted version to compare";Qe.innerHTML='<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1" y="2" width="14" height="12" rx="1"/><path d="M8 2v12"/></svg>';L("viewport").before(Qe);var he="tokens",Le={},bS=new Map,Pc=!0,Wu=[],Ku=[],Nc=[],Go,Ji,me,Ue,Ko,Fi,Xo,Du,Zi,Rt=0,Qo=at.get("capture")!=="1"&&at.get("viewport")==="phone",ar=at.get("capture")==="1"&&at.get("theme")==="dark"?"dark":"light";if(at.get("capture")==="1")document.documentElement.dataset.capture="true";document.documentElement.dataset.theme=ar;var Lu,zS=!0,Tc=!1,$c,Fu,qc=!1,Hi=!1,Jr,ir,Uu=0,Di,Wr=new AbortController,xt=new Qg({name:"ads-showcase",version:"1.0.0"},{versionNegotiation:{mode:"auto"},capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}),wS=(e,t={},r={})=>xt.callTool({name:e,arguments:t},{signal:Wr.signal,...r}),Cc=dS((e)=>xt.readResource(e,{signal:Wr.signal}),{signal:Wr.signal,onDiagnostic:(e)=>{if(e.state==="retry")document.documentElement.dataset.adsResourceRetries=String(Number(document.documentElement.dataset.adsResourceRetries??0)+1);console.warn("ADS resource transport",e)}}),RS=async(e)=>JSON.parse((await Cc({uri:e})).contents.find((t)=>typeof t.text==="string").text);function xS(e){let t=Nc.find((r)=>r.name===e.name);if(!t||!(t._meta?.ui?.visibility??["model","app"]).includes("app"))throw Error("This tool is not callable from an App.");return xt.callTool(e)}function Se(e,t=!1,r=t?"error":e?"checking":"ready"){let o=e||"Preview is up to date.";if(L("preview-error").hidden=!t,L("preview-error-message").textContent=t?o.split(`
118
+ - "app": Tool callable by the app from this server only`),csp:Wl().optional(),permissions:Wl().optional()}),BP=p({mimeTypes:g(c()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),nw=p({method:h("ui/download-file"),params:p({contents:g(T([Nr,qr])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),sw=p({method:h("ui/message"),params:p({role:h("user").describe('Message role, currently only "user" is supported.'),content:g(yt).describe("Message content blocks (text, image, etc.).")})}),WP=p({method:h("ui/notifications/sandbox-resource-ready"),params:p({html:c().describe("HTML content to load into the inner iframe."),sandbox:c().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Mu.optional().describe("CSP configuration from resource metadata."),permissions:ju.optional().describe("Sandbox permissions from resource metadata.")})}),KP=p({method:h("ui/notifications/tool-result"),params:nr.describe("Standard MCP tool execution result.")}),lS=p({toolInfo:p({id:nt.optional().describe("JSON-RPC id of the tools/call request."),tool:or.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:Zz.optional().describe("Current color theme preference."),styles:Yz.optional().describe("Style configuration for theming the app."),displayMode:ji.optional().describe("How the UI is currently displayed."),availableDisplayModes:g(ji).optional().describe("Display modes the host supports."),containerDimensions:T([p({height:z().describe("Fixed container height in pixels.")}),p({maxHeight:T([z(),Bl()]).optional().describe("Maximum container height in pixels.")})]).and(T([p({width:z().describe("Fixed container width in pixels.")}),p({maxWidth:T([z(),Bl()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
119
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:c().optional().describe("User's language and region preference in BCP 47 format."),timeZone:c().optional().describe("User's timezone in IANA format."),userAgent:c().optional().describe("Host application identifier."),platform:T([h("web"),h("desktop"),h("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p({touch:E().optional().describe("Whether the device supports touch input."),hover:E().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p({top:z().describe("Top safe area inset in pixels."),right:z().describe("Right safe area inset in pixels."),bottom:z().describe("Bottom safe area inset in pixels."),left:z().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),GP=p({method:h("ui/notifications/host-context-changed"),params:lS.describe("Partial context update containing only changed fields.")}),iw=p({method:h("ui/update-model-context"),params:p({content:g(yt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:P(c(),A().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),aw=p({method:h("ui/initialize"),params:p({appInfo:_t.describe("App identification (name and version)."),appCapabilities:tw.describe("Features and capabilities this app provides."),protocolVersion:c().describe("Protocol version this app supports.")})}),cw=p({protocolVersion:c().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:_t.describe("Host application identification and version."),hostCapabilities:ew.describe("Features and capabilities provided by the host."),hostContext:lS.describe("Rich context about the host environment.")}).passthrough();class Li{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=(r)=>{if(t&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let o=st.safeParse(r.data);if(o.success)console.debug("Parsed message",o.data),this.onmessage?.(o.data);else if(r.data?.jsonrpc!=="2.0")console.debug("Ignoring non-JSON-RPC message",o.error.message,r);else console.error("Failed to parse message",o.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+o.error.message))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,t){if(e.method!==Uz)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var lw=[cS];class Ui extends yc{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new iS;_methods=new aS;setRequestHandler=(...e)=>{let[t,...r]=rS("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...r)};setNotificationHandler=(...e)=>{let[t,...r]=rS("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...r)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_wrapHandler(e,t){let r=super._wrapHandler(e,t);if(e==="ui/initialize"||e==="ping")return r;return async(o,n)=>{if(!this._initializedReceived)console.warn(`[ext-apps] AppBridge received '${e}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`);return r(o,n)}}eventSchemas={sizechange:Kz,sandboxready:Wz,initialized:rw,requestteardown:Qz,loggingmessage:Ar};setEventHandler(e,t){this._ensureEventSlot(e),this._events.setHandler(e,t)}getEventHandler(e){return this._events.getHandler(e)}addEventListener(e,t){this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);let r=(o)=>{if(e==="initialized")this._initializedReceived=!0;this._events.dispatch(e,o)};if(e==="loggingmessage")this.setNotificationHandler("notifications/message",(o)=>{r(o.params)});else this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(o)=>r(o));this._registeredEvents.add(e)}warnIfRequestHandlerReplaced(e,t,r){if(t&&r)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t,r,o){super(o);this._client=e,this._hostInfo=t,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=o?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:aw.shape.params,result:cw},(n)=>this._onAppsInitialize(n)),this.replaceRequestHandler("ping",(n,i)=>(this.onping?.(n.params,i),{})),this.replaceRequestHandler("ui/request-display-mode",{params:nS.shape.params,result:sS},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(e){return e}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(e){this.setEventHandler("sizechange",e)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(e){this.setEventHandler("sandboxready",e)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(e){this.setEventHandler("initialized",e)}_onmessage;get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,e),this._onmessage=e,this.replaceRequestHandler("ui/message",{params:sw.shape.params,result:Bz},async(t,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(t,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler("ui/open-link",{params:Hz.shape.params,result:Vz},async(t,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(t,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler("ui/download-file",{params:nw.shape.params,result:Jz},async(t,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(t,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(e){this.setEventHandler("requestteardown",e)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler("ui/request-display-mode",{params:nS.shape.params,result:sS},async(t,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(t,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(e){this.setEventHandler("loggingmessage",e)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler("ui/update-model-context",{params:iw.shape.params,result:tr},async(t,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(t,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",async(t,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(e){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,e),this._oncreatesamplingmessage=e,this.replaceRequestHandler("sampling/createMessage",async(t,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(t.params,r)})}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler("resources/list",async(t,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(t.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler("resources/templates/list",async(t,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(t.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler("resources/read",async(t,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(t.params,r)})}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler("prompts/list",async(t,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(t.params,r)})}sendPromptListChanged(e={}){return this.notification({method:"notifications/prompts/list_changed",params:e})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(e){let t=e.protocolVersion;if(this._appInfo!==void 0)console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values.");return this._appCapabilities=e.appCapabilities,this._appInfo=e.appInfo,{protocolVersion:lw.includes(t)?t:cS,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},r=!1;for(let o of Object.keys(e)){let n=this._hostContext[o],i=e[o];if(uw(n,i))continue;t[o]=i,r=!0}if(r)this._hostContext=e,this.sendHostContextChange(t)}sendHostContextChange(e){return this.notification({method:"ui/notifications/host-context-changed",params:e})}sendToolInput(e){return this.notification({method:"ui/notifications/tool-input",params:e})}sendToolInputPartial(e){return this.notification({method:"ui/notifications/tool-input-partial",params:e})}sendToolResult(e){return this.notification({method:"ui/notifications/tool-result",params:e})}sendToolCancelled(e){return this.notification({method:"ui/notifications/tool-cancelled",params:e})}sendSandboxResourceReady(e){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:e})}teardownResource(e,t){return this.request({method:"ui/resource-teardown",params:e},Xz,t)}sendResourceTeardown=this.teardownResource;callTool(e,t){return this.request({method:"tools/call",params:e},t)}listTools(e,t){return this.request({method:"tools/list",params:e},t)}async connect(e){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let t=this._client.getServerCapabilities();if(!t)throw Error("Client server capabilities not available");if(t.tools){if(this.oncalltool=async(r,o)=>this._client.request({method:"tools/call",params:r},{signal:o.mcpReq.signal}),t.tools.listChanged)this._client.setNotificationHandler("notifications/tools/list_changed",(r)=>this.sendToolListChanged(r.params))}if(t.resources){if(this.onlistresources=async(r,o)=>this._client.request({method:"resources/list",params:r},{signal:o.mcpReq.signal}),this.onlistresourcetemplates=async(r,o)=>this._client.request({method:"resources/templates/list",params:r},{signal:o.mcpReq.signal}),this.onreadresource=async(r,o)=>this._client.request({method:"resources/read",params:r},{signal:o.mcpReq.signal}),t.resources.listChanged)this._client.setNotificationHandler("notifications/resources/list_changed",(r)=>this.sendResourceListChanged(r.params))}if(t.prompts){if(this.onlistprompts=async(r,o)=>this._client.request({method:"prompts/list",params:r},{signal:o.mcpReq.signal}),t.prompts.listChanged)this._client.setNotificationHandler("notifications/prompts/list_changed",(r)=>this.sendPromptListChanged(r.params))}}return super.connect(e)}}function uw(e,t){return JSON.stringify(e)===JSON.stringify(t)}var uS=[200,800],dw=(e)=>e?.name==="TypeError"&&/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.)$/.test(e.message);function pw(e,t){return new Promise((r,o)=>{t?.throwIfAborted();let i=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),s=()=>{clearTimeout(i),t.removeEventListener("abort",s),o(t.reason)};t?.addEventListener("abort",s,{once:!0})})}function dS(e,{signal:t,onDiagnostic:r,wait:o=pw}={}){return async(n)=>{for(let i=1;;i++){t?.throwIfAborted();try{let s=await e(n);if(t?.throwIfAborted(),i>1)r?.({state:"recovered",uri:n.uri,attempt:i});return s}catch(s){if(t?.throwIfAborted(),!dw(s))throw s;if(i>uS.length)throw r?.({state:"exhausted",uri:n.uri,attempt:i,message:s.message}),Object.assign(Error(`MCP resource transport failed for ${n.uri} after ${i} attempts: ${s.message}. Inspect the host connection and browser network diagnostics; this resource-loading error does not establish a component assertion failure.`,{cause:s}),{code:"ADS_RESOURCE_TRANSPORT"});let a=uS[i-1];r?.({state:"retry",uri:n.uri,attempt:i,nextAttempt:i+1,delayMs:a,message:s.message}),await o(a,t)}}}}function pS(e){let t=[],r=new Map;for(let o of e){if(!o.group){t.push(o);continue}if(!r.has(o.group))r.set(o.group,[]);r.get(o.group).push(o)}return[...t.length?[{label:null,entries:t}]:[],...[...r].sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>({label:o,entries:n}))]}async function mS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:i,callTool:s,context:a,onError:l,onState:u}){let d={slot:e,title:t,sandboxUrl:r,resourceUri:o,readResource:i,callTool:s,context:a,onError:l,onState:u},m=n,f,S,b,y=!1;function v(){if(y||b)return;u?.({state:"loading"}),b=Promise.resolve().then(async()=>{if(await S,await f?.close(),y)return;S=hS({...d,result:m,onReopen:v});try{f=await S}finally{S=void 0}}).catch((U)=>{if(!y)l(U)}).finally(()=>{b=void 0})}S=hS({...d,result:m,onReopen:v});try{f=await S}finally{S=void 0}return{async updateResult(U){if(m=U,await b,!y)await f.updateResult(m)},refreshContext(){if(!y&&!b)f.refreshContext()},async close(){y=!0,await b,await f?.close()}}}async function hS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:i,callTool:s,context:a,onError:l,onState:u,onReopen:d}){let m=!1,S=(await i({uri:o})).contents.find((x)=>x.mimeType==="text/html;profile=mcp-app"&&typeof x.text==="string");if(!S)throw Error("Comparison preview App is unavailable.");let b=document.createElement("iframe");b.title=t,b.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),b.src=r,e.append(b);let y=new Ui(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:a(b)});y.onreadresource=i,y.oncalltool=s,y.onerror=(x)=>{if(!m)l(x)},y.onloggingmessage=(x)=>{if(m||x.logger!=="ads-preview")return;if(x.data?.code==="ADS_PREVIEW_REOPEN"){d();return}if(u?.(x.data),x.data?.state==="error")l(Error(x.data.message))};let v,U=new Promise((x,Z)=>{v=setTimeout(()=>Z(Error("Comparison App initialization timed out.")),15000),y.oninitialized=()=>{clearTimeout(v),x()}});y.onsandboxready=()=>y.sendSandboxResourceReady({html:S.text,csp:S._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});let H=new ResizeObserver(()=>y.setHostContext(a(b)));try{await Promise.all([y.connect(new Li(b.contentWindow,b.contentWindow)),U]),H.observe(b),await y.sendToolInput({arguments:{}}),await y.sendToolResult(n)}catch(x){throw H.disconnect(),b.remove(),await y.close(),x}finally{clearTimeout(v)}return{updateResult:(x)=>y.sendToolResult(x),refreshContext:()=>y.setHostContext(a(b)),async close(){m=!0,H.disconnect();try{await y.teardownResource({},{timeout:500})}catch{}await y.close(),b.remove()}}}function Lu(e,t){return t===e||t.startsWith(e+"/")||t.startsWith(e+".")}function fS(e,t,r,o=new Map){let n=new Map(r.map(({id:l,title:u,revision:d,state:m,preview:f})=>[l,{id:l,title:u,revision:d,state:m,...f?{preview:f}:{}}])),i=new Map(e.map((l)=>[l.id,{...l,drafts:(l.drafts??[]).flatMap((u)=>n.has(u.id)?[n.get(u.id)]:[])}]));for(let l of t){let u=i.get(l.id);i.set(l.id,{...u,...l,kind:"tokens",drafts:u?.drafts??[]})}let s=(l,u)=>l==="tokens"&&u.kind==="tokens"||(u.unit?u.unit===l:Lu(l,u.id)),a=(l,u)=>{if(!l.drafts.some((d)=>d.id===u.id))l.drafts.push(n.get(u.id))};for(let l of r){let u=o.get(l.id);for(let d of u?.scenarios??[]){if(!l.units.some((f)=>s(f,d)))continue;let m=i.get(d.id);if(!m)m={...d,draftOnly:!0,drafts:[]},i.set(d.id,m);a(m,l)}}for(let l of r)for(let u of l.units){let d=u.split("/")[0];if(!["brand","tokens","components","patterns","composition"].includes(d))continue;let m=[...i.values()].filter((f)=>s(u,f));if(m.length)for(let f of m)a(f,l);else i.set(u,{id:u,unit:u,title:u.split("/").at(-1),kind:d,draftOnly:!0,pendingDraftScenario:!0,drafts:[n.get(l.id)]})}return{scenarios:[...i.values()],categories:[...i.values()].filter((l)=>l.kind==="tokens")}}function gS(e,t,r){let o=e.drafts?.find((l)=>l.id===r)??e.drafts?.[0],n=o&&(t?.drafts?.find((l)=>l.id===o.id)??o.preview),i=o?n?.scenarios?.find((l)=>l.id===e.id)??n:t?.previews?.find((l)=>l.id===e.id)??e.build,s=i?.state==="error"?"error":i?.state==="checking"||i?.live?"checking":i?.building||["queued","building"].includes(i?.state)?"building":i?.current?"ready":i?.stale?"stale":"unreported",a={error:pa(i),checking:"Preview compiled; checking changes",building:"Preview build in progress",ready:"Preview build complete",stale:"Previous preview; current source not built",unreported:"Preview not built"};return{state:s,label:`${o?"Draft · ":""}${a[s]}${o&&s==="ready"?" · unaccepted":""}`}}var SS={unreported:'<circle cx="8" cy="8" r="3"/>',building:'<circle cx="8" cy="8" r="5" stroke-dasharray="22 10"/>',checking:'<circle cx="8" cy="8" r="5" stroke-dasharray="3 3"/><path d="m6 8 1.5 1.5L10 6"/>',ready:'<circle cx="8" cy="8" r="5"/><path d="m5.5 8 1.7 1.7 3.3-3.4"/>',stale:'<circle cx="8" cy="8" r="5" stroke-dasharray="2 3"/>',error:'<circle cx="8" cy="8" r="5"/><path d="M8 5.5v3M8 10.5h.01"/>'};var L=(e)=>document.getElementById(e),at=new URLSearchParams(location.search),_S=at.get("scenario")??at.get("category"),hw=["brand","tokens","components","patterns","composition"],Yo=[],_e,kc=at.get("draft"),Bu=[],vS=[],Wu=new Map,en=at.get("split")==="1",Du,tn=[],Dt=0,Ic;async function Oc(){let e=tn;tn=[],await Promise.allSettled(e.map((t)=>t.close()))}var Qe=document.createElement("button");Qe.id="split-view";Qe.setAttribute("aria-label","Split view");Qe.setAttribute("aria-pressed","false");Qe.disabled=!0;Qe.title="Select a draft with an accepted version to compare";Qe.innerHTML='<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1" y="2" width="14" height="12" rx="1"/><path d="M8 2v12"/></svg>';L("viewport").before(Qe);var se="brand",Le={},bS=new Map,Pc=!0,Ku=[],Nc=[],qc=[],Go,Ji,me,Ue,Ko,Fi,Xo,Fu,Zi,Rt=0,Qo=at.get("capture")!=="1"&&at.get("viewport")==="phone",ar=at.get("capture")==="1"&&at.get("theme")==="dark"?"dark":"light";if(at.get("capture")==="1")document.documentElement.dataset.capture="true";document.documentElement.dataset.theme=ar;var Uu,zS=!0,Tc=!1,$c,Hu,Ac=!1,Hi=!1,Jr,ir,Zu=0,Di,Wr=new AbortController,xt=new Qg({name:"ads-showcase",version:"1.0.0"},{versionNegotiation:{mode:"auto"},capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}),wS=(e,t={},r={})=>xt.callTool({name:e,arguments:t},{signal:Wr.signal,...r}),Cc=dS((e)=>xt.readResource(e,{signal:Wr.signal}),{signal:Wr.signal,onDiagnostic:(e)=>{if(e.state==="retry")document.documentElement.dataset.adsResourceRetries=String(Number(document.documentElement.dataset.adsResourceRetries??0)+1);console.warn("ADS resource transport",e)}}),RS=async(e)=>JSON.parse((await Cc({uri:e})).contents.find((t)=>typeof t.text==="string").text);function xS(e){let t=qc.find((r)=>r.name===e.name);if(!t||!(t._meta?.ui?.visibility??["model","app"]).includes("app"))throw Error("This tool is not callable from an App.");return xt.callTool(e)}function Se(e,t=!1,r=t?"error":e?"checking":"ready"){let o=e||"Preview is up to date.";if(L("preview-error").hidden=!t,L("preview-error-message").textContent=t?o.split(`
120
120
  `)[0]:"",L("preview-error-message").title=t?o:"",L("status").textContent=o,L("status").dataset.error=String(t),!t)for(let n of["errorCategory","errorCode","resourceUri"])delete L("status").dataset[n];if(t)L("status").removeAttribute("role");else L("status").setAttribute("role","status");L("preview-status").dataset.phase=r,L("preview-status").title=o,L("preview-status").setAttribute("aria-label",`Preview status: ${o.split(`
121
121
  `)[0]}`),PS()}function PS(){let e=Ji?.warmup,t=e?`Background views: ${e.completed}/${e.total} compiled${e.failed?`; ${e.failed} failed`:""}.`:"";L("warmup-status").hidden=!e,L("warmup-status").textContent=t,L("preview-status").dataset.warmup=e?.state??"disabled",L("preview-status").title=[L("status").textContent,t].filter(Boolean).join(`
122
- `)}function TS(){Se(me?"Updating preview…":"Opening preview…",!1,"reloading")}function rn(){return Bi().find((e)=>e.id===Le[he])}function on(e=rn()){let t=Yo.find((r)=>r.id===kc&&Bu.get(r.id)?.scenario===e?.id);return e?.drafts?.find((r)=>r.id===kc)??t??e?.drafts?.[0]}function Gu(){return Boolean(on()&&(rn()?.draftOnly||en))}function Vi(){return`${he}:${Le[he]}${Gu()?`:draft:${on().id}`:""}`}function Ec(e=me){return e?.key===Vi()}function ES(e=Ji){if(Gu()){let t=e?.drafts?.find((r)=>r.id===on()?.id);return t?.scenarios?.find((r)=>r.id===Le[he])??t}return e?.previews?.find((t)=>t.id===Le[he])}var kS=(e)=>JSON.stringify(e&&[e.session,e.revision,e.current,e.live]);function $S(){({scenarios:Ku,categories:Wu}=fS(Ju,vS,Yo,Bu))}function mw(e){Bu.set(e.structuredContent.id,e.structuredContent),$S()}async function Hu(e,t,r=Wr.signal){let o=(Go?.previewWatch?.buildTimeoutMs??30000)+15000;try{return await wS(e,t,{signal:AbortSignal.any([Wr.signal,r]),timeout:o})}catch(n){if(n.code!=="REQUEST_TIMEOUT")throw n;throw Object.assign(Error(`The preview request timed out after ${Math.ceil(o/1000)} seconds. No preview result was received. Retry the preview.`,{cause:n}),{code:"ADS_PREVIEW_REQUEST_TIMEOUT",category:"transport"})}}async function Yu(e,t,r){let o=rn()?.id===t&&rn().pendingDraftScenario||e.units?.includes(t)&&!Ju.some((s)=>s.id===t),n=await Hu("ads_show_draft",{id:e.id,...!o&&t?{scenario:t}:{}},r);if(n.isError)throw Error(n.content?.find((s)=>s.type==="text")?.text??"Draft preview failed.");if(o){let s=n.structuredContent.scenarios.find((i)=>t==="tokens"?i.kind==="tokens":i.unit?i.unit===t:ju(t,i.id));if(!s)throw Error("Draft owner has no scenario yet. Add an independently mountable scenario before previewing it.");if(s.id!==n.structuredContent.scenario)n=await Hu("ads_show_draft",{id:e.id,scenario:s.id},r);if(n.isError)throw Error(n.content?.find((i)=>i.type==="text")?.text??"Draft preview failed.")}return mw(n),n}function cr(e=!1){if(e)Zi=me?.key;Xo=void 0,L("loader").hidden=!0,L("preview").setAttribute("aria-busy","false")}function yS(e){let t=new URL(location.href);for(let n of["scenario","category","draft","split"])t.searchParams.delete(n);if(e)t.searchParams.set("scenario",e);let r=Bi().find((n)=>n.id===e),o=on(r);if(o&&(r.draftOnly||en)){if(t.searchParams.set("draft",o.id),!r.draftOnly)t.searchParams.set("split","1")}return t.pathname+t.search+t.hash}function Bi(){return he==="tokens"?Wu:Ku.filter((e)=>e.kind===he)}function CS(e,t){let{state:r,label:o}=gS(t,Ji,kc),n=e.querySelector(".entry-preview");if(!n)n=document.createElement("span"),n.className="entry-preview",n.setAttribute("aria-hidden","true"),e.append(n);n.dataset.state=r,n.title=o,n.innerHTML=`<svg viewBox="0 0 16 16">${SS[r]}</svg>`,e.dataset.buildState=r,e.setAttribute("aria-description",o)}function Xu(){return{theme:ar,displayMode:"inline",containerDimensions:{width:L("frame-slot").clientWidth,height:L("frame-slot").clientHeight}}}function Wi(){let e=Bi();if(!e.some((o)=>o.id===Le[he]))Le[he]=e[0]?.id??null;history.replaceState(null,"",yS(Le[he]));let t=L("sidebar").scrollTop;L("entries").setAttribute("aria-label",he[0].toUpperCase()+he.slice(1));let r=(o)=>{let n=document.createElement("a");if(n.textContent=o.title,o.drafts?.length){let s=document.createElement("span");s.className="draft-badge",s.textContent=o.drafts.length>1?`Drafts ${o.drafts.length}`:"Draft",s.title=o.draftOnly?"Draft only; no accepted version yet":"Draft available; use Split view to compare",n.append(" ",s)}if(n.href=yS(o.id),n.dataset.scenario=o.id,CS(n,o),o.id===Le[he])n.setAttribute("aria-current","page");return n.addEventListener("click",(s)=>{if(s.button||s.metaKey||s.ctrlKey||s.shiftKey||s.altKey)return;s.preventDefault(),Le[he]=o.id,Wi(),Ft().catch(Pt)}),n};L("entries").replaceChildren(...pS(e).flatMap((o)=>{if(!o.label)return o.entries.map(r);let n=`${he}:${o.label}`,s=document.createElement("details");s.className="entry-group",s.open=bS.get(n)??!0;let i=document.createElement("summary");i.textContent=o.label;let a=document.createElement("div");return a.setAttribute("role","group"),a.setAttribute("aria-label",o.label),a.append(...o.entries.map(r)),s.append(i,a),s.addEventListener("toggle",()=>{if(s.isConnected)bS.set(n,s.open)}),[s]})),L("sidebar").scrollTop=t;for(let o of L("sections").querySelectorAll("button"))if(o.dataset.section===he)o.setAttribute("aria-current","page");else o.removeAttribute("aria-current");Vu()}function Pt(e){if(!qc&&!Hi)cr(),L("status").dataset.errorCategory=e.category??(e.code==="ADS_RESOURCE_TRANSPORT"?"transport":"runner"),L("status").dataset.errorCode=e.code??"ADS_HOST_STARTUP",Se(`${e.message}${me?`
123
- The retained preview is not verified against the current source.`:""}`,!0)}async function Br(e){if(!e)return;try{await e.teardownResource({},{timeout:500})}catch{}await e.close()}function IS(){if(qc||Hi)return;Hi=!0,Wr.abort(),++Rt,clearTimeout($c),cr(),Se("MCP disconnected. The retained preview is stale. Refresh the page after restarting ADS.",!0);let e=Ue;Ue=void 0,Br(e),++Dt,Oc()}async function Qu(){let e=await RS("ads://project/explorer");Go=e.status,Ji=Go.build,Nc=e.tools,vS=e.categories,Ju=e.scenarios,Yo=e.drafts,L("title").textContent=(Go.drafts?.previewOnly?"Draft · ":"")+Go.project.showcase.title,L("title").title=Go.projectRoot,$S();let t=Pc?_S:Le[he],r=Pc&&Yo.find((s)=>s.id===kc),o=me?.draft&&Yo.find((s)=>s.id===me.draftId);if(r||o&&_e&&(o.revision!==_e.revision||_e.discovery?.state==="pending")){let s=await Yu(r||o,r?_S:_e.scenario);if(r)t=s.structuredContent.scenario;if(me?.draft&&o){_e=s.structuredContent,Ic=s;for(let i of tn)if(i.side==="draft")await i.updateResult(s)}}let n=Ku.find((s)=>s.id===t);if(n&&hw.includes(n.kind))he=n.kind,Le[he]=n.id;else if(Pc&&Wu.some((s)=>s.id===t))Le.tokens=t;Pc=!1,Wi()}function Ft({force:e=!1}={}){if(Hi)return Promise.resolve();let t=Le[he],r=Vi();if(Ko?.key===r)return Ko.promise;if(!e&&Fi?.key===r)return Promise.resolve();if(!e&&!Ko&&me?.key===r)return Promise.resolve();Fi=void 0;let o={key:r};return Ko=o,o.promise=fw(t,r,he==="tokens").finally(()=>{if(Ko===o)Ko=void 0}),o.promise}async function fw(e,t,r){Du?.abort();let o=Du=new AbortController,n=++Rt;Xo=!0,L("loader").hidden=t===Zi,L("preview").setAttribute("aria-busy","true");try{if(++Dt,await Oc(),n!==Rt)return;if(Gu()){await Br(Ue),Ue=void 0,Jr=void 0,ir=void 0;let u=on(),d=await Yu(u,e,o.signal);if(n!==Rt)return;if(_e=d.structuredContent,Ic=d,rn()?.pendingDraftScenario||!Bi().some((m)=>m.id===e))Le[he]=_e.scenario;me={key:Vi(),id:_e.scenario,draftId:u.id,generation:n,draft:!0},Vu(),await _w(),Wi(),cr(!0),Se("Draft preview only. Acceptance checks have not run.",!1,"ready");return}if(_e=void 0,Vu(),!e&&!r){if(await Br(Ue),n!==Rt)return;Ue=void 0,me=void 0,Zi=void 0,Jr=void 0,ir=void 0,L("frame-slot").replaceChildren(),cr(),Se("No scenarios discovered. Colocate an independently mountable scenario and fixture with the public implementation.");return}let s=Nc.find((u)=>u.name===(r?"ads_show_tokens":"ads_show_scenario"));if(!s?._meta?.ui?.resourceUri)throw Error("The server did not expose a preview App tool.");let i=r?e?{category:e}:{}:{id:e};if(s.inputSchema?.properties?.waitFor)i.waitFor=at.get("capture")==="1"||at.get("waitFor")==="verified"?"verified":"compiled";TS();let a=await Hu(s.name,i,o.signal);if(n!==Rt)return;if(a.isError)throw Object.assign(Error(a.content?.find((u)=>u.type==="text")?.text??"Preview build failed."),a.structuredContent?.failure);me={key:t,id:e,generation:n,token:r&&!a.structuredContent?.scenario,build:a.structuredContent?.build,manifestRevision:a.structuredContent?.manifestRevision};let l=await gw(s._meta.ui.resourceUri);if(n!==Rt)return;if(Jr==="ui://ads/preview"&&!me.manifestRevision)throw Error("The resource preview has no manifest revision.");if(Zi!==t)Zi=void 0;if(await l.sendToolInput({arguments:i}),await l.sendToolResult(a),n===Rt&&!a.structuredContent?.manifestUri)cr(!0),Se("")}catch(s){if(n===Rt)Fi={key:Vi(),build:kS(ES())},Pt(s)}}async function gw(e){if(Jr===e&&ir)return ir;let t=++Uu,r=Ue;Ue=void 0,Jr=e,ir=(async()=>{await Br(r);let o=await Cc({uri:e});if(t!==Uu||qc||Hi)throw Error("Preview opening was superseded.");let n=o.contents.find((u)=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text==="string");if(!n)throw Error("The preview resource contains no MCP App.");let s=document.createElement("iframe");s.title="Design-system preview",s.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),s.src=Di,L("frame-slot").replaceChildren(s);let i=new Ui(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:Xu()});Ue=i,i.onreadresource=(u)=>Cc(u),i.oncalltool=xS,i.onloggingmessage=(u)=>{if(i!==Ue||u.logger!=="ads-preview"||me?.generation!==Rt||!Ec()||u.data?.id!==me?.id)return;let d=u.data.revision===me.manifestRevision||u.data.selectionRevision===me.manifestRevision;if(u.data.state==="ready"&&d)me.manifestRevision=u.data.revision,cr(!0),Se("");else if(u.data.state==="checking"&&(!Xo||d))cr(!0),Se("Checking changes…");else if(u.data.state==="loading")Se("Updating preview…",!1,"reloading");else if(u.data.state==="reverting")Se("Restoring the last verified preview…",!1,"reverting");else if(u.data.code==="ADS_PREVIEW_REOPEN")Ue=void 0,Jr=void 0,ir=void 0,TS(),Br(i).then(()=>Ft({force:!0})).catch(Pt);else if(u.data.state==="error"){if(cr(),L("status").dataset.errorCategory=u.data.category??"build",L("status").dataset.errorCode=u.data.code??"ADS_PREVIEW_BUILD",u.data.resourceUri)L("status").dataset.resourceUri=u.data.resourceUri;else delete L("status").dataset.resourceUri;Se([u.data.message,u.data.code,u.data.resourceUri].filter(Boolean).join(`
124
- `),!0)}},i.onerror=Pt;let a,l=new Promise((u,d)=>{a=setTimeout(()=>d(Error("MCP App initialization timed out.")),15000),i.oninitialized=()=>{clearTimeout(a),u()}});i.onsandboxready=()=>i.sendSandboxResourceReady({html:n.text,csp:n._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});try{await Promise.all([i.connect(new Li(s.contentWindow,s.contentWindow)),l])}catch(u){throw await Br(i),u}finally{clearTimeout(a)}return i})();try{return await ir}catch(o){if(t===Uu)Jr=void 0,ir=void 0;throw o}}async function Sw(){let e=me,t=await RS("ads://project/build");Ji=t,PS();for(let o of L("entries").querySelectorAll("a[data-scenario]")){let n=Bi().find((s)=>s.id===o.dataset.scenario);if(n)CS(o,n)}if(Fi?.key===Vi()){let o=ES(t);if(o&&(o.current||o.live)&&kS(o)!==Fi.build)await Ft({force:!0});return}if(!e||e.token||Xo||!Ec(e))return;if(e.draft){let o=t.drafts?.find((i)=>i.id===e.draftId),n=o?.scenarios?.find((i)=>i.id===_e?.scenario)??o,s=n&&JSON.stringify([o?.session,n.revision,n.live?.revision,n.current]);if(n&&(n.current||n.live)&&e.buildSignature!==s){e.buildSignature=s;let i=Yo.find((a)=>a.id===e.draftId);if(i){let a=await Yu(i,_e.scenario);if(me!==e||Xo||!Ec(e))return;_e=a.structuredContent,Ic=a;for(let l of tn)if(l.side==="draft")await l.updateResult(a)}}if(n?.state==="error")Se("Draft preview build failed. Showing the previous preview.",!0);else if(n?.building)Se(n.live||n.state==="checking"?"Draft preview compiled; checking changes…":"Building draft preview… Showing the previous preview.",!1,n.live||n.state==="checking"?"checking":"compiling");else if(n?.current&&Zu?.state==="ready")Se("Draft preview ready · unaccepted.");return}if(me!==e||Xo||!Ec(e))return;let r=t.previews.find((o)=>o.id===e.id);if(!r){Se("The selected scenario is no longer registered.",!0);return}if(["idle","building"].includes(r.state)&&e.build?.current&&r.session===e.build.session&&r.revision<=e.build.revision)return;if(r.state==="error"){Se(`${pa(r)}. Showing an earlier view.
125
- ${od(r.diagnostics)}`,!0);return}if(["idle","building"].includes(r.state)){Se(r.live?"Checking changes…":"Compiling changes… The current view is the previous preview.",!1,r.live?"checking":"compiling");return}if(r.current&&(r.revision!==e.build?.revision||r.session!==e.build?.session))await Ft({force:!0})}function Ki(e=!1,t=!1){if(Tc||=e,t&&me?.token)me.key="invalidated";if(clearTimeout($c),zS)return;$c=setTimeout(()=>{if(Lu){Ki(e,t);return}Lu=(async()=>{if(Tc)Tc=!1,await Qu();await Ft(),await Sw()})().catch(Pt).finally(()=>{Lu=void 0})},150)}async function _w(){if(!_e)return;let e=_e,t=Ic;Zu=void 0;let r=++Dt;if(await Oc(),r!==Dt)return;let o=en&&e.acceptedExists;Qe.setAttribute("aria-pressed",String(o));let n=document.createElement("div");n.className="draft-comparison",n.dataset.split=String(o);for(let s of o?["accepted","draft"]:["draft"]){let i=document.createElement("section");i.className="draft-version";let a=document.createElement("h2");a.dataset.version=s,a.textContent=s==="accepted"?"Accepted":"Draft · unaccepted";let l=document.createElement("div");l.className="draft-stage",l.dataset.version=s,i.append(a,l),n.append(i)}L("frame-slot").replaceChildren(n),await Promise.all([...n.querySelectorAll(".draft-stage")].map(async(s)=>{let i=s.dataset.version,a=i==="draft"?t:await wS("ads_show_scenario",{id:e.scenario,waitFor:"compiled"});if(a.isError)throw Error(a.content?.find((d)=>d.type==="text")?.text??"Comparison build failed.");if(r!==Dt)return;let l=Nc.find((d)=>d.name===(i==="draft"?"ads_show_draft":"ads_show_scenario")),u=await mS({slot:s,title:i==="draft"?"Draft version":"Accepted version",sandboxUrl:Di,resourceUri:l._meta.ui.resourceUri,result:a,readResource:Cc,callTool:xS,context:(d)=>({theme:ar,displayMode:"inline",containerDimensions:{width:d.clientWidth,height:d.clientHeight}}),onError:(d)=>{if(r===Dt)Pt(d)},onState:(d)=>{if(r!==Dt||i!=="draft")return;if(Zu=d,d.state==="ready")Se("Draft preview ready · unaccepted.");else if(d.state==="checking")Se("Draft preview compiled; checking changes…",!1,"checking");else if(["loading","reverting"].includes(d.state))Se("Updating draft preview…",!1,"reloading")}});if(r!==Dt)await u.close();else tn.push({...u,side:i})}))}function Vu(){let e=rn(),t=Boolean(on(e))&&!e?.draftOnly;Qe.disabled=!t,Qe.title=e?.draftOnly?"No accepted version yet":t?"Compare accepted and draft versions":"No draft for this entry",Qe.setAttribute("aria-pressed",String(t&&en));let r=document.querySelector('.draft-version h2[data-version="draft"]');if(r&&_e){let o={draft:"unaccepted",checking:"checking acceptance",failed:"acceptance failed",conflict:"source conflict",interrupted:"acceptance interrupted","dependency-error":"dependency needs attention"};r.textContent=`Draft · ${o[_e.state]??_e.state}`,r.title=_e.dependencies?.length?`Draft dependencies: ${_e.dependencies.join(", ")}`:""}}Qe.addEventListener("click",()=>{en=!en,Wi(),Ft().catch(Pt)});for(let e of L("sections").querySelectorAll("button"))e.addEventListener("click",()=>{he=e.dataset.section,Wi(),Ft().catch(Pt)});var ed=window.matchMedia("(max-width: 760px)");function OS(e){document.body.classList.toggle("collapsed",e),L("pane-toggle").setAttribute("aria-expanded",String(!e)),L("pane-toggle").setAttribute("aria-label",e?"Show navigation pane":"Hide navigation pane"),L("pane-toggle").title=e?"Show navigation pane":"Hide navigation pane",L("pane-toggle").querySelector("path").setAttribute("d",e?"M6 4l4 4-4 4":"M10 4l-4 4 4 4")}var td=()=>OS(L("header").hidden||ed.matches);td();ed.addEventListener("change",td);L("pane-toggle").addEventListener("click",()=>OS(!document.body.classList.contains("collapsed")));function NS(){document.documentElement.dataset.viewport=Qo?"phone":"auto",L("viewport").setAttribute("aria-pressed",String(Qo)),L("viewport").title=Qo?"Use available preview width":"Preview at phone width (390 px)"}NS();L("viewport").addEventListener("click",()=>{Qo=!Qo,NS();let e=new URL(location.href);if(Qo)e.searchParams.set("viewport","phone");else e.searchParams.delete("viewport");history.replaceState(null,"",e.pathname+e.search+e.hash)});L("theme").addEventListener("click",()=>{ar=ar==="light"?"dark":"light",document.documentElement.dataset.theme=ar,L("theme").setAttribute("aria-label",ar==="dark"?"Use light theme":"Use dark theme"),L("theme").title=L("theme").getAttribute("aria-label"),L("theme").querySelector("svg").innerHTML=ar==="dark"?'<circle cx="8" cy="8" r="3"/><path d="M8 1v1M8 14v1M1 8h1M14 8h1M3 3l1 1M12 12l1 1M3 13l1-1M12 4l1-1"/>':'<path d="M13.5 9a5.5 5.5 0 0 1-6.5-6.5A5.5 5.5 0 1 0 13.5 9Z"/>',Ue?.setHostContext(Xu())});L("theme").addEventListener("click",()=>{for(let e of tn)e.refreshContext()});L("minimize").addEventListener("click",()=>{L("header").hidden=!0,document.body.classList.add("collapsed")});var qS=new ResizeObserver(()=>Ue?.setHostContext(Xu()));qS.observe(L("frame-slot"));L("retry-preview").addEventListener("click",()=>{(async()=>{await Qu(),await Ft({force:!0})})().catch(Pt)});window.addEventListener("pagehide",()=>{qc=!0,Du?.abort(),Wr.abort(),clearTimeout($c),qS.disconnect(),ed.removeEventListener("change",td),Br(Ue),++Dt,Oc(),Fu?.close(),xt.close()},{once:!0});xt.onclose=IS;xt.setNotificationHandler("notifications/resources/list_changed",()=>Ki(!0));xt.setNotificationHandler("notifications/tools/list_changed",()=>Ki(!0));xt.setNotificationHandler("notifications/resources/updated",({params:e})=>Ki(e.uri==="ads://project/explorer",e.uri==="ads://project/tokens"));try{if(Di=(await fetch("/host.json").then((e)=>e.json())).sandboxUrl,!Di||new URL(Di).origin===location.origin)throw Error("The separate-origin MCP App sandbox is unavailable.");if(await xt.connect(new eS(new URL("/mcp",location.href))),Fu=await xt.listen({resourcesListChanged:!0,toolsListChanged:!0,resourceSubscriptions:["ads://project/build","ads://project/tokens","ads://project/explorer"]}),Fu.closed.then((e)=>{if(e!=="local")IS()}),await Qu(),zS=!1,await Ft(),Tc)Ki()}catch(e){Pt(e)}
122
+ `)}function TS(){Se(me?"Updating preview…":"Opening preview…",!1,"reloading")}function rn(){return Bi().find((e)=>e.id===Le[se])}function on(e=rn()){let t=Yo.find((r)=>r.id===kc&&Wu.get(r.id)?.scenario===e?.id);return e?.drafts?.find((r)=>r.id===kc)??t??e?.drafts?.[0]}function Gu(){return Boolean(on()&&(rn()?.draftOnly||en))}function Vi(){return`${se}:${Le[se]}${Gu()?`:draft:${on().id}`:""}`}function Ec(e=me){return e?.key===Vi()}function ES(e=Ji){if(Gu()){let t=e?.drafts?.find((r)=>r.id===on()?.id);return t?.scenarios?.find((r)=>r.id===Le[se])??t}return e?.previews?.find((t)=>t.id===Le[se])}var kS=(e)=>JSON.stringify(e&&[e.session,e.revision,e.current,e.live]);function $S(){({scenarios:Nc,categories:Ku}=fS(Bu,vS,Yo,Wu))}function mw(e){Wu.set(e.structuredContent.id,e.structuredContent),$S()}async function Vu(e,t,r=Wr.signal){let o=(Go?.previewWatch?.buildTimeoutMs??30000)+15000;try{return await wS(e,t,{signal:AbortSignal.any([Wr.signal,r]),timeout:o})}catch(n){if(n.code!=="REQUEST_TIMEOUT")throw n;throw Object.assign(Error(`The preview request timed out after ${Math.ceil(o/1000)} seconds. No preview result was received. Retry the preview.`,{cause:n}),{code:"ADS_PREVIEW_REQUEST_TIMEOUT",category:"transport"})}}async function Yu(e,t,r){let o=rn()?.id===t&&rn().pendingDraftScenario||e.units?.includes(t)&&!Bu.some((i)=>i.id===t),n=await Vu("ads_show_draft",{id:e.id,...!o&&t?{scenario:t}:{}},r);if(n.isError)throw Error(n.content?.find((i)=>i.type==="text")?.text??"Draft preview failed.");if(o){let i=n.structuredContent.scenarios.find((s)=>t==="tokens"?s.kind==="tokens":s.unit?s.unit===t:Lu(t,s.id));if(!i)throw Error("Draft owner has no scenario yet. Add an independently mountable scenario before previewing it.");if(i.id!==n.structuredContent.scenario)n=await Vu("ads_show_draft",{id:e.id,scenario:i.id},r);if(n.isError)throw Error(n.content?.find((s)=>s.type==="text")?.text??"Draft preview failed.")}return mw(n),n}function cr(e=!1){if(e)Zi=me?.key;Xo=void 0,L("loader").hidden=!0,L("preview").setAttribute("aria-busy","false")}function yS(e){let t=new URL(location.href);for(let n of["scenario","category","draft","split"])t.searchParams.delete(n);if(e)t.searchParams.set("scenario",e);let r=Bi().find((n)=>n.id===e),o=on(r);if(o&&(r.draftOnly||en)){if(t.searchParams.set("draft",o.id),!r.draftOnly)t.searchParams.set("split","1")}return t.pathname+t.search+t.hash}function Bi(){return se==="tokens"?Ku:Nc.filter((e)=>e.kind===se)}function CS(e,t){let{state:r,label:o}=gS(t,Ji,kc),n=e.querySelector(".entry-preview");if(!n)n=document.createElement("span"),n.className="entry-preview",n.setAttribute("aria-hidden","true"),e.append(n);n.dataset.state=r,n.title=o,n.innerHTML=`<svg viewBox="0 0 16 16">${SS[r]}</svg>`,e.dataset.buildState=r,e.setAttribute("aria-description",o)}function Xu(){return{theme:ar,displayMode:"inline",containerDimensions:{width:L("frame-slot").clientWidth,height:L("frame-slot").clientHeight}}}function Wi(){let e=Nc.some((n)=>n.kind==="brand");if(L("sections").querySelector('[data-section="brand"]').hidden=!e,se==="brand"&&!e)se="tokens";let t=Bi();if(!t.some((n)=>n.id===Le[se]))Le[se]=t[0]?.id??null;history.replaceState(null,"",yS(Le[se]));let r=L("sidebar").scrollTop;L("entries").setAttribute("aria-label",se[0].toUpperCase()+se.slice(1));let o=(n)=>{let i=document.createElement("a");if(i.textContent=n.title,n.drafts?.length){let s=document.createElement("span");s.className="draft-badge",s.textContent=n.drafts.length>1?`Drafts ${n.drafts.length}`:"Draft",s.title=n.draftOnly?"Draft only; no accepted version yet":"Draft available; use Split view to compare",i.append(" ",s)}if(i.href=yS(n.id),i.dataset.scenario=n.id,CS(i,n),n.id===Le[se])i.setAttribute("aria-current","page");return i.addEventListener("click",(s)=>{if(s.button||s.metaKey||s.ctrlKey||s.shiftKey||s.altKey)return;s.preventDefault(),Le[se]=n.id,Wi(),Ft().catch(Pt)}),i};L("entries").replaceChildren(...pS(t).flatMap((n)=>{if(!n.label)return n.entries.map(o);let i=`${se}:${n.label}`,s=document.createElement("details");s.className="entry-group",s.open=bS.get(i)??!0;let a=document.createElement("summary");a.textContent=n.label;let l=document.createElement("div");return l.setAttribute("role","group"),l.setAttribute("aria-label",n.label),l.append(...n.entries.map(o)),s.append(a,l),s.addEventListener("toggle",()=>{if(s.isConnected)bS.set(i,s.open)}),[s]})),L("sidebar").scrollTop=r;for(let n of L("sections").querySelectorAll("button"))if(n.dataset.section===se)n.setAttribute("aria-current","page");else n.removeAttribute("aria-current");Ju()}function Pt(e){if(!Ac&&!Hi)cr(),L("status").dataset.errorCategory=e.category??(e.code==="ADS_RESOURCE_TRANSPORT"?"transport":"runner"),L("status").dataset.errorCode=e.code??"ADS_HOST_STARTUP",Se(`${e.message}${me?`
123
+ The retained preview is not verified against the current source.`:""}`,!0)}async function Br(e){if(!e)return;try{await e.teardownResource({},{timeout:500})}catch{}await e.close()}function IS(){if(Ac||Hi)return;Hi=!0,Wr.abort(),++Rt,clearTimeout($c),cr(),Se("MCP disconnected. The retained preview is stale. Refresh the page after restarting ADS.",!0);let e=Ue;Ue=void 0,Br(e),++Dt,Oc()}async function Qu(){let e=await RS("ads://project/explorer");Go=e.status,Ji=Go.build,qc=e.tools,vS=e.categories,Bu=e.scenarios,Yo=e.drafts,L("title").textContent=(Go.drafts?.previewOnly?"Draft · ":"")+Go.project.showcase.title,L("title").title=Go.projectRoot,$S();let t=Pc?_S:Le[se],r=Pc&&Yo.find((i)=>i.id===kc),o=me?.draft&&Yo.find((i)=>i.id===me.draftId);if(r||o&&_e&&(o.revision!==_e.revision||_e.discovery?.state==="pending")){let i=await Yu(r||o,r?_S:_e.scenario);if(r)t=i.structuredContent.scenario;if(me?.draft&&o){_e=i.structuredContent,Ic=i;for(let s of tn)if(s.side==="draft")await s.updateResult(i)}}let n=Nc.find((i)=>i.id===t);if(n&&hw.includes(n.kind))se=n.kind,Le[se]=n.id;else if(Pc&&Ku.some((i)=>i.id===t))se="tokens",Le.tokens=t;Pc=!1,Wi()}function Ft({force:e=!1}={}){if(Hi)return Promise.resolve();let t=Le[se],r=Vi();if(Ko?.key===r)return Ko.promise;if(!e&&Fi?.key===r)return Promise.resolve();if(!e&&!Ko&&me?.key===r)return Promise.resolve();Fi=void 0;let o={key:r};return Ko=o,o.promise=fw(t,r,se==="tokens").finally(()=>{if(Ko===o)Ko=void 0}),o.promise}async function fw(e,t,r){Fu?.abort();let o=Fu=new AbortController,n=++Rt;Xo=!0,L("loader").hidden=t===Zi,L("preview").setAttribute("aria-busy","true");try{if(++Dt,await Oc(),n!==Rt)return;if(Gu()){await Br(Ue),Ue=void 0,Jr=void 0,ir=void 0;let u=on(),d=await Yu(u,e,o.signal);if(n!==Rt)return;if(_e=d.structuredContent,Ic=d,rn()?.pendingDraftScenario||!Bi().some((m)=>m.id===e))Le[se]=_e.scenario;me={key:Vi(),id:_e.scenario,draftId:u.id,generation:n,draft:!0},Ju(),await _w(),Wi(),cr(!0),Se("Draft preview only. Acceptance checks have not run.",!1,"ready");return}if(_e=void 0,Ju(),!e&&!r){if(await Br(Ue),n!==Rt)return;Ue=void 0,me=void 0,Zi=void 0,Jr=void 0,ir=void 0,L("frame-slot").replaceChildren(),cr(),Se("No scenarios discovered. Colocate an independently mountable scenario and fixture with the public implementation.");return}let i=qc.find((u)=>u.name===(r?"ads_show_tokens":"ads_show_scenario"));if(!i?._meta?.ui?.resourceUri)throw Error("The server did not expose a preview App tool.");let s=r?e?{category:e}:{}:{id:e};if(i.inputSchema?.properties?.waitFor)s.waitFor=at.get("capture")==="1"||at.get("waitFor")==="verified"?"verified":"compiled";TS();let a=await Vu(i.name,s,o.signal);if(n!==Rt)return;if(a.isError)throw Object.assign(Error(a.content?.find((u)=>u.type==="text")?.text??"Preview build failed."),a.structuredContent?.failure);me={key:t,id:e,generation:n,token:r&&!a.structuredContent?.scenario,build:a.structuredContent?.build,manifestRevision:a.structuredContent?.manifestRevision};let l=await gw(i._meta.ui.resourceUri);if(n!==Rt)return;if(Jr==="ui://ads/preview"&&!me.manifestRevision)throw Error("The resource preview has no manifest revision.");if(Zi!==t)Zi=void 0;if(await l.sendToolInput({arguments:s}),await l.sendToolResult(a),n===Rt&&!a.structuredContent?.manifestUri)cr(!0),Se("")}catch(i){if(n===Rt)Fi={key:Vi(),build:kS(ES())},Pt(i)}}async function gw(e){if(Jr===e&&ir)return ir;let t=++Zu,r=Ue;Ue=void 0,Jr=e,ir=(async()=>{await Br(r);let o=await Cc({uri:e});if(t!==Zu||Ac||Hi)throw Error("Preview opening was superseded.");let n=o.contents.find((u)=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text==="string");if(!n)throw Error("The preview resource contains no MCP App.");let i=document.createElement("iframe");i.title="Design-system preview",i.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),i.src=Di,L("frame-slot").replaceChildren(i);let s=new Ui(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:Xu()});Ue=s,s.onreadresource=(u)=>Cc(u),s.oncalltool=xS,s.onloggingmessage=(u)=>{if(s!==Ue||u.logger!=="ads-preview"||me?.generation!==Rt||!Ec()||u.data?.id!==me?.id)return;let d=u.data.revision===me.manifestRevision||u.data.selectionRevision===me.manifestRevision;if(u.data.state==="ready"&&d)me.manifestRevision=u.data.revision,cr(!0),Se("");else if(u.data.state==="checking"&&(!Xo||d))cr(!0),Se("Checking changes…");else if(u.data.state==="loading")Se("Updating preview…",!1,"reloading");else if(u.data.state==="reverting")Se("Restoring the last verified preview…",!1,"reverting");else if(u.data.code==="ADS_PREVIEW_REOPEN")Ue=void 0,Jr=void 0,ir=void 0,TS(),Br(s).then(()=>Ft({force:!0})).catch(Pt);else if(u.data.state==="error"){if(cr(),L("status").dataset.errorCategory=u.data.category??"build",L("status").dataset.errorCode=u.data.code??"ADS_PREVIEW_BUILD",u.data.resourceUri)L("status").dataset.resourceUri=u.data.resourceUri;else delete L("status").dataset.resourceUri;Se([u.data.message,u.data.code,u.data.resourceUri].filter(Boolean).join(`
124
+ `),!0)}},s.onerror=Pt;let a,l=new Promise((u,d)=>{a=setTimeout(()=>d(Error("MCP App initialization timed out.")),15000),s.oninitialized=()=>{clearTimeout(a),u()}});s.onsandboxready=()=>s.sendSandboxResourceReady({html:n.text,csp:n._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});try{await Promise.all([s.connect(new Li(i.contentWindow,i.contentWindow)),l])}catch(u){throw await Br(s),u}finally{clearTimeout(a)}return s})();try{return await ir}catch(o){if(t===Zu)Jr=void 0,ir=void 0;throw o}}async function Sw(){let e=me,t=await RS("ads://project/build");Ji=t,PS();for(let o of L("entries").querySelectorAll("a[data-scenario]")){let n=Bi().find((i)=>i.id===o.dataset.scenario);if(n)CS(o,n)}if(Fi?.key===Vi()){let o=ES(t);if(o&&(o.current||o.live)&&kS(o)!==Fi.build)await Ft({force:!0});return}if(!e||e.token||Xo||!Ec(e))return;if(e.draft){let o=t.drafts?.find((s)=>s.id===e.draftId),n=o?.scenarios?.find((s)=>s.id===_e?.scenario)??o,i=n&&JSON.stringify([o?.session,n.revision,n.live?.revision,n.current]);if(n&&(n.current||n.live)&&e.buildSignature!==i){e.buildSignature=i;let s=Yo.find((a)=>a.id===e.draftId);if(s){let a=await Yu(s,_e.scenario);if(me!==e||Xo||!Ec(e))return;_e=a.structuredContent,Ic=a;for(let l of tn)if(l.side==="draft")await l.updateResult(a)}}if(n?.state==="error")Se("Draft preview build failed. Showing the previous preview.",!0);else if(n?.building)Se(n.live||n.state==="checking"?"Draft preview compiled; checking changes…":"Building draft preview… Showing the previous preview.",!1,n.live||n.state==="checking"?"checking":"compiling");else if(n?.current&&Du?.state==="ready")Se("Draft preview ready · unaccepted.");return}if(me!==e||Xo||!Ec(e))return;let r=t.previews.find((o)=>o.id===e.id);if(!r){Se("The selected scenario is no longer registered.",!0);return}if(["idle","building"].includes(r.state)&&e.build?.current&&r.session===e.build.session&&r.revision<=e.build.revision)return;if(r.state==="error"){Se(`${pa(r)}. Showing an earlier view.
125
+ ${od(r.diagnostics)}`,!0);return}if(["idle","building"].includes(r.state)){Se(r.live?"Checking changes…":"Compiling changes… The current view is the previous preview.",!1,r.live?"checking":"compiling");return}if(r.current&&(r.revision!==e.build?.revision||r.session!==e.build?.session))await Ft({force:!0})}function Ki(e=!1,t=!1){if(Tc||=e,t&&me?.token)me.key="invalidated";if(clearTimeout($c),zS)return;$c=setTimeout(()=>{if(Uu){Ki(e,t);return}Uu=(async()=>{if(Tc)Tc=!1,await Qu();await Ft(),await Sw()})().catch(Pt).finally(()=>{Uu=void 0})},150)}async function _w(){if(!_e)return;let e=_e,t=Ic;Du=void 0;let r=++Dt;if(await Oc(),r!==Dt)return;let o=en&&e.acceptedExists;Qe.setAttribute("aria-pressed",String(o));let n=document.createElement("div");n.className="draft-comparison",n.dataset.split=String(o);for(let i of o?["accepted","draft"]:["draft"]){let s=document.createElement("section");s.className="draft-version";let a=document.createElement("h2");a.dataset.version=i,a.textContent=i==="accepted"?"Accepted":"Draft · unaccepted";let l=document.createElement("div");l.className="draft-stage",l.dataset.version=i,s.append(a,l),n.append(s)}L("frame-slot").replaceChildren(n),await Promise.all([...n.querySelectorAll(".draft-stage")].map(async(i)=>{let s=i.dataset.version,a=s==="draft"?t:await wS("ads_show_scenario",{id:e.scenario,waitFor:"compiled"});if(a.isError)throw Error(a.content?.find((d)=>d.type==="text")?.text??"Comparison build failed.");if(r!==Dt)return;let l=qc.find((d)=>d.name===(s==="draft"?"ads_show_draft":"ads_show_scenario")),u=await mS({slot:i,title:s==="draft"?"Draft version":"Accepted version",sandboxUrl:Di,resourceUri:l._meta.ui.resourceUri,result:a,readResource:Cc,callTool:xS,context:(d)=>({theme:ar,displayMode:"inline",containerDimensions:{width:d.clientWidth,height:d.clientHeight}}),onError:(d)=>{if(r===Dt)Pt(d)},onState:(d)=>{if(r!==Dt||s!=="draft")return;if(Du=d,d.state==="ready")Se("Draft preview ready · unaccepted.");else if(d.state==="checking")Se("Draft preview compiled; checking changes…",!1,"checking");else if(["loading","reverting"].includes(d.state))Se("Updating draft preview…",!1,"reloading")}});if(r!==Dt)await u.close();else tn.push({...u,side:s})}))}function Ju(){let e=rn(),t=Boolean(on(e))&&!e?.draftOnly;Qe.disabled=!t,Qe.title=e?.draftOnly?"No accepted version yet":t?"Compare accepted and draft versions":"No draft for this entry",Qe.setAttribute("aria-pressed",String(t&&en));let r=document.querySelector('.draft-version h2[data-version="draft"]');if(r&&_e){let o={draft:"unaccepted",checking:"checking acceptance",failed:"acceptance failed",conflict:"source conflict",interrupted:"acceptance interrupted","dependency-error":"dependency needs attention"};r.textContent=`Draft · ${o[_e.state]??_e.state}`,r.title=_e.dependencies?.length?`Draft dependencies: ${_e.dependencies.join(", ")}`:""}}Qe.addEventListener("click",()=>{en=!en,Wi(),Ft().catch(Pt)});for(let e of L("sections").querySelectorAll("button"))e.addEventListener("click",()=>{se=e.dataset.section,Wi(),Ft().catch(Pt)});var ed=window.matchMedia("(max-width: 760px)");function OS(e){document.body.classList.toggle("collapsed",e),L("pane-toggle").setAttribute("aria-expanded",String(!e)),L("pane-toggle").setAttribute("aria-label",e?"Show navigation pane":"Hide navigation pane"),L("pane-toggle").title=e?"Show navigation pane":"Hide navigation pane",L("pane-toggle").querySelector("path").setAttribute("d",e?"M6 4l4 4-4 4":"M10 4l-4 4 4 4")}var td=()=>OS(L("header").hidden||ed.matches);td();ed.addEventListener("change",td);L("pane-toggle").addEventListener("click",()=>OS(!document.body.classList.contains("collapsed")));function NS(){document.documentElement.dataset.viewport=Qo?"phone":"auto",L("viewport").setAttribute("aria-pressed",String(Qo)),L("viewport").title=Qo?"Use available preview width":"Preview at phone width (390 px)"}NS();L("viewport").addEventListener("click",()=>{Qo=!Qo,NS();let e=new URL(location.href);if(Qo)e.searchParams.set("viewport","phone");else e.searchParams.delete("viewport");history.replaceState(null,"",e.pathname+e.search+e.hash)});L("theme").addEventListener("click",()=>{ar=ar==="light"?"dark":"light",document.documentElement.dataset.theme=ar,L("theme").setAttribute("aria-label",ar==="dark"?"Use light theme":"Use dark theme"),L("theme").title=L("theme").getAttribute("aria-label"),L("theme").querySelector("svg").innerHTML=ar==="dark"?'<circle cx="8" cy="8" r="3"/><path d="M8 1v1M8 14v1M1 8h1M14 8h1M3 3l1 1M12 12l1 1M3 13l1-1M12 4l1-1"/>':'<path d="M13.5 9a5.5 5.5 0 0 1-6.5-6.5A5.5 5.5 0 1 0 13.5 9Z"/>',Ue?.setHostContext(Xu())});L("theme").addEventListener("click",()=>{for(let e of tn)e.refreshContext()});L("minimize").addEventListener("click",()=>{L("header").hidden=!0,document.body.classList.add("collapsed")});var qS=new ResizeObserver(()=>Ue?.setHostContext(Xu()));qS.observe(L("frame-slot"));L("retry-preview").addEventListener("click",()=>{(async()=>{await Qu(),await Ft({force:!0})})().catch(Pt)});window.addEventListener("pagehide",()=>{Ac=!0,Fu?.abort(),Wr.abort(),clearTimeout($c),qS.disconnect(),ed.removeEventListener("change",td),Br(Ue),++Dt,Oc(),Hu?.close(),xt.close()},{once:!0});xt.onclose=IS;xt.setNotificationHandler("notifications/resources/list_changed",()=>Ki(!0));xt.setNotificationHandler("notifications/tools/list_changed",()=>Ki(!0));xt.setNotificationHandler("notifications/resources/updated",({params:e})=>Ki(e.uri==="ads://project/explorer",e.uri==="ads://project/tokens"));try{if(Di=(await fetch("/host.json").then((e)=>e.json())).sandboxUrl,!Di||new URL(Di).origin===location.origin)throw Error("The separate-origin MCP App sandbox is unavailable.");if(await xt.connect(new eS(new URL("/mcp",location.href))),Hu=await xt.listen({resourcesListChanged:!0,toolsListChanged:!0,resourceSubscriptions:["ads://project/build","ads://project/tokens","ads://project/explorer"]}),Hu.closed.then((e)=>{if(e!=="local")IS()}),await Qu(),zS=!1,await Ft(),Tc)Ki()}catch(e){Pt(e)}