@omnivoice/page-agent 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +117 -201
- package/package.json +74 -62
- package/src/voice/README.md +48 -0
- package/src/voice/bridge.ts +230 -0
- package/src/voice/config.ts +200 -0
- package/src/voice/engines.ts +161 -0
- package/src/voice/index.ts +17 -0
- package/src/voice/session.ts +309 -0
- package/src/voice/types.ts +98 -0
- package/LICENSE +0 -22
- package/dist/esm/PageAgent.d.ts +0 -160
- package/dist/esm/page-agent.js +0 -426
- package/dist/esm/page-agent.js.map +0 -1
- package/dist/iife/page-agent.demo.js +0 -402
- package/server/agent-gateway.mjs +0 -215
|
@@ -1,402 +0,0 @@
|
|
|
1
|
-
(function(){var __vite_style__=document.createElement(`style`);__vite_style__.textContent=`._wrapper_1ooyb_1{z-index:2147483641;cursor:wait;display:none;position:fixed;inset:0;overflow:hidden}._wrapper_1ooyb_1._visible_1ooyb_11{display:block}._cursor_1dgwb_2{width:var(--cursor-size,75px);height:var(--cursor-size,75px);pointer-events:none;z-index:10000;position:absolute}._cursorBorder_1dgwb_10{transform-origin:50%;background:linear-gradient(45deg,#39b6ff,#bd45fb);width:100%;height:100%;margin-top:-18px;margin-left:-10px;position:absolute;transform:rotate(-135deg)scale(1.2);-webkit-mask-image:url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20100%20100'%20fill='none'%3e%3cg%3e%3cpath%20d='M%2015%2042%20L%2015%2036.99%20Q%2015%2031.99%2023.7%2031.99%20L%2028.05%2031.99%20Q%2032.41%2031.99%2032.41%2021.99%20L%2032.41%2017%20Q%2032.41%2012%2041.09%2016.95%20L%2076.31%2037.05%20Q%2085%2042%2076.31%2046.95%20L%2041.09%2067.05%20Q%2032.41%2072%2032.41%2062.01%20L%2032.41%2057.01%20Q%2032.41%2052.01%2023.7%2052.01%20L%2019.35%2052.01%20Q%2015%2052.01%2015%2047.01%20Z'%20fill='none'%20stroke='%23000000'%20stroke-width='6'%20stroke-miterlimit='10'%20style='stroke:%20light-dark(rgb(0,%200,%200),%20rgb(255,%20255,%20255));'/%3e%3c/g%3e%3c/svg%3e");mask-image:url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20100%20100'%20fill='none'%3e%3cg%3e%3cpath%20d='M%2015%2042%20L%2015%2036.99%20Q%2015%2031.99%2023.7%2031.99%20L%2028.05%2031.99%20Q%2032.41%2031.99%2032.41%2021.99%20L%2032.41%2017%20Q%2032.41%2012%2041.09%2016.95%20L%2076.31%2037.05%20Q%2085%2042%2076.31%2046.95%20L%2041.09%2067.05%20Q%2032.41%2072%2032.41%2062.01%20L%2032.41%2057.01%20Q%2032.41%2052.01%2023.7%2052.01%20L%2019.35%2052.01%20Q%2015%2052.01%2015%2047.01%20Z'%20fill='none'%20stroke='%23000000'%20stroke-width='6'%20stroke-miterlimit='10'%20style='stroke:%20light-dark(rgb(0,%200,%200),%20rgb(255,%20255,%20255));'/%3e%3c/g%3e%3c/svg%3e");-webkit-mask-size:100% 100%;mask-size:100% 100%;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat}._cursorFilling_1dgwb_25{transform-origin:50%;background:url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20100%20100'%3e%3cdefs%3e%3c/defs%3e%3cg%20xmlns='http://www.w3.org/2000/svg'%20style='filter:%20drop-shadow(light-dark(rgba(0,%200,%200,%200.4),%20rgba(237,%20237,%20237,%200.4))%203px%204px%204px);'%3e%3cpath%20d='M%2015%2042%20L%2015%2036.99%20Q%2015%2031.99%2023.7%2031.99%20L%2028.05%2031.99%20Q%2032.41%2031.99%2032.41%2021.99%20L%2032.41%2017%20Q%2032.41%2012%2041.09%2016.95%20L%2076.31%2037.05%20Q%2085%2042%2076.31%2046.95%20L%2041.09%2067.05%20Q%2032.41%2072%2032.41%2062.01%20L%2032.41%2057.01%20Q%2032.41%2052.01%2023.7%2052.01%20L%2019.35%2052.01%20Q%2015%2052.01%2015%2047.01%20Z'%20fill='%23ffffff'%20stroke='none'%20style='fill:%20%23ffffff;'/%3e%3c/g%3e%3c/svg%3e") 0 0/100% 100% no-repeat;width:100%;height:100%;margin-top:-18px;margin-left:-10px;position:absolute;transform:rotate(-135deg)scale(1.2)}._cursorRipple_1dgwb_39{pointer-events:none;width:100%;height:100%;margin-top:-50%;margin-left:-50%;position:absolute}._cursorRipple_1dgwb_39:after{content:"";opacity:0;border:4px solid #39b6ff;border-radius:50%;position:absolute;inset:0}._cursor_1dgwb_2._clicking_1dgwb_57 ._cursorRipple_1dgwb_39:after{animation:.3s ease-out forwards _cursor-ripple_1dgwb_1}@keyframes _cursor-ripple_1dgwb_1{0%{opacity:1;transform:scale(0)}to{opacity:0;transform:scale(2)}}._wrapper_1rq3n_1{opacity:0;z-index:2147483642;box-sizing:border-box;position:fixed;bottom:100px;left:50%;overflow:visible;transform:translate(-50%)translateY(20px)}._wrapper_1rq3n_1 *{box-sizing:border-box}._wrapper_1rq3n_1{--width:360px;--height:40px;--border-radius:12px;--side-space:12px;--history-width:calc(var(--width) - var(--side-space) * 2);--color-1:#39b6ff;--color-2:#bd45fb;--color-3:#ff5733;--color-4:#ffd600;width:var(--width);height:var(--height);transition:all .3s ease-in-out}@media (width<=640px){._wrapper_1rq3n_1{--width:calc(100vw - 16px);--side-space:8px;width:var(--width);bottom:calc(12px + env(safe-area-inset-bottom,0px));--history-max:min(60vh, calc(100dvh - 120px - var(--height)))}}@media (prefers-reduced-motion:reduce){._wrapper_1rq3n_1{transition:none}._wrapper_1rq3n_1 *{transition:none!important;animation:none!important}}._wrapper_1rq3n_1 ._background_1rq3n_55{border-radius:calc(var(--border-radius) + 4px);filter:blur(16px);position:absolute;inset:-2px -8px;overflow:hidden}._wrapper_1rq3n_1 ._background_1rq3n_55:before{content:"";z-index:-1;pointer-events:none;background-image:linear-gradient(to bottom left, var(--color-1), var(--color-2), var(--color-1));width:100%;height:100%;animation:2s linear infinite _mask-running_1rq3n_1;position:absolute;top:0;left:0}._wrapper_1rq3n_1 ._background_1rq3n_55:after{content:"";z-index:-1;pointer-events:none;background-image:linear-gradient(to bottom left, var(--color-2), var(--color-1), var(--color-2));width:100%;height:100%;animation:2s linear 1s infinite _mask-running_1rq3n_1;position:absolute;top:0;left:0}@keyframes _mask-running_1rq3n_1{0%{transform:translate(-100%)}to{transform:translate(100%)}}._header_1rq3n_115{-webkit-user-select:none;user-select:none;cursor:pointer;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);border-radius:var(--border-radius);background:#00000080 padding-box padding-box;flex-shrink:0;justify-content:space-between;align-items:center;padding:8px 12px;display:flex;position:absolute;inset:0;box-shadow:0 0 0 2px #fff6,0 0 5px 1px #ffffff4d}._header_1rq3n_115 ._statusSection_1rq3n_137{flex:1;align-items:center;gap:8px;min-height:24px;display:flex}._header_1rq3n_115 ._statusSection_1rq3n_137 ._indicator_1rq3n_144{background:#ffffff80;border-radius:50%;flex-shrink:0;width:6px;height:6px;animation:none}._header_1rq3n_115 ._statusSection_1rq3n_137 ._indicator_1rq3n_144._thinking_1rq3n_153{background:#39b6ff;animation:.8s ease-in-out infinite _pulse_1rq3n_1}._header_1rq3n_115 ._statusSection_1rq3n_137 ._indicator_1rq3n_144._tool_executing_1rq3n_158{background:#bd45fb;animation:.6s ease-in-out infinite _pulse_1rq3n_1}._header_1rq3n_115 ._statusSection_1rq3n_137 ._indicator_1rq3n_144._retry_1rq3n_163{background:#ffd600;animation:1s ease-in-out infinite _retryPulse_1rq3n_1}._header_1rq3n_115 ._statusSection_1rq3n_137 ._indicator_1rq3n_144._completed_1rq3n_169,._header_1rq3n_115 ._statusSection_1rq3n_137 ._indicator_1rq3n_144._input_1rq3n_170,._header_1rq3n_115 ._statusSection_1rq3n_137 ._indicator_1rq3n_144._output_1rq3n_171{background:#22c55e;animation:none}._header_1rq3n_115 ._statusSection_1rq3n_137 ._indicator_1rq3n_144._error_1rq3n_176{background:#ef4444;animation:none}._header_1rq3n_115 ._statusSection_1rq3n_137 ._statusText_1rq3n_182{color:#fff;align-items:center;min-height:24px;font-size:12px;font-weight:500;line-height:1;transition:all .3s ease-in-out;display:flex;position:relative;overflow:hidden}._header_1rq3n_115 ._statusSection_1rq3n_137 ._statusText_1rq3n_182._fadeOut_1rq3n_194{animation:.3s forwards _statusTextFadeOut_1rq3n_1}._header_1rq3n_115 ._statusSection_1rq3n_137 ._statusText_1rq3n_182._fadeIn_1rq3n_198{animation:.3s forwards _statusTextFadeIn_1rq3n_1}._header_1rq3n_115 ._controls_1rq3n_204{align-items:center;gap:4px;display:flex}._header_1rq3n_115 ._controls_1rq3n_204 ._controlButton_1rq3n_209{color:#fff;cursor:pointer;background:#ffffff1a;border:none;border-radius:4px;justify-content:center;align-items:center;width:24px;height:24px;font-size:12px;line-height:1;display:flex}._header_1rq3n_115 ._controls_1rq3n_204 ._controlButton_1rq3n_209:hover{background:#fff3}._header_1rq3n_115 ._controls_1rq3n_204 ._stopButton_1rq3n_228{color:#ff2929;background:#ef444433;font-weight:600}._header_1rq3n_115 ._controls_1rq3n_204 ._stopButton_1rq3n_228:hover{background:#ef44444d}@keyframes _statusTextFadeIn_1rq3n_1{0%{opacity:0;transform:translateY(5px)}to{opacity:1;transform:translateY(0)}}@keyframes _statusTextFadeOut_1rq3n_1{0%{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-5px)}}._historySectionWrapper_1rq3n_262{width:var(--history-width);bottom:var(--height);left:var(--side-space);z-index:-2;visibility:collapse;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);text-shadow:0 0 1px #0003;border-top-left-radius:calc(var(--border-radius) + 4px);border-top-right-radius:calc(var(--border-radius) + 4px);background:#02001480;border:2px solid #fff6;padding-top:0;transition:all .2s;position:absolute;overflow:hidden;box-shadow:0 4px 16px #0009}._expanded_1rq3n_294 ._historySectionWrapper_1rq3n_262{visibility:visible;padding-top:8px}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262{overscroll-behavior:contain;scrollbar-width:none;max-height:0;padding-inline:8px;transition:max-height .2s;position:relative;overflow-y:auto}._expanded_1rq3n_294 :is(._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262){max-height:var(--history-max,min(500px, calc(100vh - 200px - var(--height))))}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyRow_1rq3n_320{margin-bottom:8px;display:flex}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyRow_1rq3n_320:last-child{margin-bottom:12px}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyRow_1rq3n_320._fromPessoa_1rq3n_328{justify-content:flex-end}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyRow_1rq3n_320._fromAgente_1rq3n_332,._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyRow_1rq3n_320._fromSistema_1rq3n_333{justify-content:flex-start}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338{--bolha:#22222e;--bolha-texto:#ececf2;--bolha-meta:#a9a9bd;--bolha-realce:#7a8cff;background:var(--bolha);min-width:0;max-width:88%;color:var(--bolha-texto);border-radius:12px;padding:7px 10px 8px;font-size:13px;line-height:1.45;box-shadow:0 1px 2px #00000059}._fromPessoa_1rq3n_328 :is(._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338){--bolha:#2f4f74;--bolha-texto:#f2f6fb;--bolha-meta:#bcd0e6;border-bottom-right-radius:4px}._fromAgente_1rq3n_332 :is(._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338),._fromSistema_1rq3n_333 :is(._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338){border-bottom-left-radius:4px}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338._output_1rq3n_171{--bolha-realce:#58d68d}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338._observation_1rq3n_374{--bolha-realce:#c49bff}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338._question_1rq3n_378{--bolha-realce:#ffb067}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338._doneSuccess_1rq3n_382{--bolha:#1d3b2a;--bolha-texto:#e3f8ec;--bolha-meta:#a9d8bd;--bolha-realce:#58d68d;font-weight:500}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338._doneFailure_1rq3n_390,._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338._error_1rq3n_176{--bolha:#412128;--bolha-texto:#fde8ec;--bolha-meta:#e3aeb8;--bolha-realce:#ff8095}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338._retry_1rq3n_163{--bolha-realce:#ffd166}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338 ._historyHeader_1rq3n_402{color:var(--bolha-realce);align-items:center;gap:6px;margin-bottom:3px;display:flex}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338 ._historyAuthor_1rq3n_410{letter-spacing:.01em;font-size:11px;font-weight:600}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338 ._historyMeta_1rq3n_416{color:var(--bolha-meta);white-space:nowrap;margin-left:auto;font-size:11px}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338 ._statusIcon_1rq3n_426{flex-shrink:0;width:14px;height:14px;line-height:1}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338 ._statusIcon_1rq3n_426 svg{width:100%;height:100%;display:block}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338 ._historyContent_1rq3n_439{word-break:normal;overflow-wrap:anywhere}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338 ._historyContent_1rq3n_439>span,._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338 ._historyContent_1rq3n_439 ._reflectionLine_1rq3n_446{white-space:pre-wrap}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338 ._reflectionLines_1rq3n_451{flex-direction:column;gap:7px;display:flex}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338 ._reflectionLine_1rq3n_446{display:block}._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338 ._reflectionLabel_1rq3n_462{letter-spacing:.07em;text-transform:uppercase;color:var(--bolha-meta);margin-bottom:1px;font-size:10px;font-weight:700;display:block}@media (prefers-contrast:more){._historySectionWrapper_1rq3n_262 ._historySection_1rq3n_262 ._historyItem_1rq3n_338{--bolha:#000;--bolha-texto:#fff;--bolha-meta:#e0e0e0;border:1px solid #fff}}@keyframes _pulse_1rq3n_1{0%,to{opacity:1;transform:scale(1)}50%{opacity:.4;transform:scale(1.3)}}@keyframes _retryPulse_1rq3n_1{0%,to{opacity:1;transform:scale(1)rotate(0)}25%{opacity:.6;transform:scale(1.2)rotate(90deg)}50%{opacity:.8;transform:scale(1.1)rotate(180deg)}75%{opacity:.6;transform:scale(1.2)rotate(270deg)}}@keyframes _celebrate_1rq3n_1{0%,to{transform:scale(1)}25%{transform:scale(1.2)rotate(-5deg)}75%{transform:scale(1.2)rotate(5deg)}}@keyframes _shimmer_1rq3n_1{0%{left:-100%}to{left:100%}}._inputSectionWrapper_1rq3n_544{width:var(--history-width);top:var(--height);left:var(--side-space);z-index:-1;visibility:visible;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);border-bottom-left-radius:calc(var(--border-radius) + 4px);border-bottom-right-radius:calc(var(--border-radius) + 4px);background:#bababa33;border:2px solid #ffffff4d;height:48px;transition:all .2s;position:absolute;overflow:hidden;box-shadow:0 1px 16px #0006}._inputSectionWrapper_1rq3n_544._hidden_1rq3n_567{visibility:collapse;height:0}._inputSectionWrapper_1rq3n_544 ._inputSection_1rq3n_544{align-items:center;gap:4px;padding:8px;display:flex}._inputSectionWrapper_1rq3n_544 ._inputSection_1rq3n_544 ._taskInput_1rq3n_578{color:#141414;background:#fff6;border:1px solid #ffffff4d;border-radius:10px;outline:none;flex:1;height:28px;padding-inline:10px;font-size:12px;line-height:1;transition:all .2s}._inputSectionWrapper_1rq3n_544 ._inputSection_1rq3n_544 ._taskInput_1rq3n_578::placeholder{color:#353535}._inputSectionWrapper_1rq3n_544 ._inputSection_1rq3n_544 ._taskInput_1rq3n_578:focus{background:#fffc;border-color:#39b6ff99;box-shadow:0 0 0 2px #39b6ff33}.page-agent-widget-launcher{z-index:2147483630;color:#f9fafb;cursor:pointer;-webkit-tap-highlight-color:transparent;width:48px;height:48px;right:calc(20px + env(safe-area-inset-right,0px));bottom:calc(20px + env(safe-area-inset-bottom,0px));background:#111827;border:none;border-radius:50%;justify-content:center;align-items:center;padding:0;transition:transform .12s,box-shadow .12s,background .12s;display:inline-flex;position:fixed;box-shadow:0 4px 14px #00000047}.page-agent-widget-launcher:hover{background:#1f2937;transform:translateY(-1px);box-shadow:0 6px 18px #00000057}.page-agent-widget-launcher:active{transform:translateY(0)scale(.97)}.page-agent-widget-launcher:focus-visible{outline-offset:2px;outline:3px solid #60a5fa}.page-agent-widget-launcher svg{display:block}.page-agent-voice-mic{width:34px;height:34px;color:inherit;cursor:pointer;-webkit-tap-highlight-color:transparent;background:#94a3b81f;border:1px solid #94a3b866;border-radius:8px;flex:none;justify-content:center;align-items:center;margin-right:8px;padding:0;transition:background .12s,border-color .12s,transform .12s;display:inline-flex}.page-agent-voice-mic:hover{background:#94a3b838;border-color:#94a3b899}.page-agent-voice-mic:active{transform:scale(.96)}.page-agent-voice-mic:focus-visible{outline-offset:1px;outline:2px solid #60a5fa}.page-agent-voice-mic.is-listening{background:#ef444429;border-color:#ef444499;animation:1.4s ease-in-out infinite page-agent-voice-pulse}@keyframes page-agent-voice-pulse{0%,to{box-shadow:0 0 #ef444459}50%{box-shadow:0 0 0 6px #ef444400}}@media (prefers-reduced-motion:reduce){.page-agent-voice-mic.is-listening{animation:none}}
|
|
2
|
-
/*$vite$:1*/`,document.head.appendChild(__vite_style__);var __defProp=Object.defineProperty,__esmMin=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},__exportAll=(e,t)=>{let n={};for(var r in e)__defProp(n,r,{get:e[r],enumerable:!0});return t||__defProp(n,Symbol.toStringTag,{value:`Module`}),n};function getEnumValues(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function joinValues(e,t=`|`){return e.map(e=>stringifyPrimitive(e)).join(t)}function jsonStringifyReplacer(e,t){return typeof t==`bigint`?t.toString():t}function cached(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function nullish(e){return e==null}function cleanRegex(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function floatSafeRemainder(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}function assignProp(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function esc(e){return JSON.stringify(e)}function slugify(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var captureStackTrace=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var allowsEval=cached(()=>{if(globalConfig.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function isPlainObject(e){if(isObject(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return isObject(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function shallowClone(e){return isPlainObject(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var propertyKeyTypes=new Set([`string`,`number`,`symbol`]);function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function clone(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function normalizeParams(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}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function stringifyPrimitive(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function optionalKeys(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}var NUMBER_FORMAT_RANGES={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function pick(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return clone(e,mergeDefs(e._zod.def,{get shape(){let e={};for(let r of Reflect.ownKeys(t)){if(!Object.prototype.hasOwnProperty.call(n.shape,r))throw Error(`Unrecognized key: "${String(r)}"`);t[r]&&assignProp(e,r,n.shape[r])}return assignProp(this,`shape`,e),e},checks:[]}))}function omit(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return clone(e,mergeDefs(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e of Reflect.ownKeys(t)){if(!Object.prototype.hasOwnProperty.call(n.shape,e))throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&delete r[e]}return assignProp(this,`shape`,r),r},checks:[]}))}function extend(e,t){if(!isPlainObject(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return clone(e,mergeDefs(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return assignProp(this,`shape`,n),n}}))}function safeExtend(e,t){if(!isPlainObject(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return clone(e,mergeDefs(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return assignProp(this,`shape`,n),n}}))}function merge(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return clone(e,mergeDefs(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return assignProp(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function partial(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);return clone(t,mergeDefs(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t of Reflect.ownKeys(n)){if(!Object.prototype.hasOwnProperty.call(r,t))throw Error(`Unrecognized key: "${String(t)}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t of Reflect.ownKeys(r))i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return assignProp(this,`shape`,i),i},checks:[]}))}function required(e,t,n){return clone(t,mergeDefs(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t of Reflect.ownKeys(n)){if(!Object.prototype.hasOwnProperty.call(i,t))throw Error(`Unrecognized key: "${String(t)}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t of Reflect.ownKeys(r))i[t]=new e({type:`nonoptional`,innerType:r[t]});return assignProp(this,`shape`,i),i}}))}function aborted(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function explicitlyAborted(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function prefixIssues(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function unwrapMessage(e){return typeof e==`string`?e:e?.message}function attachSchema(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function finalizeIssue(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(a?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(n.customError?.(e))??unwrapMessage(n.localeError?.(e))??`Invalid input`,{inst:s,schema:c,continue:l,input:u,...d}=e;return d.path??=[],d.message=o,t?.reportInput&&(d.input=u),d}var highSurrogate=/[\uD800-\uDBFF]/;function codePointLength(e){let t=e.length;if(!highSurrogate.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function getLengthableOrigin(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function parsedType(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 t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function issue(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function members(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):defineBound(e,n,r.value)}}function own(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function hide(e,t,n){return own(e,t,n,!1)}function defineBound(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return own(this,t,n.bind(this))},set(e){own(this,t,e)}})}function claim(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var installing,broke=!1,breaker={configurable:!0,get(){broke=!0}};function defineLazyInternal(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&installing!==e._zod){installing=void 0;return}installing=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,breaker);let e=broke;broke=!1;try{let r=n(this);return broke?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),broke||=e,r}catch(n){throw delete this[t],broke||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})}function installLazyProp(e,t,n,r){let i=claim(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}var CONSTANT_CATCH=`~constantCatch`;function constantCatch(e){let t=()=>e;return t[CONSTANT_CATCH]=!0,t}var _a$1,_zodDesc$1={value:void 0,enumerable:!1},_E=`captureStackTrace`in Error?Error:null;function newError(e){let t=_E;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return _E=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function $constructor(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(!n._zod){_zodDesc$1.value=new a(r);try{Object.defineProperty(n,"_zod",_zodDesc$1)}finally{_zodDesc$1.value=void 0}}if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),members(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?newError(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var $ZodAsyncError=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},$ZodEncodeError=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(_a$1=globalThis).__zod_globalConfig??(_a$1.__zod_globalConfig={});var globalConfig=globalThis.__zod_globalConfig;function config(e){return e&&Object.assign(globalConfig,e),globalConfig}function _getMessage(){let e=this._zod;return e.message??=JSON.stringify(e.def,jsonStringifyReplacer,2),e.message}function _setMessage(e){this._zod.message=e}var _messageDesc={get:_getMessage,set:_setMessage,enumerable:!0,configurable:!0},_zodDesc={value:void 0,enumerable:!1},_issuesDesc={value:void 0,enumerable:!1},_installedToString=new WeakSet([Object.prototype,Error.prototype]),initializer$1=(e,t)=>{e.name=`$ZodError`,_zodDesc.value=e._zod,Object.defineProperty(e,"_zod",_zodDesc),_issuesDesc.value=t,Object.defineProperty(e,"issues",_issuesDesc),_zodDesc.value=void 0,_issuesDesc.value=void 0,Object.defineProperty(e,"message",_messageDesc);let n=Object.getPrototypeOf(e);_installedToString.has(n)||(_installedToString.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},$ZodError=$constructor(`$ZodError`,initializer$1),$ZodRealError=$constructor(`$ZodError`,initializer$1,void 0,{Parent:Error});function node(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function flattenError(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?node(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function formatError(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i],o=i===e.length-1;if(n===`_errors`){o&&r._errors.push(t(a)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(a)),r=s,i++}}}};return r(e),n}function toDotPath(e){let t=[],n=e.map(e=>typeof e==`object`?e.key:e);for(let e of n)typeof e==`number`?t.push(`[${e}]`):typeof e==`symbol`?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push(`.`),t.push(e));return t.join(``)}function prettifyError(e){let t=[],n=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(let e of n)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${toDotPath(e.path)}`);return t.join(`
|
|
3
|
-
`)}function finalizeParams(e,t){return{callee:t?.callee??e,Err:t?.Err}}var _parse=e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new $ZodAsyncError;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>finalizeIssue(e,o,config())));throw captureStackTrace(n,a?.callee??t),n}return s.value};return t},_parseAsync=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>finalizeIssue(e,o,config())));throw captureStackTrace(n,a?.callee??t),n}return s.value};return t},_safeParse=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new $ZodAsyncError;return a.issues.length?{success:!1,error:new(e??$ZodError)(a.issues.map(e=>finalizeIssue(e,i,config())))}:{success:!0,data:a.value}},safeParse$1=_safeParse($ZodRealError),_safeParseAsync=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>finalizeIssue(e,i,config())))}:{success:!0,data:a.value}},safeParseAsync$1=_safeParseAsync($ZodRealError),_encode=e=>{let t=_parse(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,finalizeParams(n,a))};return n},_decode=e=>{let t=_parse(e),n=(e,r,i,a)=>t(e,r,i,finalizeParams(n,a));return n},_encodeAsync=e=>{let t=_parseAsync(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,finalizeParams(n,a))};return n},_decodeAsync=e=>{let t=_parseAsync(e),n=async(e,r,i,a)=>await t(e,r,i,finalizeParams(n,a));return n},_safeEncode=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _safeParse(e)(t,n,i)},_safeDecode=e=>(t,n,r)=>_safeParse(e)(t,n,r),_safeEncodeAsync=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _safeParseAsync(e)(t,n,i)},_safeDecodeAsync=e=>async(t,n,r)=>_safeParseAsync(e)(t,n,r),cuid=/^[cC][0-9a-z]{6,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/;function nanoidOfLength(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([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})$/,uuid=e=>e?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})$`):/^([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)$/,email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji$1=`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;function emoji(){return new RegExp(_emoji$1,`u`)}var ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([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}|:))$/,cidrv4=/^((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])$/,cidrv6=/^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/,dateSource=`(?:(?:\\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])))`;function anchor(e){return RegExp(`^${e}$`)}var date=anchor(dateSource);function timeSource(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time(e){return RegExp(`^${timeSource(e)}$`)}function datetime(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${timeSource({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${timeSource({precision:e.precision})}`:n;return RegExp(`^${dateSource}T(?:${r})$`)}var string$1=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},integer=/^-?\d+$/,number$1=/^-?\d+(?:\.\d+)?$/,boolean$1=/^(?:true|false)$/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/,$ZodCheck=$constructor(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),_whenHasLength=e=>{let t=e.value;return!nullish(t)&&t.length!==void 0},numericOriginMap={number:`number`,bigint:`bigint`,object:`date`},$ZodCheckLessThan=$constructor(`$ZodCheckLessThan`,(e,t)=>{$ZodCheck.init(e,t);let n=numericOriginMap[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:numericOriginMap[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$ZodCheckGreaterThan=$constructor(`$ZodCheckGreaterThan`,(e,t)=>{$ZodCheck.init(e,t);let n=numericOriginMap[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:numericOriginMap[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$ZodCheckMultipleOf=$constructor(`$ZodCheckMultipleOf`,(e,t)=>{$ZodCheck.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):floatSafeRemainder(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),$ZodCheckNumberFormat=$constructor(`$ZodCheckNumberFormat`,(e,t)=>{$ZodCheck.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=NUMBER_FORMAT_RANGES[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=integer)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),$ZodCheckMaxLength=$constructor(`$ZodCheckMaxLength`,(e,t)=>{var n;$ZodCheck.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?codePointLength(r):i)<=t.maximum)return;let a=getLengthableOrigin(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),$ZodCheckMinLength=$constructor(`$ZodCheckMinLength`,(e,t)=>{var n;$ZodCheck.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?codePointLength(r):i)>=t.minimum)return;let a=getLengthableOrigin(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),$ZodCheckLengthEquals=$constructor(`$ZodCheckLengthEquals`,(e,t)=>{var n;$ZodCheck.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?codePointLength(r):i;if(a===t.length)return;let o=getLengthableOrigin(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),$ZodCheckStringFormat=$constructor(`$ZodCheckStringFormat`,(e,t)=>{var n,r;$ZodCheck.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&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})}):(r=e._zod).check??(r.check=()=>{})}),$ZodCheckRegex=$constructor(`$ZodCheckRegex`,(e,t)=>{$ZodCheckStringFormat.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),$ZodCheckLowerCase=$constructor(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=lowercase,$ZodCheckStringFormat.init(e,t)}),$ZodCheckUpperCase=$constructor(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=uppercase,$ZodCheckStringFormat.init(e,t)}),$ZodCheckIncludes=$constructor(`$ZodCheckIncludes`,(e,t)=>{$ZodCheck.init(e,t);let n=escapeRegex(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),$ZodCheckStartsWith=$constructor(`$ZodCheckStartsWith`,(e,t)=>{$ZodCheck.init(e,t);let n=RegExp(`^${escapeRegex(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),$ZodCheckEndsWith=$constructor(`$ZodCheckEndsWith`,(e,t)=>{$ZodCheck.init(e,t);let n=RegExp(`.*${escapeRegex(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),$ZodCheckOverwrite=$constructor(`$ZodCheckOverwrite`,(e,t)=>{$ZodCheck.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Doc=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
4
|
-
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
|
|
5
|
-
`)}\n};`)(...Object.values(this.closed))}},version={major:4,minor:5,patch:1},$ZodType=$constructor(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=version;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=aborted(t),a;for(let o of n){if(o._zod.def.when){if(explicitlyAborted(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new $ZodAsyncError;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(attachSchema(t.issues,n,e),i||=aborted(t,n))});else{if(t.issues.length===n)continue;attachSchema(t.issues,n,e),i||=aborted(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(aborted(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new $ZodAsyncError;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new $ZodAsyncError;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return hide(this,`~standard`,standardProps(this))},set"~standard"(e){own(this,`~standard`,e)}}),toStandardResult=e=>e.success?{value:e.data}:{issues:e.error?.issues};function standardProps(e){return{validate:t=>{try{return toStandardResult(safeParse$1(e,t))}catch{return safeParseAsync$1(e,t).then(toStandardResult)}},vendor:`zod`,version:1}}var $ZodString=$constructor(`$ZodString`,(e,t)=>{$ZodType.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??string$1(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),$ZodStringFormat=$constructor(`$ZodStringFormat`,(e,t)=>{$ZodCheckStringFormat.init(e,t),$ZodString.init(e,t)}),$ZodGUID=$constructor(`$ZodGUID`,(e,t)=>{t.pattern??=guid,$ZodStringFormat.init(e,t)}),$ZodUUID=$constructor(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=uuid(e)}else t.pattern??=uuid();$ZodStringFormat.init(e,t)}),$ZodEmail=$constructor(`$ZodEmail`,(e,t)=>{t.pattern??=email,$ZodStringFormat.init(e,t)}),URL_BAD_FORMAT=1,URL_UNPARSEABLE=2;function parseURLObject(e,t){if(!t.normalize&&t.protocol?.source===httpProtocol.source&&!/^https?:\/\//i.test(e))return 1;try{return new URL(e)}catch{return 2}}var asciiTabOrNewline=/[\t\n\r]/g;function stripTabAndNewline(e){return e.replace(asciiTabOrNewline,``)}function urlHostnameOk(e,t){return t.lastIndex=0,t.test(e.hostname)}function urlProtocolOk(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}var $ZodURL=$constructor(`$ZodURL`,(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=parseURLObject(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}t.hostname&&!urlHostnameOk(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!urlProtocolOk(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:stripTabAndNewline(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),$ZodEmoji=$constructor(`$ZodEmoji`,(e,t)=>{t.pattern??=emoji(),$ZodStringFormat.init(e,t)}),$ZodNanoID=$constructor(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?nanoid:nanoidOfLength(t.length),$ZodStringFormat.init(e,t)}),$ZodCUID=$constructor(`$ZodCUID`,(e,t)=>{t.pattern??=cuid,$ZodStringFormat.init(e,t)}),$ZodCUID2=$constructor(`$ZodCUID2`,(e,t)=>{t.pattern??=cuid2,$ZodStringFormat.init(e,t)}),$ZodULID=$constructor(`$ZodULID`,(e,t)=>{t.pattern??=ulid,$ZodStringFormat.init(e,t)}),$ZodXID=$constructor(`$ZodXID`,(e,t)=>{t.pattern??=xid,$ZodStringFormat.init(e,t)}),$ZodKSUID=$constructor(`$ZodKSUID`,(e,t)=>{t.pattern??=ksuid,$ZodStringFormat.init(e,t)}),$ZodISODateTime=$constructor(`$ZodISODateTime`,(e,t)=>{t.pattern??=datetime(t),$ZodStringFormat.init(e,t),(t.local||t.precision===-1)&&(e._zod.bag.laxFormat=!0,e._zod.onattach.push(e=>{e._zod.bag.laxFormat=!0}))}),$ZodISODate=$constructor(`$ZodISODate`,(e,t)=>{t.pattern??=date,$ZodStringFormat.init(e,t)}),$ZodISOTime=$constructor(`$ZodISOTime`,(e,t)=>{t.pattern??=time(t),$ZodStringFormat.init(e,t)}),$ZodISODuration=$constructor(`$ZodISODuration`,(e,t)=>{t.pattern??=duration,$ZodStringFormat.init(e,t)}),$ZodIPv4=$constructor(`$ZodIPv4`,(e,t)=>{t.pattern??=ipv4,$ZodStringFormat.init(e,t),e._zod.bag.format=`ipv4`}),ipv6Alphabet=/^[0-9a-fA-F:.]+$/;function isValidIPv6(e){if(!ipv6Alphabet.test(e))return!1;try{return new URL(`http://[${e}]`),!0}catch{return!1}}var $ZodIPv6=$constructor(`$ZodIPv6`,(e,t)=>{t.pattern??=ipv6,$ZodStringFormat.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{isValidIPv6(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),$ZodCIDRv4=$constructor(`$ZodCIDRv4`,(e,t)=>{t.pattern??=cidrv4,$ZodStringFormat.init(e,t)});function isValidCIDRv6(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:isValidIPv6(n)}var $ZodCIDRv6=$constructor(`$ZodCIDRv6`,(e,t)=>{t.pattern??=cidrv6,$ZodStringFormat.init(e,t),e._zod.check=n=>{isValidCIDRv6(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function isValidBase64(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var $ZodBase64=$constructor(`$ZodBase64`,(e,t)=>{t.pattern??=base64,$ZodStringFormat.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{isValidBase64(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function isValidBase64URL(e){if(!base64url.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return isValidBase64(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var $ZodBase64URL=$constructor(`$ZodBase64URL`,(e,t)=>{t.pattern??=base64url,$ZodStringFormat.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{isValidBase64URL(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),$ZodE164=$constructor(`$ZodE164`,(e,t)=>{t.pattern??=e164,$ZodStringFormat.init(e,t)});function isValidJWT(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var $ZodJWT=$constructor(`$ZodJWT`,(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=n=>{isValidJWT(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),$ZodNumber=$constructor(`$ZodNumber`,(e,t)=>{$ZodType.init(e,t),e._zod.pattern=e._zod.bag.pattern??number$1,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),$ZodNumberFormat=$constructor(`$ZodNumberFormat`,(e,t)=>{$ZodCheckNumberFormat.init(e,t),$ZodNumber.init(e,t)}),$ZodBoolean=$constructor(`$ZodBoolean`,(e,t)=>{$ZodType.init(e,t),e._zod.pattern=boolean$1,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),$ZodUnknown=$constructor(`$ZodUnknown`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=e=>e}),$ZodNever=$constructor(`$ZodNever`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function handleArrayResult(e,t,n){e.issues.length&&t.issues.push(...prefixIssues(n,e.issues)),t.value[n]=e.value}var $ZodArray=$constructor(`$ZodArray`,(e,t)=>{$ZodType.init(e,t);let n=globalConfig.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[];for(let e=0;e<a.length;e++){let n=a[e],s=t.element._zod.run({value:n,issues:[]},i);s instanceof Promise?o.push(s.then(t=>handleArrayResult(t,r,e))):handleArrayResult(s,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function handlePropertyResult(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...prefixIssues(n,e.issues))}if(!o&&i===void 0){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}}var NO_SYMBOL_KEYS=[];function normalizeDef(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:NO_SYMBOL_KEYS,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=optionalKeys(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function handleCatchall(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin,d=c.optout;for(let i in t){if(s.has(i))continue;if(i===`__proto__`){l===`never`&&o.push(i);continue}if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>handlePropertyResult(e,n,i,t,u,d))):handlePropertyResult(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}var propShapes=new WeakMap,$ZodObject=$constructor(`$ZodObject`,(e,t)=>{if($ZodType.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;propShapes.set(t,e),Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),propShapes.set(t,n),n}})}let n=cached(()=>normalizeDef(t));defineLazyInternal(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||assignProp(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let r=isObject,i=t.catchall,a,o=globalConfig.memoizer;o?.attach(e),e._zod.parse=(t,s)=>{a??=n.value;let c=t.value;if(!r(c))return t.issues.push({expected:`object`,code:`invalid_type`,input:c,inst:e}),t;t.value=o?o.alloc(e,t,{},s):{};let l=[],u=a.shape;for(let e of a.allKeys){if(e===`__proto__`)continue;let n=u[e],r=n._zod.optin,i=n._zod.optout,a=n._zod.run({value:c[e],issues:[]},s);a instanceof Promise?l.push(a.then(n=>handlePropertyResult(n,t,e,c,r,i))):handlePropertyResult(a,t,e,c,r,i)}return i?handleCatchall(l,c,t,s,n.value,e):l.length?Promise.all(l).then(()=>t):t}}),$ZodObjectJIT=$constructor(`$ZodObjectJIT`,(e,t)=>{$ZodObject.init(e,t);let n=e._zod.parse,r=cached(()=>normalizeDef(t)),i=globalConfig.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new Doc([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
|
|
6
|
-
for (let i = 0; i < ${e}.issues.length; i++) {
|
|
7
|
-
const iss = ${e}.issues[i];
|
|
8
|
-
iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
|
|
9
|
-
payload.issues.push(iss);
|
|
10
|
-
}`;o.write(`const input = payload.value;`);let l=Object.create(null),u=0;for(let e of n.allKeys)l[e]=`key_${u++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=l[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:esc(e),i=`${r} in input`,u=t[e],d=u?._zod?.optin,f=d!==void 0,p=u?._zod?.optout===`optional`;if(o.write(`const ${n} = ${s(r)};`),f&&p){let e=d===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
|
|
11
|
-
const ${n}_present = ${i};
|
|
12
|
-
if (!${n}.issues.length || ${n}_present) {
|
|
13
|
-
if (${n}.issues.length) {${c(n,r)}
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
if (${e}) {
|
|
17
|
-
newResult[${r}] = ${n}.value;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
`)}else f?o.write(`
|
|
22
|
-
if (${n}.issues.length) {${c(n,r)}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
if (${n}.value === undefined) {
|
|
26
|
-
if (${i}) {
|
|
27
|
-
newResult[${r}] = undefined;
|
|
28
|
-
}
|
|
29
|
-
} else {
|
|
30
|
-
newResult[${r}] = ${n}.value;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
`):o.write(`
|
|
34
|
-
const ${n}_present = ${i};
|
|
35
|
-
if (${n}.issues.length) {${c(n,r)}
|
|
36
|
-
}
|
|
37
|
-
if (!${n}_present && !${n}.issues.length) {
|
|
38
|
-
payload.issues.push({
|
|
39
|
-
code: "invalid_type",
|
|
40
|
-
expected: "nonoptional",
|
|
41
|
-
input: undefined,
|
|
42
|
-
path: [${r}]
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
if (${n}_present) {
|
|
47
|
-
newResult[${r}] = ${n}.value;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
`)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=isObject,c=!globalConfig.jitless,l=c&&allowsEval.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?handleCatchall([],p,i,f,d,e):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function handleUnionResults(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!aborted(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>finalizeIssue(e,r,config())))}),t)}var $ZodUnion=$constructor(`$ZodUnion`,(e,t)=>{$ZodType.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),defineLazyInternal(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),defineLazyInternal(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),defineLazyInternal(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>cleanRegex(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>handleUnionResults(t,r,e,i)):handleUnionResults(o,r,e,i)}}),$ZodIntersection=$constructor(`$ZodIntersection`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>handleIntersectionResults(e,t,n)):handleIntersectionResults(e,i,a)}});function mergeValues(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(isPlainObject(e)&&isPlainObject(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=mergeValues(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=mergeValues(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=mergeValues(t.value,n.value);if(!c.valid){if(aborted(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var $ZodEnum=$constructor(`$ZodEnum`,(e,t)=>{$ZodType.init(e,t);let n=getEnumValues(t.entries),r=new Set(n);e._zod.values=r;let i=n.filter(e=>propertyKeyTypes.has(typeof e));e._zod.pattern=RegExp(i.length?`^(${i.map(e=>escapeRegex(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),$ZodTransform=$constructor(`$ZodTransform`,(e,t)=>{$ZodType.init(e,t),e._zod.optin=`optional`,globalConfig.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new $ZodAsyncError;return n.value=i,n}});function handleOptionalResult(e,t){return e.value=t.issues.length?void 0:t.value,e}var $ZodOptional=$constructor(`$ZodOptional`,(e,t)=>{$ZodType.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,defineLazyInternal(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),defineLazyInternal(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${cleanRegex(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>handleOptionalResult(e,t)):handleOptionalResult(e,r)}return t.innerType._zod.run(e,n)}}),$ZodExactOptional=$constructor(`$ZodExactOptional`,(e,t)=>{$ZodOptional.init(e,t),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),defineLazyInternal(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),$ZodNullable=$constructor(`$ZodNullable`,(e,t)=>{$ZodType.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.innerType._zod.optin),defineLazyInternal(e,`optout`,e=>e.def.innerType._zod.optout),defineLazyInternal(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${cleanRegex(t.source)}|null)$`):void 0}),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),$ZodDefault=$constructor(`$ZodDefault`,(e,t)=>{$ZodType.init(e,t),e._zod.optin=`defaulted`,defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>handleDefaultResult(e,t)):handleDefaultResult(r,t)}});function handleDefaultResult(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var $ZodPrefault=$constructor(`$ZodPrefault`,(e,t)=>{$ZodType.init(e,t),e._zod.optin=`defaulted`,defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),$ZodNonOptional=$constructor(`$ZodNonOptional`,(e,t)=>{$ZodType.init(e,t),defineLazyInternal(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>handleNonOptionalResult(t,e)):handleNonOptionalResult(i,e)}});function handleNonOptionalResult(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function handleCatchResult(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>finalizeIssue(e,r,config()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var $ZodCatch=$constructor(`$ZodCatch`,(e,t)=>{$ZodType.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),defineLazyInternal(e,`optout`,e=>e.def.innerType._zod.optout),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>handleCatchResult(e,r,t,n)):handleCatchResult(e,r,t,n)}}),$ZodPipe=$constructor(`$ZodPipe`,(e,t)=>{$ZodType.init(e,t),defineLazyInternal(e,`values`,e=>e.def.in._zod.values),defineLazyInternal(e,`optin`,e=>e.def.in._zod.optin),defineLazyInternal(e,`optout`,e=>e.def.out._zod.optout),defineLazyInternal(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>handlePipeResult(e,t.in,n)):handlePipeResult(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>handlePipeResult(e,t.out,n)):handlePipeResult(r,t.out,n)}});function handlePipeResult(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var $ZodReadonly=$constructor(`$ZodReadonly`,(e,t)=>{$ZodType.init(e,t),defineLazyInternal(e,`propValues`,e=>e.def.innerType._zod.propValues),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),defineLazyInternal(e,`optin`,e=>e.def.innerType?._zod?.optin),defineLazyInternal(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(handleReadonlyResult):handleReadonlyResult(r)}});function handleReadonlyResult(e){return e.memo||(e.value=Object.freeze(e.value)),e}var $ZodCustom=$constructor(`$ZodCustom`,(e,t)=>{$ZodCheck.init(e,t),$ZodType.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>handleRefineResult(t,n,r,e));handleRefineResult(i,n,r,e)}});function handleRefineResult(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(issue(e))}}var $ZodCyclicError=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},STATE=`~memo`,NO_ISSUES=[];function cloneIssues(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var recursive=new WeakMap;function isRecursive(e,t){let n=recursive.get(e);if(n!==void 0)return n;if(t.has(e))return!0;t.add(e);let r=!1,i=e=>{!r&&e?._zod&&isRecursive(e,t)&&(r=!0)},a=e._zod.def;if(a.type===`lazy`)i(e._zod.innerType);else{let e=a.shape;if(e)for(let t of Reflect.ownKeys(e))i(e[t]);for(let e in a){let t=a[e];if(t&&typeof t==`object`){if(t._zod)i(t);else if(Array.isArray(t))for(let e of t)i(e)}}}return t.delete(e),recursive.set(e,r),r}function bucketFor(e,t){let n=e.buckets.get(t);return n||(n=new Map,e.buckets.set(t,n)),n}var handoff,open=[],memo={alloc(e,t,n){let r=handoff;if(!r)return n;handoff=void 0;let i={value:n,issues:null};return r.set(t.value,i),open.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&isBackEdge(n,e.value))throw new $ZodCyclicError;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r,i;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,a=(o,s)=>{if(n===void 0&&(n=isRecursive(e,new Set),!n))return e._zod.parse=t,e._zod.run===a&&(e._zod.run=t),t(o,s);let c=o.value;if(typeof c!=`object`||!c)return t(o,s);let l=s[STATE];l||(l={buckets:new Map,backEdges:void 0},s[STATE]=l);let u;r===s?u=i:(u=bucketFor(l,e),r=s,i=u);let d=u.get(c);if(d)return o.value=d.value,d.issues?d.issues.length&&o.issues.push(...cloneIssues(d.issues)):(o.memo=!0,l.backEdges??(l.backEdges=new Set),l.backEdges.add(d.value)),o;handoff=u;let f=open.length,p=t(o,s);handoff=void 0;let m=open.length>f?open.pop():void 0;return p instanceof Promise?p.then(e=>(m&&(m.issues=e.issues.length?cloneIssues(e.issues):NO_ISSUES),e)):(m&&(m.issues=p.issues.length?cloneIssues(p.issues):NO_ISSUES),p)};e._zod.parse=a,e._zod.run===t&&(e._zod.run=a)})}};function memoizer(){return memo}function isBackEdge(e,t){let n=e[STATE]?.backEdges;return n!==void 0&&typeof t==`object`&&!!t&&n.has(t)}var error$1=()=>{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(t){return e[t]??null}let n={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`,credit_card:`credit card number`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(parsedType(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${stringifyPrimitive(e.values[0])}`:`Invalid option: expected one of ${joinValues(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${joinValues(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function en_default(){return{localeError:error$1()}}var _a,$ZodRegistry=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function registry(){return new $ZodRegistry}(_a=globalThis).__zod_globalRegistry??(_a.__zod_globalRegistry=registry());var globalRegistry=globalThis.__zod_globalRegistry;function _string(e,t){return new e({type:`string`,...normalizeParams(t)})}function _email(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _guid(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _uuid(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _uuidv4(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...normalizeParams(t)})}function _uuidv6(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...normalizeParams(t)})}function _uuidv7(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...normalizeParams(t)})}function _url(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _emoji(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _nanoid(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cuid(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cuid2(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ulid(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _xid(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ksuid(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ipv4(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ipv6(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cidrv4(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cidrv6(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _base64(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _base64url(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _e164(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _jwt(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _isoDateTime(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...normalizeParams(t)})}function _isoDate(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...normalizeParams(t)})}function _isoTime(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...normalizeParams(t)})}function _isoDuration(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...normalizeParams(t)})}function _number(e,t){return new e({type:`number`,checks:[],...normalizeParams(t)})}function _int(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...normalizeParams(t)})}function _boolean(e,t){return new e({type:`boolean`,...normalizeParams(t)})}function _unknown(e){return new e({type:`unknown`})}function _never(e,t){return new e({type:`never`,...normalizeParams(t)})}function _lt(e,t){return new $ZodCheckLessThan({check:`less_than`,...normalizeParams(t),value:e,inclusive:!1})}function _lte(e,t){return new $ZodCheckLessThan({check:`less_than`,...normalizeParams(t),value:e,inclusive:!0})}function _gt(e,t){return new $ZodCheckGreaterThan({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!1})}function _gte(e,t){return new $ZodCheckGreaterThan({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!0})}function _multipleOf(e,t){return new $ZodCheckMultipleOf({check:`multiple_of`,...normalizeParams(t),value:e})}function _maxLength(e,t){return new $ZodCheckMaxLength({check:`max_length`,...normalizeParams(t),maximum:e})}function _minLength(e,t){return new $ZodCheckMinLength({check:`min_length`,...normalizeParams(t),minimum:e})}function _length(e,t){return new $ZodCheckLengthEquals({check:`length_equals`,...normalizeParams(t),length:e})}function _regex(e,t){return new $ZodCheckRegex({check:`string_format`,format:`regex`,...normalizeParams(t),pattern:e})}function _lowercase(e){return new $ZodCheckLowerCase({check:`string_format`,format:`lowercase`,...normalizeParams(e)})}function _uppercase(e){return new $ZodCheckUpperCase({check:`string_format`,format:`uppercase`,...normalizeParams(e)})}function _includes(e,t){return new $ZodCheckIncludes({check:`string_format`,format:`includes`,...normalizeParams(t),includes:e})}function _startsWith(e,t){return new $ZodCheckStartsWith({check:`string_format`,format:`starts_with`,...normalizeParams(t),prefix:e})}function _endsWith(e,t){return new $ZodCheckEndsWith({check:`string_format`,format:`ends_with`,...normalizeParams(t),suffix:e})}function _overwrite(e){return new $ZodCheckOverwrite({check:`overwrite`,tx:e})}function _normalize(e){return _overwrite(t=>t.normalize(e))}function _trim(){return _overwrite(e=>e.trim())}function _toLowerCase(){return _overwrite(e=>e.toLowerCase())}function _toUpperCase(){return _overwrite(e=>e.toUpperCase())}function _slugify(){return _overwrite(e=>slugify(e))}function _array(e,t,n){return new e({type:`array`,element:t,...normalizeParams(n)})}function _refine(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...normalizeParams(n)})}function _superRefine(e,t){let n=_check(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(issue(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(issue(r))}},e(t.value,t)),t);return n}function _check(e,t){let n=new $ZodCheck({check:`custom`,...normalizeParams(t)});return n._zod.check=e,n}function assignProps(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&assignProp(e,t,n[t]);return e}function initializeContext(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??globalRegistry,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],external:e?.external??void 0}}function handleUnrepresentable(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function process(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,process(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&assignProps(o.schema,c),t.io===`input`&&isTransforming(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function encodeJSONPointerSegment(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function extractDefs(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${encodeJSONPointerSegment(a)}`}}let i=`#`,a=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let o=t[1].schema.id??`__schema${e.counter++}`;return{defId:o,ref:a+encodeJSONPointerSegment(o)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
51
|
-
|
|
52
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}e.external&&(e.sharedDefsExtractedFor=e.external)}function compactTypeUnion(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;compactTypeUnion(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var FOLDABLE_KEYS=new Set([`type`,`properties`,`required`,`additionalProperties`]),UNION_KEYS=[`oneOf`,`anyOf`];function undeclaredConstraint(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function foldObjects(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!FOLDABLE_KEYS.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??undeclaredConstraint(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}assignProp(n,r,e.length===1?e[0]:foldObjects(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=undeclaredConstraint(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function foldIntersection(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of FOLDABLE_KEYS)if(t in e)return;let n=t.filter(e=>UNION_KEYS.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=foldObjects(t);else{let e=n[0],i=UNION_KEYS.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>foldObjects([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,assignProps(e,r))}function finalize(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):assignProps(i,s),assignProps(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())compactTypeUnion(t[1].def??t[1].schema);if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])foldIntersection(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}assignProps(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,assignProp(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:createStandardJSONSchemaMethod(t,`input`,e.processors),output:createStandardJSONSchemaMethod(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function isTransforming(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return isTransforming(r.element,n);if(r.type===`set`)return isTransforming(r.valueType,n);if(r.type===`lazy`)return isTransforming(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return isTransforming(r.innerType,n);if(r.type===`intersection`)return isTransforming(r.left,n)||isTransforming(r.right,n);if(r.type===`record`||r.type===`map`)return isTransforming(r.keyType,n)||isTransforming(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:isTransforming(r.in,n)||isTransforming(r.out,n);if(r.type===`object`){for(let e in r.shape)if(isTransforming(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(isTransforming(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(isTransforming(e,n))return!0;return!!(r.rest&&isTransforming(r.rest,n))}return!1}var createToJSONSchemaMethod=(e,t={})=>n=>{let r=initializeContext({...n,processors:t});return process(e,r),extractDefs(r,e),finalize(r,e)},createStandardJSONSchemaMethod=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=initializeContext({...i??{},target:a,io:t,processors:n});return process(e,o),extractDefs(o,e),finalize(o,e)},formatMap={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},stringProcessor=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=formatMap[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},numberProcessor=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(Number.isFinite(c)&&c!==0?i.multipleOf=Math.abs(c):handleUnrepresentable(e,t,i,r,`A multipleOf divisor of ${c} cannot be represented in JSON Schema`))},booleanProcessor=(e,t,n,r)=>{n.type=`boolean`},bigintProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`BigInt cannot be represented in JSON Schema`)},symbolProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Symbols cannot be represented in JSON Schema`)},nullProcessor=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},undefinedProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Undefined cannot be represented in JSON Schema`)},voidProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Void cannot be represented in JSON Schema`)},neverProcessor=(e,t,n,r)=>{n.not={}},anyProcessor=(e,t,n,r)=>{},unknownProcessor=(e,t,n,r)=>{},dateProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Date cannot be represented in JSON Schema`)},enumProcessor=(e,t,n,r)=>{let i=e._zod.def,a=getEnumValues(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},literalProcessor=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(handleUnrepresentable(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(handleUnrepresentable(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},nanProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`NaN cannot be represented in JSON Schema`)},templateLiteralProcessor=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},fileProcessor=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},successProcessor=(e,t,n,r)=>{n.type=`boolean`},customProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},functionProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Function types cannot be represented in JSON Schema`)},transformProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},mapProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Map cannot be represented in JSON Schema`)},setProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Set cannot be represented in JSON Schema`)},arrayProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=process(a.element,t,{...r,path:[...r.path,`items`]})};function inputOptin(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?inputOptin(t.out):t.type===`catch`?inputOptin(t.innerType):e._zod.optin}var objectProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&handleUnrepresentable(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)assignProp(i.properties,e,process(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e];return t.io===`input`?inputOptin(n)===void 0:n._zod.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=process(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},unionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>process(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},intersectionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=process(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=process(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},tupleProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>process(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?process(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?inputOptin(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=e._zod.bag;typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)},recordProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=process(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)assignProp(i.patternProperties,t.source,e)}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=process(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=process(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values,l=t.io===`input`&&inputOptin(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},nullableProcessor=(e,t,n,r)=>{let i=e._zod.def,a=process(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},nonoptionalProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(handleUnrepresentable(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),UNREPRESENTABLE_DEFAULT):JSON.parse(o)}var defaultProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=serializeDefaultValue(i.defaultValue,e,t,n,r);o!==UNREPRESENTABLE_DEFAULT&&(n.default=o)},prefaultProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=serializeDefaultValue(i.defaultValue,e,t,n,r);o!==UNREPRESENTABLE_DEFAULT&&(n._prefault=o)},catchProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{handleUnrepresentable(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},pipeProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;process(o,t,r);let s=t.seen.get(e);s.ref=o},readonlyProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},promiseProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},optionalProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},lazyProcessor=(e,t,n,r)=>{let i=e._zod.innerType;process(i,t,r);let a=t.seen.get(e);a.ref=i},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(e,t){if(`_idmap`in e){let n=e,r=initializeContext({...t,processors:allProcessors}),i={};for(let e of n._idmap.entries()){let[t,n]=e;process(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;extractDefs(r,n),assignProp(a,t,finalize(r,n))}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=initializeContext({...t,processors:allProcessors});return process(e,n),extractDefs(n,e),finalize(n,e)}var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var initializer=(e,t)=>{$ZodError.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);_installedErrorProtos.has(n)||(_installedErrorProtos.add(n),_lazyMethod(n,`format`,e=>t=>formatError(e,t)),_lazyMethod(n,`flatten`,e=>t=>flattenError(e,t)),_lazyMethod(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}),_lazyMethod(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},ZodRealError=$constructor(`ZodError`,initializer,void 0,{Parent:Error}),parse=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse=_safeParse(ZodRealError),safeParseAsync=_safeParseAsync(ZodRealError),encode=_encode(ZodRealError),decode=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError);function _ensureDefaultLocale(){globalConfig.localeError||config(en_default())}function _ensureDefaultMemoizer(){globalConfig.memoizer||config({memoizer:memoizer()})}var ZodType=$constructor(`ZodType`,(e,t)=>(_ensureDefaultLocale(),$ZodType.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(mergeDefs(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return clone(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(refine(e,t))},superRefine(e,t){return this.check(superRefine(e,t))},overwrite(e){return this.check(_overwrite(e))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(e){return nonoptional(this,e)},array(){return array(this)},or(e){return union([this,e])},and(e){return intersection(this,e)},transform(e){return pipe(this,transform(e))},default(e){return _default(this,e)},prefault(e){return prefault(this,e)},catch(e){return _catch(this,e)},pipe(e){return pipe(this,e)},readonly(){return readonly(this)},describe(e){let t=this.clone();return globalRegistry.add(t,{description:e}),t},meta(...e){if(e.length===0)return globalRegistry.get(this);let t=this.clone();return globalRegistry.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return hide(this,`~standard`,{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,`input`),output:createStandardJSONSchemaMethod(this,`output`)}})},set"~standard"(e){own(this,`~standard`,e)},parse:function e(t,n){return parse(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await parseAsync(this,t,n,{callee:e})},safeParse(e,t){return safeParse(this,e,t)},async safeParseAsync(e,t){return safeParseAsync(this,e,t)},get spa(){return this.safeParseAsync},set spa(e){own(this,`spa`,e)},encode:function e(t,n){return encode(this,t,n,{callee:e})},decode:function e(t,n){return decode(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await encodeAsync(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await decodeAsync(this,t,n,{callee:e})},safeEncode(e,t){return safeEncode(this,e,t)},safeDecode(e,t){return safeDecode(this,e,t)},async safeEncodeAsync(e,t){return safeEncodeAsync(this,e,t)},async safeDecodeAsync(e,t){return safeDecodeAsync(this,e,t)},get toJSONSchema(){return own(this,`toJSONSchema`,createToJSONSchemaMethod(this,{}))},set toJSONSchema(e){own(this,`toJSONSchema`,e)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}}),_ZodString=$constructor(`_ZodString`,(e,t)=>{$ZodString.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>stringProcessor(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null},{regex(...e){return this.check(_regex(...e))},includes(...e){return this.check(_includes(...e))},startsWith(...e){return this.check(_startsWith(...e))},endsWith(...e){return this.check(_endsWith(...e))},min(...e){return this.check(_minLength(...e))},max(...e){return this.check(_maxLength(...e))},length(...e){return this.check(_length(...e))},nonempty(...e){return this.check(_minLength(1,...e))},lowercase(e){return this.check(_lowercase(e))},uppercase(e){return this.check(_uppercase(e))},trim(){return this.check(_trim())},normalize(...e){return this.check(_normalize(...e))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}}),ZodString=$constructor(`ZodString`,(e,t)=>{$ZodString.init(e,t),_ZodString.init(e,t)},{email(e){return this.check(_email(ZodEmail,e))},url(e){return this.check(_url(ZodURL,e))},jwt(e){return this.check(_jwt(ZodJWT,e))},emoji(e){return this.check(_emoji(ZodEmoji,e))},guid(e){return this.check(_guid(ZodGUID,e))},uuid(e){return this.check(_uuid(ZodUUID,e))},uuidv4(e){return this.check(_uuidv4(ZodUUID,e))},uuidv6(e){return this.check(_uuidv6(ZodUUID,e))},uuidv7(e){return this.check(_uuidv7(ZodUUID,e))},nanoid(e){return this.check(_nanoid(ZodNanoID,e))},cuid(e){return this.check(_cuid(ZodCUID,e))},cuid2(e){return this.check(_cuid2(ZodCUID2,e))},ulid(e){return this.check(_ulid(ZodULID,e))},base64(e){return this.check(_base64(ZodBase64,e))},base64url(e){return this.check(_base64url(ZodBase64URL,e))},xid(e){return this.check(_xid(ZodXID,e))},ksuid(e){return this.check(_ksuid(ZodKSUID,e))},ipv4(e){return this.check(_ipv4(ZodIPv4,e))},ipv6(e){return this.check(_ipv6(ZodIPv6,e))},cidrv4(e){return this.check(_cidrv4(ZodCIDRv4,e))},cidrv6(e){return this.check(_cidrv6(ZodCIDRv6,e))},e164(e){return this.check(_e164(ZodE164,e))},datetime(e){return this.check(_isoDateTime(ZodISODateTime,e))},date(e){return this.check(_isoDate(ZodISODate,e))},time(e){return this.check(_isoTime(ZodISOTime,e))},duration(e){return this.check(_isoDuration(ZodISODuration,e))}});function string(e){return _string(ZodString,e)}var ZodStringFormat=$constructor(`ZodStringFormat`,(e,t)=>{$ZodStringFormat.init(e,t),_ZodString.init(e,t)}),ZodISODateTime=$constructor(`ZodISODateTime`,(e,t)=>{$ZodISODateTime.init(e,t),ZodStringFormat.init(e,t)}),ZodISODate=$constructor(`ZodISODate`,(e,t)=>{$ZodISODate.init(e,t),ZodStringFormat.init(e,t)}),ZodISOTime=$constructor(`ZodISOTime`,(e,t)=>{$ZodISOTime.init(e,t),ZodStringFormat.init(e,t)}),ZodISODuration=$constructor(`ZodISODuration`,(e,t)=>{$ZodISODuration.init(e,t),ZodStringFormat.init(e,t)}),ZodEmail=$constructor(`ZodEmail`,(e,t)=>{$ZodEmail.init(e,t),ZodStringFormat.init(e,t)}),ZodGUID=$constructor(`ZodGUID`,(e,t)=>{$ZodGUID.init(e,t),ZodStringFormat.init(e,t)}),ZodUUID=$constructor(`ZodUUID`,(e,t)=>{$ZodUUID.init(e,t),ZodStringFormat.init(e,t)}),ZodURL=$constructor(`ZodURL`,(e,t)=>{$ZodURL.init(e,t),ZodStringFormat.init(e,t)}),ZodEmoji=$constructor(`ZodEmoji`,(e,t)=>{$ZodEmoji.init(e,t),ZodStringFormat.init(e,t)}),ZodNanoID=$constructor(`ZodNanoID`,(e,t)=>{$ZodNanoID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID=$constructor(`ZodCUID`,(e,t)=>{$ZodCUID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID2=$constructor(`ZodCUID2`,(e,t)=>{$ZodCUID2.init(e,t),ZodStringFormat.init(e,t)}),ZodULID=$constructor(`ZodULID`,(e,t)=>{$ZodULID.init(e,t),ZodStringFormat.init(e,t)}),ZodXID=$constructor(`ZodXID`,(e,t)=>{$ZodXID.init(e,t),ZodStringFormat.init(e,t)}),ZodKSUID=$constructor(`ZodKSUID`,(e,t)=>{$ZodKSUID.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv4=$constructor(`ZodIPv4`,(e,t)=>{$ZodIPv4.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv6=$constructor(`ZodIPv6`,(e,t)=>{$ZodIPv6.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv4=$constructor(`ZodCIDRv4`,(e,t)=>{$ZodCIDRv4.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv6=$constructor(`ZodCIDRv6`,(e,t)=>{$ZodCIDRv6.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64=$constructor(`ZodBase64`,(e,t)=>{$ZodBase64.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64URL=$constructor(`ZodBase64URL`,(e,t)=>{$ZodBase64URL.init(e,t),ZodStringFormat.init(e,t)}),ZodE164=$constructor(`ZodE164`,(e,t)=>{$ZodE164.init(e,t),ZodStringFormat.init(e,t)}),ZodJWT=$constructor(`ZodJWT`,(e,t)=>{$ZodJWT.init(e,t),ZodStringFormat.init(e,t)}),ZodNumber=$constructor(`ZodNumber`,(e,t)=>{$ZodNumber.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>numberProcessor(e,t,n,r);let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null},{gt(e,t){return this.check(_gt(e,t))},gte(e,t){return this.check(_gte(e,t))},min(e,t){return this.check(_gte(e,t))},lt(e,t){return this.check(_lt(e,t))},lte(e,t){return this.check(_lte(e,t))},max(e,t){return this.check(_lte(e,t))},int(e){return this.check(int(e))},safe(e){return this.check(int(e))},positive(e){return this.check(_gt(0,e))},nonnegative(e){return this.check(_gte(0,e))},negative(e){return this.check(_lt(0,e))},nonpositive(e){return this.check(_lte(0,e))},multipleOf(e,t){return this.check(_multipleOf(e,t))},step(e,t){return this.check(_multipleOf(e,t))},finite(){return this}});function number(e){return _number(ZodNumber,e)}var ZodNumberFormat=$constructor(`ZodNumberFormat`,(e,t)=>{$ZodNumberFormat.init(e,t),ZodNumber.init(e,t)});function int(e){return _int(ZodNumberFormat,e)}var ZodBoolean=$constructor(`ZodBoolean`,(e,t)=>{$ZodBoolean.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>booleanProcessor(e,t,n,r)});function boolean(e){return _boolean(ZodBoolean,e)}var ZodUnknown=$constructor(`ZodUnknown`,(e,t)=>{$ZodUnknown.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>unknownProcessor(e,t,n,r)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor(`ZodNever`,(e,t)=>{$ZodNever.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>neverProcessor(e,t,n,r)});function never(e){return _never(ZodNever,e)}var ZodArray=$constructor(`ZodArray`,(e,t)=>{_ensureDefaultMemoizer(),$ZodArray.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>arrayProcessor(e,t,n,r),e.element=t.element},{min(e,t){return this.check(_minLength(e,t))},nonempty(e){return this.check(_minLength(1,e))},max(e,t){return this.check(_maxLength(e,t))},length(e,t){return this.check(_length(e,t))},unwrap(){return this.element}});function array(e,t){return _array(ZodArray,e,t)}var ZodObject=$constructor(`ZodObject`,(e,t)=>{_ensureDefaultMemoizer(),$ZodObjectJIT.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>objectProcessor(e,t,n,r),installLazyProp(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:unknown()})},loose(){return this.clone({...this._zod.def,catchall:unknown()})},strict(){return this.clone({...this._zod.def,catchall:never()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return extend(this,e)},safeExtend(e){return safeExtend(this,e)},merge(e){return merge(this,e)},pick(e){return pick(this,e)},omit(e){return omit(this,e)},partial(...e){return partial(ZodOptional,this,e[0])},exactPartial(...e){return partial(ZodExactOptional,this,e[0],`exactPartial`)},required(...e){return required(ZodNonOptional,this,e[0])}});function object(e,t){return new ZodObject({type:`object`,shape:e??{},...normalizeParams(t)})}var ZodUnion=$constructor(`ZodUnion`,(e,t)=>{$ZodUnion.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>unionProcessor(e,t,n,r),e.options=t.options});function union(e,t){return new ZodUnion({type:`union`,options:e,...normalizeParams(t)})}var ZodIntersection=$constructor(`ZodIntersection`,(e,t)=>{$ZodIntersection.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>intersectionProcessor(e,t,n,r)});function intersection(e,t){return new ZodIntersection({type:`intersection`,left:e,right:t})}var ZodEnum=$constructor(`ZodEnum`,(e,t)=>{$ZodEnum.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>enumProcessor(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new ZodEnum({...t,checks:[],...normalizeParams(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new ZodEnum({...t,checks:[],...normalizeParams(r),entries:i})}});function _enum(e,t){return new ZodEnum({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...normalizeParams(t)})}var ZodTransform=$constructor(`ZodTransform`,(e,t)=>{_ensureDefaultMemoizer(),$ZodTransform.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>transformProcessor(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(issue(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(issue(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function transform(e){return new ZodTransform({type:`transform`,transform:e})}var ZodOptional=$constructor(`ZodOptional`,(e,t)=>{$ZodOptional.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new ZodOptional({type:`optional`,innerType:e})}var ZodExactOptional=$constructor(`ZodExactOptional`,(e,t)=>{$ZodExactOptional.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function exactOptional(e){return new ZodExactOptional({type:`optional`,innerType:e})}var ZodNullable=$constructor(`ZodNullable`,(e,t)=>{$ZodNullable.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nullableProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new ZodNullable({type:`nullable`,innerType:e})}var ZodDefault=$constructor(`ZodDefault`,(e,t)=>{$ZodDefault.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>defaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new ZodDefault({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}var ZodPrefault=$constructor(`ZodPrefault`,(e,t)=>{$ZodPrefault.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>prefaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new ZodPrefault({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}var ZodNonOptional=$constructor(`ZodNonOptional`,(e,t)=>{$ZodNonOptional.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nonoptionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new ZodNonOptional({type:`nonoptional`,innerType:e,...normalizeParams(t)})}var ZodCatch=$constructor(`ZodCatch`,(e,t)=>{$ZodCatch.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>catchProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new ZodCatch({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:constantCatch(t)})}var ZodPipe=$constructor(`ZodPipe`,(e,t)=>{$ZodPipe.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pipeProcessor(e,t,n,r),e.in=t.in,e.out=t.out});function pipe(e,t){return new ZodPipe({type:`pipe`,in:e,out:t})}var ZodReadonly=$constructor(`ZodReadonly`,(e,t)=>{$ZodReadonly.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>readonlyProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function readonly(e){return new ZodReadonly({type:`readonly`,innerType:e})}var ZodCustom=$constructor(`ZodCustom`,(e,t)=>{$ZodCustom.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>customProcessor(e,t,n,r)});function refine(e,t={}){return _refine(ZodCustom,e,t)}function superRefine(e,t){return _superRefine(e,t)}var InvokeErrorTypes={NETWORK_ERROR:`network_error`,RATE_LIMIT:`rate_limit`,SERVER_ERROR:`server_error`,NO_TOOL_CALL:`no_tool_call`,INVALID_TOOL_ARGS:`invalid_tool_args`,TOOL_EXECUTION_ERROR:`tool_execution_error`,INVALID_RESPONSE:`invalid_response`,INVALID_SCHEMA:`invalid_schema`,UNKNOWN:`unknown`,CONFIG_ERROR:`config_error`,AUTH_ERROR:`auth_error`,CONTEXT_LENGTH:`context_length`,CONTENT_FILTER:`content_filter`},RETRYABLE_TYPES=[InvokeErrorTypes.NETWORK_ERROR,InvokeErrorTypes.RATE_LIMIT,InvokeErrorTypes.SERVER_ERROR,InvokeErrorTypes.NO_TOOL_CALL,InvokeErrorTypes.INVALID_TOOL_ARGS,InvokeErrorTypes.TOOL_EXECUTION_ERROR,InvokeErrorTypes.INVALID_RESPONSE,InvokeErrorTypes.INVALID_SCHEMA,InvokeErrorTypes.UNKNOWN],InvokeError=class extends Error{type;retryable;statusCode;rawError;rawResponse;constructor(e,t,n,r){super(t),this.name=`InvokeError`,this.type=e,this.retryable=RETRYABLE_TYPES.includes(e),this.rawError=n,this.rawResponse=r}};function stringReplaceAll(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.slice(a),o}function stringEncaseCRLFWithFirstIndex(e,t,n,r){let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.slice(i,o?r-1:r)+t+(o?`\r
|
|
53
|
-
`:`
|
|
54
|
-
`)+n,i=r+1,r=e.indexOf(`
|
|
55
|
-
`,i)}while(r!==-1);return a+=e.slice(i),a}var ANSI_BACKGROUND_OFFSET=10,ANSI_UNDERLINE_OFFSET=20,wrapAnsi16=(e=0)=>t=>`\u{1B}[${t+e}m`,wrapAnsi256=(e=0)=>t=>`\u{1B}[${38+e};5;${t}m`,wrapAnsi16m=(e=0)=>(t,n,r)=>`\u{1B}[${38+e};2;${t};${n};${r}m`,wrapUnderlineAnsi=e=>`\u{1B}[58;5;${e<90?e-30:e-90+8}m`,styles$1={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],underlineDouble:[`4:2`,24],underlineCurly:[`4:3`,24],underlineDotted:[`4:4`,24],underlineDashed:[`4:5`,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]},underlineColor:{underlineBlack:[`58;5;0`,59],underlineRed:[`58;5;1`,59],underlineGreen:[`58;5;2`,59],underlineYellow:[`58;5;3`,59],underlineBlue:[`58;5;4`,59],underlineMagenta:[`58;5;5`,59],underlineCyan:[`58;5;6`,59],underlineWhite:[`58;5;7`,59],underlineBlackBright:[`58;5;8`,59],underlineGray:[`58;5;8`,59],underlineGrey:[`58;5;8`,59],underlineRedBright:[`58;5;9`,59],underlineGreenBright:[`58;5;10`,59],underlineYellowBright:[`58;5;11`,59],underlineBlueBright:[`58;5;12`,59],underlineMagentaBright:[`58;5;13`,59],underlineCyanBright:[`58;5;14`,59],underlineWhiteBright:[`58;5;15`,59]}},modifierNames=Object.keys(styles$1.modifier),foregroundColorNames=Object.keys(styles$1.color),backgroundColorNames=Object.keys(styles$1.bgColor),underlineColorNames=Object.keys(styles$1.underlineColor),colorNames=[...foregroundColorNames,...backgroundColorNames];function assembleStyles(){let e=new Map;for(let[t,n]of Object.entries(styles$1)){for(let[t,r]of Object.entries(n))styles$1[t]={open:`\u{1B}[${r[0]}m`,close:`\u{1B}[${r[1]}m`},n[t]=styles$1[t],e.set(Number.parseInt(r[0],10),r[1]);Object.defineProperty(styles$1,t,{value:n,enumerable:!1})}return Object.defineProperty(styles$1,"codes",{value:e,enumerable:!1}),styles$1.color.close=`\x1B[39m`,styles$1.bgColor.close=`\x1B[49m`,styles$1.underlineColor.close=`\x1B[59m`,styles$1.color.ansi=wrapAnsi16(),styles$1.color.ansi256=wrapAnsi256(),styles$1.color.ansi16m=wrapAnsi16m(),styles$1.bgColor.ansi=wrapAnsi16(ANSI_BACKGROUND_OFFSET),styles$1.bgColor.ansi256=wrapAnsi256(ANSI_BACKGROUND_OFFSET),styles$1.bgColor.ansi16m=wrapAnsi16m(ANSI_BACKGROUND_OFFSET),styles$1.underlineColor.ansi=wrapUnderlineAnsi,styles$1.underlineColor.ansi256=wrapAnsi256(ANSI_UNDERLINE_OFFSET),styles$1.underlineColor.ansi16m=wrapAnsi16m(ANSI_UNDERLINE_OFFSET),Object.defineProperties(styles$1,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[\da-f]{6}|[\da-f]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>styles$1.rgbToAnsi256(...styles$1.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(e)),enumerable:!1}}),styles$1}var ansiStyles=assembleStyles(),level=`navigator`in globalThis?globalThis.navigator.userAgentData&&globalThis.navigator.userAgentData.brands.find(({brand:e})=>e===`Chromium`)?.version>93?3:+!!/\b(?:Chrome|Chromium)\//.test(globalThis.navigator.userAgent):0,colorSupport=level!==0&&{level,hasBasic:!0,has256:level>=2,has16m:level>=3},supportsColor={stdout:colorSupport,stderr:colorSupport},{stdout:stdoutColor,stderr:stderrColor}=supportsColor,GENERATOR=Symbol(`GENERATOR`),STYLER=Symbol(`STYLER`),IS_EMPTY=Symbol(`IS_EMPTY`),LEVEL=Symbol(`LEVEL`),styles=Object.create(null),assertValidLevel=e=>{if(!Number.isSafeInteger(e)||e<0||e>3)throw Error("The `level` should be an integer from 0 to 3")},levelDescriptor={enumerable:!0,get(){return this[LEVEL]},set(e){assertValidLevel(e),this[LEVEL]=e}},applyOptions=(e,t={})=>{t.level!==void 0&&assertValidLevel(t.level);let n=stdoutColor?stdoutColor.level:0;e[LEVEL]=t.level===void 0?n:t.level},chalkFactory=e=>{let t=(...e)=>e.join(` `);return applyOptions(t,e),Object.setPrototypeOf(t,createChalk.prototype),t};function createChalk(e){return chalkFactory(e)}Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(let[e,t]of Object.entries(ansiStyles))styles[e]={get(){let n=createBuilder(this,createStyler(t.open,t.close,this[STYLER]),this[IS_EMPTY]);return Object.defineProperty(this,e,{value:n}),n}};styles.visible={get(){let e=createBuilder(this,this[STYLER],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var createModelConverters=(e,t)=>{let n=ansiStyles[t];if(e===`rgb`){let e=(e,t,r)=>n.ansi(ansiStyles.rgbToAnsi(e,t,r));return[e,e,(e,t,r)=>n.ansi256(ansiStyles.rgbToAnsi256(e,t,r)),n.ansi16m]}if(e===`hex`){let e=e=>n.ansi(ansiStyles.hexToAnsi(e));return[e,e,e=>n.ansi256(ansiStyles.hexToAnsi256(e)),e=>n.ansi16m(...ansiStyles.hexToRgb(e))]}let r=e=>n.ansi(ansiStyles.ansi256ToAnsi(e));return[r,r,n.ansi256,n.ansi256]};for(let e of[`rgb`,`hex`,`ansi256`]){let t=e[0].toUpperCase()+e.slice(1);for(let[n,r]of[[e,`color`],[`bg`+t,`bgColor`],[`underline`+t,`underlineColor`]]){let{close:t}=ansiStyles[r],i=createModelConverters(e,r);styles[n]={get(){let e=function(e,n,r){let a=i[this.level](e,n,r);return createBuilder(this,createStyler(a,t,this[STYLER]),this[IS_EMPTY])};return Object.defineProperty(this,n,{value:e}),e}}}}var proto=Object.defineProperties(()=>{},{...styles,level:{enumerable:!0,get(){return this[GENERATOR].level},set(e){this[GENERATOR].level=e}}}),createStyler=(e,t,n)=>{let r,i;return n===void 0?(r=e,i=t):(r=n.openAll+e,i=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:n}},createBuilder=(e,t,n)=>{let r=(...e)=>e.length===1?applyStyle(r,``+e[0]):e.length===2?applyStyle(r,e[0]+` `+e[1]):applyStyle(r,e.join(` `));return Object.setPrototypeOf(r,proto),r[GENERATOR]=e[GENERATOR]??e,r[STYLER]=t,r[IS_EMPTY]=n,r},applyStyle=(e,t)=>{if(e[GENERATOR][LEVEL]<=0||!t)return e[IS_EMPTY]?``:t;let n=e[STYLER];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes(`\x1B`))for(;n!==void 0;)t=stringReplaceAll(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
|
|
56
|
-
`);return a!==-1&&(t=stringEncaseCRLFWithFirstIndex(t,i,r,a)),r+t+i};Object.defineProperties(createChalk.prototype,{...styles,level:levelDescriptor});var chalk=createChalk(),chalkStderr=createChalk({level:stderrColor?stderrColor.level:0});function debug(...e){console.debug(chalk.gray(`[LLM]`),...e)}function zodToOpenAITool(e,t){return{type:`function`,function:{name:e,description:t.description,parameters:toJSONSchema(t.inputSchema,{target:`openapi-3.0`})}}}function modelPatch(e,t){let n=e.model||``;if(!n)return e;let r=getProvider(t),i=normalizeModelName(n);if(i.startsWith(`qwen`)&&(r===`openrouter`&&i.startsWith(`qwen38-max`)?(debug(`Patch Qwen3.8-max on OpenRouter: reasoning_effort=low, remove tool_choice`),e.reasoning_effort=`low`,delete e.tool_choice):(debug(`Patch Qwen: disable thinking`),e.enable_thinking=!1),e.temperature===void 0&&!/max|plus/.test(i)&&(debug(`Patch Qwen: raise temperature to 1.0`),e.temperature=1)),i.startsWith(`deepseek`)&&(debug(`Patch DeepSeek: disable thinking, remove tool_choice`),e.thinking={type:`disabled`},delete e.tool_choice),i.startsWith(`gpt`)&&(i.startsWith(`gpt-5`)&&(e.verbosity=`low`),i.includes(`chat-latest`)?(debug(`Patch chat-latest: omit reasoning_effort and temperature`),delete e.reasoning_effort,delete e.temperature):/^gpt-5[12](-|$)/.test(i)?(debug(`Patch GPT-5.1/5.2: reasoning_effort=none`),e.reasoning_effort=`none`):/^gpt-5(-|$)/.test(i)?(debug(`Patch GPT-5: reasoning_effort=minimal`),e.reasoning_effort=`minimal`):(debug(`Patch GPT: omit reasoning_effort`),delete e.reasoning_effort)),i.startsWith(`claude`)&&(/opus|sonnet|haiku/.test(i)?(debug(`Patch Claude: disable thinking`),e.thinking={type:`disabled`},r!==`openrouter`&&(e.tool_choice===`required`?(debug(`Applying Claude patch: convert tool_choice "required" to { type: "any" }`),e.tool_choice={type:`any`}):e.tool_choice?.function?.name&&(debug(`Applying Claude patch: convert tool_choice format`),e.tool_choice={type:`tool`,name:e.tool_choice.function.name}))):(debug(`Patch Claude: reasoning_effort=low`),e.reasoning_effort=`low`,delete e.tool_choice)),i.startsWith(`gemini`)&&(debug(`Patch Gemini: reasoning_effort=low`),e.reasoning_effort=`low`,/^gemini-25(?!.*pro)/.test(i)?(debug(`Patch Gemini 2.5 non-Pro: reasoning_effort=none`),e.reasoning_effort=`none`):(i.startsWith(`gemini-35-flash`)||i.startsWith(`gemini-31-flash-lite`)||i.startsWith(`gemini-3-flash`))&&(debug(`Patch Gemini 3.x Flash/Lite: reasoning_effort=minimal`),e.reasoning_effort=`minimal`)),i.startsWith(`glm`)&&(/^glm-5[3-9]/.test(i)?(debug(`Patch GLM 5.3+: reasoning_effort=low`),e.reasoning_effort=`low`):(debug(`Patch GLM: disable thinking`),e.thinking={type:`disabled`})),i.startsWith(`hy`)&&(debug(`Patch Hunyuan: disable thinking, reasoning_effort=low`),e.thinking={type:`disabled`},e.reasoning_effort=`low`),i.startsWith(`grok`)&&(/^grok-4-?3/.test(i)?(debug(`Patch Grok 4.3: reasoning_effort=none`),e.reasoning_effort=`none`):(i.startsWith(`grok-3-mini`)||i.startsWith(`grok-code-fast`))&&(debug(`Patch Grok mini/code: reasoning_effort=low`),e.reasoning_effort=`low`)),i.startsWith(`kimi`)&&(i.startsWith(`kimi-k3`)?(debug(`Patch Kimi K3: use required tool choice, remove parallel tool calls`),delete e.parallel_tool_calls,e.tool_choice?.function?.name&&(e.tool_choice=`required`)):i.includes(`code`)||(debug(`Patch Kimi: disable thinking`),e.thinking={type:`disabled`})),i.startsWith(`minimax`)&&(debug(`Patch MiniMax: remove parallel_tool_calls`),delete e.parallel_tool_calls,i.includes(`m3`)&&(debug(`Patch MiniMax: disable thinking`),e.thinking={type:`disabled`})),r===`openrouter`){let t=e.reasoning_effort;e.thinking?.type===`disabled`||e.enable_thinking===!1||t===`none`?e.reasoning={enabled:!1}:t&&(e.reasoning={enabled:!0,effort:t})}return e}function normalizeModelName(e){let t=e.toLowerCase();return t.includes(`/`)&&(t=t.split(`/`)[1]),t=t.replace(/_/g,``),t=t.replace(/\./g,``),t}function getProvider(e){if(e)try{return new URL(e).hostname===`openrouter.ai`?`openrouter`:void 0}catch{return}}var OpenAIClient=class{config;fetch;constructor(e){this.config=e,this.fetch=e.customFetch}async invoke(e,t,n,r){n?.throwIfAborted();let i=Object.entries(t).map(([e,t])=>zodToOpenAITool(e,t)),a=`required`;r?.toolChoiceName&&!this.config.disableNamedToolChoice&&(a={type:`function`,function:{name:r.toolChoiceName}});let o={model:this.config.model,messages:e,tools:i,parallel_tool_calls:!1,tool_choice:a};this.config.temperature!==void 0&&(o.temperature=this.config.temperature),modelPatch(o,this.config.baseURL);let s;try{s=this.config.transformRequestBody(o)}catch(e){throw new InvokeError(InvokeErrorTypes.CONFIG_ERROR,`transformRequestBody failed: ${e.message}`,e)}let c=s??o,l;try{l=await this.fetch(`${this.config.baseURL}/chat/completions`,{method:`POST`,headers:{"Content-Type":`application/json`,...this.config.apiKey&&{Authorization:`Bearer ${this.config.apiKey}`}},body:JSON.stringify(c),signal:n})}catch(e){throw e?.name===`AbortError`?e:(console.error(e),new InvokeError(InvokeErrorTypes.NETWORK_ERROR,`Network request failed`,e))}if(!l.ok){let e;try{e=await l.json()}catch(e){if(e?.name===`AbortError`)throw e}let t=e?.error?.message||l.statusText;throw l.status===401||l.status===403?new InvokeError(InvokeErrorTypes.AUTH_ERROR,`Authentication failed: ${t}`,e):l.status===429?new InvokeError(InvokeErrorTypes.RATE_LIMIT,`Rate limit exceeded: ${t}`,e):l.status>=500?new InvokeError(InvokeErrorTypes.SERVER_ERROR,`Server error: ${t}`,e):new InvokeError(InvokeErrorTypes.UNKNOWN,`HTTP ${l.status}: ${t}`,e)}let u;try{u=await l.json()}catch(e){throw e?.name===`AbortError`?e:new InvokeError(InvokeErrorTypes.INVALID_RESPONSE,`Response body is not valid JSON`,e)}let d=u.choices?.[0];if(!d)throw new InvokeError(InvokeErrorTypes.INVALID_SCHEMA,`No choices in response`,u);switch(d.finish_reason){case`tool_calls`:case`function_call`:case`stop`:break;case`length`:throw new InvokeError(InvokeErrorTypes.CONTEXT_LENGTH,`Response truncated: max tokens reached`,void 0,u);case`content_filter`:throw new InvokeError(InvokeErrorTypes.CONTENT_FILTER,`Content filtered by safety system`,void 0,u);default:throw new InvokeError(InvokeErrorTypes.INVALID_SCHEMA,`Unexpected finish_reason: ${d.finish_reason}`,void 0,u)}let f=(r?.normalizeResponse?r.normalizeResponse(u):u).choices?.[0],p=f?.message?.tool_calls?.[0]?.function?.name;if(!p)throw new InvokeError(InvokeErrorTypes.NO_TOOL_CALL,`No tool call found in response`,void 0,u);let m=t[p];if(!m)throw new InvokeError(InvokeErrorTypes.UNKNOWN,`Tool "${p}" not found in tools`,void 0,u);let h=f.message?.tool_calls?.[0]?.function?.arguments;if(!h)throw new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`No tool call arguments found`,void 0,u);let g;try{g=JSON.parse(h)}catch(e){throw new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`Failed to parse tool arguments as JSON`,e,u)}let _=m.inputSchema.safeParse(g);if(!_.success)throw console.error(prettifyError(_.error)),new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`Tool arguments validation failed`,_.error,u);let v=_.data,y;try{y=await m.execute(v)}catch(e){throw e?.name===`AbortError`?e:new InvokeError(InvokeErrorTypes.TOOL_EXECUTION_ERROR,`Tool execution failed: ${e?.message}`,e,u)}return{toolCall:{name:p,args:v},toolResult:y,usage:{promptTokens:u.usage?.prompt_tokens??0,completionTokens:u.usage?.completion_tokens??0,totalTokens:u.usage?.total_tokens??0,cachedTokens:u.usage?.prompt_tokens_details?.cached_tokens,reasoningTokens:u.usage?.completion_tokens_details?.reasoning_tokens},rawResponse:u,rawRequest:c}}},LLM=class extends EventTarget{config;client;constructor(e){super(),this.config=parseLLMConfig(e),this.client=new OpenAIClient(this.config)}async invoke(e,t,n,r){return await withRetry(async()=>this.client.invoke(e,t,n,r),{maxRetries:this.config.maxRetries,onRetry:(e,t)=>{this.dispatchEvent(new CustomEvent(`retry`,{detail:{attempt:e,maxAttempts:this.config.maxRetries,lastError:t}}))}})}};async function withRetry(e,t){let n=0;for(;;)try{return await e()}catch(e){if(e?.name===`AbortError`||e instanceof InvokeError&&!e.retryable||(n++,n>t.maxRetries))throw e;console.debug(`[LLM] retryable failure, will retry:`,e),t.onRetry(n,e),await new Promise(e=>setTimeout(e,100))}}function parseLLMConfig(e){if(!e.baseURL||!e.model)throw Error(`[PageAgent] LLM configuration required. Please provide: baseURL, model. See: https://alibaba.github.io/page-agent/docs/features/models`);return e.temperature!==void 0&&console.warn(`[PageAgent] LLMConfig.temperature is deprecated and will be removed in a future version. Use transformRequestBody to set it only for models you have verified accept it.`),{baseURL:e.baseURL,model:e.model,apiKey:e.apiKey||``,temperature:e.temperature,maxRetries:e.maxRetries??2,transformRequestBody:e.transformRequestBody??(e=>e),disableNamedToolChoice:e.disableNamedToolChoice??!1,customFetch:(e.customFetch??fetch).bind(globalThis)}}var system_prompt_default=`You are an AI agent designed to operate in an iterative loop to automate browser tasks. Your ultimate goal is accomplishing the task provided in <user_request>.
|
|
57
|
-
|
|
58
|
-
<intro>
|
|
59
|
-
You excel at following tasks:
|
|
60
|
-
1. Navigating complex websites and extracting precise information
|
|
61
|
-
2. Automating form submissions and interactive web actions
|
|
62
|
-
3. Gathering and saving information
|
|
63
|
-
4. Operate effectively in an agent loop
|
|
64
|
-
5. Efficiently performing diverse web tasks
|
|
65
|
-
</intro>
|
|
66
|
-
|
|
67
|
-
<language_settings>
|
|
68
|
-
- Default working language: **English**
|
|
69
|
-
- Use the language that user is using. Return in user's language.
|
|
70
|
-
</language_settings>
|
|
71
|
-
|
|
72
|
-
<input>
|
|
73
|
-
At every step, your input will consist of:
|
|
74
|
-
1. <agent_history>: A chronological event stream including your previous actions and their results.
|
|
75
|
-
2. <agent_state>: Current <user_request> and <step_info>.
|
|
76
|
-
3. <browser_state>: Current URL, interactive elements indexed for actions, and visible page content.
|
|
77
|
-
</input>
|
|
78
|
-
|
|
79
|
-
<agent_history>
|
|
80
|
-
Agent history will be given as a list of step information as follows:
|
|
81
|
-
|
|
82
|
-
<step_{step_number}>:
|
|
83
|
-
Evaluation of Previous Step: Assessment of last action
|
|
84
|
-
Memory: Your memory of this step
|
|
85
|
-
Next Goal: Your goal for this step
|
|
86
|
-
Action Results: Your actions and their results
|
|
87
|
-
</step_{step_number}>
|
|
88
|
-
|
|
89
|
-
and system messages wrapped in <sys> tag.
|
|
90
|
-
</agent_history>
|
|
91
|
-
|
|
92
|
-
<user_request>
|
|
93
|
-
USER REQUEST: This is your ultimate objective and always remains visible.
|
|
94
|
-
- This has the highest priority. Make the user happy.
|
|
95
|
-
- If the user request is very specific - then carefully follow each step and don't skip or hallucinate steps.
|
|
96
|
-
- If the task is open ended you can plan yourself how to get it done.
|
|
97
|
-
</user_request>
|
|
98
|
-
|
|
99
|
-
<browser_state>
|
|
100
|
-
1. Browser State will be given as:
|
|
101
|
-
|
|
102
|
-
Current URL: URL of the page you are currently viewing.
|
|
103
|
-
Interactive Elements: All interactive elements will be provided in format as [index]<type>text</type> where
|
|
104
|
-
- index: Numeric identifier for interaction
|
|
105
|
-
- type: HTML element type (button, input, etc.)
|
|
106
|
-
- text: Element description
|
|
107
|
-
|
|
108
|
-
Examples:
|
|
109
|
-
[33]<div>User form</div>
|
|
110
|
-
\\t*[35]<button aria-label='Submit form'>Submit</button>
|
|
111
|
-
|
|
112
|
-
Note that:
|
|
113
|
-
- Only elements with numeric indexes in [] are interactive
|
|
114
|
-
- (stacked) indentation (with \\t) is important and means that the element is a (html) child of the element above (with a lower index)
|
|
115
|
-
- Elements tagged with \`*[\` are the new clickable elements that appeared on the website since the last step - if url has not changed.
|
|
116
|
-
- Pure text elements without [] are not interactive.
|
|
117
|
-
</browser_state>
|
|
118
|
-
|
|
119
|
-
<browser_rules>
|
|
120
|
-
Strictly follow these rules while using the browser and navigating the web:
|
|
121
|
-
- Only interact with elements that have a numeric [index] assigned.
|
|
122
|
-
- Only use indexes that are explicitly provided.
|
|
123
|
-
- If the page changes after, for example, an input text action, analyze if you need to interact with new elements, e.g. selecting the right option from the list.
|
|
124
|
-
- By default, only elements in the visible viewport are listed. Use scrolling actions if you suspect relevant content is offscreen which you need to interact with. Scroll ONLY if there are more pixels below or above the page.
|
|
125
|
-
- You can scroll by a specific number of pages using the num_pages parameter (e.g., 0.5 for half page, 2.0 for two pages).
|
|
126
|
-
- All the elements that are scrollable are marked with \`data-scrollable\` attribute. Including the scrollable distance in every directions. You can scroll *the element* in case some area are overflowed.
|
|
127
|
-
- If a captcha appears, tell user you can not solve captcha. Finish the task and ask user to solve it.
|
|
128
|
-
- If the page is not fully loaded, use the \`wait\` action.
|
|
129
|
-
- Do not repeat one action for more than 3 times unless some conditions changed.
|
|
130
|
-
- If you fill an input field and your action sequence is interrupted, most often something changed e.g. suggestions popped up under the field.
|
|
131
|
-
- If the <user_request> includes specific page information such as product type, rating, price, location, etc., try to apply filters to be more efficient.
|
|
132
|
-
- The <user_request> is the ultimate goal. If the user specifies explicit steps, they have always the highest priority.
|
|
133
|
-
- If you input_text into a field, you might need to press enter, click the search button, or select from dropdown for completion.
|
|
134
|
-
- Don't login into a page if you don't have to. Don't login if you don't have the credentials.
|
|
135
|
-
- There are 2 types of tasks always first think which type of request you are dealing with:
|
|
136
|
-
1. Very specific step by step instructions:
|
|
137
|
-
- Follow them as very precise and don't skip steps. Try to complete everything as requested.
|
|
138
|
-
2. Open ended tasks. Plan yourself, be creative in achieving them.
|
|
139
|
-
- If you get stuck e.g. with logins or captcha in open-ended tasks you can re-evaluate the task and try alternative ways, e.g. sometimes accidentally login pops up, even though there some part of the page is accessible or you get some information via web search.
|
|
140
|
-
</browser_rules>
|
|
141
|
-
|
|
142
|
-
<capability>
|
|
143
|
-
- You can only handle single page app. Do not jump out of current page.
|
|
144
|
-
- Do not click on link if it will open in a new page (e.g., <a target="_blank">)
|
|
145
|
-
- It is ok to fail the task.
|
|
146
|
-
- User can be wrong. If the request of user is not achievable, inappropriate or you do not have enough information or tools to achieve it. Tell user to make a better request.
|
|
147
|
-
- Webpage can be broken. All webpages or apps have bugs. Some bug will make it hard for your job. It's encouraged to tell user the problem of current page. Your feedbacks (including failing) are valuable for user.
|
|
148
|
-
- Trying too hard can be harmful. Repeating some action back and forth or pushing for a complex procedure with little knowledge can cause unwanted results and harmful side-effects. User would rather you complete the task with a fail.
|
|
149
|
-
- If you do not have knowledge for the current webpage or task. You must require user to give specific instructions and detailed steps.
|
|
150
|
-
</capability>
|
|
151
|
-
|
|
152
|
-
<task_completion_rules>
|
|
153
|
-
You must call the \`done\` action in one of three cases:
|
|
154
|
-
- When you have fully completed the USER REQUEST.
|
|
155
|
-
- When you reach the final allowed step (\`max_steps\`), even if the task is incomplete.
|
|
156
|
-
- When you feel stuck or unable to solve user request. Or user request is not clear or contains inappropriate content.
|
|
157
|
-
- If it is ABSOLUTELY IMPOSSIBLE to continue.
|
|
158
|
-
|
|
159
|
-
The \`done\` action is your opportunity to terminate and share your findings with the user.
|
|
160
|
-
- Set \`success\` to \`true\` only if the full USER REQUEST has been completed with no missing components.
|
|
161
|
-
- If any part of the request is missing, incomplete, or uncertain, set \`success\` to \`false\`.
|
|
162
|
-
- You can use the \`text\` field of the \`done\` action to communicate your findings and to provide a coherent reply to the user and fulfill the USER REQUEST.
|
|
163
|
-
- You are ONLY ALLOWED to call \`done\` as a single action. Don't call it together with other actions.
|
|
164
|
-
- If the user asks for specified format, such as "return JSON with following structure", "return a list of format...", MAKE sure to use the right format in your answer.
|
|
165
|
-
- If the user asks for a structured output, your \`done\` action's schema may be modified. Take this schema into account when solving the task!
|
|
166
|
-
</task_completion_rules>
|
|
167
|
-
|
|
168
|
-
<reasoning_rules>
|
|
169
|
-
Exhibit the following reasoning patterns to successfully achieve the <user_request>:
|
|
170
|
-
|
|
171
|
-
- Reason about <agent_history> to track progress and context toward <user_request>.
|
|
172
|
-
- Analyze the most recent "Next Goal" and "Action Result" in <agent_history> and clearly state what you previously tried to achieve.
|
|
173
|
-
- Analyze all relevant items in <agent_history> and <browser_state> to understand your state.
|
|
174
|
-
- Explicitly judge success/failure/uncertainty of the last action. Never assume an action succeeded just because it appears to be executed in your last step in <agent_history>. If the expected change is missing, mark the last action as failed (or uncertain) and plan a recovery.
|
|
175
|
-
- Analyze whether you are stuck, e.g. when you repeat the same actions multiple times without any progress. Then consider alternative approaches e.g. scrolling for more context or ask user for help.
|
|
176
|
-
- Ask user for help if you have any difficulty. Keep user in the loop.
|
|
177
|
-
- If you see information relevant to <user_request>, plan saving the information to memory.
|
|
178
|
-
- Always reason about the <user_request>. Make sure to carefully analyze the specific steps and information required. E.g. specific filters, specific form fields, specific information to search. Make sure to always compare the current trajectory with the user request and think carefully if thats how the user requested it.
|
|
179
|
-
</reasoning_rules>
|
|
180
|
-
|
|
181
|
-
<examples>
|
|
182
|
-
Here are examples of good output patterns. Use them as reference but never copy them directly.
|
|
183
|
-
|
|
184
|
-
<evaluation_examples>
|
|
185
|
-
"evaluation_previous_goal": "Successfully navigated to the product page and found the target information. Verdict: Success"
|
|
186
|
-
"evaluation_previous_goal": "Clicked the login button and user authentication form appeared. Verdict: Success"
|
|
187
|
-
</evaluation_examples>
|
|
188
|
-
|
|
189
|
-
<memory_examples>
|
|
190
|
-
"memory": "Found many pending reports that need to be analyzed in the main page. Successfully processed the first 2 reports on quarterly sales data and moving on to inventory analysis and customer feedback reports."
|
|
191
|
-
</memory_examples>
|
|
192
|
-
|
|
193
|
-
<next_goal_examples>
|
|
194
|
-
"next_goal": "Click on the 'Add to Cart' button to proceed with the purchase flow."
|
|
195
|
-
</next_goal_examples>
|
|
196
|
-
</examples>
|
|
197
|
-
|
|
198
|
-
<output>
|
|
199
|
-
{
|
|
200
|
-
"evaluation_previous_goal": "Concise one-sentence analysis of your last action. Clearly state success, failure, or uncertain.",
|
|
201
|
-
"memory": "1-3 concise sentences of specific memory of this step and overall progress. You should put here everything that will help you track progress in future steps. Like counting pages visited, items found, etc.",
|
|
202
|
-
"next_goal": "State the next immediate goal and action to achieve it, in one clear sentence.",
|
|
203
|
-
"action":{
|
|
204
|
-
"Action name": {// Action parameters}
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
</output>
|
|
208
|
-
`,log=console.log.bind(console,chalk.yellow(`[autoFixer]`));function normalizeResponse(e,t){let n,r=e.choices?.[0];if(!r)throw Error(`No choices in response`);let i=r.message;if(!i)throw Error(`No message in choice`);let a=i.tool_calls?.[0];if(a?.function?.arguments)n=safeJsonParse(a.function.arguments),a.function.name&&a.function.name!==`AgentOutput`&&(log(`#1: fixing tool_call`),n={action:safeJsonParse(n)});else if(i.content){let e=retrieveJsonFromString(i.content.trim());if(e)n=safeJsonParse(e),n?.name===`AgentOutput`&&(log(`#2: fixing tool_call`),n=safeJsonParse(n.arguments)),n?.type===`function`&&(log(`#3: fixing tool_call`),n=safeJsonParse(n.function.arguments)),!n?.action&&!n?.evaluation_previous_goal&&!n?.memory&&!n?.next_goal&&!n?.thinking&&(log(`#4: fixing tool_call`),n={action:safeJsonParse(n)});else throw Error(`No tool_call and the message content does not contain valid JSON`)}else throw Error(`No tool_call nor message content is present`);return n=safeJsonParse(n),n.action&&(n.action=safeJsonParse(n.action)),n.action&&t&&(n.action=validateAction(n.action,t)),n.action||(log(`#5: fixing tool_call`),n.action={wait:{seconds:1}}),{...e,choices:[{...r,message:{...i,tool_calls:[{...a||{},function:{...a?.function||{},name:`AgentOutput`,arguments:JSON.stringify(n)}}]}}]}}function validateAction(e,t){if(typeof e!=`object`||!e)return e;let n=Object.keys(e)[0];if(!n)return e;let r=t.get(n);if(!r){let e=Array.from(t.keys()).join(`, `);throw new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`Unknown action "${n}". Available: ${e}`)}let i=e[n],a=r.inputSchema;if(a instanceof ZodObject&&i!==null&&typeof i!=`object`){let e=Object.keys(a.shape).find(e=>!a.shape[e].safeParse(void 0).success);e&&(log(`coercing primitive action input for "${n}"`),i={[e]:i})}let o=a.safeParse(i);if(!o.success)throw new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`Invalid input for action "${n}": ${prettifyError(o.error)}`);return{[n]:o.data}}function safeJsonParse(e){if(typeof e==`string`)try{return JSON.parse(e.trim())}catch{return e}return e}function retrieveJsonFromString(e){try{let t=/({[\s\S]*})/.exec(e)??[];return t.length===0?null:JSON.parse(t[0])}catch{return null}}async function waitFor$1(e,t){if(!t){await new Promise(t=>setTimeout(t,e*1e3));return}t.throwIfAborted(),await new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e*1e3),a=()=>{clearTimeout(i),r(t.reason)};t.addEventListener(`abort`,a,{once:!0})})}function truncate$1(e,t){return e.length>t?e.substring(0,t)+`...`:e}function randomID(e){let t=Math.random().toString(36).substring(2,11);if(!e)return t;let n=1e3,r=0;for(;e.includes(t);)if(t=Math.random().toString(36).substring(2,11),r++,r>1e3)throw Error(`randomID: too many tries`);return t}var _global=globalThis;_global.__PAGE_AGENT_IDS__||=[];var ids=_global.__PAGE_AGENT_IDS__;function uid(){let e=randomID(ids);return ids.push(e),e}var llmsTxtCache=new Map;async function fetchLlmsTxt(e){let t;try{t=new URL(e).origin}catch{return null}if(t===`null`)return null;if(llmsTxtCache.has(t))return llmsTxtCache.get(t);let n=`${t}/llms.txt`,r=null;try{console.log(chalk.gray(`[llms.txt] Fetching ${n}`));let e=await fetch(n,{signal:AbortSignal.timeout(3e3)});e.ok?(r=await e.text(),console.log(chalk.green(`[llms.txt] Found (${r.length} chars)`)),r.length>1e3&&(console.log(chalk.yellow(`[llms.txt] Truncating to 1000 chars`)),r=truncate$1(r,1e3))):console.debug(chalk.gray(`[llms.txt] ${e.status} for ${n}`))}catch(e){console.debug(chalk.gray(`[llms.txt] not found for ${n}`),e)}return llmsTxtCache.set(t,r),r}function assert(e,t,n){if(!e){let e=t??`Assertion failed`;throw n||console.error(chalk.red(`❌ assert: ${e}`)),Error(e)}}async function suppress(e){try{return await e()}catch(e){console.error(e);return}}function tool(e){return e}var tools=new Map;tools.set(`done`,tool({description:`Complete task. Text is your final response to the user — keep it concise unless the user explicitly asks for detail.`,inputSchema:object({text:string(),success:boolean().default(!0)}),execute:async function(e){return Promise.resolve(`Task completed`)}})),tools.set(`wait`,tool({description:`Wait for x seconds. Can be used to wait until the page or data is fully loaded.`,inputSchema:object({seconds:number().min(1).max(10).default(1)}),execute:async function(e,{signal:t}){let n=await this.pageController.getLastUpdateTime(),r=(Date.now()-n)/1e3,i=Math.max(0,e.seconds-r);return console.log(`actualWaitTime: ${i} seconds`),await waitFor$1(i,t),`✅ Waited for ${(r+i).toFixed(2)} seconds.`}})),tools.set(`ask_user`,tool({description:`Ask the user a question and wait for their answer. Use this if you need more information or clarification.`,inputSchema:object({question:string()}),execute:async function(e,{signal:t}){if(!this.onAskUser)throw Error(`ask_user tool requires onAskUser callback to be set`);return`User answered: ${await this.onAskUser(e.question,{signal:t})}`}})),tools.set(`click_element_by_index`,tool({description:`Click element by index`,inputSchema:object({index:int().min(0)}),execute:async function(e){return(await this.pageController.clickElement(e.index)).message}})),tools.set(`input_text`,tool({description:`Click and type text into an interactive input element`,inputSchema:object({index:int().min(0),text:string()}),execute:async function(e){return(await this.pageController.inputText(e.index,e.text)).message}})),tools.set(`select_dropdown_option`,tool({description:`Select dropdown option for interactive element index by the text of the option you want to select`,inputSchema:object({index:int().min(0),text:string()}),execute:async function(e){return(await this.pageController.selectOption(e.index,e.text)).message}})),tools.set(`scroll`,tool({description:`Scroll vertically. Without index: scrolls the document. With index: scrolls the container at that index (or its nearest scrollable ancestor). Use index of a data-scrollable element to scroll a specific area.`,inputSchema:object({down:boolean().default(!0),num_pages:number().min(0).max(10).optional().default(.1),pixels:number().int().min(0).optional(),index:number().int().min(0).optional()}),execute:async function(e){return(await this.pageController.scroll({...e,numPages:e.num_pages})).message}})),tools.set(`scroll_horizontally`,tool({description:`Scroll horizontally. Without index: scrolls the document. With index: scrolls the container at that index (or its nearest scrollable ancestor). Use index of a data-scrollable element to scroll a specific area.`,inputSchema:object({right:boolean().default(!0),pixels:number().int().min(0),index:number().int().min(0).optional()}),execute:async function(e){return(await this.pageController.scrollHorizontally(e)).message}})),tools.set(`execute_javascript`,tool({description:"Execute JavaScript code on the current page. Supports async/await syntax. Use with caution! An `AbortSignal` named `signal` is available in scope: long-running async code MUST honor it (e.g. `await fetch(url, { signal })`, or `signal.throwIfAborted()` in loops)",inputSchema:object({script:string()}),execute:async function(e,{signal:t}){let n=await this.pageController.executeJavascript(e.script,t);return t.throwIfAborted(),n.message}}));var PageAgentCore=class extends EventTarget{id=uid();config;tools;pageController;task=``;taskId=``;history=[];disposed=!1;onAskUser;#e=`idle`;#t;#n=new AbortController;#r=[];#i=Promise.resolve();#a=null;#o={totalWaitTime:0,lastURL:``,browserState:null};constructor(e){if(super(),this.config={...e,maxSteps:e.maxSteps??40},this.#t=new LLM(this.config),this.tools=new Map(tools),this.pageController=e.pageController,this.#t.addEventListener(`retry`,e=>{let{attempt:t,maxAttempts:n,lastError:r}=e.detail;this.#l({type:`retrying`,attempt:t,maxAttempts:n}),this.history.push({type:`error`,message:String(r),rawResponse:r.rawResponse}),this.history.push({type:`retry`,message:`LLM retry attempt ${t} of ${n}`,attempt:t,maxAttempts:n}),this.#c()}),this.config.customTools)for(let[e,t]of Object.entries(this.config.customTools)){if(t===null){this.tools.delete(e);continue}this.tools.set(e,t)}this.config.experimentalScriptExecutionTool||this.tools.delete(`execute_javascript`)}get status(){return this.#e}get lastResult(){return this.#a}#s(){this.dispatchEvent(new Event(`statuschange`))}#c(e){e&&this.history.push(e),this.dispatchEvent(new Event(`historychange`))}#l(e){this.dispatchEvent(new CustomEvent(`activity`,{detail:e}))}#u(e){this.#e!==e&&(this.#e=e,this.#s())}pushObservation(e){this.#r.push(e)}async stop(){this.#e===`running`&&(this.#n.abort(),await this.#i)}async execute(e){if(this.disposed)throw Error(`PageAgent has been disposed. Create a new instance.`);if(this.#e===`running`)throw Error(`A task is already running.`);if(!e)throw Error(`Task is required`);this.task=e,this.taskId=uid(),this.history=[],this.#r=[],this.#o={totalWaitTime:0,lastURL:``,browserState:null},this.#n=new AbortController;let t=this.#n.signal,n;this.#i=new Promise(e=>n=e),this.#u(`running`),this.#c(),this.onAskUser||this.tools.delete(`ask_user`);let r=this.config.onBeforeStep,i=this.config.onAfterStep,a=this.config.onBeforeTask,o=this.config.onAfterTask,s=this.config.stepDelay??.4,c=this.config.maxSteps,l=0,u,d=`error`;await suppress(()=>this.pageController.showMask());try{for(await a?.(this);;){await r?.(this,l);try{console.group(`step: ${l}`),l>0&&await waitFor$1(s,t),t.throwIfAborted(),console.log(chalk.blue.bold(`👀 Observing...`)),this.#o.browserState=await this.pageController.getBrowserState(),await this.#m(l);let e=[{role:`system`,content:this.#f()},{role:`user`,content:await this.#h()}],n={AgentOutput:this.#d()};console.log(chalk.blue.bold(`🧠 Thinking...`)),this.#l({type:`thinking`});let r=await this.#t.invoke(e,n,t,{toolChoiceName:`AgentOutput`,normalizeResponse:e=>normalizeResponse(e,this.tools)}),i=r.toolResult,a=i.input,o=i.output,c={evaluation_previous_goal:a.evaluation_previous_goal,memory:a.memory,next_goal:a.next_goal},f=Object.keys(a.action)[0],p={name:f,input:a.action[f],output:o};if(this.#c({type:`step`,stepIndex:l,reflection:c,action:p,usage:r.usage,rawResponse:r.rawResponse,rawRequest:r.rawRequest}),f===`done`){let e=p.input?.success??!1,t=p.input?.text||`no text provided`;console.log(chalk.green.bold(`Task completed`),e,t),u={success:e,data:t,history:this.history},this.#a=u,d=`completed`;break}}catch(e){let t=e?.name===`AbortError`;t||console.error(`Task failed`,e);let n=t?`Tarefa interrompida`:String(e);this.#l({type:`error`,message:n}),this.#c({type:`error`,message:n,rawResponse:e}),u={success:!1,data:n,history:this.history},this.#a=u,d=t?`stopped`:`error`;break}finally{console.groupEnd(),await i?.(this,this.history)}if(l++,l>c){let e=`Step count exceeded maximum limit`;console.error(e),this.#l({type:`error`,message:e}),this.#c({type:`error`,message:e}),u={success:!1,data:e,history:this.history},this.#a=u,d=`error`;break}}return await o?.(this,u),u}catch(e){throw this.#l({type:`error`,message:String(e)}),d=`error`,e}finally{await suppress(()=>this.pageController.cleanUpHighlights()),await suppress(()=>this.pageController.hideMask()),this.#n.abort(),n(),this.#u(d)}}#d(){let e=this.tools,t=union(Array.from(e.entries()).map(([e,t])=>object({[e]:t.inputSchema}).describe(t.description)));return{description:`You MUST call this tool every step!`,inputSchema:object({evaluation_previous_goal:string().optional(),memory:string().optional(),next_goal:string().optional(),action:t}),execute:async t=>{let n=this.#n.signal;n.throwIfAborted(),console.log(chalk.blue.bold(`MacroTool input`),t);let r=t.action,i=Object.keys(r)[0],a=r[i],o=[];t.evaluation_previous_goal&&o.push(`✅: ${t.evaluation_previous_goal}`),t.memory&&o.push(`💾: ${t.memory}`),t.next_goal&&o.push(`🎯: ${t.next_goal}`);let s=o.length>0?o.join(`
|
|
209
|
-
`):``;s&&console.log(s);let c=e.get(i);assert(c,`Tool ${i} not found`),console.log(chalk.blue.bold(`Executing tool: ${i}`),a),this.#l({type:`executing`,tool:i,input:a});let l=Date.now(),u=await c.execute.bind(this)(a,{signal:n});n.throwIfAborted();let d=Date.now()-l;return console.log(chalk.green.bold(`Tool (${i}) executed for ${d}ms`),u),this.#l({type:`executed`,tool:i,input:a,output:u,duration:d}),i===`wait`?this.#o.totalWaitTime+=a?.seconds||0:this.#o.totalWaitTime=0,{input:t,output:u}}}}#f(){if(this.config.customSystemPrompt)return this.config.customSystemPrompt;let e=this.config.language===`pt-BR`?`Portuguese (Brazil)`:this.config.language===`zh-CN`?`Chinese`:`English`;return system_prompt_default.replace(/Default working language: \*\*.*?\*\*/,`Default working language: **${e}**`)}async#p(){let{instructions:e,experimentalLlmsTxt:t}=this.config,n=e?.system?.trim(),r,i=this.#o.browserState?.url||``;if(e?.getPageInstructions&&i)try{r=e.getPageInstructions(i)?.trim()}catch(e){console.error(chalk.red(`[PageAgent] Failed to execute getPageInstructions callback:`),e)}let a=t&&i?await fetchLlmsTxt(i):void 0;if(!n&&!r&&!a)return``;let o=`<instructions>
|
|
210
|
-
`;return n&&(o+=`<system_instructions>\n${n}\n</system_instructions>\n`),r&&(o+=`<page_instructions>\n${r}\n</page_instructions>\n`),a&&(o+=`<llms_txt>\n${a}\n</llms_txt>\n`),o+=`</instructions>
|
|
211
|
-
|
|
212
|
-
`,o}async#m(e){this.#o.totalWaitTime>=3&&this.pushObservation(`You have waited ${this.#o.totalWaitTime} seconds accumulatively. DO NOT wait any longer unless you have a good reason.`);let t=this.#o.browserState?.url||``;t!==this.#o.lastURL&&(this.pushObservation(`A página navegou para → ${t}`),this.#o.lastURL=t,await waitFor$1(.5));let n=this.config.maxSteps-e;if(n===5?this.pushObservation(`⚠️ Only ${n} steps remaining. Consider wrapping up or calling done with partial results.`):n===2&&this.pushObservation(`⚠️ Critical: Only ${n} steps left! You must finish the task or call done immediately.`),this.#r.length>0){for(let e of this.#r)this.history.push({type:`observation`,content:e}),console.log(chalk.cyan(`Observation:`),e);this.#r=[],this.#c()}}async#h(){let e=this.#o.browserState,t=``;t+=await this.#p();let n=this.history.filter(e=>e.type===`step`).length;t+=`<agent_state>
|
|
213
|
-
`,t+=`<user_request>
|
|
214
|
-
`,t+=`${this.task}\n`,t+=`</user_request>
|
|
215
|
-
`,t+=`<step_info>
|
|
216
|
-
`,t+=`Step ${n+1} of ${this.config.maxSteps} max possible steps\n`,t+=`Current time: ${new Date().toLocaleString()}\n`,t+=`</step_info>
|
|
217
|
-
`,t+=`</agent_state>
|
|
218
|
-
|
|
219
|
-
`,t+=`<agent_history>
|
|
220
|
-
`;let r=0;for(let e of this.history)e.type===`step`?(r++,t+=`<step_${r}>\n`,t+=`Evaluation of Previous Step: ${e.reflection.evaluation_previous_goal}\n`,t+=`Memory: ${e.reflection.memory}\n`,t+=`Next Goal: ${e.reflection.next_goal}\n`,t+=`Action Results: ${e.action.output}\n`,t+=`</step_${r}>\n`):e.type===`observation`?t+=`<sys>${e.content}</sys>\n`:e.type===`user_takeover`?t+=`<sys>User took over control and made changes to the page</sys>
|
|
221
|
-
`:e.type;t+=`</agent_history>
|
|
222
|
-
|
|
223
|
-
`;let i=e.content;return this.config.transformPageContent&&(i=await this.config.transformPageContent(i)),t+=`<browser_state>
|
|
224
|
-
`,t+=e.header+`
|
|
225
|
-
`,t+=i+`
|
|
226
|
-
`,t+=e.footer+`
|
|
227
|
-
|
|
228
|
-
`,t+=`</browser_state>
|
|
229
|
-
|
|
230
|
-
`,t}dispose(){console.log(`Disposing PageAgent...`),this.disposed=!0,this.pageController.dispose(),this.#n.abort(),this.dispatchEvent(new Event(`dispose`)),this.config.onDispose?.(this)}};function isHTMLElement(e){return!!e&&e.nodeType===1}function isInputElement(e){return e?.nodeType===1&&e.tagName===`INPUT`}function isTextAreaElement(e){return e?.nodeType===1&&e.tagName===`TEXTAREA`}function isSelectElement(e){return e?.nodeType===1&&e.tagName===`SELECT`}function isAnchorElement(e){return e?.nodeType===1&&e.tagName===`A`}function getIframeOffset(e){let t=e.ownerDocument.defaultView?.frameElement;if(!t)return{x:0,y:0};let n=t.getBoundingClientRect();return{x:n.left,y:n.top}}function getNativeValueSetter(e){return Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),`value`).set}async function waitFor(e){await new Promise(t=>setTimeout(t,e*1e3))}async function movePointerToElement(e,t,n){let r=getIframeOffset(e);window.dispatchEvent(new CustomEvent(`PageAgent::MovePointerTo`,{detail:{x:t+r.x,y:n+r.y}})),await waitFor(.3)}async function clickPointer(){window.dispatchEvent(new CustomEvent(`PageAgent::ClickPointer`))}async function enablePassThrough(){window.dispatchEvent(new CustomEvent(`PageAgent::EnablePassThrough`))}async function disablePassThrough(){window.dispatchEvent(new CustomEvent(`PageAgent::DisablePassThrough`))}function getElementByIndex(e,t){let n=e.get(t);if(!n)throw Error(`No interactive element found at index ${t}`);let r=n.ref;if(!r)throw Error(`Element at index ${t} does not have a reference`);if(!isHTMLElement(r))throw Error(`Element at index ${t} is not an HTMLElement`);return r}var lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&=(lastClickedElement.dispatchEvent(new PointerEvent(`pointerout`,{bubbles:!0})),lastClickedElement.dispatchEvent(new PointerEvent(`pointerleave`,{bubbles:!1})),lastClickedElement.dispatchEvent(new MouseEvent(`mouseout`,{bubbles:!0})),lastClickedElement.dispatchEvent(new MouseEvent(`mouseleave`,{bubbles:!1})),lastClickedElement.blur(),null)}async function clickElement(e){blurLastClickedElement(),lastClickedElement=e,await scrollIntoViewIfNeeded(e);let t=e.ownerDocument.defaultView?.frameElement;t&&await scrollIntoViewIfNeeded(t);let n=e.getBoundingClientRect(),r=n.left+n.width/2,i=n.top+n.height/2;await movePointerToElement(e,r,i),await clickPointer(),await waitFor(.1);let a=e.ownerDocument;await enablePassThrough();let o=a.elementFromPoint(r,i);await disablePassThrough();let s=o instanceof HTMLElement&&e.contains(o)?o:e,c={bubbles:!0,cancelable:!0,clientX:r,clientY:i,pointerType:`mouse`},l={bubbles:!0,cancelable:!0,clientX:r,clientY:i,button:0};s.dispatchEvent(new PointerEvent(`pointerover`,c)),s.dispatchEvent(new PointerEvent(`pointerenter`,{...c,bubbles:!1})),s.dispatchEvent(new MouseEvent(`mouseover`,l)),s.dispatchEvent(new MouseEvent(`mouseenter`,{...l,bubbles:!1})),s.dispatchEvent(new PointerEvent(`pointerdown`,c)),s.dispatchEvent(new MouseEvent(`mousedown`,l)),e.focus({preventScroll:!0}),s.dispatchEvent(new PointerEvent(`pointerup`,c)),s.dispatchEvent(new MouseEvent(`mouseup`,l)),s.click(),await waitFor(.2)}async function inputTextElement(e,t){let n=e.isContentEditable;if(!isInputElement(e)&&!isTextAreaElement(e)&&!n)throw Error(`Element is not an input, textarea, or contenteditable`);if(await clickElement(e),n){if(e.dispatchEvent(new InputEvent(`beforeinput`,{bubbles:!0,cancelable:!0,inputType:`deleteContent`}))&&(e.innerText=``,e.dispatchEvent(new InputEvent(`input`,{bubbles:!0,inputType:`deleteContent`}))),e.dispatchEvent(new InputEvent(`beforeinput`,{bubbles:!0,cancelable:!0,inputType:`insertText`,data:t}))&&(e.innerText=t,e.dispatchEvent(new InputEvent(`input`,{bubbles:!0,inputType:`insertText`,data:t}))),e.innerText.trim()!==t.trim()){e.focus();let n=e.ownerDocument,r=(n.defaultView||window).getSelection(),i=n.createRange();i.selectNodeContents(e),r?.removeAllRanges(),r?.addRange(i),n.execCommand(`delete`,!1),n.execCommand(`insertText`,!1,t)}e.dispatchEvent(new Event(`change`,{bubbles:!0})),e.blur()}else getNativeValueSetter(e).call(e,t);n||e.dispatchEvent(new Event(`input`,{bubbles:!0})),await waitFor(.1)}async function selectOptionElement(e,t){if(!isSelectElement(e))throw Error(`Element is not a select element`);let n=Array.from(e.options).find(e=>e.textContent?.trim()===t.trim());if(!n)throw Error(`Option with text "${t}" not found in select element`);e.value=n.value,e.dispatchEvent(new Event(`change`,{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(e){let t=e;typeof t.scrollIntoViewIfNeeded==`function`?t.scrollIntoViewIfNeeded():e.scrollIntoView({behavior:`auto`,block:`center`,inline:`nearest`})}async function scrollVertically(e,t){if(t){let n=t,r=n,i=!1,a=null,o=0,s=0,c=e;for(;r&&s<10;){let e=window.getComputedStyle(r),t=/(auto|scroll|overlay)/.test(e.overflowY)||e.scrollbarWidth&&e.scrollbarWidth!==`auto`||e.scrollbarGutter&&e.scrollbarGutter!==`auto`,n=r.scrollHeight>r.clientHeight;if(t&&n){let e=r.scrollTop,t=r.scrollHeight-r.clientHeight,n=c/3;n=n>0?Math.min(n,t-e):Math.max(n,-e),r.scrollTop=e+n;let s=r.scrollTop-e;if(Math.abs(s)>.5){i=!0,a=r,o=s;break}}if(r===document.body||r===document.documentElement)break;r=r.parentElement,s++}return i?`Scrolled container (${a?.tagName}) by ${o}px`:`No scrollable container found for element (${n.tagName})`}let n=e,r=e=>e.clientHeight>=window.innerHeight*.5,i=e=>!!(e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowY)&&e.scrollHeight>e.clientHeight&&r(e)),a=document.activeElement;for(;a&&!i(a)&&a!==document.body;)a=a.parentElement;if(a=i(a)?a:Array.from(document.querySelectorAll(`*`)).find(i)||document.scrollingElement||document.documentElement,a===document.scrollingElement||a===document.documentElement||a===document.body){let e=window.scrollY,t=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,n);let r=window.scrollY,i=r-e;return Math.abs(i)<1?n>0?`⚠️ Already at the bottom of the page, cannot scroll down further.`:`⚠️ Already at the top of the page, cannot scroll up further.`:n>0&&r>=t-1?`✅ Scrolled page by ${i}px. Reached the bottom of the page.`:n<0&&r<=1?`✅ Scrolled page by ${i}px. Reached the top of the page.`:`✅ Scrolled page by ${i}px.`}{let e=`The document is not scrollable. Falling back to container scroll.`;console.log(`[PageController] ${e}`);let t=a.scrollTop,r=a.scrollHeight-a.clientHeight;a.scrollBy({top:n,behavior:`smooth`}),await waitFor(.1);let i=a.scrollTop,o=i-t;return Math.abs(o)<1?n>0?`⚠️ ${e} Already at the bottom of container (${a.tagName}), cannot scroll down further.`:`⚠️ ${e} Already at the top of container (${a.tagName}), cannot scroll up further.`:n>0&&i>=r-1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the bottom.`:n<0&&i<=1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the top.`:`✅ ${e} Scrolled container (${a.tagName}) by ${o}px.`}}async function scrollHorizontally(e,t){if(t){let n=t,r=n,i=!1,a=null,o=0,s=0,c=e;for(;r&&s<10;){let e=window.getComputedStyle(r),t=/(auto|scroll|overlay)/.test(e.overflowX)||e.scrollbarWidth&&e.scrollbarWidth!==`auto`||e.scrollbarGutter&&e.scrollbarGutter!==`auto`,n=r.scrollWidth>r.clientWidth;if(t&&n){let e=r.scrollLeft,t=r.scrollWidth-r.clientWidth,n=c/3;n=n>0?Math.min(n,t-e):Math.max(n,-e),r.scrollLeft=e+n;let s=r.scrollLeft-e;if(Math.abs(s)>.5){i=!0,a=r,o=s;break}}if(r===document.body||r===document.documentElement)break;r=r.parentElement,s++}return i?`Scrolled container (${a?.tagName}) horizontally by ${o}px`:`No horizontally scrollable container found for element (${n.tagName})`}let n=e,r=e=>e.clientWidth>=window.innerWidth*.5,i=e=>!!(e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowX)&&e.scrollWidth>e.clientWidth&&r(e)),a=document.activeElement;for(;a&&!i(a)&&a!==document.body;)a=a.parentElement;if(a=i(a)?a:Array.from(document.querySelectorAll(`*`)).find(i)||document.scrollingElement||document.documentElement,a===document.scrollingElement||a===document.documentElement||a===document.body){let e=window.scrollX,t=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(n,0);let r=window.scrollX,i=r-e;return Math.abs(i)<1?n>0?`⚠️ Already at the right edge of the page, cannot scroll right further.`:`⚠️ Already at the left edge of the page, cannot scroll left further.`:n>0&&r>=t-1?`✅ Scrolled page by ${i}px. Reached the right edge of the page.`:n<0&&r<=1?`✅ Scrolled page by ${i}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${i}px.`}{let e=`The document is not scrollable. Falling back to container scroll.`;console.log(`[PageController] ${e}`);let t=a.scrollLeft,r=a.scrollWidth-a.clientWidth;a.scrollBy({left:n,behavior:`smooth`}),await waitFor(.1);let i=a.scrollLeft,o=i-t;return Math.abs(o)<1?n>0?`⚠️ ${e} Already at the right edge of container (${a.tagName}), cannot scroll right further.`:`⚠️ ${e} Already at the left edge of container (${a.tagName}), cannot scroll left further.`:n>0&&i>=r-1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the right edge.`:n<0&&i<=1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the left edge.`:`✅ ${e} Scrolled container (${a.tagName}) horizontally by ${o}px.`}}var dom_tree_default=(e={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{let{interactiveBlacklist:t,interactiveWhitelist:n,highlightOpacity:r,highlightLabelOpacity:i}=e,{doHighlightElements:a,focusHighlightIndex:o,viewportExpansion:s,debugMode:c}=e,l=0,u=new WeakMap;function d(e,t){e&&e.nodeType===Node.ELEMENT_NODE&&u.set(e,{...u.get(e),...t})}let f={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{f.boundingRects=new WeakMap,f.clientRects=new WeakMap,f.computedStyles=new WeakMap}};function p(e){if(!e)return null;if(f.boundingRects.has(e))return f.boundingRects.get(e);let t=e.getBoundingClientRect();return t&&f.boundingRects.set(e,t),t}function m(e){if(!e)return null;if(f.computedStyles.has(e))return f.computedStyles.get(e);let t=window.getComputedStyle(e);return t&&f.computedStyles.set(e,t),t}function h(e){if(!e)return null;if(f.clientRects.has(e))return f.clientRects.get(e);let t=e.getClientRects();return t&&f.clientRects.set(e,t),t}let g={},_={current:0},v=`playwright-highlight-container`;function y(e,t,n=null){if(!e)return t;let a=[],o=null,s=20,c=16,l=null;try{let u=document.getElementById(v);u||(u=document.createElement(`div`),u.id=v,u.style.position=`fixed`,u.style.pointerEvents=`none`,u.style.top=`0`,u.style.left=`0`,u.style.width=`100%`,u.style.height=`100%`,u.style.zIndex=`2147483640`,u.style.backgroundColor=`transparent`,document.body.appendChild(u));let d=e.getClientRects();if(!d||d.length===0)return t;let f=[`#FF0000`,`#00FF00`,`#0000FF`,`#FFA500`,`#800080`,`#008080`,`#FF69B4`,`#4B0082`,`#FF4500`,`#2E8B57`,`#DC143C`,`#4682B4`],p=f[t%f.length],m=p+Math.floor(r*255).toString(16).padStart(2,`0`);p+=Math.floor(i*255).toString(16).padStart(2,`0`);let h={x:0,y:0};if(n){let e=n.getBoundingClientRect();h.x=e.left,h.y=e.top}let g=document.createDocumentFragment();for(let e of d){if(e.width===0||e.height===0)continue;let t=document.createElement(`div`);t.style.position=`fixed`,t.style.border=`2px solid ${p}`,t.style.backgroundColor=m,t.style.pointerEvents=`none`,t.style.boxSizing=`border-box`;let n=e.top+h.y,r=e.left+h.x;t.style.top=`${n}px`,t.style.left=`${r}px`,t.style.width=`${e.width}px`,t.style.height=`${e.height}px`,g.appendChild(t),a.push({element:t,initialRect:e})}let _=d[0];o=document.createElement(`div`),o.className=`playwright-highlight-label`,o.style.position=`fixed`,o.style.background=p,o.style.color=`white`,o.style.padding=`1px 4px`,o.style.borderRadius=`4px`,o.style.fontSize=`${Math.min(12,Math.max(8,_.height/2))}px`,o.textContent=t.toString(),s=o.offsetWidth>0?o.offsetWidth:s,c=o.offsetHeight>0?o.offsetHeight:c;let y=_.top+h.y,b=_.left+h.x,x=y+2,S=b+_.width-s-2;(_.width<s+4||_.height<c+4)&&(x=y-c-2,S=b+_.width-s,S<h.x&&(S=b)),x=Math.max(0,Math.min(x,window.innerHeight-c)),S=Math.max(0,Math.min(S,window.innerWidth-s)),o.style.top=`${x}px`,o.style.left=`${S}px`,g.appendChild(o);let C=((e,t)=>{let n=0;return(...r)=>{let i=performance.now();if(!(i-n<t))return n=i,e(...r)}})(()=>{let t=e.getClientRects(),r={x:0,y:0};if(n){let e=n.getBoundingClientRect();r.x=e.left,r.y=e.top}if(a.forEach((e,n)=>{if(n<t.length){let i=t[n],a=i.top+r.y,o=i.left+r.x;e.element.style.top=`${a}px`,e.element.style.left=`${o}px`,e.element.style.width=`${i.width}px`,e.element.style.height=`${i.height}px`,e.element.style.display=i.width===0||i.height===0?`none`:`block`}else e.element.style.display=`none`}),t.length<a.length)for(let e=t.length;e<a.length;e++)a[e].element.style.display=`none`;if(o&&t.length>0){let e=t[0],n=e.top+r.y,i=e.left+r.x,a=n+2,l=i+e.width-s-2;(e.width<s+4||e.height<c+4)&&(a=n-c-2,l=i+e.width-s,l<r.x&&(l=i)),a=Math.max(0,Math.min(a,window.innerHeight-c)),l=Math.max(0,Math.min(l,window.innerWidth-s)),o.style.top=`${a}px`,o.style.left=`${l}px`,o.style.display=`block`}else o&&(o.style.display=`none`)},16);return window.addEventListener(`scroll`,C,!0),window.addEventListener(`resize`,C),l=()=>{window.removeEventListener(`scroll`,C,!0),window.removeEventListener(`resize`,C),a.forEach(e=>e.element.remove()),o&&o.remove()},u.appendChild(g),t+1}finally{l&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(l)}}function b(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return null;let t=m(e);if(!t)return null;let n=t.display;if(n===`inline`||n===`inline-block`)return null;let r=t.overflowX,i=t.overflowY,a=t.scrollbarWidth&&t.scrollbarWidth!==`auto`||t.scrollbarGutter&&t.scrollbarGutter!==`auto`,o=r===`auto`||r===`scroll`,s=i===`auto`||i===`scroll`;if(!o&&!s&&!a)return null;let c=e.scrollWidth-e.clientWidth,l=e.scrollHeight-e.clientHeight,u=4;if(c<4&&l<4||!s&&!a&&c<4||!o&&!a&&l<4)return null;let f=e.scrollTop,p=e.scrollLeft,h={top:f,right:e.scrollWidth-e.clientWidth-e.scrollLeft,bottom:e.scrollHeight-e.clientHeight-e.scrollTop,left:p};return d(e,{scrollable:!0,scrollData:h}),h}function x(e){try{if(s===-1){let t=e.parentElement;if(!t)return!1;try{return t.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{let e=window.getComputedStyle(t);return e.display!==`none`&&e.visibility!==`hidden`&&e.opacity!==`0`}}let t=document.createRange();t.selectNodeContents(e);let n=t.getClientRects();if(!n||n.length===0)return!1;let r=!1,i=!1;for(let e of n)if(e.width>0&&e.height>0&&(r=!0,!(e.bottom<-s||e.top>window.innerHeight+s||e.right<-s||e.left>window.innerWidth+s))){i=!0;break}if(!r||!i)return!1;let a=e.parentElement;if(!a)return!1;try{return a.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{let e=window.getComputedStyle(a);return e.display!==`none`&&e.visibility!==`hidden`&&e.opacity!==`0`}}catch(e){return console.warn(`Error checking text node visibility:`,e),!1}}function S(e){if(!e||!e.tagName)return!1;let t=new Set([`body`,`div`,`main`,`article`,`section`,`nav`,`header`,`footer`]),n=e.tagName.toLowerCase();return t.has(n)?!0:!new Set([`svg`,`script`,`style`,`link`,`meta`,`noscript`,`template`]).has(n)}function C(e){let t=m(e);return e.offsetWidth>0&&e.offsetHeight>0&&t?.visibility!==`hidden`&&t?.display!==`none`}function w(e){if(!e||e.nodeType!==Node.ELEMENT_NODE||t.includes(e))return!1;if(n.includes(e))return!0;let r=e.tagName.toLowerCase(),i=m(e),a=new Set(`pointer.move.text.grab.grabbing.cell.copy.alias.all-scroll.col-resize.context-menu.crosshair.e-resize.ew-resize.help.n-resize.ne-resize.nesw-resize.ns-resize.nw-resize.nwse-resize.row-resize.s-resize.se-resize.sw-resize.vertical-text.w-resize.zoom-in.zoom-out`.split(`.`)),o=new Set([`not-allowed`,`no-drop`,`wait`,`progress`,`initial`,`inherit`]);function s(e){return e.tagName.toLowerCase()!==`html`&&!!(i?.cursor&&a.has(i.cursor))}if(s(e))return!0;let c=new Set([`a`,`button`,`input`,`select`,`textarea`,`details`,`summary`,`label`,`option`,`optgroup`,`fieldset`,`legend`]),l=new Set([`disabled`,`readonly`]);if(c.has(r)){if(i?.cursor&&o.has(i.cursor))return!1;for(let t of l)if(e.hasAttribute(t)||e.getAttribute(t)===`true`||e.getAttribute(t)===``)return!1;return!(e.disabled||e.readOnly||e.inert)}let u=e.getAttribute(`role`),d=e.getAttribute(`aria-role`);if(e.getAttribute(`contenteditable`)===`true`||e.isContentEditable||e.classList&&(e.classList.contains(`button`)||e.classList.contains(`dropdown-toggle`)||e.getAttribute(`data-index`)||e.getAttribute(`data-toggle`)===`dropdown`||e.getAttribute(`aria-haspopup`)===`true`))return!0;let f=new Set([`button`,`menu`,`menubar`,`menuitem`,`menuitemradio`,`menuitemcheckbox`,`radio`,`checkbox`,`tab`,`switch`,`slider`,`spinbutton`,`combobox`,`searchbox`,`textbox`,`listbox`,`option`,`scrollbar`]);if(c.has(r)||u&&f.has(u)||d&&f.has(d))return!0;try{if(typeof getEventListeners==`function`){let t=getEventListeners(e);for(let e of[`click`,`mousedown`,`mouseup`,`dblclick`])if(t[e]&&t[e].length>0)return!0}let t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof t==`function`){let n=t(e);for(let e of[`click`,`mousedown`,`mouseup`,`keydown`,`keyup`,`submit`,`change`,`input`,`focus`,`blur`])for(let t of n)if(t.type===e)return!0}for(let t of[`onclick`,`onmousedown`,`onmouseup`,`ondblclick`])if(e.hasAttribute(t)||typeof e[t]==`function`)return!0}catch{}return!!b(e)}function T(e){if(s===-1)return!0;let t=h(e);if(!t||t.length===0)return!1;let n=!1;for(let e of t)if(e.width>0&&e.height>0&&!(e.bottom<-s||e.top>window.innerHeight+s||e.right<-s||e.left>window.innerWidth+s)){n=!0;break}if(!n)return!1;if(e.ownerDocument!==window.document)return!0;let r=Array.from(t).find(e=>e.width>0&&e.height>0);if(!r)return!1;let i=e.getRootNode();if(i instanceof ShadowRoot){let t=r.left+r.width/2,n=r.top+r.height/2;try{let r=i.elementFromPoint(t,n);if(!r)return!1;let a=r;for(;a&&a!==i;){if(a===e)return!0;a=a.parentElement}return!1}catch{return!0}}let a=5;return[{x:r.left+r.width/2,y:r.top+r.height/2},{x:r.left+5,y:r.top+5},{x:r.right-5,y:r.bottom-5}].some(({x:t,y:n})=>{try{let r=document.elementFromPoint(t,n);if(!r)return!1;let i=r;for(;i&&i!==document.documentElement;){if(i===e)return!0;i=i.parentElement}return!1}catch{return!0}})}function E(e,t){if(t===-1)return!0;let n=e.getClientRects();if(!n||n.length===0){let n=p(e);return!n||n.width===0||n.height===0?!1:!(n.bottom<-t||n.top>window.innerHeight+t||n.right<-t||n.left>window.innerWidth+t)}for(let e of n)if(e.width!==0&&e.height!==0&&!(e.bottom<-t||e.top>window.innerHeight+t||e.right<-t||e.left>window.innerWidth+t))return!0;return!1}let D=[`aria-expanded`,`aria-checked`,`aria-selected`,`aria-pressed`,`aria-haspopup`,`aria-controls`,`aria-owns`,`aria-activedescendant`,`aria-valuenow`,`aria-valuetext`,`aria-valuemax`,`aria-valuemin`,`aria-autocomplete`];function O(e){for(let t=0;t<D.length;t++)if(e.hasAttribute(D[t]))return!0;return!1}function k(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;let t=e.tagName.toLowerCase();return new Set([`a`,`button`,`input`,`select`,`textarea`,`details`,`summary`,`label`]).has(t)?!0:e.hasAttribute(`onclick`)||e.hasAttribute(`role`)||e.hasAttribute(`tabindex`)||O(e)||e.hasAttribute(`data-action`)||e.getAttribute(`contenteditable`)===`true`}let A=new Set([`a`,`button`,`input`,`select`,`textarea`,`summary`,`details`,`label`,`option`,`li`]),j=new Set([`button`,`link`,`menuitem`,`menuitemradio`,`menuitemcheckbox`,`radio`,`checkbox`,`tab`,`switch`,`slider`,`spinbutton`,`combobox`,`searchbox`,`textbox`,`listbox`,`listitem`,`treeitem`,`row`,`option`,`scrollbar`]);function M(e){if(!e||e.nodeType!==Node.ELEMENT_NODE||!C(e))return!1;let t=e.hasAttribute(`role`)||e.hasAttribute(`tabindex`)||e.hasAttribute(`onclick`)||typeof e.onclick==`function`,n=/\b(btn|clickable|menu|item|entry|link)\b/i.test(e.className||``),r=!!e.closest(`button,a,[role="button"],.menu,.dropdown,.list,.toolbar`),i=[...e.children].some(C),a=e.parentElement&&e.parentElement.isSameNode(document.body);return(w(e)||t||n)&&i&&r&&!a}function N(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;let t=e.tagName.toLowerCase(),n=e.getAttribute(`role`);if(t===`iframe`||A.has(t)||n&&j.has(n)||e.isContentEditable||e.getAttribute(`contenteditable`)===`true`||e.hasAttribute(`data-testid`)||e.hasAttribute(`data-cy`)||e.hasAttribute(`data-test`)||e.hasAttribute(`onclick`)||typeof e.onclick==`function`||O(e))return!0;try{let t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof t==`function`){let n=t(e);for(let e of[`click`,`mousedown`,`mouseup`,`keydown`,`keyup`,`submit`,`change`,`input`,`focus`,`blur`])for(let t of n)if(t.type===e)return!0}if([`onmousedown`,`onmouseup`,`onkeydown`,`onkeyup`,`onsubmit`,`onchange`,`oninput`,`onfocus`,`onblur`].some(t=>e.hasAttribute(t)))return!0}catch{}return!!(M(e)||u.get(e)?.scrollable)}function P(e,t,n,r){if(!e.isInteractive)return!1;let i=!1;return i=!r||!!N(t),i&&(e.isInViewport=E(t,s),(e.isInViewport||s===-1)&&(e.highlightIndex=l++,a))?(o>=0?o===e.highlightIndex&&y(t,e.highlightIndex,n):y(t,e.highlightIndex,n),!0):!1}function F(e,t=null,n=!1){if(!e||e.id===v||e.nodeType!==Node.ELEMENT_NODE&&e.nodeType!==Node.TEXT_NODE||!e||e.id===v||e.dataset?.browserUseIgnore===`true`||e.dataset?.pageAgentIgnore===`true`||e.getAttribute&&e.getAttribute(`aria-hidden`)===`true`)return null;if(e===document.body){let n={tagName:`body`,attributes:{},xpath:`/body`,children:[]};for(let r of e.childNodes){let e=F(r,t,!1);e&&n.children.push(e)}let r=`${_.current++}`;return g[r]=n,r}if(e.nodeType!==Node.ELEMENT_NODE&&e.nodeType!==Node.TEXT_NODE)return null;if(e.nodeType===Node.TEXT_NODE){let t=e.textContent?.trim();if(!t)return null;let n=e.parentElement;if(!n||n.tagName.toLowerCase()===`script`)return null;let r=`${_.current++}`;return g[r]={type:`TEXT_NODE`,text:t,isVisible:x(e)},r}if(e.nodeType===Node.ELEMENT_NODE&&!S(e))return null;if(s!==-1&&!e.shadowRoot){let t=p(e),n=m(e),r=n&&(n.position===`fixed`||n.position===`sticky`),i=e.offsetWidth>0||e.offsetHeight>0;if(!t||!r&&!i&&(t.bottom<-s||t.top>window.innerHeight+s||t.right<-s||t.left>window.innerWidth+s))return null}let r={tagName:e.tagName.toLowerCase(),attributes:{},children:[]};if(k(e)||e.tagName.toLowerCase()===`iframe`||e.tagName.toLowerCase()===`body`){let t=e.getAttributeNames?.()||[];for(let n of t){let t=e.getAttribute(n);r.attributes[n]=t}e.tagName.toLowerCase()===`input`&&(e.type===`checkbox`||e.type===`radio`)&&(r.attributes.checked=e.checked?`true`:`false`)}let i=!1;if(e.nodeType===Node.ELEMENT_NODE&&(r.isVisible=C(e),r.isVisible)){r.isTopElement=T(e);let a=e.getAttribute(`role`),o=a===`menu`||a===`menubar`||a===`listbox`;if((r.isTopElement||o)&&(r.isInteractive=w(e),i=P(r,e,t,n),r.ref=e,r.isInteractive&&Object.keys(r.attributes).length===0)){let t=e.getAttributeNames?.()||[];for(let n of t){let t=e.getAttribute(n);r.attributes[n]=t}}}if(e.tagName){let a=e.tagName.toLowerCase();if(a===`iframe`)try{let t=e.contentDocument||e.contentWindow?.document;if(t)for(let n of t.childNodes){let t=F(n,e,!1);t&&r.children.push(t)}}catch(e){console.warn(`Unable to access iframe:`,e)}else if(e.isContentEditable||e.getAttribute(`contenteditable`)===`true`||e.id===`tinymce`||e.classList.contains(`mce-content-body`)||a===`body`&&e.getAttribute(`data-id`)?.startsWith(`mce_`))for(let n of e.childNodes){let e=F(n,t,i);e&&r.children.push(e)}else{if(e.shadowRoot){r.shadowRoot=!0;for(let n of e.shadowRoot.childNodes){let e=F(n,t,i);e&&r.children.push(e)}}for(let a of e.childNodes){let e=F(a,t,i||n);e&&r.children.push(e)}}}if(r.tagName===`a`&&r.children.length===0&&!r.attributes.href){let t=p(e);if(!(t&&t.width>0&&t.height>0||e.offsetWidth>0||e.offsetHeight>0))return null}r.extra=u.get(e)||null;let a=`${_.current++}`;return g[a]=r,a}let I=F(document.body);return f.clearCache(),{rootId:I,map:g}},dom_exports=__exportAll({cleanUpHighlights:()=>cleanUpHighlights,flatTreeToString:()=>flatTreeToString,getAllTextTillNextClickableElement:()=>getAllTextTillNextClickableElement,getElementTextMap:()=>getElementTextMap,getFlatTree:()=>getFlatTree,getSelectorMap:()=>getSelectorMap,resolveViewportExpansion:()=>resolveViewportExpansion}),DEFAULT_VIEWPORT_EXPANSION=-1;function resolveViewportExpansion(e){return e??DEFAULT_VIEWPORT_EXPANSION}var SEMANTIC_TAGS=new Set([`nav`,`menu`,`header`,`footer`,`aside`,`dialog`]),newElementsCache=new WeakMap;function getFlatTree(e){let t=resolveViewportExpansion(e.viewportExpansion),n=[];for(let t of e.interactiveBlacklist||[])typeof t==`function`?n.push(t()):n.push(t);let r=[];for(let t of e.interactiveWhitelist||[])typeof t==`function`?r.push(t()):r.push(t);let i=dom_tree_default({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:t,interactiveBlacklist:n,interactiveWhitelist:r,highlightOpacity:e.highlightOpacity??0,highlightLabelOpacity:e.highlightLabelOpacity??.1}),a=window.location.href;for(let e in i.map){let t=i.map[e];if(t.isInteractive&&t.ref){let e=t.ref;newElementsCache.has(e)||(newElementsCache.set(e,a),t.isNew=!0)}}return i}var globRegexCache=new Map;function globToRegex(e){let t=globRegexCache.get(e);if(!t){let n=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`);t=RegExp(`^${n.replace(/\*/g,`.*`)}$`),globRegexCache.set(e,t)}return t}function matchAttributes(e,t){let n={};for(let r of t)if(r.includes(`*`)){let t=globToRegex(r);for(let r of Object.keys(e))t.test(r)&&e[r].trim()&&(n[r]=e[r].trim())}else{let t=e[r];t&&t.trim()&&(n[r]=t.trim())}return n}function flatTreeToString(e,t=[],n=!1){let r=[`title`,`type`,`checked`,`name`,`role`,`value`,`placeholder`,`data-date-format`,`alt`,`aria-label`,`aria-expanded`,`data-state`,`aria-checked`,`id`,`for`,`target`,`aria-haspopup`,`aria-controls`,`aria-owns`,`contenteditable`],i=[...t,...r],a=(e,t)=>e.length>t?e.substring(0,t)+`...`:e,o=t=>{let n=e.map[t];if(!n)return null;if(n.type===`TEXT_NODE`){let e=n;return{type:`text`,text:e.text,isVisible:e.isVisible,parent:null,children:[]}}{let e=n,t=[];if(e.children)for(let n of e.children){let e=o(n);e&&(e.parent=null,t.push(e))}return{type:`element`,tagName:e.tagName,attributes:e.attributes??{},isVisible:e.isVisible??!1,isInteractive:e.isInteractive??!1,isTopElement:e.isTopElement??!1,isNew:e.isNew??!1,highlightIndex:e.highlightIndex,parent:null,children:t,extra:e.extra??{}}}},s=(e,t=null)=>{e.parent=t;for(let t of e.children)s(t,e)},c=o(e.rootId);if(!c)return``;s(c);let l=e=>{let t=e.parent;for(;t;){if(t.type===`element`&&t.highlightIndex!==void 0)return!0;t=t.parent}return!1},u=(e,t,r)=>{let o=t,s=` `.repeat(t);if(e.type===`element`){let t=n&&e.tagName&&SEMANTIC_TAGS.has(e.tagName);if(e.highlightIndex!==void 0){o+=1;let t=getAllTextTillNextClickableElement(e),n=``;if(i.length>0&&e.attributes){let r=matchAttributes(e.attributes,i),o=Object.keys(r);if(o.length>1){let e=new Set,t={};for(let n of o){let i=r[n];i.length>5&&(i in t?e.add(n):t[i]=n)}for(let t of e)delete r[t]}r.role===e.tagName&&delete r.role;for(let e of[`aria-label`,`placeholder`,`title`])r[e]&&r[e].toLowerCase().trim()===t.toLowerCase().trim()&&delete r[e];Object.keys(r).length>0&&(n=Object.entries(r).map(([e,t])=>`${e}=${a(t,20)}`).join(` `))}let c=`${s}${e.isNew?`*[${e.highlightIndex}]`:`[${e.highlightIndex}]`}<${e.tagName??``}`;if(n&&(c+=` ${n}`),e.extra&&e.extra.scrollable){let t=``;e.extra.scrollData?.left&&(t+=`left=${e.extra.scrollData.left}, `),e.extra.scrollData?.top&&(t+=`top=${e.extra.scrollData.top}, `),e.extra.scrollData?.right&&(t+=`right=${e.extra.scrollData.right}, `),e.extra.scrollData?.bottom&&(t+=`bottom=${e.extra.scrollData.bottom}`),c+=` data-scrollable="${t}"`}if(t){let e=t.trim();n||(c+=` `),c+=`>${e}`}else n||(c+=` `);c+=` />`,r.push(c)}let c=t&&e.highlightIndex===void 0,l=c?r.length:-1;c&&(r.push(`${s}<${e.tagName}>`),o+=1);for(let t of e.children)u(t,o,r);c&&(r.length===l+1?r.pop():r.push(`${s}</${e.tagName}>`))}else if(e.type===`text`){if(l(e))return;e.parent&&e.parent.type===`element`&&e.parent.isVisible&&e.parent.isTopElement&&r.push(`${s}${e.text??``}`)}},d=[];return u(c,0,d),d.join(`
|
|
231
|
-
`)}var getAllTextTillNextClickableElement=(e,t=-1)=>{let n=[],r=(i,a)=>{if(!(t!==-1&&a>t)&&(i.type!==`element`||i===e||i.highlightIndex===void 0)){if(i.type===`text`&&i.text)n.push(i.text);else if(i.type===`element`)for(let e of i.children)r(e,a+1)}};return r(e,0),n.join(`
|
|
232
|
-
`).trim()};function getSelectorMap(e){let t=new Map,n=Object.keys(e.map);for(let r of n){let n=e.map[r];n.isInteractive&&typeof n.highlightIndex==`number`&&t.set(n.highlightIndex,n)}return t}function getElementTextMap(e){let t=e.split(`
|
|
233
|
-
`).map(e=>e.trim()).filter(e=>e.length>0),n=new Map;for(let e of t){let t=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(e);if(t){let r=parseInt(t[1],10);n.set(r,e)}}return n}function cleanUpHighlights(){let e=window._highlightCleanupFunctions||[];for(let t of e)typeof t==`function`&&t();window._highlightCleanupFunctions=[]}window.addEventListener(`popstate`,()=>{cleanUpHighlights()}),window.addEventListener(`hashchange`,()=>{cleanUpHighlights()}),window.addEventListener(`beforeunload`,()=>{cleanUpHighlights()});var navigation=window.navigation;if(navigation&&typeof navigation.addEventListener==`function`)navigation.addEventListener(`navigate`,()=>{cleanUpHighlights()});else{let e=window.location.href;setInterval(()=>{window.location.href!==e&&(e=window.location.href,cleanUpHighlights())},500)}function getPageInfo(){let e=window.innerWidth,t=window.innerHeight,n=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),r=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),i=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,a=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,o=Math.max(0,r-(window.innerHeight+a)),s=Math.max(0,n-(window.innerWidth+i));return{viewport_width:e,viewport_height:t,page_width:n,page_height:r,scroll_x:i,scroll_y:a,pixels_above:a,pixels_below:o,pages_above:t>0?a/t:0,pages_below:t>0?o/t:0,total_pages:t>0?r/t:0,current_page_position:a/Math.max(1,r-t),pixels_left:i,pixels_right:s}}function patchReact(e){let t=document.querySelectorAll(`[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root`);for(let e of t)e.setAttribute(`data-page-agent-not-interactive`,`true`)}function computeBorderGeometry(e,t,n,r){let i=Math.max(1,Math.min(e,t)),a=Math.min(Math.min(n,20)+r,i),o=Math.min(a,Math.floor(e/2)),s=Math.min(a,Math.floor(t/2)),c=t=>t/e*2-1,l=e=>e/t*2-1,u=0,d=e,f=0,p=t,m=o,h=e-o,g=s,_=t-s,v=c(0),y=c(d),b=l(0),x=l(p),S=c(m),C=c(h),w=l(g),T=l(_),E=0,D=0,O=1,k=1,A=o/e,j=1-o/e,M=s/t,N=1-s/t;return{positions:new Float32Array([v,b,y,b,v,w,v,w,y,b,y,w,v,T,y,T,v,x,v,x,y,T,y,x,v,w,S,w,v,T,v,T,S,w,S,T,C,w,y,w,C,T,C,T,y,w,y,T]),uvs:new Float32Array([0,0,1,0,0,M,0,M,1,0,1,M,0,N,1,N,0,1,0,1,1,N,1,1,0,M,A,M,0,N,0,N,A,M,A,N,j,M,1,M,j,N,j,N,1,M,1,N])}}function compileShader(e,t,n){let r=e.createShader(t);if(!r)throw Error(`Failed to create shader`);if(e.shaderSource(r,n),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){let t=e.getShaderInfoLog(r)||`Unknown shader error`;throw e.deleteShader(r),Error(t)}return r}function createProgram(e,t,n){let r=compileShader(e,e.VERTEX_SHADER,t),i=compileShader(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error(`Failed to create program`);if(e.attachShader(a,r),e.attachShader(a,i),e.linkProgram(a),!e.getProgramParameter(a,e.LINK_STATUS)){let t=e.getProgramInfoLog(a)||`Unknown link error`;throw e.deleteProgram(a),e.deleteShader(r),e.deleteShader(i),Error(t)}return e.deleteShader(r),e.deleteShader(i),a}function parseColor(e){let t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!t)throw Error(`Invalid color format: ${e}`);let[,n,r,i]=t;return[parseInt(n)/255,parseInt(r)/255,parseInt(i)/255]}var fragmentShaderSource,vertexShaderSource,DEFAULT_COLORS,Motion,init_Motion=__esmMin((()=>{fragmentShaderSource=`#version 300 es
|
|
234
|
-
precision lowp float;
|
|
235
|
-
in vec2 vUV;
|
|
236
|
-
out vec4 outColor;
|
|
237
|
-
uniform vec2 uResolution;
|
|
238
|
-
uniform float uTime;
|
|
239
|
-
uniform float uBorderWidth;
|
|
240
|
-
uniform float uGlowWidth;
|
|
241
|
-
uniform float uBorderRadius;
|
|
242
|
-
uniform vec3 uColors[4];
|
|
243
|
-
uniform float uGlowExponent;
|
|
244
|
-
uniform float uGlowFactor;
|
|
245
|
-
const float PI = 3.14159265359;
|
|
246
|
-
const float TWO_PI = 2.0 * PI;
|
|
247
|
-
const float HALF_PI = 0.5 * PI;
|
|
248
|
-
const vec4 startPositions = vec4(0.0, PI, HALF_PI, 1.5 * PI);
|
|
249
|
-
const vec4 speeds = vec4(-1.9, -1.9, -1.5, 2.1);
|
|
250
|
-
const vec4 innerRadius = vec4(PI * 0.8, PI * 0.7, PI * 0.3, PI * 0.1);
|
|
251
|
-
const vec4 outerRadius = vec4(PI * 1.2, PI * 0.9, PI * 0.6, PI * 0.4);
|
|
252
|
-
float random(vec2 st) {
|
|
253
|
-
return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453123);
|
|
254
|
-
}
|
|
255
|
-
vec2 random2(vec2 st) {
|
|
256
|
-
return vec2(random(st), random(st + 1.0));
|
|
257
|
-
}
|
|
258
|
-
float aaStep(float edge, float d) {
|
|
259
|
-
float width = fwidth(d);
|
|
260
|
-
return smoothstep(edge - width * 0.5, edge + width * 0.5, d);
|
|
261
|
-
}
|
|
262
|
-
float aaFract(float x) {
|
|
263
|
-
float f = fract(x);
|
|
264
|
-
float w = fwidth(x);
|
|
265
|
-
float smooth_f = f * (1.0 - smoothstep(1.0 - w, 1.0, f));
|
|
266
|
-
return smooth_f;
|
|
267
|
-
}
|
|
268
|
-
float sdRoundedBox(in vec2 p, in vec2 b, in float r) {
|
|
269
|
-
vec2 q = abs(p) - b + r;
|
|
270
|
-
return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r;
|
|
271
|
-
}
|
|
272
|
-
float getInnerGlow(vec2 p, vec2 b, float radius) {
|
|
273
|
-
float dist_x = b.x - abs(p.x);
|
|
274
|
-
float dist_y = b.y - abs(p.y);
|
|
275
|
-
float glow_x = smoothstep(radius, 0.0, dist_x);
|
|
276
|
-
float glow_y = smoothstep(radius, 0.0, dist_y);
|
|
277
|
-
return 1.0 - (1.0 - glow_x) * (1.0 - glow_y);
|
|
278
|
-
}
|
|
279
|
-
float getVignette(vec2 uv) {
|
|
280
|
-
vec2 vignetteUv = uv;
|
|
281
|
-
vignetteUv = vignetteUv * (1.0 - vignetteUv);
|
|
282
|
-
float vignette = vignetteUv.x * vignetteUv.y * 25.0;
|
|
283
|
-
vignette = pow(vignette, 0.16);
|
|
284
|
-
vignette = 1.0 - vignette;
|
|
285
|
-
return vignette;
|
|
286
|
-
}
|
|
287
|
-
float uvToAngle(vec2 uv) {
|
|
288
|
-
vec2 center = vec2(0.5);
|
|
289
|
-
vec2 dir = uv - center;
|
|
290
|
-
return atan(dir.y, dir.x) + PI;
|
|
291
|
-
}
|
|
292
|
-
void main() {
|
|
293
|
-
vec2 uv = vUV;
|
|
294
|
-
vec2 pos = uv * uResolution;
|
|
295
|
-
vec2 centeredPos = pos - uResolution * 0.5;
|
|
296
|
-
vec2 size = uResolution - uBorderWidth;
|
|
297
|
-
vec2 halfSize = size * 0.5;
|
|
298
|
-
float dBorderBox = sdRoundedBox(centeredPos, halfSize, uBorderRadius);
|
|
299
|
-
float border = aaStep(0.0, dBorderBox);
|
|
300
|
-
float glow = getInnerGlow(centeredPos, halfSize, uGlowWidth);
|
|
301
|
-
float vignette = getVignette(uv);
|
|
302
|
-
glow *= vignette;
|
|
303
|
-
float posAngle = uvToAngle(uv);
|
|
304
|
-
vec4 lightCenter = mod(startPositions + speeds * uTime, TWO_PI);
|
|
305
|
-
vec4 angleDist = abs(posAngle - lightCenter);
|
|
306
|
-
vec4 disToLight = min(angleDist, TWO_PI - angleDist) / TWO_PI;
|
|
307
|
-
float intensityBorder[4];
|
|
308
|
-
intensityBorder[0] = 1.0;
|
|
309
|
-
intensityBorder[1] = smoothstep(0.4, 0.0, disToLight.y);
|
|
310
|
-
intensityBorder[2] = smoothstep(0.4, 0.0, disToLight.z);
|
|
311
|
-
intensityBorder[3] = smoothstep(0.2, 0.0, disToLight.w) * 0.5;
|
|
312
|
-
vec3 borderColor = vec3(0.0);
|
|
313
|
-
for(int i = 0; i < 4; i++) {
|
|
314
|
-
borderColor = mix(borderColor, uColors[i], intensityBorder[i]);
|
|
315
|
-
}
|
|
316
|
-
borderColor *= 1.1;
|
|
317
|
-
borderColor = clamp(borderColor, 0.0, 1.0);
|
|
318
|
-
float intensityGlow[4];
|
|
319
|
-
intensityGlow[0] = smoothstep(0.9, 0.0, disToLight.x);
|
|
320
|
-
intensityGlow[1] = smoothstep(0.7, 0.0, disToLight.y);
|
|
321
|
-
intensityGlow[2] = smoothstep(0.4, 0.0, disToLight.z);
|
|
322
|
-
intensityGlow[3] = smoothstep(0.1, 0.0, disToLight.w) * 0.7;
|
|
323
|
-
vec4 breath = smoothstep(0.0, 1.0, sin(uTime * 1.0 + startPositions * PI) * 0.2 + 0.8);
|
|
324
|
-
vec3 glowColor = vec3(0.0);
|
|
325
|
-
glowColor += uColors[0] * intensityGlow[0] * breath.x;
|
|
326
|
-
glowColor += uColors[1] * intensityGlow[1] * breath.y;
|
|
327
|
-
glowColor += uColors[2] * intensityGlow[2] * breath.z;
|
|
328
|
-
glowColor += uColors[3] * intensityGlow[3] * breath.w * glow;
|
|
329
|
-
glow = pow(glow, uGlowExponent);
|
|
330
|
-
glow *= random(pos + uTime) * 0.1 + 1.0;
|
|
331
|
-
glowColor *= glow * uGlowFactor;
|
|
332
|
-
glowColor = clamp(glowColor, 0.0, 1.0);
|
|
333
|
-
vec3 color = mix(glowColor, borderColor + glowColor * 0.2, border);
|
|
334
|
-
float alpha = mix(glow, 1.0, border);
|
|
335
|
-
outColor = vec4(color, alpha);
|
|
336
|
-
}`,vertexShaderSource=`#version 300 es
|
|
337
|
-
in vec2 aPosition;
|
|
338
|
-
in vec2 aUV;
|
|
339
|
-
out vec2 vUV;
|
|
340
|
-
void main() {
|
|
341
|
-
vUV = aUV;
|
|
342
|
-
gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
343
|
-
}`,DEFAULT_COLORS=[`rgb(57, 182, 255)`,`rgb(189, 69, 251)`,`rgb(255, 87, 51)`,`rgb(255, 214, 0)`],Motion=class{element;canvas;options;running=!1;disposed=!1;startTime=0;lastTime=0;rafId=null;glr;observer;constructor(e={}){this.options={width:e.width??600,height:e.height??600,ratio:e.ratio??window.devicePixelRatio??1,borderWidth:e.borderWidth??8,glowWidth:e.glowWidth??200,borderRadius:e.borderRadius??8,mode:e.mode??`light`,...e},this.canvas=document.createElement(`canvas`),this.options.classNames&&(this.canvas.className=this.options.classNames),this.options.styles&&Object.assign(this.canvas.style,this.options.styles),this.canvas.style.display=`block`,this.canvas.style.transformOrigin=`center`,this.canvas.style.pointerEvents=`none`,this.element=this.canvas,this.setupGL(),this.options.skipGreeting||this.greet()}start(){if(this.disposed)throw Error(`Motion instance has been disposed.`);if(this.running)return;if(!this.glr){console.error(`WebGL resources are not initialized.`);return}this.running=!0,this.startTime=performance.now(),this.resize(this.options.width??600,this.options.height??600,this.options.ratio),this.glr.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.glr.gl.useProgram(this.glr.program),this.glr.gl.uniform2f(this.glr.uResolution,this.canvas.width,this.canvas.height),this.checkGLError(this.glr.gl,`start: after initial setup`);let e=()=>{if(!this.running||!this.glr)return;this.rafId=requestAnimationFrame(e);let t=performance.now();if(t-this.lastTime<1e3/32)return;this.lastTime=t;let n=(t-this.startTime)*.001;this.render(n)};this.rafId=requestAnimationFrame(e)}pause(){if(this.disposed)throw Error(`Motion instance has been disposed.`);this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId)}dispose(){if(this.disposed)return;this.disposed=!0,this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId);let{gl:e,vao:t,positionBuffer:n,uvBuffer:r,program:i}=this.glr;t&&e.deleteVertexArray(t),n&&e.deleteBuffer(n),r&&e.deleteBuffer(r),e.deleteProgram(i),this.observer&&this.observer.disconnect(),this.canvas.remove()}resize(e,t,n){if(this.disposed)throw Error(`Motion instance has been disposed.`);if(this.options.width=e,this.options.height=t,n&&(this.options.ratio=n),!this.running)return;let{gl:r,program:i,vao:a,positionBuffer:o,uvBuffer:s,uResolution:c}=this.glr,l=n??this.options.ratio??window.devicePixelRatio??1,u=Math.max(1,Math.floor(e*l)),d=Math.max(1,Math.floor(t*l));this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,(this.canvas.width!==u||this.canvas.height!==d)&&(this.canvas.width=u,this.canvas.height=d),r.viewport(0,0,this.canvas.width,this.canvas.height),this.checkGLError(r,`resize: after viewport setup`);let{positions:f,uvs:p}=computeBorderGeometry(this.canvas.width,this.canvas.height,this.options.borderWidth*l,this.options.glowWidth*l);r.bindVertexArray(a),r.bindBuffer(r.ARRAY_BUFFER,o),r.bufferData(r.ARRAY_BUFFER,f,r.STATIC_DRAW);let m=r.getAttribLocation(i,`aPosition`);r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,0),this.checkGLError(r,`resize: after position buffer update`),r.bindBuffer(r.ARRAY_BUFFER,s),r.bufferData(r.ARRAY_BUFFER,p,r.STATIC_DRAW);let h=r.getAttribLocation(i,`aUV`);r.enableVertexAttribArray(h),r.vertexAttribPointer(h,2,r.FLOAT,!1,0,0),this.checkGLError(r,`resize: after UV buffer update`),r.useProgram(i),r.uniform2f(c,this.canvas.width,this.canvas.height),r.uniform1f(this.glr.uBorderWidth,this.options.borderWidth*l),r.uniform1f(this.glr.uGlowWidth,this.options.glowWidth*l),r.uniform1f(this.glr.uBorderRadius,this.options.borderRadius*l),this.checkGLError(r,`resize: after uniform updates`);let g=performance.now();this.lastTime=g;let _=(g-this.startTime)*.001;this.render(_)}autoResize(e){this.observer&&this.observer.disconnect(),this.observer=new ResizeObserver(()=>{let t=e.getBoundingClientRect();this.resize(t.width,t.height)}),this.observer.observe(e)}fadeIn(){if(this.disposed)throw Error(`Motion instance has been disposed.`);return new Promise((e,t)=>{let n=this.canvas.animate([{opacity:0,transform:`scale(1.2)`},{opacity:1,transform:`scale(1)`}],{duration:300,easing:`ease-out`,fill:`forwards`});n.onfinish=()=>e(),n.oncancel=()=>t(`canceled`)})}fadeOut(){if(this.disposed)throw Error(`Motion instance has been disposed.`);return new Promise((e,t)=>{let n=this.canvas.animate([{opacity:1,transform:`scale(1)`},{opacity:0,transform:`scale(1.2)`}],{duration:300,easing:`ease-in`,fill:`forwards`});n.onfinish=()=>e(),n.oncancel=()=>t(`canceled`)})}checkGLError(e,t){let n=e.getError();if(n!==e.NO_ERROR){for(console.group(`🔴 WebGL Error in ${t}`);n!==e.NO_ERROR;){let t=this.getGLErrorName(e,n);console.error(`${t} (0x${n.toString(16)})`),n=e.getError()}console.groupEnd()}}getGLErrorName(e,t){switch(t){case e.INVALID_ENUM:return`INVALID_ENUM`;case e.INVALID_VALUE:return`INVALID_VALUE`;case e.INVALID_OPERATION:return`INVALID_OPERATION`;case e.INVALID_FRAMEBUFFER_OPERATION:return`INVALID_FRAMEBUFFER_OPERATION`;case e.OUT_OF_MEMORY:return`OUT_OF_MEMORY`;case e.CONTEXT_LOST_WEBGL:return`CONTEXT_LOST_WEBGL`;default:return`UNKNOWN_ERROR`}}setupGL(){let e=this.canvas.getContext(`webgl2`,{antialias:!1,alpha:!0});if(!e)throw Error(`WebGL2 is required but not available.`);let t=createProgram(e,vertexShaderSource,fragmentShaderSource);this.checkGLError(e,`setupGL: after createProgram`);let n=e.createVertexArray();e.bindVertexArray(n),this.checkGLError(e,`setupGL: after VAO creation`);let{positions:r,uvs:i}=computeBorderGeometry(this.canvas.width||2,this.canvas.height||2,this.options.borderWidth,this.options.glowWidth),a=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,a),e.bufferData(e.ARRAY_BUFFER,r,e.STATIC_DRAW);let o=e.getAttribLocation(t,`aPosition`);e.enableVertexAttribArray(o),e.vertexAttribPointer(o,2,e.FLOAT,!1,0,0),this.checkGLError(e,`setupGL: after position buffer setup`);let s=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,s),e.bufferData(e.ARRAY_BUFFER,i,e.STATIC_DRAW);let c=e.getAttribLocation(t,`aUV`);e.enableVertexAttribArray(c),e.vertexAttribPointer(c,2,e.FLOAT,!1,0,0),this.checkGLError(e,`setupGL: after UV buffer setup`);let l=e.getUniformLocation(t,`uResolution`),u=e.getUniformLocation(t,`uTime`),d=e.getUniformLocation(t,`uBorderWidth`),f=e.getUniformLocation(t,`uGlowWidth`),p=e.getUniformLocation(t,`uBorderRadius`),m=e.getUniformLocation(t,`uColors`),h=e.getUniformLocation(t,`uGlowExponent`),g=e.getUniformLocation(t,`uGlowFactor`);e.useProgram(t),e.uniform1f(d,this.options.borderWidth),e.uniform1f(f,this.options.glowWidth),e.uniform1f(p,this.options.borderRadius),this.options.mode===`dark`?(e.uniform1f(h,2),e.uniform1f(g,1.8)):(e.uniform1f(h,1),e.uniform1f(g,1));let _=(this.options.colors||DEFAULT_COLORS).map(parseColor);for(let n=0;n<_.length;n++)e.uniform3f(e.getUniformLocation(t,`uColors[${n}]`),..._[n]);this.checkGLError(e,`setupGL: after uniform setup`),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),this.glr={gl:e,program:t,vao:n,positionBuffer:a,uvBuffer:s,uResolution:l,uTime:u,uBorderWidth:d,uGlowWidth:f,uBorderRadius:p,uColors:m}}render(e){if(!this.glr)return;let{gl:t,program:n,vao:r,uTime:i}=this.glr;t.useProgram(n),t.bindVertexArray(r),t.uniform1f(i,e),t.disable(t.DEPTH_TEST),t.disable(t.CULL_FACE),t.disable(t.BLEND),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.drawArrays(t.TRIANGLES,0,24),this.checkGLError(t,`render: after draw call`),t.bindVertexArray(null)}greet(){console.log(`%c🌈 ai-motion 0.4.8 🌈`,`background: linear-gradient(90deg, #39b6ff, #bd45fb, #ff5733, #ffd600); color: white; text-shadow: 0 0 2px rgba(0, 0, 0, 0.2); font-weight: bold; font-size: 1em; padding: 2px 12px; border-radius: 6px;`)}}}));function isPageDark(){try{return!!(hasDarkModeClass()||hasDarkModeDataAttribute()||isColorSchemeDark()||isBackgroundDark()||isMainContentBackgroundDark()||isTextColorLight())}catch(e){return console.warn(`Error determining if page is dark:`,e),!1}}function hasDarkModeClass(){let e=[`dark`,`dark-mode`,`theme-dark`,`night`,`night-mode`],t=document.documentElement,n=document.body||document.documentElement;for(let r of e)if(t.classList.contains(r)||n?.classList.contains(r))return!0;return!1}function hasDarkModeDataAttribute(){let e=document.documentElement,t=document.body||document.documentElement;for(let n of[`data-theme`,`data-color-mode`,`data-bs-theme`,`data-mui-color-scheme`]){let r=t?.getAttribute(n),i=e.getAttribute(n);if(r?.toLowerCase()===`dark`||i?.toLowerCase()===`dark`)return!0}return!1}function isColorSchemeDark(){let e=document.querySelector(`meta[name="color-scheme"]`)?.content.toLowerCase();if(e===`dark`||e===`only dark`)return!0;let t=window.getComputedStyle(document.documentElement).getPropertyValue(`color-scheme`).trim().toLowerCase();return t===`dark`||t===`only dark`}function isBackgroundDark(){let e=window.getComputedStyle(document.documentElement),t=window.getComputedStyle(document.body||document.documentElement),n=e.backgroundColor,r=t.backgroundColor;return isColorDark(r)?!0:r===`transparent`||r.startsWith(`rgba(0, 0, 0, 0)`)?isColorDark(n):!1}function isTextColorLight(){let e=200,t=getLuminance(window.getComputedStyle(document.body||document.documentElement).color);return t!==null&&t>200}function isMainContentBackgroundDark(){let{innerWidth:e,innerHeight:t}=window,n=e*t*.5;for(let e of[`#app`,`#root`,`#__next`]){let t=document.querySelector(e);if(!t)continue;let r=t.getBoundingClientRect();if(!(r.width*r.height<n)&&isColorDark(window.getComputedStyle(t).backgroundColor))return!0}return!1}function parseRgbColor(e){let t=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(e);return t?{r:parseInt(t[1]),g:parseInt(t[2]),b:parseInt(t[3])}:null}function getLuminance(e){if(!e||e===`transparent`||e.startsWith(`rgba(0, 0, 0, 0)`))return null;let t=parseRgbColor(e);return t?.299*t.r+.587*t.g+.114*t.b:null}function isColorDark(e,t=128){let n=getLuminance(e);return n!==null&&n<t}var init_checkDarkMode=__esmMin((()=>{})),wrapper$1,visible,SimulatorMask_module_default,init_SimulatorMask_module=__esmMin((()=>{wrapper$1=`_wrapper_1ooyb_1`,visible=`_visible_1ooyb_11`,SimulatorMask_module_default={wrapper:wrapper$1,visible}})),cursor,cursorBorder,cursorFilling,cursorRipple,clicking,cursor_module_default,init_cursor_module=__esmMin((()=>{cursor=`_cursor_1dgwb_2`,cursorBorder=`_cursorBorder_1dgwb_10`,cursorFilling=`_cursorFilling_1dgwb_25`,cursorRipple=`_cursorRipple_1dgwb_39`,clicking=`_clicking_1dgwb_57`,cursor_module_default={cursor,cursorBorder,cursorFilling,cursorRipple,clicking,"cursor-ripple":`_cursor-ripple_1dgwb_1`}})),SimulatorMask_exports=__exportAll({SimulatorMask:()=>SimulatorMask}),SimulatorMask,init_SimulatorMask=__esmMin((()=>{init_Motion(),init_checkDarkMode(),init_SimulatorMask_module(),init_cursor_module(),SimulatorMask=class extends EventTarget{shown=!1;wrapper=document.createElement(`div`);motion=null;#e=!1;#t=document.createElement(`div`);#n=0;#r=0;#i=0;#a=0;constructor(){super(),this.wrapper.id=`page-agent-runtime_simulator-mask`,this.wrapper.className=SimulatorMask_module_default.wrapper,this.wrapper.setAttribute(`data-browser-use-ignore`,`true`),this.wrapper.setAttribute(`data-page-agent-ignore`,`true`);try{let e=new Motion({mode:isPageDark()?`dark`:`light`,styles:{position:`absolute`,inset:`0`}});this.motion=e,this.wrapper.appendChild(e.element),e.autoResize(this.wrapper)}catch(e){console.warn(`[SimulatorMask] Motion overlay unavailable:`,e)}this.wrapper.addEventListener(`click`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mousedown`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mouseup`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mousemove`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`wheel`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`keydown`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`keyup`,e=>{e.stopPropagation(),e.preventDefault()}),this.#o(),document.body.appendChild(this.wrapper),this.#s();let e=e=>{let{x:t,y:n}=e.detail;this.setCursorPosition(t,n)},t=()=>{this.triggerClickAnimation()},n=()=>{this.wrapper.style.pointerEvents=`none`},r=()=>{this.wrapper.style.pointerEvents=`auto`};window.addEventListener(`PageAgent::MovePointerTo`,e),window.addEventListener(`PageAgent::ClickPointer`,t),window.addEventListener(`PageAgent::EnablePassThrough`,n),window.addEventListener(`PageAgent::DisablePassThrough`,r),this.addEventListener(`dispose`,()=>{window.removeEventListener(`PageAgent::MovePointerTo`,e),window.removeEventListener(`PageAgent::ClickPointer`,t),window.removeEventListener(`PageAgent::EnablePassThrough`,n),window.removeEventListener(`PageAgent::DisablePassThrough`,r)})}#o(){this.#t.className=cursor_module_default.cursor;let e=document.createElement(`div`);e.className=cursor_module_default.cursorRipple,this.#t.appendChild(e);let t=document.createElement(`div`);t.className=cursor_module_default.cursorFilling,this.#t.appendChild(t);let n=document.createElement(`div`);n.className=cursor_module_default.cursorBorder,this.#t.appendChild(n),this.wrapper.appendChild(this.#t)}#s(){if(this.#e)return;let e=this.#n+(this.#i-this.#n)*.2,t=this.#r+(this.#a-this.#r)*.2,n=Math.abs(e-this.#i);n>0&&(this.#n=n<2?this.#i:e,this.#t.style.left=`${this.#n}px`);let r=Math.abs(t-this.#a);r>0&&(this.#r=r<2?this.#a:t,this.#t.style.top=`${this.#r}px`),requestAnimationFrame(()=>this.#s())}setCursorPosition(e,t){this.#e||(this.#i=e,this.#a=t)}triggerClickAnimation(){this.#e||(this.#t.classList.remove(cursor_module_default.clicking),this.#t.getBoundingClientRect(),this.#t.classList.add(cursor_module_default.clicking))}show(){this.shown||this.#e||(this.shown=!0,this.motion?.start(),this.motion?.fadeIn(),this.wrapper.classList.add(SimulatorMask_module_default.visible),this.#n=window.innerWidth/2,this.#r=window.innerHeight/2,this.#i=this.#n,this.#a=this.#r,this.#t.style.left=`${this.#n}px`,this.#t.style.top=`${this.#r}px`)}hide(){!this.shown||this.#e||(this.shown=!1,this.motion?.fadeOut(),this.motion?.pause(),this.#t.classList.remove(cursor_module_default.clicking),setTimeout(()=>{this.wrapper.classList.remove(SimulatorMask_module_default.visible)},800))}dispose(){this.#e=!0,this.motion?.dispose(),this.wrapper.remove(),this.dispatchEvent(new Event(`dispose`))}}})),PageController=class extends EventTarget{config;flatTree=null;selectorMap=new Map;elementTextMap=new Map;simplifiedHTML=`<EMPTY>`;lastTimeUpdate=0;isIndexed=!1;mask=null;maskReady=null;constructor(e={}){super(),this.config=e,patchReact(this),e.enableMask&&this.initMask()}readFlatTree(){return this.flatTree}readSelectorMap(){return this.selectorMap}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{let{SimulatorMask:e}=await Promise.resolve().then(()=>(init_SimulatorMask(),SimulatorMask_exports));this.mask=new e})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){let e=window.location.href,t=document.title,n=getPageInfo(),r=resolveViewportExpansion(this.config.viewportExpansion);await this.updateTree();let i=this.simplifiedHTML;return{url:e,title:t,header:`${`Current Page: [${t}](${e})`}\n${`Page info: ${n.viewport_width}x${n.viewport_height}px viewport, ${n.page_width}x${n.page_height}px total page size, ${n.pages_above.toFixed(1)} pages above, ${n.pages_below.toFixed(1)} pages below, ${n.total_pages.toFixed(1)} total pages, at ${(n.current_page_position*100).toFixed(0)}% of page`}\n\n${r===-1?`Interactive elements from top layer of the current page (full page):`:`Interactive elements from top layer of the current page inside the viewport:`}\n\n${n.pixels_above>4&&r!==-1?`... ${n.pixels_above} pixels above (${n.pages_above.toFixed(1)} pages) - scroll to see more ...`:`[Start of page]`}`,content:i,footer:n.pixels_below>4&&r!==-1?`... ${n.pixels_below} pixels below (${n.pages_below.toFixed(1)} pages) - scroll to see more ...`:`[End of page]`}}async updateTree(){this.dispatchEvent(new Event(`beforeUpdate`)),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents=`none`),cleanUpHighlights();let e=[...this.config.interactiveBlacklist||[],...Array.from(document.querySelectorAll(`[data-page-agent-not-interactive]`))];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:e}),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.includeAttributes,this.config.keepSemanticTags),this.selectorMap.clear(),this.selectorMap=getSelectorMap(this.flatTree),this.elementTextMap.clear(),this.elementTextMap=getElementTextMap(this.simplifiedHTML),this.isIndexed=!0,this.mask&&(this.mask.wrapper.style.pointerEvents=`auto`),this.dispatchEvent(new Event(`afterUpdate`)),this.simplifiedHTML}async cleanUpHighlights(){console.log(`[PageController] cleanUpHighlights`),cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw Error(`DOM tree not indexed yet. Can not perform actions on elements.`)}async clickElement(e){try{this.assertIndexed();let t=getElementByIndex(this.selectorMap,e),n=this.elementTextMap.get(e);return await clickElement(t),isAnchorElement(t)&&t.target===`_blank`?{success:!0,message:`OK: elemento (${n??e}) clicado. ATENÇÃO: o link abriu em uma nova aba.`}:{success:!0,message:`OK: elemento (${n??e}) clicado.`}}catch(e){return{success:!1,message:`ERRO: não foi possível clicar no elemento: ${e}`}}}async inputText(e,t){try{this.assertIndexed();let n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return await inputTextElement(n,t),{success:!0,message:`OK: texto (${t}) digitado no elemento (${r??e}).`}}catch(e){return{success:!1,message:`ERRO: não foi possível digitar o texto: ${e}`}}}async selectOption(e,t){try{this.assertIndexed();let n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return await selectOptionElement(n,t),{success:!0,message:`OK: opção (${t}) escolhida no elemento (${r??e}).`}}catch(e){return{success:!1,message:`ERRO: não foi possível escolher a opção: ${e}`}}}async scroll(e){try{let{down:t,numPages:n,pixels:r,index:i}=e;return this.assertIndexed(),{success:!0,message:await scrollVertically((r??n*window.innerHeight)*(t?1:-1),i===void 0?null:getElementByIndex(this.selectorMap,i))}}catch(e){return{success:!1,message:`ERRO: não foi possível rolar a página: ${e}`}}}async scrollHorizontally(e){try{let{right:t,pixels:n,index:r}=e;return this.assertIndexed(),{success:!0,message:await scrollHorizontally(n*(t?1:-1),r===void 0?null:getElementByIndex(this.selectorMap,r))}}catch(e){return{success:!1,message:`ERRO: não foi possível rolar na horizontal: ${e}`}}}async executeJavascript(script,signal){try{const asyncFunction=eval(`(async (signal) => { ${script} })`),result=await asyncFunction(signal);return{success:!0,message:`OK: JavaScript executado. Resultado: ${result}`}}catch(e){return{success:!1,message:`ERRO: falha ao executar JavaScript: ${e}`}}}async showMask(){await this.maskReady,this.mask?.show()}async hideMask(){await this.maskReady,this.mask?.hide()}dispose(){cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML=`<EMPTY>`,this.isIndexed=!1,this.mask?.dispose(),this.mask=null}},enUS={ui:{panel:{ready:`Ready`,thinking:`Thinking...`,taskInput:`Enter new task, describe steps in detail, press Enter to submit`,userAnswerPrompt:`Please answer the question above, press Enter to submit`,taskTerminated:`Task terminated`,taskCompleted:`Task completed`,userAnswer:`User answer: {{input}}`,question:`Question: {{question}}`,waitingPlaceholder:`Waiting for task to start...`,stop:`Stop`,close:`Close`,expand:`Expand history`,collapse:`Collapse history`,step:`Step {{number}}`,userTakeover:`User takeover`,retrying:`Retrying`,errorLabel:`Error`,reflectionEvaluation:`Assessment`,reflectionMemory:`Memory`,reflectionNextGoal:`Next goal`,authorPerson:`You`,authorAgent:`Agent`,authorReasoning:`Reasoning`,authorAction:`Action`,authorResult:`Result`,authorPage:`Page`,authorSystem:`System`,historyLabel:`Agent activity history`,panelLabel:`Agent panel`},tools:{clicking:`Clicking element [{{index}}]...`,inputting:`Inputting text to element [{{index}}]...`,selecting:`Selecting option "{{text}}"...`,scrolling:`Scrolling page...`,waiting:`Waiting {{seconds}} seconds...`,askingUser:`Asking user...`,done:`Task done`,clicked:`Clicked element [{{index}}]`,inputted:`Inputted text "{{text}}"`,selected:`Selected option "{{text}}"`,scrolled:`Page scrolled`,waited:`Wait completed`,executing:`Executing {{toolName}}...`,resultSuccess:`success`,resultFailure:`failed`,resultError:`error`},errors:{elementNotFound:`No interactive element found at index {{index}}`,taskRequired:`Task description is required`,executionFailed:`Task execution failed`,notInputElement:`Element is not an input or textarea`,notSelectElement:`Element is not a select element`,optionNotFound:`Option "{{text}}" not found`}}},ptBR={ui:{panel:{ready:`Pronto`,thinking:`Pensando...`,taskInput:`Descreva a próxima tarefa com os passos em detalhe e tecle Enter`,userAnswerPrompt:`Responda à pergunta acima e tecle Enter`,taskTerminated:`Tarefa interrompida`,taskCompleted:`Tarefa concluída`,userAnswer:`Resposta: {{input}}`,question:`Pergunta: {{question}}`,waitingPlaceholder:`Aguardando o início da tarefa...`,stop:`Parar`,close:`Fechar`,expand:`Abrir histórico`,collapse:`Fechar histórico`,step:`Passo {{number}}`,userTakeover:`A pessoa assumiu o controle`,retrying:`Tentando de novo`,errorLabel:`Erro`,reflectionEvaluation:`Avaliação`,reflectionMemory:`Memória`,reflectionNextGoal:`Próximo passo`,authorPerson:`Você`,authorAgent:`Agente`,authorReasoning:`Raciocínio`,authorAction:`Ação`,authorResult:`Resultado`,authorPage:`Página`,authorSystem:`Sistema`,historyLabel:`Histórico de atividade do agente`,panelLabel:`Painel do agente`},tools:{clicking:`Clicando no elemento [{{index}}]...`,inputting:`Digitando no elemento [{{index}}]...`,selecting:`Escolhendo a opção "{{text}}"...`,scrolling:`Rolando a página...`,waiting:`Aguardando {{seconds}} segundos...`,askingUser:`Perguntando à pessoa...`,done:`Tarefa encerrada`,clicked:`Elemento [{{index}}] clicado`,inputted:`Texto "{{text}}" digitado`,selected:`Opção "{{text}}" escolhida`,scrolled:`Página rolada`,waited:`Espera concluída`,executing:`Executando {{toolName}}...`,resultSuccess:`sucesso`,resultFailure:`falha`,resultError:`erro`},errors:{elementNotFound:`Nenhum elemento interativo no índice {{index}}`,taskRequired:`A descrição da tarefa é obrigatória`,executionFailed:`A execução da tarefa falhou`,notInputElement:`O elemento não é um campo de texto`,notSelectElement:`O elemento não é uma lista de seleção`,optionNotFound:`Opção "{{text}}" não encontrada`}}},locales={"en-US":enUS,"pt-BR":ptBR},I18n=class{language;translations;constructor(e=`en-US`){this.language=e in locales?e:`en-US`,this.translations=locales[this.language]}t(e,t){let n=this.getNestedValue(this.translations,e);return n?t?this.interpolate(n,t):n:(console.warn(`Translation key "${e}" not found for language "${this.language}"`),e)}getNestedValue(e,t){return t.split(`.`).reduce((e,t)=>e?.[t],e)}interpolate(e,t){return e.replace(/\{\{(\w+)\}\}/g,(e,n)=>t[n]==null?e:t[n].toString())}getLanguage(){return this.language}};function truncate(e,t){return e.length>t?e.substring(0,t)+`...`:e}function escapeHtml(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}var wrapper=`_wrapper_1rq3n_1`,background=`_background_1rq3n_55`,header=`_header_1rq3n_115`,pulse=`_pulse_1rq3n_1`,retryPulse=`_retryPulse_1rq3n_1`,statusTextFadeOut=`_statusTextFadeOut_1rq3n_1`,statusTextFadeIn=`_statusTextFadeIn_1rq3n_1`,statusSection=`_statusSection_1rq3n_137`,indicator=`_indicator_1rq3n_144`,thinking=`_thinking_1rq3n_153`,tool_executing=`_tool_executing_1rq3n_158`,retry=`_retry_1rq3n_163`,completed=`_completed_1rq3n_169`,input=`_input_1rq3n_170`,output=`_output_1rq3n_171`,error=`_error_1rq3n_176`,statusText=`_statusText_1rq3n_182`,fadeOut=`_fadeOut_1rq3n_194`,fadeIn=`_fadeIn_1rq3n_198`,controls=`_controls_1rq3n_204`,controlButton=`_controlButton_1rq3n_209`,stopButton=`_stopButton_1rq3n_228`,historySectionWrapper=`_historySectionWrapper_1rq3n_262`,expanded=`_expanded_1rq3n_294`,historySection=`_historySection_1rq3n_262`,historyRow=`_historyRow_1rq3n_320`,fromPessoa=`_fromPessoa_1rq3n_328`,fromAgente=`_fromAgente_1rq3n_332`,fromSistema=`_fromSistema_1rq3n_333`,historyItem=`_historyItem_1rq3n_338`,observation=`_observation_1rq3n_374`,question=`_question_1rq3n_378`,doneSuccess=`_doneSuccess_1rq3n_382`,doneFailure=`_doneFailure_1rq3n_390`,historyHeader=`_historyHeader_1rq3n_402`,historyAuthor=`_historyAuthor_1rq3n_410`,historyMeta=`_historyMeta_1rq3n_416`,statusIcon=`_statusIcon_1rq3n_426`,historyContent=`_historyContent_1rq3n_439`,reflectionLine=`_reflectionLine_1rq3n_446`,reflectionLines=`_reflectionLines_1rq3n_451`,reflectionLabel=`_reflectionLabel_1rq3n_462`,inputSectionWrapper=`_inputSectionWrapper_1rq3n_544`,hidden=`_hidden_1rq3n_567`,inputSection=`_inputSection_1rq3n_544`,taskInput=`_taskInput_1rq3n_578`,celebrate=`_celebrate_1rq3n_1`,shimmer=`_shimmer_1rq3n_1`,Panel_module_default={wrapper,"mask-running":`_mask-running_1rq3n_1`,background,header,pulse,retryPulse,statusTextFadeOut,statusTextFadeIn,statusSection,indicator,thinking,tool_executing,retry,completed,input,output,error,statusText,fadeOut,fadeIn,controls,controlButton,stopButton,historySectionWrapper,expanded,historySection,historyRow,fromPessoa,fromAgente,fromSistema,historyItem,observation,question,doneSuccess,doneFailure,historyHeader,historyAuthor,historyMeta,statusIcon,historyContent,reflectionLine,reflectionLines,reflectionLabel,inputSectionWrapper,hidden,inputSection,taskInput,celebrate,shimmer};function createCard({icon:e,content:t,meta:n,type:r,from:i=`agente`,author:a}){let o=r?Panel_module_default[r]:``,s=i===`pessoa`?Panel_module_default.fromPessoa:i===`sistema`?Panel_module_default.fromSistema:Panel_module_default.fromAgente,c=Array.isArray(t)?`<div class="${Panel_module_default.reflectionLines}">${t.map(e=>`<span class="${Panel_module_default.reflectionLine}"><span class="${Panel_module_default.reflectionLabel}">${escapeHtml(e.label)}</span>${escapeHtml(e.text)}</span>`).join(``)}</div>`:`<span>${escapeHtml(t)}</span>`,l=`
|
|
344
|
-
<div class="${Panel_module_default.historyHeader}">
|
|
345
|
-
<span class="${Panel_module_default.statusIcon}">${e}</span>
|
|
346
|
-
<span class="${Panel_module_default.historyAuthor}" data-autor="${i}">${escapeHtml(a||``)}</span>
|
|
347
|
-
${n?`<span class="${Panel_module_default.historyMeta}">${escapeHtml(n)}</span>`:``}
|
|
348
|
-
</div>`;return`
|
|
349
|
-
<div class="${Panel_module_default.historyRow} ${s}">
|
|
350
|
-
<div class="${Panel_module_default.historyItem} ${o}" data-mensagem="${i}">
|
|
351
|
-
${l}
|
|
352
|
-
<div class="${Panel_module_default.historyContent}" data-conteudo>${c}</div>
|
|
353
|
-
</div>
|
|
354
|
-
</div>
|
|
355
|
-
`}function createReflectionLines(e,t){let n=[];return e.evaluation_previous_goal&&n.push({label:t.evaluation,text:e.evaluation_previous_goal}),e.memory&&n.push({label:t.memory,text:e.memory}),e.next_goal&&n.push({label:t.nextGoal,text:e.next_goal}),n}var svg=e=>`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">${e}</svg>`,iconTask=svg(`<circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="4"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2"/>`),iconThinking=svg(`<path d="M12 3l1.8 4.2L18 9l-4.2 1.8L12 15l-1.8-4.2L6 9l4.2-1.8z"/><path d="M18 15l.9 2.1L21 18l-2.1.9L18 21l-.9-2.1L15 18l2.1-.9z"/>`),iconObservation=svg(`<path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6-10-6-10-6z"/><circle cx="12" cy="12" r="2.5"/>`),iconUser=svg(`<circle cx="12" cy="8" r="3.5"/><path d="M5 20c0-3.3 3.1-5.5 7-5.5s7 2.2 7 5.5"/>`),iconRetry=svg(`<path d="M20 11a8 8 0 1 0-2.3 6.3"/><path d="M20 5v6h-6"/>`),iconError=svg(`<circle cx="12" cy="12" r="9"/><path d="M12 7.5v5"/><path d="M12 16.2h.01"/>`),iconDone=svg(`<circle cx="12" cy="12" r="9"/><path d="M8.2 12.3l2.6 2.6 5-5.2"/>`),iconQuestion=svg(`<circle cx="12" cy="12" r="9"/><path d="M9.6 9.4a2.5 2.5 0 1 1 3.3 2.4c-.6.2-.9.8-.9 1.4v.3"/><path d="M12 16.6h.01"/>`),iconAnswer=svg(`<path d="M20 14.5a2.5 2.5 0 0 1-2.5 2.5H9l-5 3.5V6.5A2.5 2.5 0 0 1 6.5 4h11A2.5 2.5 0 0 1 20 6.5z"/>`),iconTool=svg(`<path d="M5 7.5l3.5 3.5L5 14.5"/><path d="M11.5 15.5H19"/><rect x="2.5" y="3.5" width="19" height="17" rx="2.5"/>`),Panel=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u=!1;#d;#f=null;#p=!1;#m=null;#h=null;#g=!1;#_=()=>this.#x();#v=()=>this.#S();#y=e=>this.#C(e.detail);#b=()=>this.dispose();get wrapper(){return this.#e}constructor(e,t={}){this.#c=e,this.#l=t,this.#d=new I18n(t.language??`en-US`),this.#c.onAskUser=(e,t)=>this.#w(e,t?.signal),this.#e=this.#N(),this.#t=this.#e.querySelector(`.${Panel_module_default.indicator}`),this.#n=this.#e.querySelector(`.${Panel_module_default.statusText}`),this.#r=this.#e.querySelector(`.${Panel_module_default.historySection}`),this.#i=this.#e.querySelector(`.${Panel_module_default.expandButton}`),this.#a=this.#e.querySelector(`.${Panel_module_default.stopButton}`),this.#o=this.#e.querySelector(`.${Panel_module_default.inputSectionWrapper}`),this.#s=this.#e.querySelector(`.${Panel_module_default.taskInput}`),this.#c.addEventListener(`statuschange`,this.#_),this.#c.addEventListener(`historychange`,this.#v),this.#c.addEventListener(`activity`,this.#y),this.#c.addEventListener(`dispose`,this.#b),this.#P(),this.#R(),this.#A(),this.hide()}#x(){let e=this.#c.status,t=e===`completed`&&this.#c.lastResult?.success===!1;this.#H(t?`error`:e),e===`running`?(this.#a.textContent=`■`,this.#a.title=this.#d.t(`ui.panel.stop`)):(this.#a.textContent=`X`,this.#a.title=this.#d.t(`ui.panel.close`)),e===`running`&&(this.show(),this.#j()),(e===`completed`||e===`error`||e===`stopped`)&&(this.#u||this.#I(),this.#M()&&this.#A())}#S(){this.#W()}#C(e){switch(e.type){case`thinking`:this.#h=this.#d.t(`ui.panel.thinking`),this.#H(`thinking`);break;case`executing`:this.#h=this.#E(e.tool,e.input),this.#H(`executing`);break;case`executed`:this.#h=truncate(e.output,50);break;case`retrying`:this.#h=`Retrying (${e.attempt}/${e.maxAttempts})`,this.#H(`retrying`);break;case`error`:this.#h=truncate(e.message,50),this.#H(`error`)}}#w(e,t){return new Promise((n,r)=>{this.#p=!0,this.#f=n,this.#u||this.#I();let i=document.createElement(`div`);i.innerHTML=createCard({icon:iconQuestion,content:this.#d.t(`ui.panel.question`,{question:e}),type:`question`,author:this.#d.t(`ui.panel.authorAgent`)});let a=i.firstElementChild;a.setAttribute(`data-temp-card`,`true`),this.#r.appendChild(a),this.#U(),this.#A(this.#d.t(`ui.panel.userAnswerPrompt`)),t?.addEventListener(`abort`,()=>{this.#T(),this.#p=!1,this.#f=null,r(t.reason)},{once:!0})})}#T(){Array.from(this.#r.children).forEach(e=>{e.getAttribute(`data-temp-card`)===`true`&&e.remove()})}show(){this.wrapper.style.display=`block`,this.wrapper.getBoundingClientRect(),this.wrapper.style.opacity=`1`,this.wrapper.style.transform=`translateX(-50%) translateY(0)`}hide(){this.wrapper.style.opacity=`0`,this.wrapper.style.transform=`translateX(-50%) translateY(20px)`,this.wrapper.style.display=`none`}reset(){this.#n.textContent=this.#d.t(`ui.panel.ready`),this.#H(`thinking`),this.#W(),this.#L(),this.#p=!1,this.#f=null,this.#A()}expand(){this.#I()}collapse(){this.#L()}dispose(){this.#c.removeEventListener(`statuschange`,this.#_),this.#c.removeEventListener(`historychange`,this.#v),this.#c.removeEventListener(`activity`,this.#y),this.#c.removeEventListener(`dispose`,this.#b),this.#p=!1,this.#z(),this.wrapper.remove()}#E(e,t){let n=t;switch(e){case`click_element_by_index`:return this.#d.t(`ui.tools.clicking`,{index:n.index});case`input_text`:return this.#d.t(`ui.tools.inputting`,{index:n.index});case`select_dropdown_option`:return this.#d.t(`ui.tools.selecting`,{text:n.text});case`scroll`:return this.#d.t(`ui.tools.scrolling`);case`wait`:return this.#d.t(`ui.tools.waiting`,{seconds:n.seconds});case`ask_user`:return this.#d.t(`ui.tools.askingUser`);case`done`:return this.#d.t(`ui.tools.done`);default:return this.#d.t(`ui.tools.executing`,{toolName:e})}}#D(){this.#c.status===`running`?this.#c.stop():this.#c.dispose()}#O(){let e=this.#s.value.trim();e&&(this.#j(),this.#p?this.#k(e):this.#c.execute(e))}#k(e){this.#T(),this.#p=!1,this.#f&&=(this.#f(e),null)}#A(e){this.#s.value=``,this.#s.placeholder=e||this.#d.t(`ui.panel.taskInput`),this.#o.classList.remove(Panel_module_default.hidden),setTimeout(()=>{this.#s.focus()},100)}#j(){this.#o.classList.add(Panel_module_default.hidden)}#M(){if(this.#p||this.#c.history.length===0)return!0;let e=this.#c.status;return e===`completed`||e===`error`||e===`stopped`?this.#l.promptForNextTask??!0:!1}#N(){let e=1e3,t=document.createElement(`div`);return t.id=`page-agent-runtime_agent-panel`,t.className=Panel_module_default.wrapper,t.setAttribute(`data-browser-use-ignore`,`true`),t.setAttribute(`data-page-agent-ignore`,`true`),t.setAttribute(`role`,`complementary`),t.setAttribute(`aria-label`,this.#d.t(`ui.panel.panelLabel`)),t.innerHTML=`
|
|
356
|
-
<div class="${Panel_module_default.background}"></div>
|
|
357
|
-
<div class="${Panel_module_default.historySectionWrapper}">
|
|
358
|
-
<!-- FORK: role=log + aria-live faz o leitor de tela anunciar cada mensagem nova sem
|
|
359
|
-
roubar o foco de quem está usando a página. aria-relevant=additions evita
|
|
360
|
-
reanunciar o histórico inteiro a cada render. -->
|
|
361
|
-
<div
|
|
362
|
-
class="${Panel_module_default.historySection}"
|
|
363
|
-
role="log"
|
|
364
|
-
aria-live="polite"
|
|
365
|
-
aria-relevant="additions"
|
|
366
|
-
aria-label="${this.#d.t(`ui.panel.historyLabel`)}"
|
|
367
|
-
>
|
|
368
|
-
<div class="${Panel_module_default.historyRow} ${Panel_module_default.fromSistema}">
|
|
369
|
-
<div class="${Panel_module_default.historyItem}" data-mensagem="sistema">
|
|
370
|
-
<div class="${Panel_module_default.historyHeader}">
|
|
371
|
-
<span class="${Panel_module_default.statusIcon}">${iconThinking}</span>
|
|
372
|
-
<span class="${Panel_module_default.historyAuthor}" data-autor="sistema">${this.#d.t(`ui.panel.authorSystem`)}</span>
|
|
373
|
-
</div>
|
|
374
|
-
<div class="${Panel_module_default.historyContent}" data-conteudo><span>${this.#d.t(`ui.panel.waitingPlaceholder`)}</span></div>
|
|
375
|
-
</div>
|
|
376
|
-
</div>
|
|
377
|
-
</div>
|
|
378
|
-
</div>
|
|
379
|
-
<div class="${Panel_module_default.header}">
|
|
380
|
-
<div class="${Panel_module_default.statusSection}">
|
|
381
|
-
<div class="${Panel_module_default.indicator} ${Panel_module_default.thinking}"></div>
|
|
382
|
-
<div class="${Panel_module_default.statusText}">${this.#d.t(`ui.panel.ready`)}</div>
|
|
383
|
-
</div>
|
|
384
|
-
<div class="${Panel_module_default.controls}">
|
|
385
|
-
<button class="${Panel_module_default.controlButton} ${Panel_module_default.expandButton}" title="${this.#d.t(`ui.panel.expand`)}">
|
|
386
|
-
▼
|
|
387
|
-
</button>
|
|
388
|
-
<button class="${Panel_module_default.controlButton} ${Panel_module_default.stopButton}" title="${this.#d.t(`ui.panel.close`)}">
|
|
389
|
-
X
|
|
390
|
-
</button>
|
|
391
|
-
</div>
|
|
392
|
-
</div>
|
|
393
|
-
<div class="${Panel_module_default.inputSectionWrapper} ${Panel_module_default.hidden}">
|
|
394
|
-
<div class="${Panel_module_default.inputSection}">
|
|
395
|
-
<input
|
|
396
|
-
type="text"
|
|
397
|
-
class="${Panel_module_default.taskInput}"
|
|
398
|
-
maxlength="1000"
|
|
399
|
-
/>
|
|
400
|
-
</div>
|
|
401
|
-
</div>
|
|
402
|
-
`,document.body.appendChild(t),t}#P(){this.wrapper.querySelector(`.${Panel_module_default.header}`).addEventListener(`click`,e=>{e.target.closest(`.${Panel_module_default.controlButton}`)||this.#F()}),this.#i.addEventListener(`click`,e=>{e.stopPropagation(),this.#F()}),this.#a.addEventListener(`click`,e=>{e.stopPropagation(),this.#D()}),this.#s.addEventListener(`keydown`,e=>{e.isComposing||e.key===`Enter`&&(e.preventDefault(),this.#O())}),this.#o.addEventListener(`click`,e=>{e.stopPropagation()})}#F(){this.#u?this.#L():this.#I()}#I(){this.#u=!0,this.wrapper.classList.add(Panel_module_default.expanded),this.#i.textContent=`▲`}#L(){this.#u=!1,this.wrapper.classList.remove(Panel_module_default.expanded),this.#i.textContent=`▼`}#R(){this.#m=setInterval(()=>{this.#B()},450)}#z(){this.#m&&=(clearInterval(this.#m),null)}#B(){if(!this.#h||this.#g)return;if(this.#n.textContent===this.#h){this.#h=null;return}let e=this.#h;this.#h=null,this.#V(e)}#V(e){this.#g=!0,this.#n.classList.add(Panel_module_default.fadeOut),setTimeout(()=>{this.#n.textContent=e,this.#n.classList.remove(Panel_module_default.fadeOut),this.#n.classList.add(Panel_module_default.fadeIn),setTimeout(()=>{this.#n.classList.remove(Panel_module_default.fadeIn),this.#g=!1},300)},150)}#H(e){let t=e===`running`?`thinking`:e;this.#t.className=Panel_module_default.indicator,t!==`idle`&&t!==`stopped`&&this.#t.classList.add(Panel_module_default[t])}#U(){setTimeout(()=>{this.#r.scrollTop=this.#r.scrollHeight},0)}#W(){let e=[],t=this.#c.task;t&&e.push(this.#G(t));let n=this.#c.history;for(let t of n)e.push(...this.#K(t));this.#r.innerHTML=e.join(``),this.#U()}#G(e){return createCard({icon:iconTask,content:e,type:`input`,from:`pessoa`,author:this.#d.t(`ui.panel.authorPerson`)})}#K(e){let t=[],n=e.type===`step`&&e.stepIndex!==void 0?this.#d.t(`ui.panel.step`,{number:(e.stepIndex+1).toString()}):void 0;if(e.type===`step`){if(e.reflection){let r=createReflectionLines(e.reflection,{evaluation:this.#d.t(`ui.panel.reflectionEvaluation`),memory:this.#d.t(`ui.panel.reflectionMemory`),nextGoal:this.#d.t(`ui.panel.reflectionNextGoal`)});r.length>0&&t.push(createCard({icon:iconThinking,content:r,meta:n,author:this.#d.t(`ui.panel.authorReasoning`)}))}let r=e.action;r&&t.push(...this.#q(r,n))}else if(e.type===`observation`)t.push(createCard({icon:iconObservation,content:e.content||``,meta:n,type:`observation`,author:this.#d.t(`ui.panel.authorPage`)}));else if(e.type===`user_takeover`)t.push(createCard({icon:iconUser,content:this.#d.t(`ui.panel.userTakeover`),meta:n,type:`input`,from:`pessoa`,author:this.#d.t(`ui.panel.authorPerson`)}));else if(e.type===`retry`){let r=`${e.message||this.#d.t(`ui.panel.retrying`)} (${e.attempt}/${e.maxAttempts})`;t.push(createCard({icon:iconRetry,content:r,meta:n,type:`observation`,from:`sistema`,author:this.#d.t(`ui.panel.authorSystem`)}))}else e.type===`error`&&t.push(createCard({icon:iconError,content:e.message||this.#d.t(`ui.panel.errorLabel`),meta:n,type:`observation`,from:`sistema`,author:this.#d.t(`ui.panel.authorSystem`)}));return t}#q(e,t){let n=[];if(e.name===`done`){let r=e.input.text||e.output||``;r&&n.push(createCard({icon:iconDone,content:r,meta:t,type:`output`,author:this.#d.t(`ui.panel.authorAgent`)}))}else if(e.name===`ask_user`){let r=e.input,i=e.output.replace(/^User answered:\s*/i,``);n.push(createCard({icon:iconQuestion,content:this.#d.t(`ui.panel.question`,{question:r.question||``}),meta:t,type:`question`,author:this.#d.t(`ui.panel.authorAgent`)})),n.push(createCard({icon:iconAnswer,content:this.#d.t(`ui.panel.userAnswer`,{input:i}),meta:t,type:`input`,from:`pessoa`,author:this.#d.t(`ui.panel.authorPerson`)}))}else{let r=this.#E(e.name,e.input);n.push(createCard({icon:iconTool,content:r,meta:t,author:this.#d.t(`ui.panel.authorAction`)})),e.output?.length>0&&n.push(createCard({icon:iconTool,content:e.output,meta:t,type:`output`,author:this.#d.t(`ui.panel.authorResult`)}))}return n}};function getRecognitionCtor(){let e=globalThis;return e.SpeechRecognition??e.webkitSpeechRecognition??null}var STATUS_LISTENING=`listening`,STATUS_SPEAKING=`speaking`,STATUS_IDLE=`idle`;function createVoice(e={}){let t=e.lang??`pt-BR`,n=e.rate??1,r=e.pitch??1,i=e.input??!0,a=e.output??!1,o=e.listenTimeoutMs??3e4,s=i?getRecognitionCtor():null,c=typeof window<`u`?window.speechSynthesis:void 0,l={input:!!(i&&s),output:!!(a&&c)},u=STATUS_IDLE,d=new Set;function f(e){u!==e&&(u=e,d.forEach(t=>{try{t(e)}catch{}}))}let p=null,m=null;if(c){let n=()=>{if(e.voiceURI)m=c.getVoices().find(t=>t.voiceURI===e.voiceURI)??null;else{let e=c.getVoices(),n=t.split(`-`)[0].toLowerCase();m=e.find(e=>e.lang?.toLowerCase()===t.toLowerCase())??e.find(e=>e.lang?.toLowerCase().startsWith(n))??null}};n(),c.onvoiceschanged=n}function h(e,i){if(!c||!a)return;let o=(e??``).trim();if(!o)return;i?.interrupt!==!1&&c.cancel();let s=new SpeechSynthesisUtterance(o);s.lang=t,s.rate=n,s.pitch=r,m&&(s.voice=m),s.onend=()=>f(STATUS_IDLE),s.onerror=()=>f(STATUS_IDLE),f(STATUS_SPEAKING),c.speak(s)}function g(){return s?new Promise((e,n)=>{let r=new s;p=r;let i=``,a=!1,c,l=e=>{a||(a=!0,c&&clearTimeout(c),p===r&&(p=null),f(STATUS_IDLE),e())};c=setTimeout(()=>{try{r.stop()}catch{}l(()=>n(Error(`Tempo de escuta esgotado`)))},o),r.lang=t,r.continuous=!1,r.interimResults=!0,r.maxAlternatives=1,r.onstart=()=>f(STATUS_LISTENING),r.onresult=e=>{for(let t=e.resultIndex;t<e.results.length;t++){let n=e.results[t];n?.isFinal&&(i=n[0]?.transcript??i)}},r.onerror=t=>{let r=t?.error;if(r===`no-speech`||r===`aborted`){l(()=>e(i.trim()));return}l(()=>n(Error(`Erro de reconhecimento de voz: ${r??`desconhecido`}`)))},r.onend=()=>{l(()=>e(i.trim()))};try{r.start()}catch(e){l(()=>n(e instanceof Error?e:Error(String(e))))}}):Promise.reject(Error(`Voz de entrada não suportada neste navegador`))}return{supported:l,listen:g,stopListening(){try{p?.stop()}catch{}p=null,f(STATUS_IDLE)},speak:h,stopSpeaking(){c&&(c.cancel(),f(STATUS_IDLE))},onStatus(e){return d.add(e),()=>d.delete(e)}}}var DEFAULTS={language:`pt-BR`,maxSteps:30,enableMask:!0,viewportExpansion:0,promptForNextTask:!0,position:`bottom-right`,launcherLabel:`Abrir assistente da página`,open:!1},LAUNCHER_ICON=`<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3l1.9 4.6L18.5 9l-4.6 1.9L12 15.5l-1.9-4.6L5.5 9l4.6-1.4L12 3z"/><path d="M19 14l.8 2 2 .8-2 .8-.8 2-.8-2-2-.8 2-.8.8-2z"/></svg>`,MIC_ICON=`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v3"/></svg>`;function positionCss(e){switch(e){case`bottom-left`:return{bottom:`20px`,left:`20px`,right:`auto`,top:`auto`};case`top-right`:return{top:`20px`,right:`20px`,bottom:`auto`,left:`auto`};case`top-left`:return{top:`20px`,left:`20px`,bottom:`auto`,right:`auto`};default:return{bottom:`20px`,right:`20px`,top:`auto`,left:`auto`}}}function mountWidget(e={}){let t=e.position??DEFAULTS.position,n=e.launcherLabel??DEFAULTS.launcherLabel,r=e.open??DEFAULTS.open,i=null,a=null,o=null,s=!1,c=null;async function l(){if(c)return c;if(e.configUrl)return c=(async()=>{let t=await fetch(e.configUrl,{headers:{accept:`application/json`}});if(!t.ok)throw Error(`mountWidget: configUrl respondeu ${t.status} — o gateway está no ar?`);let n=await t.json();for(let t of[`model`,`language`,`maxSteps`,`promptForNextTask`,`instructions`,`voice`]){let r=n[t];r!=null&&(e[t]=r)}})(),c}function u(){return a||=createVoice(e.voice??{}),a}async function d(){if(i&&!i.disposed)return i;await l();let t=u(),n=e.model,r=e.baseURL;if(!n||!r)throw Error(e.configUrl?"mountWidget: o gateway não enviou `model` e/ou falta `baseURL` no front. Confira AGENT_MODEL no gateway e a baseURL do widget.":"mountWidget: configure `model` e `baseURL` (config central do LLM) antes de abrir o agente.");return i=new PageAgent({model:n,baseURL:r,apiKey:e.apiKey,transformRequestBody:e.transformRequestBody,customFetch:e.customFetch,maxRetries:e.maxRetries,language:e.language??DEFAULTS.language,maxSteps:e.maxSteps??DEFAULTS.maxSteps,enableMask:e.enableMask??DEFAULTS.enableMask,viewportExpansion:e.viewportExpansion??DEFAULTS.viewportExpansion,instructions:e.instructions,customTools:e.customTools,promptForNextTask:e.promptForNextTask??DEFAULTS.promptForNextTask}),f(i,t),p(i,t),i}function f(t,n){let r=e.voice?.speakOnComplete??!0,i=e.voice?.speakSteps??!1;t.addEventListener(`statuschange`,()=>{let e=t.status,a=t.lastResult;if(e===`completed`||e===`error`){r&&n.supported.output&&(e===`error`?n.speak(`A tarefa encontrou um problema e foi parada.`):a?.success?n.speak(`Tarefa concluída com sucesso.`):n.speak(`A tarefa terminou, mas o resultado não foi confirmado.`));return}if(i&&e===`running`&&n.supported.output){let e=[...t.history].reverse().find(e=>e.type===`step`)?.reflection?.next_goal;e&&n.speak(e,{interrupt:!0})}}),t.addEventListener(`activity`,e=>{let t=e.detail;t?.type===`error`&&t.message&&n.supported.output&&n.speak(t.message,{interrupt:!0})})}function p(e,t){let n=e.panel.wrapper,r=n.querySelector(`input`);r&&t.supported.input&&(n.querySelector(`[data-page-agent-voice="mic"]`)||(o&&o.remove(),o=document.createElement(`button`),o.type=`button`,o.className=`page-agent-voice-mic`,o.setAttribute(`data-page-agent-voice`,`mic`),o.setAttribute(`aria-label`,`Ditar tarefa por voz`),o.title=`Ditar tarefa por voz`,o.innerHTML=MIC_ICON,o.style.display=`inline-flex`,(r.parentElement??n).insertBefore(o,r),t.onStatus(e=>{o?.classList.toggle(`is-listening`,e===`listening`)}),o.addEventListener(`click`,async()=>{if(s){t.stopListening();return}s=!0;try{let e=await t.listen();e&&(r.value=e,r.dispatchEvent(new KeyboardEvent(`keydown`,{key:`Enter`,bubbles:!0})))}catch(e){r.setAttribute(`placeholder`,e instanceof Error?e.message:`Não foi possível ouvir; digite a tarefa.`),setTimeout(()=>r.removeAttribute(`placeholder`),6e3)}finally{s=!1}})))}let m=document.createElement(`button`);m.type=`button`,m.className=`page-agent-widget-launcher`,m.setAttribute(`aria-label`,n),m.title=n,m.innerHTML=LAUNCHER_ICON;let h=positionCss(t);Object.assign(m.style,h);let g=!1;async function _(e=!1){try{(await d()).panel.show(),g=!0}catch(t){if(e)console.error(`[page-agent-widget] não abriu o agente:`,t);else throw t}}function v(){i?.panel.hide?.(),g=!1}return m.addEventListener(`click`,()=>{g?v():_(!0)}),document.body.appendChild(m),r&&_(!0),{get agent(){return i},get voice(){return a},launcher:m,ready(){return d()},async run(e){return await(await d()).execute(e)},async stop(){i&&await i.stop()},show(){return _(!1)},hide(){v()},toggle(){m.click()},setConfig(t){Object.assign(e,t),i&&=(i.dispose(),null),g&&(g=!1,_(!0))},unmount(){a?.stopSpeaking(),a?.stopListening(),i?.dispose(),i=null,a=null,o?.remove(),o=null,m.remove()}}}var PageAgent=class extends PageAgentCore{panel;constructor(e){let t=new PageController({...e,enableMask:e.enableMask??!0});super({...e,pageController:t}),this.panel=new Panel(this,{language:e.language,promptForNextTask:e.promptForNextTask})}},currentScript=document.currentScript,currentScriptURL=currentScript?.src?new URL(currentScript.src):null,autoInit=currentScript?.getAttribute(`data-auto-init`)!==`false`&¤tScriptURL?.searchParams.get(`autoInit`)!==`false`;autoInit&&window.pageAgent&&window.pageAgent.dispose(),window.PageAgent=PageAgent,PageAgent.mountWidget=mountWidget,PageAgent.createVoice=createVoice,console.log(`🚀 page-agent.js loaded!`);var DEMO_MODEL=`qwen3.5-plus`,DEMO_BASE_URL=`https://page-ag-testing-ohftxirgbn.cn-shanghai.fcapp.run`,DEMO_API_KEY=`NA`;autoInit&&setTimeout(()=>{let e,t=!0;if(currentScriptURL){let n=currentScriptURL,r=n.searchParams.get(`model`)||DEMO_MODEL,i=n.searchParams.get(`baseURL`)||DEMO_BASE_URL,a=n.searchParams.get(`apiKey`)||DEMO_API_KEY,o=n.searchParams.get(`lang`)||`zh-CN`;t=(n.searchParams.get(`showPanel`)||`true`)===`true`,e={model:r,baseURL:i,apiKey:a,language:o}}else console.log(`🚀 page-agent.js no current script detected, using default demo config`),e={model:DEMO_MODEL,baseURL:DEMO_BASE_URL,apiKey:DEMO_API_KEY};window.pageAgent=new PageAgent(e),t&&window.pageAgent.panel.show(),console.log(`🚀 page-agent.js initialized with config:`,window.pageAgent.config)})})();
|