@guoquan.net/flow-engine 0.1.9 → 0.2.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/dist/flow.umd.js CHANGED
@@ -1 +1,39 @@
1
- (function(_,r){typeof exports=="object"&&typeof module<"u"?r(exports,require("three"),require("three/webgpu"),require("three/examples/jsm/loaders/GLTFLoader.js")):typeof define=="function"&&define.amd?define(["exports","three","three/webgpu","three/examples/jsm/loaders/GLTFLoader.js"],r):(_=typeof globalThis<"u"?globalThis:_||self,r(_.Flow={},_.THREE,_.THREE,_.GLTFLoader_js))})(this,(function(_,r,k,S){"use strict";function E(o){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const e in o)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(o,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>o[e]})}}return t.default=o,Object.freeze(t)}const n=E(r),L={type:"change"},M={type:"start"},O={type:"end"},b=new r.Ray,T=new r.Plane,v=Math.cos(70*r.MathUtils.DEG2RAD),p=new r.Vector3,u=2*Math.PI,c={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},D=1e-6;class x extends r.Controls{constructor(t,e=null){super(t,e),this.state=c.NONE,this.target=new r.Vector3,this.cursor=new r.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:r.MOUSE.ROTATE,MIDDLE:r.MOUSE.DOLLY,RIGHT:r.MOUSE.PAN},this.touches={ONE:r.TOUCH.ROTATE,TWO:r.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new r.Vector3,this._lastQuaternion=new r.Quaternion,this._lastTargetPosition=new r.Vector3,this._quat=new r.Quaternion().setFromUnitVectors(t.up,new r.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new r.Spherical,this._sphericalDelta=new r.Spherical,this._scale=1,this._panOffset=new r.Vector3,this._rotateStart=new r.Vector2,this._rotateEnd=new r.Vector2,this._rotateDelta=new r.Vector2,this._panStart=new r.Vector2,this._panEnd=new r.Vector2,this._panDelta=new r.Vector2,this._dollyStart=new r.Vector2,this._dollyEnd=new r.Vector2,this._dollyDelta=new r.Vector2,this._dollyDirection=new r.Vector3,this._mouse=new r.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=N.bind(this),this._onPointerDown=j.bind(this),this._onPointerUp=I.bind(this),this._onContextMenu=z.bind(this),this._onMouseWheel=F.bind(this),this._onKeyDown=Y.bind(this),this._onTouchStart=G.bind(this),this._onTouchMove=V.bind(this),this._onMouseDown=R.bind(this),this._onMouseMove=U.bind(this),this._interceptControlDown=K.bind(this),this._interceptControlUp=W.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}connect(t){super.connect(t),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(t){t.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=t}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(L),this.update(),this.state=c.NONE}update(t=null){const e=this.object.position;p.copy(e).sub(this.target),p.applyQuaternion(this._quat),this._spherical.setFromVector3(p),this.autoRotate&&this.state===c.NONE&&this._rotateLeft(this._getAutoRotationAngle(t)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let i=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(i)&&isFinite(s)&&(i<-Math.PI?i+=u:i>Math.PI&&(i-=u),s<-Math.PI?s+=u:s>Math.PI&&(s-=u),i<=s?this._spherical.theta=Math.max(i,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+s)/2?Math.max(i,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let a=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const h=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),a=h!=this._spherical.radius}if(p.setFromSpherical(this._spherical),p.applyQuaternion(this._quatInverse),e.copy(this.target).add(p),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let h=null;if(this.object.isPerspectiveCamera){const l=p.length();h=this._clampDistance(l*this._scale);const d=l-h;this.object.position.addScaledVector(this._dollyDirection,d),this.object.updateMatrixWorld(),a=!!d}else if(this.object.isOrthographicCamera){const l=new r.Vector3(this._mouse.x,this._mouse.y,0);l.unproject(this.object);const d=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),a=d!==this.object.zoom;const f=new r.Vector3(this._mouse.x,this._mouse.y,0);f.unproject(this.object),this.object.position.sub(f).add(l),this.object.updateMatrixWorld(),h=p.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;h!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(h).add(this.object.position):(b.origin.copy(this.object.position),b.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(b.direction))<v?this.object.lookAt(this.target):(T.setFromNormalAndCoplanarPoint(this.object.up,this.target),b.intersectPlane(T,this.target))))}else if(this.object.isOrthographicCamera){const h=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),h!==this.object.zoom&&(this.object.updateProjectionMatrix(),a=!0)}return this._scale=1,this._performCursorZoom=!1,a||this._lastPosition.distanceToSquared(this.object.position)>D||8*(1-this._lastQuaternion.dot(this.object.quaternion))>D||this._lastTargetPosition.distanceToSquared(this.target)>D?(this.dispatchEvent(L),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(t){return t!==null?u/60*this.autoRotateSpeed*t:u/60/60*this.autoRotateSpeed}_getZoomScale(t){const e=Math.abs(t*.01);return Math.pow(.95,this.zoomSpeed*e)}_rotateLeft(t){this._sphericalDelta.theta-=t}_rotateUp(t){this._sphericalDelta.phi-=t}_panLeft(t,e){p.setFromMatrixColumn(e,0),p.multiplyScalar(-t),this._panOffset.add(p)}_panUp(t,e){this.screenSpacePanning===!0?p.setFromMatrixColumn(e,1):(p.setFromMatrixColumn(e,0),p.crossVectors(this.object.up,p)),p.multiplyScalar(t),this._panOffset.add(p)}_pan(t,e){const i=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;p.copy(s).sub(this.target);let a=p.length();a*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*t*a/i.clientHeight,this.object.matrix),this._panUp(2*e*a/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(t*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(e*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(t){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=t:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(t){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=t:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(t,e){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const i=this.domElement.getBoundingClientRect(),s=t-i.left,a=e-i.top,h=i.width,l=i.height;this._mouse.x=s/h*2-1,this._mouse.y=-(a/l)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(t){return Math.max(this.minDistance,Math.min(this.maxDistance,t))}_handleMouseDownRotate(t){this._rotateStart.set(t.clientX,t.clientY)}_handleMouseDownDolly(t){this._updateZoomParameters(t.clientX,t.clientX),this._dollyStart.set(t.clientX,t.clientY)}_handleMouseDownPan(t){this._panStart.set(t.clientX,t.clientY)}_handleMouseMoveRotate(t){this._rotateEnd.set(t.clientX,t.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const e=this.domElement;this._rotateLeft(u*this._rotateDelta.x/e.clientHeight),this._rotateUp(u*this._rotateDelta.y/e.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(t){this._dollyEnd.set(t.clientX,t.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(t){this._panEnd.set(t.clientX,t.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(t){this._updateZoomParameters(t.clientX,t.clientY),t.deltaY<0?this._dollyIn(this._getZoomScale(t.deltaY)):t.deltaY>0&&this._dollyOut(this._getZoomScale(t.deltaY)),this.update()}_handleKeyDown(t){let e=!1;switch(t.code){case this.keys.UP:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateUp(u*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),e=!0;break;case this.keys.BOTTOM:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateUp(-u*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),e=!0;break;case this.keys.LEFT:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateLeft(u*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),e=!0;break;case this.keys.RIGHT:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateLeft(-u*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),e=!0;break}e&&(t.preventDefault(),this.update())}_handleTouchStartRotate(t){if(this._pointers.length===1)this._rotateStart.set(t.pageX,t.pageY);else{const e=this._getSecondPointerPosition(t),i=.5*(t.pageX+e.x),s=.5*(t.pageY+e.y);this._rotateStart.set(i,s)}}_handleTouchStartPan(t){if(this._pointers.length===1)this._panStart.set(t.pageX,t.pageY);else{const e=this._getSecondPointerPosition(t),i=.5*(t.pageX+e.x),s=.5*(t.pageY+e.y);this._panStart.set(i,s)}}_handleTouchStartDolly(t){const e=this._getSecondPointerPosition(t),i=t.pageX-e.x,s=t.pageY-e.y,a=Math.sqrt(i*i+s*s);this._dollyStart.set(0,a)}_handleTouchStartDollyPan(t){this.enableZoom&&this._handleTouchStartDolly(t),this.enablePan&&this._handleTouchStartPan(t)}_handleTouchStartDollyRotate(t){this.enableZoom&&this._handleTouchStartDolly(t),this.enableRotate&&this._handleTouchStartRotate(t)}_handleTouchMoveRotate(t){if(this._pointers.length==1)this._rotateEnd.set(t.pageX,t.pageY);else{const i=this._getSecondPointerPosition(t),s=.5*(t.pageX+i.x),a=.5*(t.pageY+i.y);this._rotateEnd.set(s,a)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const e=this.domElement;this._rotateLeft(u*this._rotateDelta.x/e.clientHeight),this._rotateUp(u*this._rotateDelta.y/e.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(t){if(this._pointers.length===1)this._panEnd.set(t.pageX,t.pageY);else{const e=this._getSecondPointerPosition(t),i=.5*(t.pageX+e.x),s=.5*(t.pageY+e.y);this._panEnd.set(i,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(t){const e=this._getSecondPointerPosition(t),i=t.pageX-e.x,s=t.pageY-e.y,a=Math.sqrt(i*i+s*s);this._dollyEnd.set(0,a),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const h=(t.pageX+e.x)*.5,l=(t.pageY+e.y)*.5;this._updateZoomParameters(h,l)}_handleTouchMoveDollyPan(t){this.enableZoom&&this._handleTouchMoveDolly(t),this.enablePan&&this._handleTouchMovePan(t)}_handleTouchMoveDollyRotate(t){this.enableZoom&&this._handleTouchMoveDolly(t),this.enableRotate&&this._handleTouchMoveRotate(t)}_addPointer(t){this._pointers.push(t.pointerId)}_removePointer(t){delete this._pointerPositions[t.pointerId];for(let e=0;e<this._pointers.length;e++)if(this._pointers[e]==t.pointerId){this._pointers.splice(e,1);return}}_isTrackingPointer(t){for(let e=0;e<this._pointers.length;e++)if(this._pointers[e]==t.pointerId)return!0;return!1}_trackPointer(t){let e=this._pointerPositions[t.pointerId];e===void 0&&(e=new r.Vector2,this._pointerPositions[t.pointerId]=e),e.set(t.pageX,t.pageY)}_getSecondPointerPosition(t){const e=t.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[e]}_customWheelEvent(t){const e=t.deltaMode,i={clientX:t.clientX,clientY:t.clientY,deltaY:t.deltaY};switch(e){case 1:i.deltaY*=16;break;case 2:i.deltaY*=100;break}return t.ctrlKey&&!this._controlActive&&(i.deltaY*=10),i}}function j(o){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(o.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(o)&&(this._addPointer(o),o.pointerType==="touch"?this._onTouchStart(o):this._onMouseDown(o)))}function N(o){this.enabled!==!1&&(o.pointerType==="touch"?this._onTouchMove(o):this._onMouseMove(o))}function I(o){switch(this._removePointer(o),this._pointers.length){case 0:this.domElement.releasePointerCapture(o.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(O),this.state=c.NONE;break;case 1:const t=this._pointers[0],e=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:e.x,pageY:e.y});break}}function R(o){let t;switch(o.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case r.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(o),this.state=c.DOLLY;break;case r.MOUSE.ROTATE:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=c.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=c.ROTATE}break;case r.MOUSE.PAN:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=c.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=c.PAN}break;default:this.state=c.NONE}this.state!==c.NONE&&this.dispatchEvent(M)}function U(o){switch(this.state){case c.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(o);break;case c.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(o);break;case c.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(o);break}}function F(o){this.enabled===!1||this.enableZoom===!1||this.state!==c.NONE||(o.preventDefault(),this.dispatchEvent(M),this._handleMouseWheel(this._customWheelEvent(o)),this.dispatchEvent(O))}function Y(o){this.enabled!==!1&&this._handleKeyDown(o)}function G(o){switch(this._trackPointer(o),this._pointers.length){case 1:switch(this.touches.ONE){case r.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(o),this.state=c.TOUCH_ROTATE;break;case r.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(o),this.state=c.TOUCH_PAN;break;default:this.state=c.NONE}break;case 2:switch(this.touches.TWO){case r.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(o),this.state=c.TOUCH_DOLLY_PAN;break;case r.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(o),this.state=c.TOUCH_DOLLY_ROTATE;break;default:this.state=c.NONE}break;default:this.state=c.NONE}this.state!==c.NONE&&this.dispatchEvent(M)}function V(o){switch(this._trackPointer(o),this.state){case c.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(o),this.update();break;case c.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(o),this.update();break;case c.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(o),this.update();break;case c.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(o),this.update();break;default:this.state=c.NONE}}function z(o){this.enabled!==!1&&o.preventDefault()}function K(o){o.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function W(o){o.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class C{loader;constructor(){this.loader=new S.GLTFLoader}async load(t){console.log(`[Flow] Loading avatar config from: ${t}`);try{const e=await fetch(t);if(!e.ok)throw new Error(`Failed to load config: ${e.statusText}`);const i=await e.json(),a=t.substring(0,t.lastIndexOf("/")+1)+i.modelSrc;console.log(`[Flow] Config loaded. Loading model from: ${a}`);let h,l=[];try{const d=await this.loader.loadAsync(a);h=d.scene,l=d.animations||[]}catch(d){console.warn(`[Flow] Failed to load 3D model at ${a}. Using fallback placeholder.`,d),h=this.createFallbackAvatar()}return this.applyConfig(h,i),{model:h,config:i,animations:l}}catch(e){throw console.error("[Flow] Error loading avatar:",e),e}}applyConfig(t,e){e.scale&&t.scale.setScalar(e.scale),e.initialPosition&&t.position.set(...e.initialPosition),t.traverse(i=>{i.isMesh&&(i.castShadow=!0,i.receiveShadow=!0)})}createFallbackAvatar(){const t=new n.Group,e=new n.MeshStandardMaterial({color:54015,roughness:.3,metalness:.8}),i=new n.BoxGeometry(.8,.9,.8),s=new n.Mesh(i,e);s.position.y=1.5,s.name="Head",t.add(s);const a=new n.SphereGeometry(.1),h=new n.MeshBasicMaterial({color:16777215}),l=new n.Mesh(a,h);l.position.set(-.2,1.5,.4),t.add(l);const d=new n.Mesh(a,h);d.position.set(.2,1.5,.4),t.add(d);const f=new n.CylinderGeometry(.6,.4,1.5,8),g=new n.Mesh(f,e);g.position.y=.5,g.name="Body",t.add(g);const y=new n.CapsuleGeometry(.15,1),w=new n.Mesh(y,e);w.position.set(-.9,.8,0),w.rotation.z=Math.PI/4,w.name="LeftArm",t.add(w);const P=new n.Mesh(y,e);return P.position.set(.9,.8,0),P.rotation.z=-Math.PI/4,P.name="RightArm",t.add(P),t}}class Z{loader;constructor(){this.loader=new S.GLTFLoader}async load(t){try{const e=await fetch(t);if(!e.ok)throw new Error("Failed to load stage config");const i=await e.json();let s,a=[];if(i.modelSrc){const l=t.substring(0,t.lastIndexOf("/")+1)+i.modelSrc,d=await this.loader.loadAsync(l);s=d.scene,a=d.animations||[]}else s=this.createProceduralStage();return this.applyConfig(s,i),{model:s,config:i,animations:a}}catch(e){throw console.error("[Flow] Stage load error:",e),e}}applyConfig(t,e){e.scale&&t.scale.setScalar(e.scale),e.position&&t.position.set(...e.position),e.rotation&&t.rotation.set(...e.rotation),t.traverse(i=>{i.isMesh&&(i.receiveShadow=!0,i.castShadow=!0)})}createProceduralStage(){const t=new n.Group,e=new n.CylinderGeometry(2,2.2,.2,32),i=new n.MeshStandardMaterial({color:2236962,roughness:.2,metalness:.8}),s=new n.Mesh(e,i);s.position.y=-.1,t.add(s);const a=new n.TorusGeometry(1.8,.05,16,100),h=new n.MeshBasicMaterial({color:54015}),l=new n.Mesh(a,h);l.rotation.x=-Math.PI/2,l.position.y=.01,t.add(l);const d=new n.BoxGeometry(.5,.05,.5);for(let f=0;f<4;f++){const g=new n.Mesh(d,i),y=f/4*Math.PI*2;g.position.set(Math.cos(y)*2.5,0,Math.sin(y)*2.5),g.lookAt(0,0,0),t.add(g)}return t}}class A{mixer;clips;states={};activeActions=new Map;currentState=null;defaultState="idle";constructor(t,e){this.mixer=new n.AnimationMixer(t),this.clips=e,this.mixer.addEventListener("finished",this.onFinished.bind(this))}init(t){this.defaultState=t.defaultState,this.states=t.states,Object.entries(this.states).forEach(([e,i])=>{this.findClip(i.clipName)||console.warn(`[AnimationController] Clip "${i.clipName}" for state "${e}" not found.`)}),this.play(this.defaultState)}update(t){this.mixer.update(t)}play(t,e=!1){const i=this.states[t];if(!i){console.warn(`[AnimationController] State "${t}" not defined.`);return}const s=this.findClip(i.clipName);if(!s||this.currentState===t&&!e)return;const a=this.mixer.clipAction(s);a.setLoop(i.loop?n.LoopRepeat:n.LoopOnce,i.loop?1/0:1),a.clampWhenFinished=!i.loop,a.timeScale=i.timeScale??1;const h=i.fadeDuration??.3;if(this.currentState){const l=this.activeActions.get(this.currentState);l&&l!==a?(l.fadeOut(h),a.reset(),a.fadeIn(h),a.play()):a.reset().play()}else a.reset().play();this.activeActions.set(t,a),this.currentState=t,console.log(`[Anim] Transition to: ${t} (Loop: ${i.loop})`)}onFinished(t){if(this.currentState&&this.activeActions.get(this.currentState)===t.action){const e=this.states[this.currentState],i=()=>{e&&e.next?this.play(e.next):!e.loop&&this.currentState!==this.defaultState&&this.play(this.defaultState)};e.holdDuration&&e.holdDuration>0?setTimeout(i,e.holdDuration*1e3):i()}}findClip(t){let e=this.clips.find(i=>i.name===t);return e||(e=this.clips.find(i=>i.name.toLowerCase()===t.toLowerCase())),e||(e=this.clips.find(i=>i.name.toLowerCase().includes(t.toLowerCase()))),e}}const m={IDLE:"IDLE",TRACKING:"TRACKING",HOLDING:"HOLDING"},B=5,Q=1.5,X=Number.EPSILON;class H{raycaster=new n.Raycaster;mouse=new n.Vector2;state=m.IDLE;stateTimer=0;lookAtTarget=new n.Vector3;currentLookAt=new n.Vector3;activePlane=new n.Plane(new n.Vector3(0,0,1),-2.5);planeCenter=new n.Vector3(0,1.5,2.5);lookAtProxy=new n.Object3D;_targetQuat=new n.Quaternion;_dummyVec=new n.Vector3;_offsetQuat=new n.Quaternion;_parentWorldQuat=new n.Quaternion;outputQuaternion=null;weight=0;container;camera;getHeadBone;getConfig;getModels;boundOnPointerDown;boundOnPointerMove;boundOnPointerUp;constructor(t,e,i,s,a){this.container=t,this.camera=e,this.getHeadBone=i,this.getConfig=s,this.getModels=a,this.boundOnPointerDown=this.onPointerDown.bind(this),this.boundOnPointerMove=this.onPointerMove.bind(this),this.boundOnPointerUp=this.onPointerUp.bind(this),this.container.addEventListener("pointerdown",this.boundOnPointerDown),this.container.addEventListener("pointermove",this.boundOnPointerMove),window.addEventListener("pointerup",this.boundOnPointerUp)}update(t,e){const i=this.getHeadBone(),s=this.getConfig();if(!i||!s||s.lookAt?.enabled===!1)return;const a=i.quaternion.clone();this.outputQuaternion||(this.outputQuaternion=a.clone()),this.updateState(t,s);const h=this.state===m.TRACKING||this.state===m.HOLDING;h?(this.calculateLookAtRotation(i,s,this._targetQuat),this.weight=1):(this._targetQuat.copy(a),this.weight=0);const l=s.lookAt?.damping??B,d=1-Math.exp(-l*e);this.outputQuaternion.slerp(this._targetQuat,d),i.quaternion.copy(this.outputQuaternion),h&&this.currentLookAt.lerp(this.lookAtTarget,d)}calculateLookAtRotation(t,e,i){const s=this._dummyVec;t.getWorldPosition(s),this.lookAtProxy.position.copy(s),this.lookAtProxy.lookAt(this.lookAtTarget),this.lookAtProxy.updateMatrixWorld();const a=e.lookAt?.rotationOffset||[0,0,0];this._offsetQuat.setFromEuler(new n.Euler(...a));const h=this.lookAtProxy.quaternion.multiply(this._offsetQuat),l=t.parent;if(l){l.getWorldQuaternion(this._parentWorldQuat);const d=this._parentWorldQuat.invert();i.copy(d.multiply(h))}else i.copy(h)}updateState(t,e){const i=e.lookAt?.holdDuration??2e3;switch(this.state){case m.TRACKING:this.calculateLookAtTarget();break;case m.HOLDING:t-this.stateTimer>i&&(this.state=m.IDLE,console.log("[Flow] LookAt: Holding finished, releasing to animation."));break}}onPointerDown(t){this.updateMouse(t);const e=this.getHeadBone();if(e){const i=new n.Vector3;e.getWorldPosition(i);const s=this.camera.position.clone(),a=new n.Vector3().subVectors(s,i),h=new n.Vector3;if(a.lengthSq()<1e-6){const d=this.camera;"getWorldDirection"in d&&typeof d.getWorldDirection=="function"?(d.getWorldDirection(h),h.negate()):h.set(0,0,1)}else h.copy(a).normalize();const l=h.clone().multiplyScalar(Q);this.planeCenter.copy(i).add(l),this.activePlane.setFromNormalAndCoplanarPoint(h,this.planeCenter)}this.state=m.TRACKING,this.calculateLookAtTarget(),this.outputQuaternion||this.currentLookAt.copy(this.lookAtTarget)}onPointerMove(t){this.state===m.TRACKING&&this.updateMouse(t)}onPointerUp(){this.state===m.TRACKING&&(this.state=m.HOLDING,this.stateTimer=performance.now())}updateMouse(t){const e=this.container.getBoundingClientRect();this.mouse.x=(t.clientX-e.left)/e.width*2-1,this.mouse.y=-((t.clientY-e.top)/e.height)*2+1}calculateLookAtTarget(){this.raycaster.setFromCamera(this.mouse,this.camera);const t=this.getModels().filter(i=>!!i);if(t.length>0){const i=this.raycaster.intersectObjects(t,!0);if(i.length>0){this.lookAtTarget.copy(i[0].point);return}}const e=this._dummyVec;this.activePlane.normal.lengthSq()>X&&this.raycaster.ray.intersectPlane(this.activePlane,e)&&this.lookAtTarget.copy(e)}getDebugInfo(){return{isEngaged:this.state!==m.IDLE,currentLookAt:this.currentLookAt,activePlane:this.activePlane,planeCenter:this.planeCenter,weight:this.weight}}interrupt(){this.state=m.IDLE}dispose(){this.container.removeEventListener("pointerdown",this.boundOnPointerDown),this.container.removeEventListener("pointermove",this.boundOnPointerMove),window.removeEventListener("pointerup",this.boundOnPointerUp)}}class q{container;scene;camera;renderer;controls;clock;loader;stageLoader;avatarModel=null;stageModel=null;headBone=null;animController=null;stageAnimController=null;lookAtProcessor;currentAvatarConfig=null;isDebug=!1;debugTargetMesh=null;debugPlaneMesh=null;constructor(t){const e=document.getElementById(t);if(!e)throw new Error(`Container #${t} not found`);this.container=e,this.clock=new n.Clock,this.loader=new C,this.stageLoader=new Z,this.scene=new n.Scene,this.scene.background=new n.Color(1710618),this.scene.fog=new n.Fog(1710618,10,50),this.camera=new n.PerspectiveCamera(45,window.innerWidth/window.innerHeight,.1,100),this.camera.position.set(0,1.5,5),this.renderer=new k.WebGPURenderer({antialias:!0,alpha:!0}),this.renderer.setSize(window.innerWidth,window.innerHeight),this.renderer.setPixelRatio(window.devicePixelRatio),this.container.appendChild(this.renderer.domElement),this.setupLights(),this.controls=new x(this.camera,this.renderer.domElement),this.controls.enableDamping=!0,this.controls.target.set(0,1,0),this.lookAtProcessor=new H(this.container,this.camera,()=>this.headBone,()=>this.currentAvatarConfig,()=>{const i=[];return this.avatarModel&&i.push(this.avatarModel),this.stageModel&&i.push(this.stageModel),i}),window.addEventListener("resize",this.onWindowResize.bind(this)),this.renderer.setAnimationLoop(this.animate.bind(this))}setupLights(){const t=new n.AmbientLight(16777215,.6);this.scene.add(t);const e=new n.DirectionalLight(16777215,1);e.position.set(5,10,7),e.castShadow=!0,this.scene.add(e);const i=new n.SpotLight(54015,5);i.position.set(-5,5,-5),i.lookAt(0,1,0),this.scene.add(i)}async loadAvatar(t){this.avatarModel&&this.scene.remove(this.avatarModel);const{model:e,config:i,animations:s}=await this.loader.load(t);this.avatarModel=e,this.currentAvatarConfig=i,this.scene.add(this.avatarModel);const a=i.lookAt?.headBoneName||"Head";if(this.headBone=this.avatarModel.getObjectByName(a)||null,this.headBone||this.avatarModel.traverse(h=>{!this.headBone&&h.name.toLowerCase().includes("head")&&(this.headBone=h)}),s.length>0){this.animController=new A(this.avatarModel,s);const h=i.animations||{defaultState:"idle",states:{idle:{clipName:"Idle",loop:!0},walk:{clipName:"Walking",loop:!0},wave:{clipName:"Wave",loop:!1,next:"idle"},dance:{clipName:"Dance",loop:!1,next:"idle"},bow:{clipName:"Bow",loop:!1,next:"idle"}}};this.animController.init(h)}console.log(`[Flow] Avatar "${i.name}" loaded.`)}async loadStage(t){this.stageModel&&this.scene.remove(this.stageModel);const{model:e,config:i,animations:s}=await this.stageLoader.load(t);this.stageModel=e,this.scene.add(this.stageModel),s.length>0&&i.animations&&(this.stageAnimController=new A(this.stageModel,s),this.stageAnimController.init(i.animations))}setDebug(t){this.isDebug=t,t?this.createDebugHelpers():this.removeDebugHelpers()}createDebugHelpers(){if(this.debugTargetMesh||(this.debugTargetMesh=new n.Mesh(new n.SphereGeometry(.1,8,8),new n.MeshBasicMaterial({color:16711680,wireframe:!0,depthTest:!1})),this.debugTargetMesh.renderOrder=999,this.scene.add(this.debugTargetMesh)),!this.debugPlaneMesh){const t=new n.GridHelper(5,10,65280,34816);t.material.transparent=!0,t.material.opacity=.5,t.rotateX(Math.PI/2),this.debugPlaneMesh=t,this.scene.add(this.debugPlaneMesh)}}updateDebugHelpers(){if(!this.isDebug||!this.lookAtProcessor)return;const t=this.lookAtProcessor.getDebugInfo(),e=!!(t.planeCenter&&t.activePlane);if(this.debugTargetMesh&&(this.debugTargetMesh.position.copy(t.currentLookAt),this.debugTargetMesh.visible=t.isEngaged),this.debugPlaneMesh&&(this.debugPlaneMesh.visible=e,e)){this.debugPlaneMesh.position.copy(t.planeCenter);const i=t.activePlane.normal,s=this.debugPlaneMesh.position.clone().add(i);this.debugPlaneMesh.lookAt(s),this.debugPlaneMesh.rotateX(Math.PI/2)}}removeDebugHelpers(){this.debugTargetMesh&&(this.scene.remove(this.debugTargetMesh),this.debugTargetMesh=null),this.debugPlaneMesh&&(this.scene.remove(this.debugPlaneMesh),this.debugPlaneMesh=null)}onWindowResize(){this.camera.aspect=window.innerWidth/window.innerHeight,this.camera.updateProjectionMatrix(),this.renderer.setSize(window.innerWidth,window.innerHeight)}isAutoRotate=!1;playAction(t){this.lookAtProcessor.interrupt(),this.animController&&this.animController.play(t.toLowerCase())}animate(t){const e=this.clock.getDelta();this.avatarModel&&(this.animController&&this.animController.update(e),this.lookAtProcessor.update(t,e)),this.updateDebugHelpers(),this.stageModel&&this.stageAnimController&&this.stageAnimController.update(e),this.controls.autoRotate=this.isAutoRotate,this.controls.update(),this.renderer.render(this.scene,this.camera)}}_.AnimationController=A,_.AvatarLoader=C,_.FlowEngine=q,Object.defineProperty(_,Symbol.toStringTag,{value:"Module"})}));
1
+ (function($,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("three"),require("three/webgpu"),require("three/examples/jsm/loaders/GLTFLoader.js")):typeof define=="function"&&define.amd?define(["exports","three","three/webgpu","three/examples/jsm/loaders/GLTFLoader.js"],g):($=typeof globalThis<"u"?globalThis:$||self,g($.Flow={},$.THREE,$.THREE,$.GLTFLoader_js))})(this,(function($,g,$t,Te){"use strict";function Mt(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const d=Mt(g),Ae={type:"change"},ue={type:"start"},Ee={type:"end"},H=new g.Ray,Ze=new g.Plane,Ct=Math.cos(70*g.MathUtils.DEG2RAD),T=new g.Vector3,Z=2*Math.PI,y={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},le=1e-6;class Nt extends g.Controls{constructor(t,n=null){super(t,n),this.state=y.NONE,this.target=new g.Vector3,this.cursor=new g.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:g.MOUSE.ROTATE,MIDDLE:g.MOUSE.DOLLY,RIGHT:g.MOUSE.PAN},this.touches={ONE:g.TOUCH.ROTATE,TWO:g.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new g.Vector3,this._lastQuaternion=new g.Quaternion,this._lastTargetPosition=new g.Vector3,this._quat=new g.Quaternion().setFromUnitVectors(t.up,new g.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new g.Spherical,this._sphericalDelta=new g.Spherical,this._scale=1,this._panOffset=new g.Vector3,this._rotateStart=new g.Vector2,this._rotateEnd=new g.Vector2,this._rotateDelta=new g.Vector2,this._panStart=new g.Vector2,this._panEnd=new g.Vector2,this._panDelta=new g.Vector2,this._dollyStart=new g.Vector2,this._dollyEnd=new g.Vector2,this._dollyDelta=new g.Vector2,this._dollyDirection=new g.Vector3,this._mouse=new g.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Lt.bind(this),this._onPointerDown=jt.bind(this),this._onPointerUp=Rt.bind(this),this._onContextMenu=Kt.bind(this),this._onMouseWheel=Ft.bind(this),this._onKeyDown=Vt.bind(this),this._onTouchStart=Gt.bind(this),this._onTouchMove=Wt.bind(this),this._onMouseDown=xt.bind(this),this._onMouseMove=Ut.bind(this),this._interceptControlDown=Bt.bind(this),this._interceptControlUp=Yt.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}connect(t){super.connect(t),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(t){t.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=t}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(Ae),this.update(),this.state=y.NONE}update(t=null){const n=this.object.position;T.copy(n).sub(this.target),T.applyQuaternion(this._quat),this._spherical.setFromVector3(T),this.autoRotate&&this.state===y.NONE&&this._rotateLeft(this._getAutoRotationAngle(t)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let o=this.minAzimuthAngle,r=this.maxAzimuthAngle;isFinite(o)&&isFinite(r)&&(o<-Math.PI?o+=Z:o>Math.PI&&(o-=Z),r<-Math.PI?r+=Z:r>Math.PI&&(r-=Z),o<=r?this._spherical.theta=Math.max(o,Math.min(r,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(o+r)/2?Math.max(o,this._spherical.theta):Math.min(r,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let i=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const s=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),i=s!=this._spherical.radius}if(T.setFromSpherical(this._spherical),T.applyQuaternion(this._quatInverse),n.copy(this.target).add(T),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let s=null;if(this.object.isPerspectiveCamera){const a=T.length();s=this._clampDistance(a*this._scale);const c=a-s;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),i=!!c}else if(this.object.isOrthographicCamera){const a=new g.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),i=c!==this.object.zoom;const l=new g.Vector3(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(a),this.object.updateMatrixWorld(),s=T.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;s!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(s).add(this.object.position):(H.origin.copy(this.object.position),H.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(H.direction))<Ct?this.object.lookAt(this.target):(Ze.setFromNormalAndCoplanarPoint(this.object.up,this.target),H.intersectPlane(Ze,this.target))))}else if(this.object.isOrthographicCamera){const s=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),s!==this.object.zoom&&(this.object.updateProjectionMatrix(),i=!0)}return this._scale=1,this._performCursorZoom=!1,i||this._lastPosition.distanceToSquared(this.object.position)>le||8*(1-this._lastQuaternion.dot(this.object.quaternion))>le||this._lastTargetPosition.distanceToSquared(this.target)>le?(this.dispatchEvent(Ae),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(t){return t!==null?Z/60*this.autoRotateSpeed*t:Z/60/60*this.autoRotateSpeed}_getZoomScale(t){const n=Math.abs(t*.01);return Math.pow(.95,this.zoomSpeed*n)}_rotateLeft(t){this._sphericalDelta.theta-=t}_rotateUp(t){this._sphericalDelta.phi-=t}_panLeft(t,n){T.setFromMatrixColumn(n,0),T.multiplyScalar(-t),this._panOffset.add(T)}_panUp(t,n){this.screenSpacePanning===!0?T.setFromMatrixColumn(n,1):(T.setFromMatrixColumn(n,0),T.crossVectors(this.object.up,T)),T.multiplyScalar(t),this._panOffset.add(T)}_pan(t,n){const o=this.domElement;if(this.object.isPerspectiveCamera){const r=this.object.position;T.copy(r).sub(this.target);let i=T.length();i*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*t*i/o.clientHeight,this.object.matrix),this._panUp(2*n*i/o.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(t*(this.object.right-this.object.left)/this.object.zoom/o.clientWidth,this.object.matrix),this._panUp(n*(this.object.top-this.object.bottom)/this.object.zoom/o.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(t){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=t:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(t){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=t:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(t,n){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const o=this.domElement.getBoundingClientRect(),r=t-o.left,i=n-o.top,s=o.width,a=o.height;this._mouse.x=r/s*2-1,this._mouse.y=-(i/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(t){return Math.max(this.minDistance,Math.min(this.maxDistance,t))}_handleMouseDownRotate(t){this._rotateStart.set(t.clientX,t.clientY)}_handleMouseDownDolly(t){this._updateZoomParameters(t.clientX,t.clientX),this._dollyStart.set(t.clientX,t.clientY)}_handleMouseDownPan(t){this._panStart.set(t.clientX,t.clientY)}_handleMouseMoveRotate(t){this._rotateEnd.set(t.clientX,t.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const n=this.domElement;this._rotateLeft(Z*this._rotateDelta.x/n.clientHeight),this._rotateUp(Z*this._rotateDelta.y/n.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(t){this._dollyEnd.set(t.clientX,t.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(t){this._panEnd.set(t.clientX,t.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(t){this._updateZoomParameters(t.clientX,t.clientY),t.deltaY<0?this._dollyIn(this._getZoomScale(t.deltaY)):t.deltaY>0&&this._dollyOut(this._getZoomScale(t.deltaY)),this.update()}_handleKeyDown(t){let n=!1;switch(t.code){case this.keys.UP:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateUp(Z*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),n=!0;break;case this.keys.BOTTOM:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateUp(-Z*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),n=!0;break;case this.keys.LEFT:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateLeft(Z*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),n=!0;break;case this.keys.RIGHT:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateLeft(-Z*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),n=!0;break}n&&(t.preventDefault(),this.update())}_handleTouchStartRotate(t){if(this._pointers.length===1)this._rotateStart.set(t.pageX,t.pageY);else{const n=this._getSecondPointerPosition(t),o=.5*(t.pageX+n.x),r=.5*(t.pageY+n.y);this._rotateStart.set(o,r)}}_handleTouchStartPan(t){if(this._pointers.length===1)this._panStart.set(t.pageX,t.pageY);else{const n=this._getSecondPointerPosition(t),o=.5*(t.pageX+n.x),r=.5*(t.pageY+n.y);this._panStart.set(o,r)}}_handleTouchStartDolly(t){const n=this._getSecondPointerPosition(t),o=t.pageX-n.x,r=t.pageY-n.y,i=Math.sqrt(o*o+r*r);this._dollyStart.set(0,i)}_handleTouchStartDollyPan(t){this.enableZoom&&this._handleTouchStartDolly(t),this.enablePan&&this._handleTouchStartPan(t)}_handleTouchStartDollyRotate(t){this.enableZoom&&this._handleTouchStartDolly(t),this.enableRotate&&this._handleTouchStartRotate(t)}_handleTouchMoveRotate(t){if(this._pointers.length==1)this._rotateEnd.set(t.pageX,t.pageY);else{const o=this._getSecondPointerPosition(t),r=.5*(t.pageX+o.x),i=.5*(t.pageY+o.y);this._rotateEnd.set(r,i)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const n=this.domElement;this._rotateLeft(Z*this._rotateDelta.x/n.clientHeight),this._rotateUp(Z*this._rotateDelta.y/n.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(t){if(this._pointers.length===1)this._panEnd.set(t.pageX,t.pageY);else{const n=this._getSecondPointerPosition(t),o=.5*(t.pageX+n.x),r=.5*(t.pageY+n.y);this._panEnd.set(o,r)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(t){const n=this._getSecondPointerPosition(t),o=t.pageX-n.x,r=t.pageY-n.y,i=Math.sqrt(o*o+r*r);this._dollyEnd.set(0,i),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const s=(t.pageX+n.x)*.5,a=(t.pageY+n.y)*.5;this._updateZoomParameters(s,a)}_handleTouchMoveDollyPan(t){this.enableZoom&&this._handleTouchMoveDolly(t),this.enablePan&&this._handleTouchMovePan(t)}_handleTouchMoveDollyRotate(t){this.enableZoom&&this._handleTouchMoveDolly(t),this.enableRotate&&this._handleTouchMoveRotate(t)}_addPointer(t){this._pointers.push(t.pointerId)}_removePointer(t){delete this._pointerPositions[t.pointerId];for(let n=0;n<this._pointers.length;n++)if(this._pointers[n]==t.pointerId){this._pointers.splice(n,1);return}}_isTrackingPointer(t){for(let n=0;n<this._pointers.length;n++)if(this._pointers[n]==t.pointerId)return!0;return!1}_trackPointer(t){let n=this._pointerPositions[t.pointerId];n===void 0&&(n=new g.Vector2,this._pointerPositions[t.pointerId]=n),n.set(t.pageX,t.pageY)}_getSecondPointerPosition(t){const n=t.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[n]}_customWheelEvent(t){const n=t.deltaMode,o={clientX:t.clientX,clientY:t.clientY,deltaY:t.deltaY};switch(n){case 1:o.deltaY*=16;break;case 2:o.deltaY*=100;break}return t.ctrlKey&&!this._controlActive&&(o.deltaY*=10),o}}function jt(e){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(e)&&(this._addPointer(e),e.pointerType==="touch"?this._onTouchStart(e):this._onMouseDown(e)))}function Lt(e){this.enabled!==!1&&(e.pointerType==="touch"?this._onTouchMove(e):this._onMouseMove(e))}function Rt(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Ee),this.state=y.NONE;break;case 1:const t=this._pointers[0],n=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:n.x,pageY:n.y});break}}function xt(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case g.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(e),this.state=y.DOLLY;break;case g.MOUSE.ROTATE:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=y.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=y.ROTATE}break;case g.MOUSE.PAN:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=y.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=y.PAN}break;default:this.state=y.NONE}this.state!==y.NONE&&this.dispatchEvent(ue)}function Ut(e){switch(this.state){case y.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(e);break;case y.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(e);break;case y.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(e);break}}function Ft(e){this.enabled===!1||this.enableZoom===!1||this.state!==y.NONE||(e.preventDefault(),this.dispatchEvent(ue),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(Ee))}function Vt(e){this.enabled!==!1&&this._handleKeyDown(e)}function Gt(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case g.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(e),this.state=y.TOUCH_ROTATE;break;case g.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(e),this.state=y.TOUCH_PAN;break;default:this.state=y.NONE}break;case 2:switch(this.touches.TWO){case g.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(e),this.state=y.TOUCH_DOLLY_PAN;break;case g.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(e),this.state=y.TOUCH_DOLLY_ROTATE;break;default:this.state=y.NONE}break;default:this.state=y.NONE}this.state!==y.NONE&&this.dispatchEvent(ue)}function Wt(e){switch(this._trackPointer(e),this.state){case y.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(e),this.update();break;case y.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(e),this.update();break;case y.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(e),this.update();break;case y.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=y.NONE}}function Kt(e){this.enabled!==!1&&e.preventDefault()}function Bt(e){e.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Yt(e){e.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class Ie{loader;constructor(){this.loader=new Te.GLTFLoader}async load(t){console.log(`[Flow] Loading avatar config from: ${t}`);try{const n=await fetch(t);if(!n.ok)throw new Error(`Failed to load config: ${n.statusText}`);const o=await n.json(),i=t.substring(0,t.lastIndexOf("/")+1)+o.modelSrc;console.log(`[Flow] Config loaded. Loading model from: ${i}`);let s,a=[];try{const c=await this.loader.loadAsync(i);s=c.scene,a=c.animations||[]}catch(c){console.warn(`[Flow] Failed to load 3D model at ${i}. Using fallback placeholder.`,c),s=this.createFallbackAvatar()}return this.applyConfig(s,o),{model:s,config:o,animations:a}}catch(n){throw console.error("[Flow] Error loading avatar:",n),n}}applyConfig(t,n){n.scale&&t.scale.setScalar(n.scale),n.initialPosition&&t.position.set(...n.initialPosition),t.traverse(o=>{o.isMesh&&(o.castShadow=!0,o.receiveShadow=!0)})}createFallbackAvatar(){const t=new d.Group,n=new d.MeshStandardMaterial({color:54015,roughness:.3,metalness:.8}),o=new d.BoxGeometry(.8,.9,.8),r=new d.Mesh(o,n);r.position.y=1.5,r.name="Head",t.add(r);const i=new d.SphereGeometry(.1),s=new d.MeshBasicMaterial({color:16777215}),a=new d.Mesh(i,s);a.position.set(-.2,1.5,.4),t.add(a);const c=new d.Mesh(i,s);c.position.set(.2,1.5,.4),t.add(c);const l=new d.CylinderGeometry(.6,.4,1.5,8),h=new d.Mesh(l,n);h.position.y=.5,h.name="Body",t.add(h);const _=new d.CapsuleGeometry(.15,1),p=new d.Mesh(_,n);p.position.set(-.9,.8,0),p.rotation.z=Math.PI/4,p.name="LeftArm",t.add(p);const m=new d.Mesh(_,n);return m.position.set(.9,.8,0),m.rotation.z=-Math.PI/4,m.name="RightArm",t.add(m),t}}class Jt{loader;constructor(){this.loader=new Te.GLTFLoader}async load(t){try{const n=await fetch(t);if(!n.ok)throw new Error("Failed to load stage config");const o=await n.json();let r,i=[];if(o.modelSrc){const a=t.substring(0,t.lastIndexOf("/")+1)+o.modelSrc,c=await this.loader.loadAsync(a);r=c.scene,i=c.animations||[]}else r=this.createProceduralStage();return this.applyConfig(r,o),{model:r,config:o,animations:i}}catch(n){throw console.error("[Flow] Stage load error:",n),n}}applyConfig(t,n){n.scale&&t.scale.setScalar(n.scale),n.position&&t.position.set(...n.position),n.rotation&&t.rotation.set(...n.rotation),t.traverse(o=>{o.isMesh&&(o.receiveShadow=!0,o.castShadow=!0)})}createProceduralStage(){const t=new d.Group,n=new d.CylinderGeometry(2,2.2,.2,32),o=new d.MeshStandardMaterial({color:2236962,roughness:.2,metalness:.8}),r=new d.Mesh(n,o);r.position.y=-.1,t.add(r);const i=new d.TorusGeometry(1.8,.05,16,100),s=new d.MeshBasicMaterial({color:54015}),a=new d.Mesh(i,s);a.rotation.x=-Math.PI/2,a.position.y=.01,t.add(a);const c=new d.BoxGeometry(.5,.05,.5);for(let l=0;l<4;l++){const h=new d.Mesh(c,o),_=l/4*Math.PI*2;h.position.set(Math.cos(_)*2.5,0,Math.sin(_)*2.5),h.lookAt(0,0,0),t.add(h)}return t}}class he{mixer;clips;states={};activeActions=new Map;currentState=null;defaultState="idle";constructor(t,n){this.mixer=new d.AnimationMixer(t),this.clips=n,this.mixer.addEventListener("finished",this.onFinished.bind(this))}init(t){this.defaultState=t.defaultState,this.states=t.states,Object.entries(this.states).forEach(([n,o])=>{this.findClip(o.clipName)||console.warn(`[AnimationController] Clip "${o.clipName}" for state "${n}" not found.`)}),this.play(this.defaultState)}update(t){this.mixer.update(t)}play(t,n=!1){const o=this.states[t];if(!o){console.warn(`[AnimationController] State "${t}" not defined.`);return}const r=this.findClip(o.clipName);if(!r||this.currentState===t&&!n)return;const i=this.mixer.clipAction(r);i.setLoop(o.loop?d.LoopRepeat:d.LoopOnce,o.loop?1/0:1),i.clampWhenFinished=!o.loop,i.timeScale=o.timeScale??1;const s=o.fadeDuration??.3;if(this.currentState){const a=this.activeActions.get(this.currentState);a&&a!==i?(a.fadeOut(s),i.reset(),i.fadeIn(s),i.play()):i.reset().play()}else i.reset().play();this.activeActions.set(t,i),this.currentState=t,console.log(`[Anim] Transition to: ${t} (Loop: ${o.loop})`)}onFinished(t){if(this.currentState&&this.activeActions.get(this.currentState)===t.action){const n=this.states[this.currentState],o=()=>{n&&n.next?this.play(n.next):!n.loop&&this.currentState!==this.defaultState&&this.play(this.defaultState)};n.holdDuration&&n.holdDuration>0?setTimeout(o,n.holdDuration*1e3):o()}}findClip(t){let n=this.clips.find(o=>o.name===t);return n||(n=this.clips.find(o=>o.name.toLowerCase()===t.toLowerCase())),n||(n=this.clips.find(o=>o.name.toLowerCase().includes(t.toLowerCase()))),n}}const M={IDLE:"IDLE",TRACKING:"TRACKING",HOLDING:"HOLDING",OVERRIDE:"OVERRIDE"},Xt=5,Ht=1.5,qt=Number.EPSILON;class Qt{raycaster=new d.Raycaster;mouse=new d.Vector2;state=M.IDLE;stateTimer=0;lookAtTarget=new d.Vector3;currentLookAt=new d.Vector3;activePlane=new d.Plane(new d.Vector3(0,0,1),-2.5);planeCenter=new d.Vector3(0,1.5,2.5);lookAtProxy=new d.Object3D;_targetQuat=new d.Quaternion;_dummyVec=new d.Vector3;_offsetQuat=new d.Quaternion;_parentWorldQuat=new d.Quaternion;outputQuaternion=null;weight=0;container;camera;getHeadBone;getConfig;getModels;boundOnPointerDown;boundOnPointerMove;boundOnPointerUp;constructor(t,n,o,r,i){this.container=t,this.camera=n,this.getHeadBone=o,this.getConfig=r,this.getModels=i,this.boundOnPointerDown=this.onPointerDown.bind(this),this.boundOnPointerMove=this.onPointerMove.bind(this),this.boundOnPointerUp=this.onPointerUp.bind(this),this.container.addEventListener("pointerdown",this.boundOnPointerDown),this.container.addEventListener("pointermove",this.boundOnPointerMove),window.addEventListener("pointerup",this.boundOnPointerUp)}update(t,n){const o=this.getHeadBone(),r=this.getConfig();if(!o||!r||r.lookAt?.enabled===!1)return;const i=o.quaternion.clone();this.outputQuaternion||(this.outputQuaternion=i.clone()),this.updateState(t,r);const s=this.state!==M.IDLE;s?(this.calculateLookAtRotation(o,r,this._targetQuat),this.weight=1):(this._targetQuat.copy(i),this.weight=0);const a=r.lookAt?.damping??Xt,c=1-Math.exp(-a*n);this.outputQuaternion.slerp(this._targetQuat,c),o.quaternion.copy(this.outputQuaternion),s&&this.currentLookAt.lerp(this.lookAtTarget,c)}calculateLookAtRotation(t,n,o){const r=this._dummyVec;t.getWorldPosition(r),this.lookAtProxy.position.copy(r),this.lookAtProxy.lookAt(this.lookAtTarget),this.lookAtProxy.updateMatrixWorld();const i=n.lookAt?.rotationOffset||[0,0,0];this._offsetQuat.setFromEuler(new d.Euler(...i));const s=this.lookAtProxy.quaternion.multiply(this._offsetQuat),a=t.parent;if(a){a.getWorldQuaternion(this._parentWorldQuat);const c=this._parentWorldQuat.invert();o.copy(c.multiply(s))}else o.copy(s)}updateState(t,n){const o=n.lookAt?.holdDuration??2e3;switch(this.state){case M.TRACKING:this.calculateLookAtTarget();break;case M.HOLDING:t-this.stateTimer>o&&(this.state=M.IDLE,console.log("[Flow] LookAt: Holding finished, releasing to animation."));break}}setTarget(t){this.state=M.OVERRIDE,this.stateTimer=performance.now(),this.lookAtTarget.copy(t)}reset(){this.state=M.IDLE}onPointerDown(t){this.updateMouse(t);const n=this.getHeadBone();if(n){const o=new d.Vector3;n.getWorldPosition(o);const r=this.camera.position.clone(),i=new d.Vector3().subVectors(r,o),s=new d.Vector3;if(i.lengthSq()<1e-6){const c=this.camera;"getWorldDirection"in c&&typeof c.getWorldDirection=="function"?(c.getWorldDirection(s),s.negate()):s.set(0,0,1)}else s.copy(i).normalize();const a=s.clone().multiplyScalar(Ht);this.planeCenter.copy(o).add(a),this.activePlane.setFromNormalAndCoplanarPoint(s,this.planeCenter)}this.state=M.TRACKING,this.calculateLookAtTarget(),this.outputQuaternion||this.currentLookAt.copy(this.lookAtTarget)}onPointerMove(t){this.state===M.TRACKING&&this.updateMouse(t)}onPointerUp(){this.state===M.TRACKING&&(this.state=M.HOLDING,this.stateTimer=performance.now())}updateMouse(t){const n=this.container.getBoundingClientRect();this.mouse.x=(t.clientX-n.left)/n.width*2-1,this.mouse.y=-((t.clientY-n.top)/n.height)*2+1}calculateLookAtTarget(){this.raycaster.setFromCamera(this.mouse,this.camera);const t=this.getModels().filter(o=>!!o);if(t.length>0){const o=this.raycaster.intersectObjects(t,!0);if(o.length>0){this.lookAtTarget.copy(o[0].point);return}}const n=this._dummyVec;this.activePlane.normal.lengthSq()>qt&&this.raycaster.ray.intersectPlane(this.activePlane,n)&&this.lookAtTarget.copy(n)}getDebugInfo(){return{isEngaged:this.state!==M.IDLE,currentLookAt:this.currentLookAt,activePlane:this.activePlane,planeCenter:this.planeCenter,weight:this.weight}}interrupt(){this.state=M.IDLE}dispose(){this.container.removeEventListener("pointerdown",this.boundOnPointerDown),this.container.removeEventListener("pointermove",this.boundOnPointerMove),window.removeEventListener("pointerup",this.boundOnPointerUp)}}const N={IDLE:"IDLE",TALKING:"TALKING",THINKING:"THINKING",LISTENING:"LISTENING",EMOTIONAL:"EMOTIONAL"};class De{currentState=N.IDLE;stateStartTime=0;stateTimeout=null;isTransitioning=!1;debug=!1;onStateChange;constructor(t){this.debug=!!t?.debug}setDebugMode(t){this.debug=t}isDebugEnabled(){return this.debug}update(t){this.stateStartTime===0&&(this.stateStartTime=t),this.stateTimeout!==null&&t-this.stateStartTime>=this.stateTimeout&&(this.debug&&console.log(`[Brain] State ${this.currentState} timed out, reverting to IDLE.`),this.stateTimeout=null,this.setIntent({state:N.IDLE},t))}setIntent(t,n){if(this.isTransitioning||this.currentState===t.state&&t.state!==N.EMOTIONAL)return;const o=n??performance.now();this.debug&&console.log(`[Brain] Transition: ${this.currentState} -> ${t.state}`),this.isTransitioning=!0;try{this.currentState=t.state,this.stateStartTime=o,this.stateTimeout=t.duration??null,this.onStateChange&&this.onStateChange(this.currentState,t)}finally{this.isTransitioning=!1}}getState(){return this.currentState}}const en=1.2;class tn{scene;sprite;target=null;offset=new d.Vector3(0,en,0);visible=!1;canvas;ctx;texture;constructor(t){this.scene=t,this.canvas=document.createElement("canvas"),this.canvas.width=512,this.canvas.height=256;const n=this.canvas.getContext("2d");if(!n)throw new Error("Failed to get 2D context for BubbleManager");this.ctx=n,this.texture=new d.CanvasTexture(this.canvas),this.texture.minFilter=d.LinearFilter;const o=new d.SpriteMaterial({map:this.texture,transparent:!0,depthTest:!1,depthWrite:!1});this.sprite=new d.Sprite(o),this.sprite.scale.set(1.5,.75,1),this.sprite.visible=!1,this.sprite.renderOrder=999,this.scene.add(this.sprite)}setTarget(t){this.target=t}show(t,n="speech"){this.drawBubble(t,n),this.sprite.visible=!0,this.visible=!0,this.update()}hide(){this.sprite.visible=!1,this.visible=!1}update(){if(!this.visible||!this.target)return;const t=new d.Vector3;this.target.getWorldPosition(t),this.sprite.position.copy(t).add(this.offset)}drawBubble(t,n){const o=this.canvas.width,r=this.canvas.height,i=this.ctx;i.clearRect(0,0,o,r);const s=20,a=40,c=40;i.font='bold 40px "Segoe UI", Roboto, Helvetica, Arial, sans-serif',i.textAlign="center",i.textBaseline="middle",i.fillStyle="rgba(255, 255, 255, 0.95)",i.shadowColor="rgba(0, 0, 0, 0.2)",i.shadowBlur=10,i.shadowOffsetX=0,i.shadowOffsetY=5;let l=o-s*2;const h=r-c-s*2,_=s,p=s;n==="speech"?(this.drawRoundedRect(i,_,p,l,h,a),i.beginPath(),i.moveTo(o/2-20,p+h),i.lineTo(o/2,p+h+c),i.lineTo(o/2+20,p+h),i.fill()):(this.drawCloud(i,_,p,l,h),i.beginPath(),i.arc(o/2-20,p+h+15,8,0,Math.PI*2),i.arc(o/2-10,p+h+35,5,0,Math.PI*2),i.fill()),i.fillStyle="#000000",i.shadowBlur=0;const m=t.split(" ");let z="";const P=50,B=l-60,V=[];for(let w=0;w<m.length;w++){const D=z+m[w]+" ";i.measureText(D).width>B&&w>0?(V.push(z),z=m[w]+" "):z=D}V.push(z);const Oe=V.length*P;let C=p+(h-Oe)/2+P/2;for(let w=0;w<V.length;w++)i.fillText(V[w],o/2,C),C+=P;this.texture.needsUpdate=!0}drawRoundedRect(t,n,o,r,i,s){t.beginPath(),t.moveTo(n+s,o),t.lineTo(n+r-s,o),t.quadraticCurveTo(n+r,o,n+r,o+s),t.lineTo(n+r,o+i-s),t.quadraticCurveTo(n+r,o+i,n+r-s,o+i),t.lineTo(n+s,o+i),t.quadraticCurveTo(n,o+i,n,o+i-s),t.lineTo(n,o+s),t.quadraticCurveTo(n,o,n+s,o),t.closePath(),t.fill()}drawCloud(t,n,o,r,i){t.beginPath();const s=n+r*.2,a=o+i*.8;t.moveTo(s,a),t.bezierCurveTo(n-20,o+i*.8,n-20,o+i*.3,n+r*.1,o+i*.3),t.bezierCurveTo(n+r*.1,o-20,n+r*.4,o-20,n+r*.5,o+i*.1),t.bezierCurveTo(n+r*.6,o-20,n+r+20,o+i*.1,n+r*.9,o+i*.4),t.bezierCurveTo(n+r+30,o+i*.5,n+r+10,o+i+10,n+r*.7,o+i*.9),t.bezierCurveTo(n+r*.5,o+i+20,n+r*.3,o+i+10,s,a),t.closePath(),t.fill()}}function u(e,t,n){function o(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);const l=s.prototype,h=Object.keys(l);for(let _=0;_<h.length;_++){const p=h[_];p in a||(a[p]=l[p].bind(a))}}const r=n?.Parent??Object;class i extends r{}Object.defineProperty(i,"name",{value:e});function s(a){var c;const l=n?.Parent?new i:this;o(l,a),(c=l._zod).deferred??(c.deferred=[]);for(const h of l._zod.deferred)h();return l}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class G extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class $e extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const Me={};function x(e){return Me}function Ce(e){const t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,r])=>t.indexOf(+o)===-1).map(([o,r])=>r)}function de(e,t){return typeof t=="bigint"?t.toString():t}function pe(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function fe(e){return e==null}function me(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function nn(e,t){const n=(e.toString().split(".")[1]||"").length,o=t.toString();let r=(o.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(o)){const c=o.match(/\d?e-(\d?)/);c?.[1]&&(r=Number.parseInt(c[1]))}const i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return s%a/10**i}const Ne=Symbol("evaluating");function b(e,t,n){let o;Object.defineProperty(e,t,{get(){if(o!==Ne)return o===void 0&&(o=Ne,o=n()),o},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function U(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function L(...e){const t={};for(const n of e){const o=Object.getOwnPropertyDescriptors(n);Object.assign(t,o)}return Object.defineProperties({},t)}function je(e){return JSON.stringify(e)}function on(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Le="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const rn=pe(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Y(e){if(q(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(q(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Re(e){return Y(e)?{...e}:Array.isArray(e)?[...e]:e}const sn=new Set(["string","number","symbol"]);function Q(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function R(e,t,n){const o=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(o._zod.parent=e),o}function f(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new 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 an(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const cn={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function un(e,t){const n=e._zod.def,o=n.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=L(e._zod.def,{get shape(){const s={};for(const a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=n.shape[a])}return U(this,"shape",s),s},checks:[]});return R(e,i)}function ln(e,t){const n=e._zod.def,o=n.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=L(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return U(this,"shape",s),s},checks:[]});return R(e,i)}function hn(e,t){if(!Y(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const i=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=L(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return U(this,"shape",i),i}});return R(e,r)}function dn(e,t){if(!Y(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=L(e._zod.def,{get shape(){const o={...e._zod.def.shape,...t};return U(this,"shape",o),o}});return R(e,n)}function pn(e,t){const n=L(e._zod.def,{get shape(){const o={...e._zod.def.shape,...t._zod.def.shape};return U(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:[]});return R(e,n)}function fn(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=L(t._zod.def,{get shape(){const a=t._zod.def.shape,c={...a};if(n)for(const l in n){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);n[l]&&(c[l]=e?new e({type:"optional",innerType:a[l]}):a[l])}else for(const l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return U(this,"shape",c),c},checks:[]});return R(t,s)}function mn(e,t,n){const o=L(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const s in n){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)i[s]=new e({type:"nonoptional",innerType:r[s]});return U(this,"shape",i),i}});return R(t,o)}function W(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 xe(e,t){return t.map(n=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(e),n})}function ee(e){return typeof e=="string"?e:e?.message}function F(e,t,n){const o={...e,path:e.path??[]};if(!e.message){const r=ee(e.inst?._zod.def?.error?.(e))??ee(t?.error?.(e))??ee(n.customError?.(e))??ee(n.localeError?.(e))??"Invalid input";o.message=r}return delete o.inst,delete o.continue,t?.reportInput||delete o.input,o}function _e(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function J(...e){const[t,n,o]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:o}:{...t}}const Ue=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,de,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Fe=u("$ZodError",Ue),Ve=u("$ZodError",Ue,{Parent:Error});function _n(e,t=n=>n.message){const n={},o=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):o.push(t(r));return{formErrors:o,fieldErrors:n}}function gn(e,t=n=>n.message){const n={_errors:[]},o=r=>{for(const i of r.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(s=>o({issues:s}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(t(i));else{let s=n,a=0;for(;a<i.path.length;){const c=i.path[a];a===i.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(t(i))):s[c]=s[c]||{_errors:[]},s=s[c],a++}}};return o(e),n}const ge=e=>(t,n,o,r)=>{const i=o?Object.assign(o,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new G;if(s.issues.length){const a=new(r?.Err??e)(s.issues.map(c=>F(c,i,x())));throw Le(a,r?.callee),a}return s.value},be=e=>async(t,n,o,r)=>{const i=o?Object.assign(o,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const a=new(r?.Err??e)(s.issues.map(c=>F(c,i,x())));throw Le(a,r?.callee),a}return s.value},te=e=>(t,n,o)=>{const r=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise)throw new G;return i.issues.length?{success:!1,error:new(e??Fe)(i.issues.map(s=>F(s,r,x())))}:{success:!0,data:i.value}},bn=te(Ve),ne=e=>async(t,n,o)=>{const r=o?Object.assign(o,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>F(s,r,x())))}:{success:!0,data:i.value}},yn=ne(Ve),vn=e=>(t,n,o)=>{const r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return ge(e)(t,n,r)},wn=e=>(t,n,o)=>ge(e)(t,n,o),kn=e=>async(t,n,o)=>{const r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return be(e)(t,n,r)},zn=e=>async(t,n,o)=>be(e)(t,n,o),Pn=e=>(t,n,o)=>{const r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return te(e)(t,n,r)},Sn=e=>(t,n,o)=>te(e)(t,n,o),On=e=>async(t,n,o)=>{const r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return ne(e)(t,n,r)},Tn=e=>async(t,n,o)=>ne(e)(t,n,o),An=/^[cC][^\s-]{8,}$/,En=/^[0-9a-z]+$/,Zn=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,In=/^[0-9a-vA-V]{20}$/,Dn=/^[A-Za-z0-9]{27}$/,$n=/^[a-zA-Z0-9_-]{21}$/,Mn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Cn=/^([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})$/,Ge=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/,Nn=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,jn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Ln(){return new RegExp(jn,"u")}const Rn=/^(?:(?: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])$/,xn=/^(([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}|:))$/,Un=/^((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])$/,Fn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Vn=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,We=/^[A-Za-z0-9_-]*$/,Gn=/^\+[1-9]\d{6,14}$/,Ke="(?:(?:\\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])))",Wn=new RegExp(`^${Ke}$`);function Be(e){const 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}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Kn(e){return new RegExp(`^${Be(e)}$`)}function Bn(e){const t=Be({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const o=`${t}(?:${n.join("|")})`;return new RegExp(`^${Ke}T(?:${o})$`)}const Yn=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Jn=/^-?\d+$/,Xn=/^-?\d+(?:\.\d+)?$/,Hn=/^[^A-Z]*$/,qn=/^[^a-z]*$/,I=u("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ye={number:"number",bigint:"bigint",object:"date"},Je=u("$ZodCheckLessThan",(e,t)=>{I.init(e,t);const n=Ye[typeof t.value];e._zod.onattach.push(o=>{const r=o._zod.bag,i=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Xe=u("$ZodCheckGreaterThan",(e,t)=>{I.init(e,t);const n=Ye[typeof t.value];e._zod.onattach.push(o=>{const r=o._zod.bag,i=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Qn=u("$ZodCheckMultipleOf",(e,t)=>{I.init(e,t),e._zod.onattach.push(n=>{var o;(o=n._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):nn(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})}}),eo=u("$ZodCheckNumberFormat",(e,t)=>{I.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),o=n?"int":"number",[r,i]=cn[t.format];e._zod.onattach.push(s=>{const a=s._zod.bag;a.format=t.format,a.minimum=r,a.maximum=i,n&&(a.pattern=Jn)}),e._zod.check=s=>{const a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}a<r&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),to=u("$ZodCheckMaxLength",(e,t)=>{var n;I.init(e,t),(n=e._zod.def).when??(n.when=o=>{const r=o.value;return!fe(r)&&r.length!==void 0}),e._zod.onattach.push(o=>{const r=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{const r=o.value;if(r.length<=t.maximum)return;const s=_e(r);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),no=u("$ZodCheckMinLength",(e,t)=>{var n;I.init(e,t),(n=e._zod.def).when??(n.when=o=>{const r=o.value;return!fe(r)&&r.length!==void 0}),e._zod.onattach.push(o=>{const r=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{const r=o.value;if(r.length>=t.minimum)return;const s=_e(r);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),oo=u("$ZodCheckLengthEquals",(e,t)=>{var n;I.init(e,t),(n=e._zod.def).when??(n.when=o=>{const r=o.value;return!fe(r)&&r.length!==void 0}),e._zod.onattach.push(o=>{const r=o._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=o=>{const r=o.value,i=r.length;if(i===t.length)return;const s=_e(r),a=i>t.length;o.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),oe=u("$ZodCheckStringFormat",(e,t)=>{var n,o;I.init(e,t),e._zod.onattach.push(r=>{const i=r._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),ro=u("$ZodCheckRegex",(e,t)=>{oe.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})}}),io=u("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Hn),oe.init(e,t)}),so=u("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=qn),oe.init(e,t)}),ao=u("$ZodCheckIncludes",(e,t)=>{I.init(e,t);const n=Q(t.includes),o=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=o,e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),co=u("$ZodCheckStartsWith",(e,t)=>{I.init(e,t);const n=new RegExp(`^${Q(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(o=>{const r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=o=>{o.value.startsWith(t.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),uo=u("$ZodCheckEndsWith",(e,t)=>{I.init(e,t);const n=new RegExp(`.*${Q(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(o=>{const r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=o=>{o.value.endsWith(t.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}}),lo=u("$ZodCheckOverwrite",(e,t)=>{I.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class ho{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const o=t.split(`
2
+ `).filter(s=>s),r=Math.min(...o.map(s=>s.length-s.trimStart().length)),i=o.map(s=>s.slice(r)).map(s=>" ".repeat(this.indent*2)+s);for(const s of i)this.content.push(s)}compile(){const t=Function,n=this?.args,r=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...n,r.join(`
3
+ `))}}const po={major:4,minor:3,patch:5},S=u("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=po;const o=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&o.unshift(e);for(const r of o)for(const i of r._zod.onattach)i(e);if(o.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const r=(s,a,c)=>{let l=W(s),h;for(const _ of a){if(_._zod.def.when){if(!_._zod.def.when(s))continue}else if(l)continue;const p=s.issues.length,m=_._zod.check(s);if(m instanceof Promise&&c?.async===!1)throw new G;if(h||m instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await m,s.issues.length!==p&&(l||(l=W(s,p)))});else{if(s.issues.length===p)continue;l||(l=W(s,p))}}return h?h.then(()=>s):s},i=(s,a,c)=>{if(W(s))return s.aborted=!0,s;const l=r(a,o,c);if(l instanceof Promise){if(c.async===!1)throw new G;return l.then(h=>e._zod.parse(h,c))}return e._zod.parse(l,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){const l=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return l instanceof Promise?l.then(h=>i(h,s,a)):i(l,s,a)}const c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new G;return c.then(l=>r(l,o,a))}return r(c,o,a)}}b(e,"~standard",()=>({validate:r=>{try{const i=bn(e,r);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return yn(e,r).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),ye=u("$ZodString",(e,t)=>{S.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Yn(e._zod.bag),e._zod.parse=(n,o)=>{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}}),v=u("$ZodStringFormat",(e,t)=>{oe.init(e,t),ye.init(e,t)}),fo=u("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Cn),v.init(e,t)}),mo=u("$ZodUUID",(e,t)=>{if(t.version){const o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Ge(o))}else t.pattern??(t.pattern=Ge());v.init(e,t)}),_o=u("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Nn),v.init(e,t)}),go=u("$ZodURL",(e,t)=>{v.init(e,t),e._zod.check=n=>{try{const o=n.value.trim(),r=new URL(o);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.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&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=r.href:n.value=o;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),bo=u("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ln()),v.init(e,t)}),yo=u("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=$n),v.init(e,t)}),vo=u("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=An),v.init(e,t)}),wo=u("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=En),v.init(e,t)}),ko=u("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Zn),v.init(e,t)}),zo=u("$ZodXID",(e,t)=>{t.pattern??(t.pattern=In),v.init(e,t)}),Po=u("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Dn),v.init(e,t)}),So=u("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Bn(t)),v.init(e,t)}),Oo=u("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Wn),v.init(e,t)}),To=u("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Kn(t)),v.init(e,t)}),Ao=u("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Mn),v.init(e,t)}),Eo=u("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Rn),v.init(e,t),e._zod.bag.format="ipv4"}),Zo=u("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=xn),v.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Io=u("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Un),v.init(e,t)}),Do=u("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Fn),v.init(e,t),e._zod.check=n=>{const o=n.value.split("/");try{if(o.length!==2)throw new Error;const[r,i]=o;if(!i)throw new Error;const s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function He(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const $o=u("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Vn),v.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{He(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Mo(e){if(!We.test(e))return!1;const t=e.replace(/[-_]/g,o=>o==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return He(n)}const Co=u("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=We),v.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{Mo(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),No=u("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Gn),v.init(e,t)});function jo(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[o]=n;if(!o)return!1;const r=JSON.parse(atob(o));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const Lo=u("$ZodJWT",(e,t)=>{v.init(e,t),e._zod.check=n=>{jo(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),qe=u("$ZodNumber",(e,t)=>{S.init(e,t),e._zod.pattern=e._zod.bag.pattern??Xn,e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;const i=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...i?{received:i}:{}}),n}}),Ro=u("$ZodNumberFormat",(e,t)=>{eo.init(e,t),qe.init(e,t)}),xo=u("$ZodUnknown",(e,t)=>{S.init(e,t),e._zod.parse=n=>n}),Uo=u("$ZodNever",(e,t)=>{S.init(e,t),e._zod.parse=(n,o)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Qe(e,t,n){e.issues.length&&t.issues.push(...xe(n,e.issues)),t.value[n]=e.value}const Fo=u("$ZodArray",(e,t)=>{S.init(e,t),e._zod.parse=(n,o)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const i=[];for(let s=0;s<r.length;s++){const a=r[s],c=t.element._zod.run({value:a,issues:[]},o);c instanceof Promise?i.push(c.then(l=>Qe(l,n,s))):Qe(c,n,s)}return i.length?Promise.all(i).then(()=>n):n}});function re(e,t,n,o,r){if(e.issues.length){if(r&&!(n in o))return;t.issues.push(...xe(n,e.issues))}e.value===void 0?n in o&&(t.value[n]=void 0):t.value[n]=e.value}function et(e){const t=Object.keys(e.shape);for(const o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);const n=an(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function tt(e,t,n,o,r,i){const s=[],a=r.keySet,c=r.catchall._zod,l=c.def.type,h=c.optout==="optional";for(const _ in t){if(a.has(_))continue;if(l==="never"){s.push(_);continue}const p=c.run({value:t[_],issues:[]},o);p instanceof Promise?e.push(p.then(m=>re(m,n,_,t,h))):re(p,n,_,t,h)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const Vo=u("$ZodObject",(e,t)=>{if(S.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const a=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}const o=pe(()=>et(t));b(e._zod,"propValues",()=>{const a=t.shape,c={};for(const l in a){const h=a[l]._zod;if(h.values){c[l]??(c[l]=new Set);for(const _ of h.values)c[l].add(_)}}return c});const r=q,i=t.catchall;let s;e._zod.parse=(a,c)=>{s??(s=o.value);const l=a.value;if(!r(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),a;a.value={};const h=[],_=s.shape;for(const p of s.keys){const m=_[p],z=m._zod.optout==="optional",P=m._zod.run({value:l[p],issues:[]},c);P instanceof Promise?h.push(P.then(B=>re(B,a,p,l,z))):re(P,a,p,l,z)}return i?tt(h,l,a,c,o.value,e):h.length?Promise.all(h).then(()=>a):a}}),Go=u("$ZodObjectJIT",(e,t)=>{Vo.init(e,t);const n=e._zod.parse,o=pe(()=>et(t)),r=p=>{const m=new ho(["shape","payload","ctx"]),z=o.value,P=C=>{const w=je(C);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};m.write("const input = payload.value;");const B=Object.create(null);let V=0;for(const C of z.keys)B[C]=`key_${V++}`;m.write("const newResult = {};");for(const C of z.keys){const w=B[C],D=je(C),Dt=p[C]?._zod?.optout==="optional";m.write(`const ${w} = ${P(C)};`),Dt?m.write(`
4
+ if (${w}.issues.length) {
5
+ if (${D} in input) {
6
+ payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
7
+ ...iss,
8
+ path: iss.path ? [${D}, ...iss.path] : [${D}]
9
+ })));
10
+ }
11
+ }
12
+
13
+ if (${w}.value === undefined) {
14
+ if (${D} in input) {
15
+ newResult[${D}] = undefined;
16
+ }
17
+ } else {
18
+ newResult[${D}] = ${w}.value;
19
+ }
20
+
21
+ `):m.write(`
22
+ if (${w}.issues.length) {
23
+ payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
24
+ ...iss,
25
+ path: iss.path ? [${D}, ...iss.path] : [${D}]
26
+ })));
27
+ }
28
+
29
+ if (${w}.value === undefined) {
30
+ if (${D} in input) {
31
+ newResult[${D}] = undefined;
32
+ }
33
+ } else {
34
+ newResult[${D}] = ${w}.value;
35
+ }
36
+
37
+ `)}m.write("payload.value = newResult;"),m.write("return payload;");const Oe=m.compile();return(C,w)=>Oe(p,C,w)};let i;const s=q,a=!Me.jitless,l=a&&rn.value,h=t.catchall;let _;e._zod.parse=(p,m)=>{_??(_=o.value);const z=p.value;return s(z)?a&&l&&m?.async===!1&&m.jitless!==!0?(i||(i=r(t.shape)),p=i(p,m),h?tt([],z,p,m,_,e):p):n(p,m):(p.issues.push({expected:"object",code:"invalid_type",input:z,inst:e}),p)}});function nt(e,t,n,o){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const r=e.filter(i=>!W(i));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(s=>F(s,o,x())))}),t)}const Wo=u("$ZodUnion",(e,t)=>{S.init(e,t),b(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),b(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),b(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),b(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>me(i.source)).join("|")})$`)}});const n=t.options.length===1,o=t.options[0]._zod.run;e._zod.parse=(r,i)=>{if(n)return o(r,i);let s=!1;const a=[];for(const c of t.options){const l=c._zod.run({value:r.value,issues:[]},i);if(l instanceof Promise)a.push(l),s=!0;else{if(l.issues.length===0)return l;a.push(l)}}return s?Promise.all(a).then(c=>nt(c,r,e,i)):nt(a,r,e,i)}}),Ko=u("$ZodIntersection",(e,t)=>{S.init(e,t),e._zod.parse=(n,o)=>{const r=n.value,i=t.left._zod.run({value:r,issues:[]},o),s=t.right._zod.run({value:r,issues:[]},o);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,l])=>ot(n,c,l)):ot(n,i,s)}});function ve(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Y(e)&&Y(t)){const n=Object.keys(t),o=Object.keys(e).filter(i=>n.indexOf(i)!==-1),r={...e,...t};for(const i of o){const s=ve(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};r[i]=s.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let o=0;o<e.length;o++){const r=e[o],i=t[o],s=ve(r,i);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ot(e,t,n){const o=new Map;let r;for(const a of t.issues)if(a.code==="unrecognized_keys"){r??(r=a);for(const c of a.keys)o.has(c)||o.set(c,{}),o.get(c).l=!0}else e.issues.push(a);for(const a of n.issues)if(a.code==="unrecognized_keys")for(const c of a.keys)o.has(c)||o.set(c,{}),o.get(c).r=!0;else e.issues.push(a);const i=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&r&&e.issues.push({...r,keys:i}),W(e))return e;const s=ve(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const Bo=u("$ZodEnum",(e,t)=>{S.init(e,t);const n=Ce(t.entries),o=new Set(n);e._zod.values=o,e._zod.pattern=new RegExp(`^(${n.filter(r=>sn.has(typeof r)).map(r=>typeof r=="string"?Q(r):r.toString()).join("|")})$`),e._zod.parse=(r,i)=>{const s=r.value;return o.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),Yo=u("$ZodTransform",(e,t)=>{S.init(e,t),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new $e(e.constructor.name);const r=t.transform(n.value,n);if(o.async)return(r instanceof Promise?r:Promise.resolve(r)).then(s=>(n.value=s,n));if(r instanceof Promise)throw new G;return n.value=r,n}});function rt(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const it=u("$ZodOptional",(e,t)=>{S.init(e,t),e._zod.optin="optional",e._zod.optout="optional",b(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),b(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${me(n.source)})?$`):void 0}),e._zod.parse=(n,o)=>{if(t.innerType._zod.optin==="optional"){const r=t.innerType._zod.run(n,o);return r instanceof Promise?r.then(i=>rt(i,n.value)):rt(r,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,o)}}),Jo=u("$ZodExactOptional",(e,t)=>{it.init(e,t),b(e._zod,"values",()=>t.innerType._zod.values),b(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,o)=>t.innerType._zod.run(n,o)}),Xo=u("$ZodNullable",(e,t)=>{S.init(e,t),b(e._zod,"optin",()=>t.innerType._zod.optin),b(e._zod,"optout",()=>t.innerType._zod.optout),b(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${me(n.source)}|null)$`):void 0}),b(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,o)=>n.value===null?n:t.innerType._zod.run(n,o)}),Ho=u("$ZodDefault",(e,t)=>{S.init(e,t),e._zod.optin="optional",b(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);if(n.value===void 0)return n.value=t.defaultValue,n;const r=t.innerType._zod.run(n,o);return r instanceof Promise?r.then(i=>st(i,t)):st(r,t)}});function st(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const qo=u("$ZodPrefault",(e,t)=>{S.init(e,t),e._zod.optin="optional",b(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,o)=>(o.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,o))}),Qo=u("$ZodNonOptional",(e,t)=>{S.init(e,t),b(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(o=>o!==void 0)):void 0}),e._zod.parse=(n,o)=>{const r=t.innerType._zod.run(n,o);return r instanceof Promise?r.then(i=>at(i,e)):at(r,e)}});function at(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const er=u("$ZodCatch",(e,t)=>{S.init(e,t),b(e._zod,"optin",()=>t.innerType._zod.optin),b(e._zod,"optout",()=>t.innerType._zod.optout),b(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);const r=t.innerType._zod.run(n,o);return r instanceof Promise?r.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(s=>F(s,o,x()))},input:n.value}),n.issues=[]),n)):(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(i=>F(i,o,x()))},input:n.value}),n.issues=[]),n)}}),tr=u("$ZodPipe",(e,t)=>{S.init(e,t),b(e._zod,"values",()=>t.in._zod.values),b(e._zod,"optin",()=>t.in._zod.optin),b(e._zod,"optout",()=>t.out._zod.optout),b(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,o)=>{if(o.direction==="backward"){const i=t.out._zod.run(n,o);return i instanceof Promise?i.then(s=>ie(s,t.in,o)):ie(i,t.in,o)}const r=t.in._zod.run(n,o);return r instanceof Promise?r.then(i=>ie(i,t.out,o)):ie(r,t.out,o)}});function ie(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const nr=u("$ZodReadonly",(e,t)=>{S.init(e,t),b(e._zod,"propValues",()=>t.innerType._zod.propValues),b(e._zod,"values",()=>t.innerType._zod.values),b(e._zod,"optin",()=>t.innerType?._zod?.optin),b(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);const r=t.innerType._zod.run(n,o);return r instanceof Promise?r.then(ct):ct(r)}});function ct(e){return e.value=Object.freeze(e.value),e}const or=u("$ZodCustom",(e,t)=>{I.init(e,t),S.init(e,t),e._zod.parse=(n,o)=>n,e._zod.check=n=>{const o=n.value,r=t.fn(o);if(r instanceof Promise)return r.then(i=>ut(i,n,o,e));ut(r,n,o,e)}});function ut(e,t,n,o){if(!e){const r={code:"custom",input:n,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(r.params=o._zod.def.params),t.issues.push(J(r))}}var lt;class rr{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const o=n[0];return this._map.set(t,o),o&&typeof o=="object"&&"id"in o&&this._idmap.set(o.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const o={...this.get(n)??{}};delete o.id;const r={...o,...this._map.get(t)};return Object.keys(r).length?r:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function ir(){return new rr}(lt=globalThis).__zod_globalRegistry??(lt.__zod_globalRegistry=ir());const X=globalThis.__zod_globalRegistry;function sr(e,t){return new e({type:"string",...f(t)})}function ar(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...f(t)})}function ht(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...f(t)})}function cr(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...f(t)})}function ur(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...f(t)})}function lr(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...f(t)})}function hr(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...f(t)})}function dr(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...f(t)})}function pr(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...f(t)})}function fr(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...f(t)})}function mr(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...f(t)})}function _r(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...f(t)})}function gr(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...f(t)})}function br(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...f(t)})}function yr(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...f(t)})}function vr(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...f(t)})}function wr(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...f(t)})}function kr(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...f(t)})}function zr(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...f(t)})}function Pr(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...f(t)})}function Sr(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...f(t)})}function Or(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...f(t)})}function Tr(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...f(t)})}function Ar(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...f(t)})}function Er(e,t){return new e({type:"string",format:"date",check:"string_format",...f(t)})}function Zr(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...f(t)})}function Ir(e,t){return new e({type:"string",format:"duration",check:"string_format",...f(t)})}function Dr(e,t){return new e({type:"number",checks:[],...f(t)})}function $r(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...f(t)})}function Mr(e){return new e({type:"unknown"})}function Cr(e,t){return new e({type:"never",...f(t)})}function dt(e,t){return new Je({check:"less_than",...f(t),value:e,inclusive:!1})}function we(e,t){return new Je({check:"less_than",...f(t),value:e,inclusive:!0})}function pt(e,t){return new Xe({check:"greater_than",...f(t),value:e,inclusive:!1})}function ke(e,t){return new Xe({check:"greater_than",...f(t),value:e,inclusive:!0})}function ft(e,t){return new Qn({check:"multiple_of",...f(t),value:e})}function mt(e,t){return new to({check:"max_length",...f(t),maximum:e})}function se(e,t){return new no({check:"min_length",...f(t),minimum:e})}function _t(e,t){return new oo({check:"length_equals",...f(t),length:e})}function Nr(e,t){return new ro({check:"string_format",format:"regex",...f(t),pattern:e})}function jr(e){return new io({check:"string_format",format:"lowercase",...f(e)})}function Lr(e){return new so({check:"string_format",format:"uppercase",...f(e)})}function Rr(e,t){return new ao({check:"string_format",format:"includes",...f(t),includes:e})}function xr(e,t){return new co({check:"string_format",format:"starts_with",...f(t),prefix:e})}function Ur(e,t){return new uo({check:"string_format",format:"ends_with",...f(t),suffix:e})}function K(e){return new lo({check:"overwrite",tx:e})}function Fr(e){return K(t=>t.normalize(e))}function Vr(){return K(e=>e.trim())}function Gr(){return K(e=>e.toLowerCase())}function Wr(){return K(e=>e.toUpperCase())}function Kr(){return K(e=>on(e))}function Br(e,t,n){return new e({type:"array",element:t,...f(n)})}function Yr(e,t,n){return new e({type:"custom",check:"custom",fn:t,...f(n)})}function Jr(e){const t=Xr(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(J(o,n.value,t._zod.def));else{const r=o;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(J(r))}},e(n.value,n)));return t}function Xr(e,t){const n=new I({check:"custom",...f(t)});return n._zod.check=e,n}function gt(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??X,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function A(e,t,n={path:[],schemaPath:[]}){var o;const r=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const h={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,h);else{const p=s.schema,m=t.processors[r.type];if(!m)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);m(e,t,p,h)}const _=e._zod.parent;_&&(s.ref||(s.ref=_),A(_,t,h),t.seen.get(_).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(s.schema,c),t.io==="input"&&E(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&s.schema._prefault&&((o=s.schema).default??(o.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function bt(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const o=new Map;for(const s of e.seen.entries()){const a=e.metadataRegistry.get(s[0])?.id;if(a){const c=o.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,s[0])}}const r=s=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const _=e.external.registry.get(s[0])?.id,p=e.external.uri??(z=>z);if(_)return{ref:p(_)};const m=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=m,{defId:m,ref:`${p("__shared")}#/${a}/${m}`}}if(s[1]===n)return{ref:"#"};const l=`#/${a}/`,h=s[1].schema.id??`__schema${e.counter++}`;return{defId:h,ref:l+h}},i=s=>{if(s[1].schema.$ref)return;const a=s[1],{ref:c,defId:l}=r(s);a.def={...a.schema},l&&(a.defId=l);const h=a.schema;for(const _ in h)delete h[_];h.$ref=c};if(e.cycles==="throw")for(const s of e.seen.entries()){const a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
38
+
39
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const a=s[1];if(t===s[0]){i(s);continue}if(e.external){const l=e.external.registry.get(s[0])?.id;if(t!==s[0]&&l){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1&&e.reused==="ref"){i(s);continue}}}function yt(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const o=s=>{const a=e.seen.get(s);if(a.ref===null)return;const c=a.def??a.schema,l={...c},h=a.ref;if(a.ref=null,h){o(h);const p=e.seen.get(h),m=p.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(m)):Object.assign(c,m),Object.assign(c,l),s._zod.parent===h)for(const P in c)P==="$ref"||P==="allOf"||P in l||delete c[P];if(m.$ref)for(const P in c)P==="$ref"||P==="allOf"||P in p.def&&JSON.stringify(c[P])===JSON.stringify(p.def[P])&&delete c[P]}const _=s._zod.parent;if(_&&_!==h){o(_);const p=e.seen.get(_);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(const m in c)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(c[m])===JSON.stringify(p.def[m])&&delete c[m]}e.override({zodSchema:s,jsonSchema:c,path:a.path??[]})};for(const s of[...e.seen.entries()].reverse())o(s[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(s)}Object.assign(r,n.def??n.schema);const i=e.external?.defs??{};for(const s of e.seen.entries()){const a=s[1];a.def&&a.defId&&(i[a.defId]=a.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?r.$defs=i:r.definitions=i);try{const s=JSON.parse(JSON.stringify(r));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:ae(t,"input",e.processors),output:ae(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function E(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return E(o.element,n);if(o.type==="set")return E(o.valueType,n);if(o.type==="lazy")return E(o.getter(),n);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return E(o.innerType,n);if(o.type==="intersection")return E(o.left,n)||E(o.right,n);if(o.type==="record"||o.type==="map")return E(o.keyType,n)||E(o.valueType,n);if(o.type==="pipe")return E(o.in,n)||E(o.out,n);if(o.type==="object"){for(const r in o.shape)if(E(o.shape[r],n))return!0;return!1}if(o.type==="union"){for(const r of o.options)if(E(r,n))return!0;return!1}if(o.type==="tuple"){for(const r of o.items)if(E(r,n))return!0;return!!(o.rest&&E(o.rest,n))}return!1}const Hr=(e,t={})=>n=>{const o=gt({...n,processors:t});return A(e,o),bt(o,e),yt(o,e)},ae=(e,t,n={})=>o=>{const{libraryOptions:r,target:i}=o??{},s=gt({...r??{},target:i,io:t,processors:n});return A(e,s),bt(s,e),yt(s,e)},qr={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Qr=(e,t,n,o)=>{const r=n;r.type="string";const{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof s=="number"&&(r.maxLength=s),a&&(r.format=qr[a]??a,r.format===""&&delete r.format,a==="time"&&delete r.format),l&&(r.contentEncoding=l),c&&c.size>0){const h=[...c];h.length===1?r.pattern=h[0].source:h.length>1&&(r.allOf=[...h.map(_=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:_.source}))])}},ei=(e,t,n,o)=>{const r=n,{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:h}=e._zod.bag;typeof a=="string"&&a.includes("int")?r.type="integer":r.type="number",typeof h=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=h,r.exclusiveMinimum=!0):r.exclusiveMinimum=h),typeof i=="number"&&(r.minimum=i,typeof h=="number"&&t.target!=="draft-04"&&(h>=i?delete r.minimum:delete r.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),typeof s=="number"&&(r.maximum=s,typeof l=="number"&&t.target!=="draft-04"&&(l<=s?delete r.maximum:delete r.exclusiveMaximum)),typeof c=="number"&&(r.multipleOf=c)},ti=(e,t,n,o)=>{n.not={}},ni=(e,t,n,o)=>{},oi=(e,t,n,o)=>{const r=e._zod.def,i=Ce(r.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},ri=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},ii=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},si=(e,t,n,o)=>{const r=n,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;typeof s=="number"&&(r.minItems=s),typeof a=="number"&&(r.maxItems=a),r.type="array",r.items=A(i.element,t,{...o,path:[...o.path,"items"]})},ai=(e,t,n,o)=>{const r=n,i=e._zod.def;r.type="object",r.properties={};const s=i.shape;for(const l in s)r.properties[l]=A(s[l],t,{...o,path:[...o.path,"properties",l]});const a=new Set(Object.keys(s)),c=new Set([...a].filter(l=>{const h=i.shape[l]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));c.size>0&&(r.required=Array.from(c)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=A(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},ci=(e,t,n,o)=>{const r=e._zod.def,i=r.inclusive===!1,s=r.options.map((a,c)=>A(a,t,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=s:n.anyOf=s},ui=(e,t,n,o)=>{const r=e._zod.def,i=A(r.left,t,{...o,path:[...o.path,"allOf",0]}),s=A(r.right,t,{...o,path:[...o.path,"allOf",1]}),a=l=>"allOf"in l&&Object.keys(l).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];n.allOf=c},li=(e,t,n,o)=>{const r=e._zod.def,i=A(r.innerType,t,o),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=r.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},hi=(e,t,n,o)=>{const r=e._zod.def;A(r.innerType,t,o);const i=t.seen.get(e);i.ref=r.innerType},di=(e,t,n,o)=>{const r=e._zod.def;A(r.innerType,t,o);const i=t.seen.get(e);i.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},pi=(e,t,n,o)=>{const r=e._zod.def;A(r.innerType,t,o);const i=t.seen.get(e);i.ref=r.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},fi=(e,t,n,o)=>{const r=e._zod.def;A(r.innerType,t,o);const i=t.seen.get(e);i.ref=r.innerType;let s;try{s=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},mi=(e,t,n,o)=>{const r=e._zod.def,i=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;A(i,t,o);const s=t.seen.get(e);s.ref=i},_i=(e,t,n,o)=>{const r=e._zod.def;A(r.innerType,t,o);const i=t.seen.get(e);i.ref=r.innerType,n.readOnly=!0},vt=(e,t,n,o)=>{const r=e._zod.def;A(r.innerType,t,o);const i=t.seen.get(e);i.ref=r.innerType},gi=u("ZodISODateTime",(e,t)=>{So.init(e,t),k.init(e,t)});function bi(e){return Ar(gi,e)}const yi=u("ZodISODate",(e,t)=>{Oo.init(e,t),k.init(e,t)});function vi(e){return Er(yi,e)}const wi=u("ZodISOTime",(e,t)=>{To.init(e,t),k.init(e,t)});function ki(e){return Zr(wi,e)}const zi=u("ZodISODuration",(e,t)=>{Ao.init(e,t),k.init(e,t)});function Pi(e){return Ir(zi,e)}const j=u("ZodError",(e,t)=>{Fe.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>gn(e,n)},flatten:{value:n=>_n(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,de,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,de,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Si=ge(j),Oi=be(j),Ti=te(j),Ai=ne(j),Ei=vn(j),Zi=wn(j),Ii=kn(j),Di=zn(j),$i=Pn(j),Mi=Sn(j),Ci=On(j),Ni=Tn(j),O=u("ZodType",(e,t)=>(S.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ae(e,"input"),output:ae(e,"output")}}),e.toJSONSchema=Hr(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(L(t,{checks:[...t.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0}),e.with=e.check,e.clone=(n,o)=>R(e,n,o),e.brand=()=>e,e.register=((n,o)=>(n.add(e,o),e)),e.parse=(n,o)=>Si(e,n,o,{callee:e.parse}),e.safeParse=(n,o)=>Ti(e,n,o),e.parseAsync=async(n,o)=>Oi(e,n,o,{callee:e.parseAsync}),e.safeParseAsync=async(n,o)=>Ai(e,n,o),e.spa=e.safeParseAsync,e.encode=(n,o)=>Ei(e,n,o),e.decode=(n,o)=>Zi(e,n,o),e.encodeAsync=async(n,o)=>Ii(e,n,o),e.decodeAsync=async(n,o)=>Di(e,n,o),e.safeEncode=(n,o)=>$i(e,n,o),e.safeDecode=(n,o)=>Mi(e,n,o),e.safeEncodeAsync=async(n,o)=>Ci(e,n,o),e.safeDecodeAsync=async(n,o)=>Ni(e,n,o),e.refine=(n,o)=>e.check(Es(n,o)),e.superRefine=n=>e.check(Zs(n)),e.overwrite=n=>e.check(K(n)),e.optional=()=>At(e),e.exactOptional=()=>_s(e),e.nullable=()=>Et(e),e.nullish=()=>At(Et(e)),e.nonoptional=n=>ks(e,n),e.array=()=>ss(e),e.or=n=>us([e,n]),e.and=n=>hs(e,n),e.transform=n=>It(e,fs(n)),e.default=n=>ys(e,n),e.prefault=n=>ws(e,n),e.catch=n=>Ps(e,n),e.pipe=n=>It(e,n),e.readonly=()=>Ts(e),e.describe=n=>{const o=e.clone();return X.add(o,{description:n}),o},Object.defineProperty(e,"description",{get(){return X.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return X.get(e);const o=e.clone();return X.add(o,n[0]),o},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),wt=u("_ZodString",(e,t)=>{ye.init(e,t),O.init(e,t),e._zod.processJSONSchema=(o,r,i)=>Qr(e,o,r);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...o)=>e.check(Nr(...o)),e.includes=(...o)=>e.check(Rr(...o)),e.startsWith=(...o)=>e.check(xr(...o)),e.endsWith=(...o)=>e.check(Ur(...o)),e.min=(...o)=>e.check(se(...o)),e.max=(...o)=>e.check(mt(...o)),e.length=(...o)=>e.check(_t(...o)),e.nonempty=(...o)=>e.check(se(1,...o)),e.lowercase=o=>e.check(jr(o)),e.uppercase=o=>e.check(Lr(o)),e.trim=()=>e.check(Vr()),e.normalize=(...o)=>e.check(Fr(...o)),e.toLowerCase=()=>e.check(Gr()),e.toUpperCase=()=>e.check(Wr()),e.slugify=()=>e.check(Kr())}),ji=u("ZodString",(e,t)=>{ye.init(e,t),wt.init(e,t),e.email=n=>e.check(ar(Li,n)),e.url=n=>e.check(dr(Ri,n)),e.jwt=n=>e.check(Tr(es,n)),e.emoji=n=>e.check(pr(xi,n)),e.guid=n=>e.check(ht(kt,n)),e.uuid=n=>e.check(cr(ce,n)),e.uuidv4=n=>e.check(ur(ce,n)),e.uuidv6=n=>e.check(lr(ce,n)),e.uuidv7=n=>e.check(hr(ce,n)),e.nanoid=n=>e.check(fr(Ui,n)),e.guid=n=>e.check(ht(kt,n)),e.cuid=n=>e.check(mr(Fi,n)),e.cuid2=n=>e.check(_r(Vi,n)),e.ulid=n=>e.check(gr(Gi,n)),e.base64=n=>e.check(Pr(Hi,n)),e.base64url=n=>e.check(Sr(qi,n)),e.xid=n=>e.check(br(Wi,n)),e.ksuid=n=>e.check(yr(Ki,n)),e.ipv4=n=>e.check(vr(Bi,n)),e.ipv6=n=>e.check(wr(Yi,n)),e.cidrv4=n=>e.check(kr(Ji,n)),e.cidrv6=n=>e.check(zr(Xi,n)),e.e164=n=>e.check(Or(Qi,n)),e.datetime=n=>e.check(bi(n)),e.date=n=>e.check(vi(n)),e.time=n=>e.check(ki(n)),e.duration=n=>e.check(Pi(n))});function ze(e){return sr(ji,e)}const k=u("ZodStringFormat",(e,t)=>{v.init(e,t),wt.init(e,t)}),Li=u("ZodEmail",(e,t)=>{_o.init(e,t),k.init(e,t)}),kt=u("ZodGUID",(e,t)=>{fo.init(e,t),k.init(e,t)}),ce=u("ZodUUID",(e,t)=>{mo.init(e,t),k.init(e,t)}),Ri=u("ZodURL",(e,t)=>{go.init(e,t),k.init(e,t)}),xi=u("ZodEmoji",(e,t)=>{bo.init(e,t),k.init(e,t)}),Ui=u("ZodNanoID",(e,t)=>{yo.init(e,t),k.init(e,t)}),Fi=u("ZodCUID",(e,t)=>{vo.init(e,t),k.init(e,t)}),Vi=u("ZodCUID2",(e,t)=>{wo.init(e,t),k.init(e,t)}),Gi=u("ZodULID",(e,t)=>{ko.init(e,t),k.init(e,t)}),Wi=u("ZodXID",(e,t)=>{zo.init(e,t),k.init(e,t)}),Ki=u("ZodKSUID",(e,t)=>{Po.init(e,t),k.init(e,t)}),Bi=u("ZodIPv4",(e,t)=>{Eo.init(e,t),k.init(e,t)}),Yi=u("ZodIPv6",(e,t)=>{Zo.init(e,t),k.init(e,t)}),Ji=u("ZodCIDRv4",(e,t)=>{Io.init(e,t),k.init(e,t)}),Xi=u("ZodCIDRv6",(e,t)=>{Do.init(e,t),k.init(e,t)}),Hi=u("ZodBase64",(e,t)=>{$o.init(e,t),k.init(e,t)}),qi=u("ZodBase64URL",(e,t)=>{Co.init(e,t),k.init(e,t)}),Qi=u("ZodE164",(e,t)=>{No.init(e,t),k.init(e,t)}),es=u("ZodJWT",(e,t)=>{Lo.init(e,t),k.init(e,t)}),zt=u("ZodNumber",(e,t)=>{qe.init(e,t),O.init(e,t),e._zod.processJSONSchema=(o,r,i)=>ei(e,o,r),e.gt=(o,r)=>e.check(pt(o,r)),e.gte=(o,r)=>e.check(ke(o,r)),e.min=(o,r)=>e.check(ke(o,r)),e.lt=(o,r)=>e.check(dt(o,r)),e.lte=(o,r)=>e.check(we(o,r)),e.max=(o,r)=>e.check(we(o,r)),e.int=o=>e.check(St(o)),e.safe=o=>e.check(St(o)),e.positive=o=>e.check(pt(0,o)),e.nonnegative=o=>e.check(ke(0,o)),e.negative=o=>e.check(dt(0,o)),e.nonpositive=o=>e.check(we(0,o)),e.multipleOf=(o,r)=>e.check(ft(o,r)),e.step=(o,r)=>e.check(ft(o,r)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Pt(e){return Dr(zt,e)}const ts=u("ZodNumberFormat",(e,t)=>{Ro.init(e,t),zt.init(e,t)});function St(e){return $r(ts,e)}const ns=u("ZodUnknown",(e,t)=>{xo.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ni()});function Ot(){return Mr(ns)}const os=u("ZodNever",(e,t)=>{Uo.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ti(e,n,o)});function rs(e){return Cr(os,e)}const is=u("ZodArray",(e,t)=>{Fo.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>si(e,n,o,r),e.element=t.element,e.min=(n,o)=>e.check(se(n,o)),e.nonempty=n=>e.check(se(1,n)),e.max=(n,o)=>e.check(mt(n,o)),e.length=(n,o)=>e.check(_t(n,o)),e.unwrap=()=>e.element});function ss(e,t){return Br(is,e,t)}const as=u("ZodObject",(e,t)=>{Go.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ai(e,n,o,r),b(e,"shape",()=>t.shape),e.keyof=()=>ds(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ot()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ot()}),e.strict=()=>e.clone({...e._zod.def,catchall:rs()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>hn(e,n),e.safeExtend=n=>dn(e,n),e.merge=n=>pn(e,n),e.pick=n=>un(e,n),e.omit=n=>ln(e,n),e.partial=(...n)=>fn(Tt,e,n[0]),e.required=(...n)=>mn(Zt,e,n[0])});function Pe(e,t){const n={type:"object",shape:e??{},...f(t)};return new as(n)}const cs=u("ZodUnion",(e,t)=>{Wo.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ci(e,n,o,r),e.options=t.options});function us(e,t){return new cs({type:"union",options:e,...f(t)})}const ls=u("ZodIntersection",(e,t)=>{Ko.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ui(e,n,o,r)});function hs(e,t){return new ls({type:"intersection",left:e,right:t})}const Se=u("ZodEnum",(e,t)=>{Bo.init(e,t),O.init(e,t),e._zod.processJSONSchema=(o,r,i)=>oi(e,o,r),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(o,r)=>{const i={};for(const s of o)if(n.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Se({...t,checks:[],...f(r),entries:i})},e.exclude=(o,r)=>{const i={...t.entries};for(const s of o)if(n.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Se({...t,checks:[],...f(r),entries:i})}});function ds(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new Se({type:"enum",entries:n,...f(t)})}const ps=u("ZodTransform",(e,t)=>{Yo.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ii(e,n),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new $e(e.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(J(i,n.value,t));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(J(s))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(i=>(n.value=i,n)):(n.value=r,n)}});function fs(e){return new ps({type:"transform",transform:e})}const Tt=u("ZodOptional",(e,t)=>{it.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>vt(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function At(e){return new Tt({type:"optional",innerType:e})}const ms=u("ZodExactOptional",(e,t)=>{Jo.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>vt(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function _s(e){return new ms({type:"optional",innerType:e})}const gs=u("ZodNullable",(e,t)=>{Xo.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>li(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function Et(e){return new gs({type:"nullable",innerType:e})}const bs=u("ZodDefault",(e,t)=>{Ho.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>di(e,n,o,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ys(e,t){return new bs({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Re(t)}})}const vs=u("ZodPrefault",(e,t)=>{qo.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>pi(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function ws(e,t){return new vs({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Re(t)}})}const Zt=u("ZodNonOptional",(e,t)=>{Qo.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>hi(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function ks(e,t){return new Zt({type:"nonoptional",innerType:e,...f(t)})}const zs=u("ZodCatch",(e,t)=>{er.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>fi(e,n,o,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ps(e,t){return new zs({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Ss=u("ZodPipe",(e,t)=>{tr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>mi(e,n,o,r),e.in=t.in,e.out=t.out});function It(e,t){return new Ss({type:"pipe",in:e,out:t})}const Os=u("ZodReadonly",(e,t)=>{nr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>_i(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function Ts(e){return new Os({type:"readonly",innerType:e})}const As=u("ZodCustom",(e,t)=>{or.init(e,t),O.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ri(e,n)});function Es(e,t={}){return Yr(As,e,t)}function Zs(e){return Jr(e)}const Is=Pe({text:ze().describe("The text content to speak."),duration:Pt().default(3e3).describe("Duration in milliseconds to stay in the talking state.")}),Ds=Pe({text:ze().default("...").describe("The thought text content (e.g., '...')."),duration:Pt().default(3e3).describe("Duration in milliseconds to stay in the thinking state.")});Pe({action:ze().describe("The name of the animation clip to play (e.g., 'wave', 'bow', 'dance').")});class $s{container;scene;camera;renderer;controls;clock;loader;stageLoader;avatarModel=null;stageModel=null;headBone=null;animController=null;stageAnimController=null;lookAtProcessor;brain;bubbleManager;currentAvatarConfig=null;isDebug=!1;debugTargetMesh=null;debugPlaneMesh=null;resizeObserver;constructor(t){const n=document.getElementById(t);if(!n)throw new Error(`Container #${t} not found`);this.container=n,this.clock=new d.Clock,this.loader=new Ie,this.stageLoader=new Jt,this.brain=new De,this.scene=new d.Scene,this.scene.background=new d.Color(1710618),this.scene.fog=new d.Fog(1710618,10,50),this.camera=new d.PerspectiveCamera(45,this.container.clientWidth/this.container.clientHeight,.1,100),this.camera.position.set(0,1.5,5),this.renderer=new $t.WebGPURenderer({antialias:!0,alpha:!0}),this.renderer.setSize(this.container.clientWidth,this.container.clientHeight),this.renderer.setPixelRatio(window.devicePixelRatio),this.container.appendChild(this.renderer.domElement),this.setupLights(),this.controls=new Nt(this.camera,this.renderer.domElement),this.controls.enableDamping=!0,this.controls.target.set(0,1,0),this.lookAtProcessor=new Qt(this.container,this.camera,()=>this.headBone,()=>this.currentAvatarConfig,()=>{const o=[];return this.avatarModel&&o.push(this.avatarModel),this.stageModel&&o.push(this.stageModel),o}),this.bubbleManager=new tn(this.scene),this.brain.onStateChange=(o,r)=>{if(this.animController)switch(o){case N.IDLE:this.animController.play("idle"),this.lookAtProcessor.reset(),this.bubbleManager.hide();break;case N.TALKING:this.animController.play("talk"),this.lookAtProcessor.setTarget(this.camera.position.clone()),r.text&&this.bubbleManager.show(r.text,"speech");break;case N.THINKING:this.animController.play("thinking"),this.bubbleManager.show(r.text||"...","thought");break;case N.LISTENING:this.animController.play("idle"),this.lookAtProcessor.setTarget(this.camera.position.clone()),this.bubbleManager.hide();break;case N.EMOTIONAL:this.animController.play("idle"),this.lookAtProcessor.setTarget(this.camera.position.clone()),this.bubbleManager.hide();break}},this.resizeObserver=new ResizeObserver(o=>{const r=o[0];this.onWindowResize(r.contentRect.width,r.contentRect.height)}),this.resizeObserver.observe(this.container),this.renderer.setAnimationLoop(this.animate.bind(this))}dispose(){this.resizeObserver.disconnect(),this.renderer.setAnimationLoop(null),this.renderer.dispose(),this.controls.dispose()}setupLights(){const t=new d.AmbientLight(16777215,.6);this.scene.add(t);const n=new d.DirectionalLight(16777215,1);n.position.set(5,10,7),n.castShadow=!0,this.scene.add(n);const o=new d.SpotLight(54015,5);o.position.set(-5,5,-5),o.lookAt(0,1,0),this.scene.add(o)}async loadAvatar(t){this.avatarModel&&this.scene.remove(this.avatarModel);const{model:n,config:o,animations:r}=await this.loader.load(t);this.avatarModel=n,this.currentAvatarConfig=o,this.scene.add(this.avatarModel);const i=o.lookAt?.headBoneName||"Head";if(this.headBone=this.avatarModel.getObjectByName(i)||null,this.headBone||this.avatarModel.traverse(s=>{!this.headBone&&s.name.toLowerCase().includes("head")&&(this.headBone=s)}),r.length>0){this.animController=new he(this.avatarModel,r);const s=o.animations||{defaultState:"idle",states:{idle:{clipName:"Idle",loop:!0},walk:{clipName:"Walking",loop:!0},wave:{clipName:"Wave",loop:!1,next:"idle"},talk:{clipName:"Talk",loop:!0},thinking:{clipName:"Thinking",loop:!0},dance:{clipName:"Dance",loop:!1,next:"idle"},bow:{clipName:"Bow",loop:!1,next:"idle"}}};this.animController.init(s)}this.headBone&&this.bubbleManager.setTarget(this.headBone),console.log(`[Flow] Avatar "${o.name}" loaded.`)}async loadStage(t){this.stageModel&&this.scene.remove(this.stageModel);const{model:n,config:o,animations:r}=await this.stageLoader.load(t);this.stageModel=n,this.scene.add(this.stageModel),r.length>0&&o.animations&&(this.stageAnimController=new he(this.stageModel,r),this.stageAnimController.init(o.animations))}setDebug(t){this.isDebug=t,t?(this.createDebugHelpers(),this.brain.setDebugMode(!0)):(this.removeDebugHelpers(),this.brain.setDebugMode(!1))}createDebugHelpers(){if(this.debugTargetMesh||(this.debugTargetMesh=new d.Mesh(new d.SphereGeometry(.1,8,8),new d.MeshBasicMaterial({color:16711680,wireframe:!0,depthTest:!1})),this.debugTargetMesh.renderOrder=999,this.scene.add(this.debugTargetMesh)),!this.debugPlaneMesh){const t=new d.GridHelper(5,10,65280,34816);t.material.transparent=!0,t.material.opacity=.5,t.rotateX(Math.PI/2),this.debugPlaneMesh=t,this.scene.add(this.debugPlaneMesh)}}updateDebugHelpers(){if(!this.isDebug||!this.lookAtProcessor)return;const t=this.lookAtProcessor.getDebugInfo(),n=!!(t.planeCenter&&t.activePlane);if(this.debugTargetMesh&&(this.debugTargetMesh.position.copy(t.currentLookAt),this.debugTargetMesh.visible=t.isEngaged),this.debugPlaneMesh&&(this.debugPlaneMesh.visible=n,n)){this.debugPlaneMesh.position.copy(t.planeCenter);const o=t.activePlane.normal,r=this.debugPlaneMesh.position.clone().add(o);this.debugPlaneMesh.lookAt(r),this.debugPlaneMesh.rotateX(Math.PI/2)}}removeDebugHelpers(){this.debugTargetMesh&&(this.scene.remove(this.debugTargetMesh),this.debugTargetMesh=null),this.debugPlaneMesh&&(this.scene.remove(this.debugPlaneMesh),this.debugPlaneMesh=null)}onWindowResize(t,n){!t||!n||(this.camera.aspect=t/n,this.camera.updateProjectionMatrix(),this.renderer.setSize(t,n))}isAutoRotate=!1;say(t){const n=typeof t=="string"?{text:t}:t,o=Is.parse(n);this.brain.setIntent({state:N.TALKING,text:o.text,duration:o.duration})}think(t){const n=typeof t=="string"?{text:t}:t||{},o=Ds.parse(n);this.brain.setIntent({state:N.THINKING,text:o.text,duration:o.duration})}setBehavior(t){this.brain.setIntent(t)}processAgentResponse(t){if(!t||typeof t!="object"){console.warn("[Flow] Invalid AgentResponse received:",t);return}console.log("[Flow] Processing Agent Response:",t),t.state?this.brain.setIntent({state:t.state,text:t.text,emotion:t.emotion}):t.text&&this.say(t.text),t.actions&&Array.isArray(t.actions)&&t.actions.forEach(n=>{setTimeout(()=>{this.executeCommand(n)},n.delay||0)})}executeCommand(t){if(!(!t||!t.type))switch(t.type){case"animation":this.animController&&this.animController.play(t.name.toLowerCase());break;case"expression":break;case"interaction":t.name==="lookAt"&&t.value instanceof d.Vector3&&this.lookAtProcessor.setTarget(t.value);break;default:console.warn("[Flow] Unknown action command type received:",t.type,t);break}}playAction(t){this.lookAtProcessor.interrupt(),this.brain.setIntent({state:N.IDLE}),this.animController&&this.animController.play(t.toLowerCase())}animate(t){const n=this.clock.getDelta();this.brain.update(t),this.avatarModel&&(this.animController&&this.animController.update(n),this.lookAtProcessor.update(t,n),this.bubbleManager.update()),this.updateDebugHelpers(),this.stageModel&&this.stageAnimController&&this.stageAnimController.update(n),this.controls.autoRotate=this.isAutoRotate,this.controls.update(),this.renderer.render(this.scene,this.camera)}}$.AnimationController=he,$.AvatarBehaviorStates=N,$.AvatarLoader=Ie,$.BehaviorController=De,$.FlowEngine=$s,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})}));
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export { FlowEngine } from './core/FlowEngine';
2
2
  export { AvatarLoader } from './core/AvatarLoader';
3
3
  export { AnimationController } from './core/AnimationController';
4
- export type { AvatarConfig, AnimationStateConfig } from './types';
4
+ export { BehaviorController } from './core/BehaviorController';
5
+ export type { AvatarConfig, AnimationStateConfig, AvatarBehaviorState, BehaviorIntent } from './types';
6
+ export { AvatarBehaviorStates } from './types';
@@ -0,0 +1,55 @@
1
+ /**
2
+ * FlowMcpServer
3
+ * A Model Context Protocol server that exposes Flow Engine capabilities as tools.
4
+ *
5
+ * Note: This server acts as a bridge. It connects to the FlowEngine instance via WebSocket.
6
+ */
7
+ export declare class FlowMcpServer {
8
+ private server;
9
+ private wss;
10
+ private clients;
11
+ private port;
12
+ /**
13
+ * Creates a new FlowMcpServer instance.
14
+ *
15
+ * @param options Optional configuration for the server.
16
+ * @param options.port TCP port for the WebSocket bridge.
17
+ * - If omitted, the server listens on port `3001` by default.
18
+ * - If set to `0`, the operating system will automatically assign an
19
+ * available ephemeral port. The actual port can then be retrieved via
20
+ * the {@link FlowMcpServer.getPort | getPort()} method.
21
+ */
22
+ constructor(options?: {
23
+ port?: number;
24
+ });
25
+ private setupTools;
26
+ private broadcast;
27
+ /**
28
+ * Implementation for the "say" tool.
29
+ */
30
+ private handleSay;
31
+ /**
32
+ * Implementation for the "think" tool.
33
+ */
34
+ private handleThink;
35
+ /**
36
+ * Implementation for the "play_action" tool.
37
+ */
38
+ private handlePlayAction;
39
+ run(): Promise<void>;
40
+ /**
41
+ * Returns the port associated with the WebSocket server.
42
+ *
43
+ * @returns The actual port if the server is successfully listening;
44
+ * otherwise, returns the configured port or -1 if the server failed to start.
45
+ */
46
+ getPort(): number;
47
+ /**
48
+ * Gracefully shuts down the MCP and WebSocket servers.
49
+ */
50
+ close(): Promise<void>;
51
+ }
52
+ /**
53
+ * Programmatic entry point for running the Flow MCP server via CLI-style usage.
54
+ */
55
+ export declare function runFlowMcpServerCli(): Promise<void>;
@@ -0,0 +1,18 @@
1
+ import { z } from 'zod';
2
+ export declare const SaySchema: z.ZodObject<{
3
+ text: z.ZodString;
4
+ duration: z.ZodDefault<z.ZodNumber>;
5
+ }, z.core.$strip>;
6
+ export declare const ThinkSchema: z.ZodObject<{
7
+ text: z.ZodDefault<z.ZodString>;
8
+ duration: z.ZodDefault<z.ZodNumber>;
9
+ }, z.core.$strip>;
10
+ export declare const PlayActionSchema: z.ZodObject<{
11
+ action: z.ZodString;
12
+ }, z.core.$strip>;
13
+ export type SayParams = z.input<typeof SaySchema>;
14
+ export type ThinkParams = z.input<typeof ThinkSchema>;
15
+ export type PlayActionParams = z.input<typeof PlayActionSchema>;
16
+ export type SayData = z.infer<typeof SaySchema>;
17
+ export type ThinkData = z.infer<typeof ThinkSchema>;
18
+ export type PlayActionData = z.infer<typeof PlayActionSchema>;
@@ -1,7 +1,70 @@
1
1
  /**
2
- * Avatar Configuration Interface
3
- * 定义数字人的元数据结构,对应资源包中的 config.json
2
+ * High-level Behavior States for the Agent Brain
4
3
  */
4
+ export declare const AvatarBehaviorStates: {
5
+ readonly IDLE: "IDLE";
6
+ readonly TALKING: "TALKING";
7
+ readonly THINKING: "THINKING";
8
+ readonly LISTENING: "LISTENING";
9
+ readonly EMOTIONAL: "EMOTIONAL";
10
+ };
11
+ export type AvatarBehaviorState = typeof AvatarBehaviorStates[keyof typeof AvatarBehaviorStates];
12
+ /**
13
+ * Encapsulates an intent to change the avatar's high-level behavior.
14
+ *
15
+ * This intent is typically forwarded to an `onStateChange` callback where
16
+ * consumers (like AnimationController or Text-to-Speech) can react.
17
+ */
18
+ export interface BehaviorIntent {
19
+ /** Target high-level behavior state for the avatar. */
20
+ state: AvatarBehaviorState;
21
+ /**
22
+ * What is being said when the state is `TALKING`.
23
+ * Useful for lip-sync, subtitles, or speech synthesis.
24
+ */
25
+ text?: string;
26
+ /**
27
+ * The current mood when the state is `EMOTIONAL`.
28
+ * Used to select appropriate facial expressions or emotional animations.
29
+ */
30
+ emotion?: string;
31
+ /**
32
+ * Optional timeout for the state in milliseconds.
33
+ * The brain will automatically revert to `IDLE` after this duration.
34
+ */
35
+ duration?: number;
36
+ }
37
+ /**
38
+ * Represents a single discrete action to be performed by the avatar.
39
+ * @template T Type of the command value (e.g. THREE.Vector3, number)
40
+ */
41
+ export interface ActionCommand<T = any> {
42
+ type: 'animation' | 'expression' | 'interaction';
43
+ name: string;
44
+ value?: T;
45
+ delay?: number;
46
+ }
47
+ /**
48
+ * Standard data structure for Agent-to-Avatar communication.
49
+ * Agents are encouraged to respond with this JSON structure.
50
+ */
51
+ export interface AgentResponse {
52
+ /** The text content to be spoken by the avatar. */
53
+ text?: string;
54
+ /** High-level behavior state to enter. */
55
+ state?: AvatarBehaviorState;
56
+ /** Discrete actions to perform alongside the speech. */
57
+ actions?: ActionCommand[];
58
+ /** Global emotion to set. */
59
+ emotion?: string;
60
+ }
61
+ /**
62
+ * Interface for autonomous behavior components
63
+ */
64
+ export interface InteractionProcessor {
65
+ update(timeMs: number, delta: number): void;
66
+ dispose(): void;
67
+ }
5
68
  export interface AvatarConfig {
6
69
  name: string;
7
70
  modelSrc: string;
@@ -40,13 +103,6 @@ export interface AnimationStateConfig {
40
103
  /** Duration to hold the last frame before transitioning (seconds) */
41
104
  holdDuration?: number;
42
105
  }
43
- /**
44
- * Interface for autonomous behavior components
45
- */
46
- export interface InteractionProcessor {
47
- update(timeMs: number, delta: number): void;
48
- dispose(): void;
49
- }
50
106
  export interface StageConfig {
51
107
  name: string;
52
108
  modelSrc?: string;
package/dist/ui.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function createLayout(app: HTMLElement): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guoquan.net/flow-engine",
3
- "version": "0.1.9",
3
+ "version": "0.2.0",
4
4
  "description": "A high-performance, WebGPU-based digital human engine.",
5
5
  "type": "module",
6
6
  "main": "./dist/flow.umd.js",
@@ -20,7 +20,9 @@
20
20
  "test:watch": "vitest",
21
21
  "test:coverage": "vitest run --coverage",
22
22
  "preview": "vite preview --host",
23
- "prepare": "npm run build"
23
+ "prepare": "npm run build",
24
+ "mcp": "tsx src/mcp/server.ts",
25
+ "docs:generate": "typedoc"
24
26
  },
25
27
  "peerDependencies": {
26
28
  "three": ">=0.170.0"
@@ -30,10 +32,13 @@
30
32
  "@playwright/test": "^1.57.0",
31
33
  "@types/node": "^25.0.3",
32
34
  "@types/three": "^0.182.0",
35
+ "@types/ws": "^8.18.1",
33
36
  "@vitest/coverage-v8": "^4.0.16",
34
37
  "cross-env": "^10.1.0",
35
38
  "jsdom": "^27.4.0",
36
39
  "three": "^0.182.0",
40
+ "tsx": "^4.21.0",
41
+ "typedoc": "^0.28.15",
37
42
  "typescript": "~5.9.3",
38
43
  "vite": "^7.2.4",
39
44
  "vite-plugin-dts": "^4.5.4",
@@ -42,5 +47,10 @@
42
47
  "repository": {
43
48
  "type": "git",
44
49
  "url": "https://github.com/guoquan/flow-engine.git"
50
+ },
51
+ "dependencies": {
52
+ "@modelcontextprotocol/sdk": "^1.25.1",
53
+ "ws": "8.18.3",
54
+ "zod": "~4.3.5"
45
55
  }
46
56
  }