@gamepadly/sdk 0.2.0 → 0.4.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.
Files changed (134) hide show
  1. package/README.md +163 -8
  2. package/dist/audio/index.d.ts +10 -0
  3. package/dist/audio/index.d.ts.map +1 -0
  4. package/dist/audio/index.js +15 -0
  5. package/dist/audio/index.js.map +7 -0
  6. package/dist/audio/routing.d.ts +40 -0
  7. package/dist/audio/routing.d.ts.map +1 -0
  8. package/dist/audio/routing.js +26 -0
  9. package/dist/audio/routing.js.map +7 -0
  10. package/dist/audio/sampleBank.d.ts +29 -0
  11. package/dist/audio/sampleBank.d.ts.map +1 -0
  12. package/dist/audio/sampleBank.js +354 -0
  13. package/dist/audio/sampleBank.js.map +7 -0
  14. package/dist/bridge/index.js +5 -93
  15. package/dist/bridge/index.js.map +3 -3
  16. package/dist/bridge/profiles.js +89 -0
  17. package/dist/bridge/profiles.js.map +7 -0
  18. package/dist/browser.d.ts +6 -2
  19. package/dist/browser.d.ts.map +1 -1
  20. package/dist/browser.js +2569 -53
  21. package/dist/browser.js.map +4 -4
  22. package/dist/browser.min.js +1 -1
  23. package/dist/diagnostics/circularity.d.ts +26 -0
  24. package/dist/diagnostics/circularity.d.ts.map +1 -0
  25. package/dist/diagnostics/circularity.js +56 -0
  26. package/dist/diagnostics/circularity.js.map +7 -0
  27. package/dist/diagnostics/index.d.ts +15 -0
  28. package/dist/diagnostics/index.d.ts.map +1 -0
  29. package/dist/diagnostics/index.js +31 -0
  30. package/dist/diagnostics/index.js.map +7 -0
  31. package/dist/diagnostics/stick.d.ts +73 -0
  32. package/dist/diagnostics/stick.d.ts.map +1 -0
  33. package/dist/diagnostics/stick.js +134 -0
  34. package/dist/diagnostics/stick.js.map +7 -0
  35. package/dist/diagnostics/telemetry.d.ts +65 -0
  36. package/dist/diagnostics/telemetry.d.ts.map +1 -0
  37. package/dist/diagnostics/telemetry.js +98 -0
  38. package/dist/diagnostics/telemetry.js.map +7 -0
  39. package/dist/game/host.d.ts +40 -0
  40. package/dist/game/host.d.ts.map +1 -0
  41. package/dist/game/host.js +206 -0
  42. package/dist/game/host.js.map +7 -0
  43. package/dist/game/index.d.ts +12 -0
  44. package/dist/game/index.d.ts.map +1 -0
  45. package/dist/game/index.js +27 -0
  46. package/dist/game/index.js.map +7 -0
  47. package/dist/game/mock.d.ts +35 -0
  48. package/dist/game/mock.d.ts.map +1 -0
  49. package/dist/game/mock.js +221 -0
  50. package/dist/game/mock.js.map +7 -0
  51. package/dist/game/seats.d.ts +27 -0
  52. package/dist/game/seats.d.ts.map +1 -0
  53. package/dist/game/seats.js +66 -0
  54. package/dist/game/seats.js.map +7 -0
  55. package/dist/game/types.d.ts +85 -0
  56. package/dist/game/types.d.ts.map +1 -0
  57. package/dist/game/types.js +7 -0
  58. package/dist/game/types.js.map +7 -0
  59. package/dist/haptics/presets.js +133 -0
  60. package/dist/haptics/presets.js.map +7 -0
  61. package/dist/haptics/router.d.ts +16 -0
  62. package/dist/haptics/router.d.ts.map +1 -1
  63. package/dist/haptics/router.js +146 -0
  64. package/dist/haptics/router.js.map +7 -0
  65. package/dist/haptics/samples.d.ts +68 -0
  66. package/dist/haptics/samples.d.ts.map +1 -0
  67. package/dist/haptics/samples.js +124 -0
  68. package/dist/haptics/samples.js.map +7 -0
  69. package/dist/haptics/triggerWrites.d.ts +41 -0
  70. package/dist/haptics/triggerWrites.d.ts.map +1 -0
  71. package/dist/haptics/triggerWrites.js +127 -0
  72. package/dist/haptics/triggerWrites.js.map +7 -0
  73. package/dist/hid/index.d.ts +7 -1
  74. package/dist/hid/index.d.ts.map +1 -1
  75. package/dist/{chunks/chunk-75I5NTQZ.js → hid/index.js} +35 -157
  76. package/dist/hid/index.js.map +7 -0
  77. package/dist/hub.d.ts +26 -2
  78. package/dist/hub.d.ts.map +1 -1
  79. package/dist/hub.js +472 -0
  80. package/dist/hub.js.map +7 -0
  81. package/dist/index.d.ts +12 -2
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +45 -793
  84. package/dist/index.js.map +4 -4
  85. package/dist/input/actions.js +244 -0
  86. package/dist/input/actions.js.map +7 -0
  87. package/dist/input/motion.d.ts +70 -0
  88. package/dist/input/motion.d.ts.map +1 -0
  89. package/dist/input/motion.js +175 -0
  90. package/dist/input/motion.js.map +7 -0
  91. package/dist/input/slotSwitcher.d.ts +31 -0
  92. package/dist/input/slotSwitcher.d.ts.map +1 -0
  93. package/dist/input/slotSwitcher.js +118 -0
  94. package/dist/input/slotSwitcher.js.map +7 -0
  95. package/dist/input/touchpad.d.ts +92 -0
  96. package/dist/input/touchpad.d.ts.map +1 -0
  97. package/dist/input/touchpad.js +268 -0
  98. package/dist/input/touchpad.js.map +7 -0
  99. package/dist/lifecycle.d.ts +37 -0
  100. package/dist/lifecycle.d.ts.map +1 -0
  101. package/dist/lifecycle.js +55 -0
  102. package/dist/lifecycle.js.map +7 -0
  103. package/dist/link/connect.d.ts +67 -0
  104. package/dist/link/connect.d.ts.map +1 -0
  105. package/dist/link/connect.js +123 -0
  106. package/dist/link/connect.js.map +7 -0
  107. package/dist/link/engine.d.ts +7 -1
  108. package/dist/link/engine.d.ts.map +1 -1
  109. package/dist/link/engine.js +985 -0
  110. package/dist/link/engine.js.map +7 -0
  111. package/dist/link/index.d.ts +15 -4
  112. package/dist/link/index.d.ts.map +1 -1
  113. package/dist/link/index.js +29 -958
  114. package/dist/link/index.js.map +4 -4
  115. package/dist/loop/index.js +0 -1
  116. package/dist/loop/index.js.map +1 -1
  117. package/dist/mic/blow.d.ts +72 -0
  118. package/dist/mic/blow.d.ts.map +1 -0
  119. package/dist/mic/blow.js +152 -0
  120. package/dist/mic/blow.js.map +7 -0
  121. package/dist/mic/index.d.ts +9 -0
  122. package/dist/mic/index.d.ts.map +1 -0
  123. package/dist/mic/index.js +23 -0
  124. package/dist/mic/index.js.map +7 -0
  125. package/dist/mic/input.d.ts +37 -0
  126. package/dist/mic/input.d.ts.map +1 -0
  127. package/dist/mic/input.js +109 -0
  128. package/dist/mic/input.js.map +7 -0
  129. package/dist/mic/level.d.ts +33 -0
  130. package/dist/mic/level.d.ts.map +1 -0
  131. package/dist/mic/level.js +61 -0
  132. package/dist/mic/level.js.map +7 -0
  133. package/package.json +17 -1
  134. package/dist/chunks/chunk-75I5NTQZ.js.map +0 -7
@@ -1 +1 @@
1
- var fe=[3302,3570],J=1406,ee=[8201],q=new Uint8Array([0,1,64,64]);function me(a){if(!Number.isFinite(a)||a<=.01)return 0;let e=Math.min(.85,Math.max(0,a));return e>=.23?Math.min(100,Math.round(Math.log2(e*8.7)*32)):e>=.12?Math.round(Math.log2(e*17)*16):Math.max(1,Math.round(e/.12*16))}function U(a){if(!a||a.highAmp<=.01&&a.lowAmp<=.01)return q.slice();let e=Math.max(81.75,Math.min(1252.6,Number.isFinite(a.highFreqHz)?a.highFreqHz:320)),t=Math.max(40.88,Math.min(626.3,Number.isFinite(a.lowFreqHz)?a.lowFreqHz:160)),n=Math.round(Math.log2(e/10)*32),i=Math.round(Math.log2(t/10)*32),r=Math.max(0,Math.min(508,(n-96)*4)),o=Math.max(1,Math.min(127,i-64)),s=me(a.highAmp),c=me(a.lowAmp),l=Math.min(200,s*2),u=(c&1)!==0?128:0,d=Math.min(114,(c>>1)+64);return new Uint8Array([r&255,l+(r>>8&1)&255,(o|u)&255,d&255])}function F(a,e=.06){let t=Math.abs(a);if(t<=e)return 0;let n=(t-e)/(1-e);return Math.sign(a)*Math.max(0,Math.min(1,n))}function xe(a){return(a.match(/vendor:\s*([0-9a-f]{4})/)??a.match(/^([0-9a-f]{1,4})-[0-9a-f]{1,4}-/))?.[1]?.padStart(4,"0")}function Ce(a){return(a.match(/product:\s*([0-9a-f]{4})/)??a.match(/^[0-9a-f]{1,4}-([0-9a-f]{1,4})-/))?.[1]?.padStart(4,"0")}function He(a){let e=xe(a);if(e==="054c")return"sony";if(e==="045e")return"xbox";if(e==="057e")return"nintendo";if(!e){if(/xbox|xinput|microsoft/.test(a))return"xbox";if(/dualsense|dualshock|wireless controller/.test(a))return"sony";if(/nintendo|pro controller|joy-con|switch/.test(a))return"nintendo"}}function ne(a){let e=(a||"").toLowerCase(),t=xe(e),n=Ce(e),i=t?Number.parseInt(t,16):void 0,r=n?Number.parseInt(n,16):void 0,o=He(e);return o==="sony"?/0df2|edge/.test(e)?{brand:"sony",model:"dualsense_edge",displayName:"DualSense Edge",rawId:a,vendorId:1356,productId:r??3570}:/0ce6|dualsense/.test(e)?{brand:"sony",model:"dualsense",displayName:"PlayStation DualSense",rawId:a,vendorId:1356,productId:r??3302}:/05c4|09cc|dualshock/.test(e)?{brand:"sony",model:"dualshock4",displayName:"DualShock 4",rawId:a,vendorId:1356,productId:r}:{brand:"sony",model:"dualsense",displayName:"PlayStation Controller",rawId:a,vendorId:1356,productId:r}:o==="xbox"?/0b12|0b13|0b20|0b21|0b22|series/.test(e)?{brand:"xbox",model:"xbox_series",displayName:"Xbox Wireless Controller",rawId:a,vendorId:1118,productId:r}:/028e|360/.test(e)?{brand:"xbox",model:"xbox_360",displayName:"Xbox 360 Controller",rawId:a,vendorId:1118,productId:r}:{brand:"xbox",model:"xbox_series",displayName:"Xbox Controller",rawId:a,vendorId:1118,productId:r}:o==="nintendo"?/2069|pro 2|switch 2/.test(e)?{brand:"nintendo",model:"switch2_pro",displayName:"Nintendo Switch 2 Pro Controller",rawId:a,vendorId:1406,productId:r??8297}:/joy-con|2006|2007/.test(e)?{brand:"nintendo",model:"joycon",displayName:"Nintendo Joy-Con",rawId:a,vendorId:1406,productId:r}:{brand:"nintendo",model:"switch_pro",displayName:"Nintendo Switch Pro Controller",rawId:a,vendorId:1406,productId:r??8201}:a?{brand:"generic",model:"generic",displayName:a.split("(")[0].trim()||a,rawId:a,vendorId:i,productId:r}:{brand:"none",model:"none",displayName:"No Controller Detected",rawId:""}}var te=(()=>{let a=new Uint32Array(256);for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;a[e]=t>>>0}return a})();function Se(a,e,t){let n=4294967295;n=te[(n^a)&255]^n>>>8,n=te[(n^e)&255]^n>>>8;for(let i=0;i<t.length;i++)n=te[(n^t[i])&255]^n>>>8;return(n^4294967295)>>>0}function z(a){let e=new Uint8Array(11);if(a.type==="off")return e[0]=5,e;if(a.type==="feedback"||a.type==="slope"){e[0]=33;let s=new Array(10).fill(0);if(a.type==="feedback"){let u=Math.max(0,Math.min(9,Math.round(a.startZone))),d=Math.max(1,Math.min(8,Math.round(a.strength)));for(let h=u;h<10;h++)s[h]=d}else{let u=Math.max(0,Math.min(8,Math.round(a.startZone))),d=Math.max(u+1,Math.min(9,Math.round(a.endZone)));for(let h=u;h<=d;h++){let w=(h-u)/(d-u);s[h]=Math.max(1,Math.min(8,Math.round(a.startStrength+w*(a.endStrength-a.startStrength))))}}let c=0,l=0;for(let u=0;u<10;u++){let d=s[u];d>0&&(c|=1<<u,l|=(d-1&7)<<3*u)}return e[1]=c&255,e[2]=c>>8&255,e[3]=l&255,e[4]=l>>8&255,e[5]=l>>16&255,e[6]=l>>24&255,e}if(a.type==="weapon"){let s=Math.max(2,Math.min(7,Math.round(a.startZone))),c=Math.max(s+1,Math.min(8,Math.round(a.endZone))),l=Math.max(1,Math.min(8,Math.round(a.strength))),u=1<<s|1<<c;return e[0]=37,e[1]=u&255,e[2]=u>>8&255,e[3]=l-1&7,e}let t=Math.max(0,Math.min(9,Math.round(a.startZone))),n=Math.max(1,Math.min(8,Math.round(a.amplitude))),i=Math.max(1,Math.min(255,Math.round(a.frequencyHz))),r=0,o=0;for(let s=t;s<10;s++)r|=1<<s,o|=(n-1&7)<<3*s;return e[0]=38,e[1]=r&255,e[2]=r>>8&255,e[3]=o&255,e[4]=o>>8&255,e[5]=o>>16&255,e[6]=o>>24&255,e[9]=i,e}function N(){return{connected:!1,source:"none",deviceName:"",isDualSense:!1,identity:{brand:"none",model:"none",displayName:"No Controller Detected",rawId:"",transport:"disconnected",source:"none"},lx:0,ly:0,rx:0,ry:0,l2:0,r2:0,buttons:{cross:!1,circle:!1,square:!1,triangle:!1,l1:!1,r1:!1,l2Btn:!1,r2Btn:!1,l3:!1,r3:!1,up:!1,down:!1,left:!1,right:!1,create:!1,options:!1,ps:!1,touchpadClick:!1,mute:!1,fnL:!1,fnR:!1,paddleL:!1,paddleR:!1},touch:{active:!1,x:.5,y:.5},touch2:{active:!1,x:.5,y:.5},gyro:{x:0,y:0,z:0},accel:{x:0,y:0,z:0},battery:{percent:0,charging:!1,full:!1,known:!1},observedReportHz:null}}function ye(){let a=()=>({center:2048,minDelta:1500,maxDelta:1500});return{lx:a(),ly:a(),rx:a(),ry:a()}}var ge=[4,10,21,27],be=[1,3,7,15];function _(a){return new Promise(e=>setTimeout(e,a))}function we(a=0){return{speakerVolume:100,headphoneVolume:100,audioRoute:"speaker",speakerPreamp:7,lightbar:[23,23,23],playerLeds:ge[a%ge.length],muteLed:"off",leftTrigger:z({type:"off"}),rightTrigger:z({type:"off"}),legacyRumbleActive:!1,legacyLeft:0,legacyRight:0}}var O=class a{hidSessions=new Map;nextHidSeq=1;activeSlotId=null;hidDisconnectAttached=!1;hidConnectAttached=!1;listeners=new Set;gamepadInputs=new Map;gamepadLastActivity=new Map;gamepadPrevBtnMask=new Map;fallbackInput=N();keysDown=new Set;kbmAttached=!1;boundConnect=e=>{this.handleConnect(e)};boundDisconnect=e=>this.handleDisconnect(e);boundKeyDown=e=>{this.keysDown.add(e.code)};boundKeyUp=e=>{this.keysDown.delete(e.code)};boundWindowBlur=()=>{this.keysDown.clear()};get device(){return this.getActiveHidSession()?.device??null}get transport(){return this.getActiveHidSession()?.transport??"disconnected"}get firmwareInfo(){return this.getActiveHidSession()?.firmwareInfo}get hidDeviceCount(){return this.hidSessions.size}static isWebHIDSupported(){return typeof navigator<"u"&&"hid"in navigator}static isGamepadSupported(){return typeof navigator<"u"&&typeof navigator.getGamepads=="function"}isSupportedHidDevice(e){return e.vendorId===1356&&fe.includes(e.productId)||e.vendorId===J&&ee.includes(e.productId)}attachHidHotplug(){this.hidConnectAttached||!a.isWebHIDSupported()||(navigator.hid.addEventListener("connect",this.boundConnect),this.hidConnectAttached=!0)}detachHidHotplug(){!this.hidConnectAttached||!a.isWebHIDSupported()||(navigator.hid.removeEventListener("connect",this.boundConnect),this.hidConnectAttached=!1)}async handleConnect(e){if(this.isSupportedHidDevice(e.device))try{await this.attachDevice(e.device)}catch{}}attachKeyboardFallback(){this.kbmAttached||typeof window>"u"||(window.addEventListener("keydown",this.boundKeyDown),window.addEventListener("keyup",this.boundKeyUp),window.addEventListener("blur",this.boundWindowBlur),this.kbmAttached=!0)}detachKeyboardFallback(){!this.kbmAttached||typeof window>"u"||(window.removeEventListener("keydown",this.boundKeyDown),window.removeEventListener("keyup",this.boundKeyUp),window.removeEventListener("blur",this.boundWindowBlur),this.keysDown.clear(),this.kbmAttached=!1)}onStatusChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emit(e){for(let t of this.listeners)try{t(e)}catch(n){console.error("[core-hid] listener error:",n)}}getAllRawGamepads(){if(!a.isGamepadSupported())return[];let e=navigator.getGamepads(),t=[];for(let n of e)n&&n.connected&&t.push(n);return t}pollGamepadActivity(e){let t=0,n=Math.min(20,e.buttons.length);for(let r=0;r<n;r++)e.buttons[r]?.pressed&&(t|=1<<r);let i=this.gamepadPrevBtnMask.get(e.index)??0;if(this.gamepadPrevBtnMask.set(e.index,t),(t&~i)!==0){let r=performance.now();return this.gamepadLastActivity.set(e.index,r),r}return this.gamepadLastActivity.get(e.index)??0}getConnectedControllers(){let e=[],t=0,n=0,i=0;for(let s of this.hidSessions.values())s.device.opened&&(s.input.identity.model==="dualsense_edge"?t++:s.input.identity.model==="switch_pro"?i++:n++,e.push({id:s.id,playerNumber:e.length+1,source:"webhid",identity:{...s.input.identity},battery:{...s.input.battery},observedReportHz:s.input.observedReportHz,lastActivityAt:s.lastActivityAt}));let r=this.getAllRawGamepads(),o=new Set;for(let s of r){o.add(s.index);let c=ne(s.id||"");if(c.model==="dualsense_edge"&&t>0){t--;continue}if(c.model==="dualsense"&&n>0){n--;continue}if(c.model==="switch_pro"&&i>0){i--;continue}let l=this.pollGamepadActivity(s);e.push({id:`gp-${s.index}`,playerNumber:e.length+1,source:"gamepad",identity:{...c,transport:"unknown",source:"gamepad"},battery:{percent:0,charging:!1,full:!1,known:!1},observedReportHz:null,lastActivityAt:l})}for(let s of this.gamepadPrevBtnMask.keys())o.has(s)||(this.gamepadPrevBtnMask.delete(s),this.gamepadLastActivity.delete(s));return e.length===0?this.activeSlotId=null:(!this.activeSlotId||!e.some(s=>s.id===this.activeSlotId))&&(this.activeSlotId=e[0].id),e}getActiveSlotId(){return this.getConnectedControllers(),this.activeSlotId}setActiveSlot(e){return this.getConnectedControllers().some(n=>n.id===e)?(this.activeSlotId!==e&&(this.activeSlotId=e,this.emit({type:"slots_changed",slotId:e})),!0):!1}getHidSessionForSlot(e){if(e!==void 0){let r=this.hidSessions.get(e);return r&&r.device.opened?r:null}let t=this.getConnectedControllers(),n=this.activeSlotId??t[0]?.id??null;if(!n)return null;let i=this.hidSessions.get(n);return i&&i.device.opened?i:null}getActiveHidSession(){return this.getHidSessionForSlot()}getGamepadForSlot(e){if(!a.isGamepadSupported())return null;if(e!==void 0){if(!e.startsWith("gp-"))return null;let i=Number(e.slice(3)),r=navigator.getGamepads()[i];return r&&r.connected?r:null}let t=this.getConnectedControllers(),n=this.activeSlotId??t[0]?.id??null;if(n&&n.startsWith("gp-")){let i=Number(n.slice(3)),r=navigator.getGamepads()[i];if(r&&r.connected)return r}if(n&&n.startsWith("hid-"))return null;for(let i of navigator.getGamepads())if(i&&i.connected)return i;return null}getActiveGamepad(){return this.getGamepadForSlot()}getGamepadActuatorEffects(e){let n=this.getGamepadForSlot(e)?.vibrationActuator;return n?Array.isArray(n.effects)&&n.effects.length>0?n.effects:typeof n.playEffect=="function"?["dual-rumble"]:[]:[]}hasTriggerRumbleSupport(e){return this.getGamepadActuatorEffects(e).includes("trigger-rumble")}hasDualRumbleSupport(e){return this.getGamepadActuatorEffects(e).includes("dual-rumble")||!!this.getGamepadForSlot(e)?.vibrationActuator?.playEffect}async connect(){if(!a.isWebHIDSupported())throw new Error("WebHID requires a Chromium browser (Chrome or Edge on desktop).");let e=await navigator.hid.requestDevice({filters:[...fe.map(n=>({vendorId:1356,productId:n})),...ee.map(n=>({vendorId:J,productId:n}))]});if(!e.length)return!1;let t=null;for(let n of e)t=await this.attachDevice(n);return t&&(this.activeSlotId=t,this.emit({type:"slots_changed",slotId:t})),!!t}async reconnectAuthorized(){if(!a.isWebHIDSupported())return!1;let t=(await navigator.hid.getDevices()).filter(i=>this.isSupportedHidDevice(i));if(!t.length)return!1;let n=!1;for(let i of t)try{await this.attachDevice(i),n=!0}catch{}return n}async readFirmwareInfoSafe(e){try{let t=await e.receiveFeatureReport(32);if(t.byteLength<44)return;let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i=n[0]===32?1:0,r=(d,h)=>{let w="";for(let y=d;y<d+h&&y<n.length;y++){let g=n[y];g>=32&&g<=126&&(w+=String.fromCharCode(g))}return w.trim()},o=r(i+0,11),s=r(i+11,8),c=new DataView(t.buffer,t.byteOffset+i),l=c.byteLength>=28?c.getUint32(24,!0):0,u=c.byteLength>=32?c.getUint32(28,!0):0;return!o&&!l?void 0:{buildDate:o||"Unknown",buildTime:s||"",hwInfoHex:`0x${l.toString(16).padStart(8,"0")}`,fwVersionHex:`0x${u.toString(16).padStart(8,"0")}`}}catch{return}}async attachDevice(e){for(let y of this.hidSessions.values())if(y.device===e&&y.device.opened)return y.id;if(e.opened||await e.open(),e.vendorId===J&&ee.includes(e.productId))return this.attachSwitchProDevice(e);let n=!1,i=!1,r=47,o=77;for(let y of e.collections||[])for(let g of y.outputReports||[]){let v=Math.ceil((g.items||[]).reduce((T,f)=>T+(f.reportSize||0)*(f.reportCount||0),0)/8);g.reportId===2&&(n=!0,v>=47&&(r=v)),g.reportId===49&&(i=!0,v>=77&&(o=v))}let s=n?"usb":i?"bluetooth":"usb",c=e.productId===3570,l=await this.readFirmwareInfoSafe(e),u=`hid-${this.nextHidSeq++}`,d=c?"DualSense Edge":"PlayStation DualSense",h=N();h.connected=!0,h.source="webhid",h.isDualSense=!0,h.deviceName=e.productName||d,h.identity={brand:"sony",model:c?"dualsense_edge":"dualsense",displayName:d,rawId:e.productName||d,vendorId:e.vendorId,productId:e.productId,transport:s,source:"webhid",firmwareInfo:l};let w={id:u,kind:"dualsense",device:e,transport:s,firmwareInfo:l,usbPayloadLength:r,btPayloadLength:o,btSeq:0,switchSubcmdLength:48,switchRumbleLength:9,switchUsb80Length:1,switchPacketNum:0,switchCal:ye(),switchRumbleTimer:null,switchSeqTimers:[],reportTimes:[],input:h,outState:we(this.hidSessions.size),legacyTimer:null,lastActivityAt:performance.now(),prevBtnMask:0,boundInputReport:y=>this.handleInputReport(w,y)};return this.hidSessions.set(u,w),this.activeSlotId||(this.activeSlotId=u),this.getConnectedControllers(),e.addEventListener("inputreport",w.boundInputReport),!this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.addEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!0),await this.flushSessionOutput(w,{includeAudioConfig:!0,includeTriggers:!0,includeLeds:!0}),this.emit({type:"connected",slotId:u,deviceName:h.deviceName,productId:e.productId,transport:s,firmwareInfo:l}),u}async attachSwitchProDevice(e){let t=!1,n=48,i=9,r=1;for(let h of e.collections||[])for(let w of h.outputReports||[]){let y=Math.ceil((w.items||[]).reduce((g,v)=>g+(v.reportSize||0)*(v.reportCount||0),0)/8);w.reportId===128&&(t=!0,y>=1&&(r=y)),w.reportId===1&&y>=10&&(n=y),w.reportId===16&&y>=9&&(i=y)}let o=t?"usb":"bluetooth",s=`hid-${this.nextHidSeq++}`,c="Nintendo Switch Pro Controller",l=N();l.connected=!0,l.source="webhid",l.isDualSense=!1,l.deviceName=e.productName||c,l.identity={brand:"nintendo",model:"switch_pro",displayName:c,rawId:e.productName||c,vendorId:e.vendorId,productId:e.productId,transport:o,source:"webhid"};let u=this.hidSessions.size,d={id:s,kind:"switch_pro",device:e,transport:o,firmwareInfo:void 0,usbPayloadLength:47,btPayloadLength:77,btSeq:0,switchSubcmdLength:n,switchRumbleLength:i,switchUsb80Length:r,switchPacketNum:0,switchCal:ye(),switchRumbleTimer:null,switchSeqTimers:[],reportTimes:[],input:l,outState:we(u),legacyTimer:null,lastActivityAt:performance.now(),prevBtnMask:0,boundInputReport:h=>this.handleSwitchProInputReport(d,h)};return this.hidSessions.set(s,d),this.activeSlotId||(this.activeSlotId=s),this.getConnectedControllers(),e.addEventListener("inputreport",d.boundInputReport),!this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.addEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!0),await this.initSwitchProSession(d,u),this.emit({type:"connected",slotId:s,deviceName:l.deviceName,productId:e.productId,transport:o}),s}async sendSwitchUsbCmd(e,t){if(!e.device.opened)return;let n=new Uint8Array(Math.max(1,e.switchUsb80Length));n[0]=t&255,await e.device.sendReport(128,n)}async sendSwitchSubcommand(e,t,n=[]){if(!e.device.opened)return;let i=Math.max(10+n.length,e.switchSubcmdLength),r=new Uint8Array(i);r[0]=e.switchPacketNum&15,e.switchPacketNum=e.switchPacketNum+1&15,r.set(q,1),r.set(q,5),r[9]=t&255;for(let o=0;o<n.length;o++)r[10+o]=n[o]&255;await e.device.sendReport(1,r)}async sendSwitchRumbleBytes(e,t,n){if(!e.device.opened)return!1;let i=Math.max(9,e.switchRumbleLength),r=new Uint8Array(i);return r[0]=e.switchPacketNum&15,e.switchPacketNum=e.switchPacketNum+1&15,r.set(t.subarray(0,4),1),r.set(n.subarray(0,4),5),await e.device.sendReport(16,r),!0}clearSwitchRumbleTimers(e){e.switchRumbleTimer&&(clearTimeout(e.switchRumbleTimer),e.switchRumbleTimer=null);for(let t of e.switchSeqTimers)clearTimeout(t);e.switchSeqTimers=[]}async initSwitchProSession(e,t){try{e.transport==="usb"&&(await this.sendSwitchUsbCmd(e,2).catch(()=>{}),await _(25),await this.sendSwitchUsbCmd(e,4).catch(()=>{}),await _(25)),await this.sendSwitchSubcommand(e,3,[48]),await _(20),await this.sendSwitchSubcommand(e,64,[1]),await _(20),await this.sendSwitchSubcommand(e,72,[1]),await _(20),await this.sendSwitchSubcommand(e,48,[be[t%be.length]]),await _(20),await this.sendSwitchSubcommand(e,16,[61,96,0,0,18]).catch(()=>{}),await _(20),await this.sendSwitchSubcommand(e,2).catch(()=>{})}catch{}}parseSwitchDeviceInfo(e,t){if(t.byteLength<17||t.getUint8(13)!==2)return;let n=t.getUint8(14),i=t.getUint8(15);if(n===0&&i===0)return;let r={buildDate:"",buildTime:"",hwInfoHex:"",fwVersionHex:`v${n}.${i}`};e.firmwareInfo=r,e.input.identity.firmwareInfo=r}parseSwitchStickCalibration(e,t){if(t.byteLength<37||t.getUint8(13)!==16||t.getUint32(14,!0)!==24637)return;let i=f=>{let x=t.getUint8(f),M=t.getUint8(f+1),A=t.getUint8(f+2);return[x|(M&15)<<8,M>>4&15|A<<4]},[r,o]=i(19),[s,c]=i(22),[l,u]=i(25),[d,h]=i(28),[w,y]=i(31),[g,v]=i(34),T=(f,x,M)=>f>=900&&f<=3200&&x>=400&&x<=2400&&M>=400&&M<=2400;T(s,l,r)&&T(c,u,o)&&(e.switchCal.lx={center:s,minDelta:l,maxDelta:r},e.switchCal.ly={center:c,minDelta:u,maxDelta:o}),T(d,w,g)&&T(h,y,v)&&(e.switchCal.rx={center:d,minDelta:w,maxDelta:g},e.switchCal.ry={center:h,minDelta:y,maxDelta:v})}handleSwitchProInputReport(e,t){let{reportId:n,data:i}=t;if(n===33&&(this.parseSwitchStickCalibration(e,i),this.parseSwitchDeviceInfo(e,i)),n!==48&&n!==33||i.byteLength<11)return;let r=e.input,o=performance.now();if(n===48&&(e.reportTimes.push(o),e.reportTimes.length>33&&e.reportTimes.shift(),e.reportTimes.length>=6)){let f=e.reportTimes[e.reportTimes.length-1]-e.reportTimes[0];f>10&&(r.observedReportHz=Math.round((e.reportTimes.length-1)*1e3/f))}let s=i.getUint8(1),c=Math.min(4,s>>5&7);r.battery.percent=c*25,r.battery.charging=!!(s&16),r.battery.full=c>=4,r.battery.known=!0;let l=i.getUint8(2),u=i.getUint8(3),d=i.getUint8(4);r.buttons.square=!!(l&1),r.buttons.triangle=!!(l&2),r.buttons.cross=!!(l&4),r.buttons.circle=!!(l&8),r.buttons.r1=!!(l&64),r.buttons.r2Btn=!!(l&128),r.buttons.create=!!(u&1),r.buttons.options=!!(u&2),r.buttons.r3=!!(u&4),r.buttons.l3=!!(u&8),r.buttons.ps=!!(u&16),r.buttons.touchpadClick=!!(u&32),r.buttons.down=!!(d&1),r.buttons.up=!!(d&2),r.buttons.right=!!(d&4),r.buttons.left=!!(d&8),r.buttons.l1=!!(d&64),r.buttons.l2Btn=!!(d&128),r.l2=r.buttons.l2Btn?1:0,r.r2=r.buttons.r2Btn?1:0;let h=l&207|(u&63)<<8|(d&207)<<16;(h&~e.prevBtnMask)!==0&&(e.lastActivityAt=o),e.prevBtnMask=h;let w=(f,x)=>{let M=f-x.center,A=M>=0?x.maxDelta:x.minDelta,m=A>0?M/A:0;return Math.max(-1,Math.min(1,m))},y=i.getUint8(5)|(i.getUint8(6)&15)<<8,g=i.getUint8(6)>>4&15|i.getUint8(7)<<4,v=i.getUint8(8)|(i.getUint8(9)&15)<<8,T=i.getUint8(9)>>4&15|i.getUint8(10)<<4;if(r.lx=w(y,e.switchCal.lx),r.ly=-w(g,e.switchCal.ly),r.rx=w(v,e.switchCal.rx),r.ry=-w(T,e.switchCal.ry),n===48&&i.byteLength>=48){let f=0,x=0,M=0,A=0,m=0,S=0;for(let R=0;R<3;R++){let B=12+R*12;f+=i.getInt16(B+0,!0),x+=i.getInt16(B+2,!0),M+=i.getInt16(B+4,!0),A+=i.getInt16(B+6,!0),m+=i.getInt16(B+8,!0),S+=i.getInt16(B+10,!0)}let p=f/3,b=x/3,C=M/3,k=A/3,P=m/3,I=S/3,H=R=>Math.max(-1,Math.min(1,R));r.accel.x=H(b/4096),r.accel.y=H(C/4096),r.accel.z=H(-p/4096),r.gyro.x=H(P/8192),r.gyro.y=H(I/8192),r.gyro.z=H(k/8192)}}async disconnect(e){let t=e??this.activeSlotId??Array.from(this.hidSessions.keys())[0];if(!t)return;let n=this.hidSessions.get(t);if(n){n.legacyTimer&&(clearTimeout(n.legacyTimer),n.legacyTimer=null),this.clearSwitchRumbleTimers(n);try{n.kind==="switch_pro"?await this.sendSwitchRumbleBytes(n,q,q):(n.outState.leftTrigger=z({type:"off"}),n.outState.rightTrigger=z({type:"off"}),n.outState.legacyRumbleActive=!1,n.outState.legacyLeft=0,n.outState.legacyRight=0,await this.flushSessionOutput(n,{includeTriggers:!0}))}catch{}n.device.removeEventListener("inputreport",n.boundInputReport);try{n.device.opened&&await n.device.close()}catch{}if(this.hidSessions.delete(t),this.hidSessions.size===0&&this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.removeEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!1),this.activeSlotId===t){let i=this.getConnectedControllers();this.activeSlotId=i[0]?.id??null}this.emit({type:"disconnected",slotId:t})}}async disconnectAll(){let e=Array.from(this.hidSessions.keys());for(let t of e)await this.disconnect(t)}handleDisconnect(e){for(let[t,n]of this.hidSessions.entries())if(n.device===e.device){if(n.legacyTimer&&(clearTimeout(n.legacyTimer),n.legacyTimer=null),this.clearSwitchRumbleTimers(n),n.device.removeEventListener("inputreport",n.boundInputReport),this.hidSessions.delete(t),this.activeSlotId===t){let i=this.getConnectedControllers();this.activeSlotId=i[0]?.id??null}this.emit({type:"disconnected",slotId:t})}this.hidSessions.size===0&&this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.removeEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!1)}handleInputReport(e,t){let{reportId:n,data:i}=t,r=0;if(n===49&&i.byteLength>=40)r=1;else if(n!==1||i.byteLength<10)return;let o=e.input,s=performance.now();if(e.reportTimes.push(s),e.reportTimes.length>33&&e.reportTimes.shift(),e.reportTimes.length>=6){let g=e.reportTimes[e.reportTimes.length-1]-e.reportTimes[0];g>10&&(o.observedReportHz=Math.round((e.reportTimes.length-1)*1e3/g))}let c=g=>{let v=g>=128?(g-128)/127:(g-128)/128;return Math.max(-1,Math.min(1,v))};o.lx=c(i.getUint8(r+0)),o.ly=c(i.getUint8(r+1)),o.rx=c(i.getUint8(r+2)),o.ry=c(i.getUint8(r+3)),o.l2=i.getUint8(r+4)/255,o.r2=i.getUint8(r+5)/255;let l=i.getUint8(r+7),u=i.getUint8(r+8),d=i.getUint8(r+9),h=l&15;o.buttons.up=h===0||h===1||h===7,o.buttons.right=h===1||h===2||h===3,o.buttons.down=h===3||h===4||h===5,o.buttons.left=h===5||h===6||h===7,o.buttons.square=!!(l&16),o.buttons.cross=!!(l&32),o.buttons.circle=!!(l&64),o.buttons.triangle=!!(l&128),o.buttons.l1=!!(u&1),o.buttons.r1=!!(u&2),o.buttons.l2Btn=!!(u&4),o.buttons.r2Btn=!!(u&8),o.buttons.create=!!(u&16),o.buttons.options=!!(u&32),o.buttons.l3=!!(u&64),o.buttons.r3=!!(u&128),o.buttons.ps=!!(d&1),o.buttons.touchpadClick=!!(d&2),o.buttons.mute=!!(d&4),o.buttons.fnL=!!(d&16),o.buttons.fnR=!!(d&32),o.buttons.paddleL=!!(d&64),o.buttons.paddleR=!!(d&128);let w=l&240|(h<8?1:0)|u<<8|(d&247)<<16;(w&~e.prevBtnMask)!==0&&(e.lastActivityAt=s),e.prevBtnMask=w,i.byteLength>r+26&&(o.gyro.x=Math.max(-1,Math.min(1,i.getInt16(r+15,!0)/16384)),o.gyro.y=Math.max(-1,Math.min(1,i.getInt16(r+17,!0)/16384)),o.gyro.z=Math.max(-1,Math.min(1,i.getInt16(r+19,!0)/16384)),o.accel.x=Math.max(-1,Math.min(1,i.getInt16(r+21,!0)/8192)),o.accel.y=Math.max(-1,Math.min(1,i.getInt16(r+23,!0)/8192)),o.accel.z=Math.max(-1,Math.min(1,i.getInt16(r+25,!0)/8192)));let y=(g,v)=>{if(i.byteLength<=g+3)return;let f=(i.getUint8(g)&128)===0;if(v.active=f,f){let x=i.getUint8(g+1),M=i.getUint8(g+2),A=i.getUint8(g+3),m=x|(M&15)<<8,S=(M&240)>>4|A<<4;v.x=Math.max(0,Math.min(1,m/1919)),v.y=Math.max(0,Math.min(1,S/1079))}};if(y(r+32,o.touch),y(r+36,o.touch2),i.byteLength>r+52){let g=i.getUint8(r+52),v=g&15,T=g>>4&15;o.battery.charging=T===1,o.battery.full=T===2,o.battery.percent=T===2?100:Math.min(100,Math.round((v+.5)/10*100)),o.battery.known=!0}}populateGamepadInput(e,t){let n=r=>Math.max(-1,Math.min(1,Number.isFinite(r)?r:0)),i=ne(e.id||"");return t.connected=!0,t.source="gamepad",t.deviceName=i.displayName,t.isDualSense=i.model==="dualsense"||i.model==="dualsense_edge",t.identity={...i,transport:"unknown",source:"gamepad"},t.lx=n(e.axes[0]??0),t.ly=n(e.axes[1]??0),t.rx=n(e.axes[2]??0),t.ry=n(e.axes[3]??0),t.l2=Math.max(0,Math.min(1,e.buttons[6]?.value??0)),t.r2=Math.max(0,Math.min(1,e.buttons[7]?.value??0)),t.buttons.cross=!!e.buttons[0]?.pressed,t.buttons.circle=!!e.buttons[1]?.pressed,t.buttons.square=!!e.buttons[2]?.pressed,t.buttons.triangle=!!e.buttons[3]?.pressed,t.buttons.l1=!!e.buttons[4]?.pressed,t.buttons.r1=!!e.buttons[5]?.pressed,t.buttons.l2Btn=!!e.buttons[6]?.pressed,t.buttons.r2Btn=!!e.buttons[7]?.pressed,t.buttons.create=!!e.buttons[8]?.pressed,t.buttons.options=!!e.buttons[9]?.pressed,t.buttons.l3=!!e.buttons[10]?.pressed,t.buttons.r3=!!e.buttons[11]?.pressed,t.buttons.up=!!e.buttons[12]?.pressed,t.buttons.down=!!e.buttons[13]?.pressed,t.buttons.left=!!e.buttons[14]?.pressed,t.buttons.right=!!e.buttons[15]?.pressed,t.buttons.ps=!!e.buttons[16]?.pressed,t.buttons.touchpadClick=!!e.buttons[17]?.pressed,t.touch.active=!1,t.touch2.active=!1,t.battery.known=!1,t.observedReportHz=null,t}getInputStateForSlot(e){let t=this.getHidSessionForSlot(e);if(t)return t.input;let n=this.getGamepadForSlot(e);if(n){let i=this.gamepadInputs.get(n.index);return i||(i=N(),this.gamepadInputs.set(n.index,i)),this.populateGamepadInput(n,i)}return N()}getInputState(e){if(e!==void 0)return this.getInputStateForSlot(e);let t=this.getActiveHidSession();if(t)return t.input;let n=this.getActiveGamepad();if(n)return this.populateGamepadInput(n,this.fallbackInput);let i=this.keysDown,r=(i.has("KeyD")||i.has("ArrowRight")?1:0)-(i.has("KeyA")||i.has("ArrowLeft")?1:0),o=(i.has("KeyS")||i.has("ArrowDown")?1:0)-(i.has("KeyW")||i.has("ArrowUp")?1:0),s=this.fallbackInput;return s.connected=!1,s.source="keyboard_mouse",s.deviceName="Keyboard & Mouse",s.isDualSense=!1,s.identity={brand:"none",model:"none",displayName:"Keyboard & Mouse",rawId:"",transport:"disconnected",source:"keyboard_mouse"},s.lx=r,s.ly=o,s.rx=0,s.ry=0,s.l2=i.has("ShiftLeft")||i.has("KeyQ")?1:0,s.r2=i.has("Space")||i.has("KeyE")?1:0,s.buttons.cross=i.has("Space")||i.has("Enter"),s.buttons.circle=i.has("KeyC")||i.has("Escape"),s.buttons.square=i.has("KeyR"),s.buttons.triangle=i.has("KeyF"),s.buttons.l1=i.has("KeyQ"),s.buttons.r1=i.has("KeyE"),s.buttons.l2Btn=s.l2>.5,s.buttons.r2Btn=s.r2>.5,s.buttons.l3=!1,s.buttons.r3=!1,s.buttons.up=i.has("ArrowUp")||i.has("KeyW"),s.buttons.down=i.has("ArrowDown")||i.has("KeyS"),s.buttons.left=i.has("ArrowLeft")||i.has("KeyA"),s.buttons.right=i.has("ArrowRight")||i.has("KeyD"),s.buttons.create=!1,s.buttons.options=!1,s.buttons.ps=!1,s.buttons.touchpadClick=!1,s.touch.active=!1,s.touch2.active=!1,s.battery.known=!1,s.observedReportHz=null,s}getCapabilityMatrixForSlot(e,t={}){let n=this.getInputState(e),i=n.identity,r=this.getHidSessionForSlot(e),o=r?.kind==="dualsense",s=r?.kind==="switch_pro",c=!!r,l=r?.transport??"unknown",u=a.isWebHIDSupported(),d=i.model==="dualsense"||i.model==="dualsense_edge",h=i.brand==="xbox",w=i.model==="switch_pro",y=i.brand==="nintendo",g=n.connected,v=this.hasTriggerRumbleSupport(e),T=this.hasDualRumbleSupport(e);if(!g){let f={inherent:!1,availability:"disconnected"};return{standard_input:f,analog_triggers:f,dual_motor_rumble:f,impulse_triggers:f,hd_rumble:f,adaptive_triggers:f,audio_haptics:f,controller_speaker:f,gyro:f,accelerometer:f,touchpad:f,lightbar:f,battery:f}}return{standard_input:{inherent:!0,availability:"ready"},analog_triggers:{inherent:!y,availability:y?"unsupported":"ready",reason:y?"Nintendo Pro/Joy-Con triggers are digital buttons":void 0},dual_motor_rumble:{inherent:!0,availability:c||T?"ready":"unsupported",reason:!c&&!T?"Browser Gamepad rumble actuator not exposed":void 0},impulse_triggers:{inherent:h,availability:h&&v?"ready":"unsupported",reason:h&&!v?"Requires Chrome/Edge 126+ with USB or Xbox Wireless Adapter (Windows Bluetooth often blocks trigger motors)":void 0},hd_rumble:{inherent:y,availability:y?s?"ready":w?u?"permission_required":"unsupported":"bridge_required":"unsupported",reason:w&&!s?u?"Connect Switch Pro via WebHID to unlock dual-band HD Rumble and 6-axis gyro":"WebHID requires desktop Chrome or Edge":void 0},adaptive_triggers:{inherent:d,availability:d?o?"ready":u?"permission_required":"unsupported":"unsupported",reason:d&&!o?u?"Click Unlock DualSense WebHID (works over USB & Bluetooth)":"WebHID requires desktop Chrome or Edge":void 0},audio_haptics:{inherent:d,availability:d?t.has4ChAudio?"ready":l==="bluetooth"?"configuration_required":"bridge_required":"unsupported",reason:d&&!t.has4ChAudio?l==="bluetooth"?"4-channel audio haptics require a wired USB-C connection on Windows":"Optional Gamepadly Link or USB 4ch audio routing required":void 0},controller_speaker:{inherent:d,availability:d?t.hasControllerSpeaker?"ready":l==="bluetooth"?"configuration_required":"bridge_required":"unsupported",reason:d&&!t.hasControllerSpeaker?"Requires wired USB-C DualSense audio output":void 0},gyro:{inherent:d||y,availability:d?o?"ready":u?"permission_required":"unsupported":w?s?"ready":u?"permission_required":"unsupported":y?"bridge_required":"unsupported"},accelerometer:{inherent:d||y,availability:d?o?"ready":u?"permission_required":"unsupported":w?s?"ready":u?"permission_required":"unsupported":y?"bridge_required":"unsupported"},touchpad:{inherent:d||i.model==="dualshock4",availability:d?o?"ready":u?"permission_required":"unsupported":"unsupported"},lightbar:{inherent:d||i.model==="dualshock4",availability:d?o?"ready":u?"permission_required":"unsupported":"unsupported"},battery:{inherent:!0,availability:d&&o||w&&s?"ready":"unknown"}}}getCapabilityMatrix(e={}){return this.getCapabilityMatrixForSlot(void 0,e)}async playSwitchHdRumble(e,t){let n=this.getHidSessionForSlot(t);if(!n||n.kind!=="switch_pro"||!n.device.opened)return!1;this.clearSwitchRumbleTimers(n);let i=U(e.left),r=U(e.right),o=Math.max(30,Math.min(2500,Math.round(e.durationMs??220)));try{await this.sendSwitchRumbleBytes(n,i,r)}catch{return!1}return n.switchRumbleTimer=setTimeout(()=>{n.switchRumbleTimer=null,this.sendSwitchRumbleBytes(n,q,q).catch(()=>{})},o),!0}async playSwitchHdRumbleSequence(e,t){let n=this.getHidSessionForSlot(t);if(!n||n.kind!=="switch_pro"||!n.device.opened||e.length===0)return!1;this.clearSwitchRumbleTimers(n);let i=0;for(let r of e){let o=Math.max(0,Math.round(r.delayMs)),s=Math.max(30,Math.min(1200,Math.round(r.durationMs??80)));o+s>i&&(i=o+s);let c=U(r.left),l=U(r.right);if(o===0)await this.sendSwitchRumbleBytes(n,c,l).catch(()=>{});else{let u=setTimeout(()=>{this.sendSwitchRumbleBytes(n,c,l).catch(()=>{})},o);n.switchSeqTimers.push(u)}}return n.switchRumbleTimer=setTimeout(()=>{n.switchRumbleTimer=null,n.switchSeqTimers=[],this.sendSwitchRumbleBytes(n,q,q).catch(()=>{})},i+15),!0}stopSwitchHdRumble(e){if(e!==void 0){let t=this.getHidSessionForSlot(e);t&&t.kind==="switch_pro"&&t.device.opened&&(this.clearSwitchRumbleTimers(t),this.sendSwitchRumbleBytes(t,q,q).catch(()=>{}));return}for(let t of this.hidSessions.values())t.kind!=="switch_pro"||!t.device.opened||(this.clearSwitchRumbleTimers(t),this.sendSwitchRumbleBytes(t,q,q).catch(()=>{}))}async playTriggerRumble(e,t,n,i=0,r=0,o){if(this.getHidSessionForSlot(o)?.kind==="switch_pro"){let T=Math.max(e,r),f=Math.max(t,i);return this.playSwitchHdRumble({left:T>.02?{highFreqHz:260,highAmp:T*.65,lowFreqHz:145,lowAmp:T*.7}:void 0,right:f>.02?{highFreqHz:340,highAmp:f*.7,lowFreqHz:170,lowAmp:f*.55}:void 0,durationMs:n},o)}let l=this.getGamepadForSlot(o)?.vibrationActuator;if(!l?.playEffect)return!1;let u=Math.max(20,Math.min(2500,Math.round(n))),d=Math.max(0,Math.min(1,e)),h=Math.max(0,Math.min(1,t)),w=Math.max(0,Math.min(1,i)),y=Math.max(0,Math.min(1,r));if(this.hasTriggerRumbleSupport(o))try{return await l.playEffect("trigger-rumble",{startDelay:0,duration:u,leftTrigger:d,rightTrigger:h,weakMagnitude:w,strongMagnitude:y}),!0}catch{}let g=Math.max(w,h*.65),v=Math.max(y,d*.65);return g>0||v>0?this.playDualRumble(g,v,u,o):!1}async playDualRumble(e,t,n,i){if(this.getHidSessionForSlot(i)?.kind==="switch_pro"){let c={highFreqHz:320,highAmp:Math.max(0,Math.min(.85,e*.8)),lowFreqHz:150,lowAmp:Math.max(0,Math.min(.85,t*.8))};return this.playSwitchHdRumble({left:c,right:c,durationMs:n},i)}let s=this.getGamepadForSlot(i)?.vibrationActuator;if(!s?.playEffect)return!1;try{return await s.playEffect("dual-rumble",{startDelay:0,duration:Math.max(20,Math.min(2500,Math.round(n))),strongMagnitude:Math.max(0,Math.min(1,t)),weakMagnitude:Math.max(0,Math.min(1,e))}),!0}catch{return!1}}stopGamepadRumble(e){if(this.stopSwitchHdRumble(e),!!a.isGamepadSupported()){if(e!==void 0){let t=this.getGamepadForSlot(e);t?.vibrationActuator?.reset&&t.vibrationActuator.reset().catch(()=>{});return}for(let t of this.getAllRawGamepads()){let n=t.vibrationActuator;n?.reset&&n.reset().catch(()=>{})}}}triggerGamepadRumbleFallback(e,t,n,i){let r=this.getHidSessionForSlot(i);if(r?.kind==="switch_pro"){this.playDualRumble(e,t,n,i);return}if(r?.kind==="dualsense"){this.pulseLegacyRumble(Math.round(Math.max(0,Math.min(1,t))*220),Math.round(Math.max(0,Math.min(1,e))*220),Math.max(25,Math.min(350,n)),i);return}this.playDualRumble(e,t,n,i)}buildCommonPayload(e,{includeAudioConfig:t=!1,includeTriggers:n=!1,includeLeds:i=!1}={}){let r=new Uint8Array(47),o=0,s=0;return e.legacyRumbleActive&&(o|=3,r[2]=Math.max(0,Math.min(255,Math.round(e.legacyRight))),r[3]=Math.max(0,Math.min(255,Math.round(e.legacyLeft)))),n&&(o|=12,r.set(e.rightTrigger.subarray(0,11),10),r.set(e.leftTrigger.subarray(0,11),21)),t&&(o|=176,s|=130,r[4]=Math.max(0,Math.min(127,e.headphoneVolume)),r[5]=Math.max(0,Math.min(255,e.speakerVolume)),r[6]=0,r[7]=e.audioRoute==="speaker"?48:e.audioRoute==="both"?32:0,r[9]=0,r[37]=e.speakerPreamp&7),i&&(s|=21,r[8]=e.muteLed==="on"?1:e.muteLed==="pulse"?2:0,r[38]=2,r[41]=2,r[42]=0,r[43]=e.playerLeds&31,r[44]=e.lightbar[0]&255,r[45]=e.lightbar[1]&255,r[46]=e.lightbar[2]&255),r[0]=o,r[1]=s,r}async flushSessionOutput(e,t={}){if(e.kind!=="dualsense"||!e.device.opened)return!1;let n=this.buildCommonPayload(e.outState,t);if(e.transport==="bluetooth"){let r=new Uint8Array(e.btPayloadLength);r[0]=(e.btSeq&15)<<4,e.btSeq=e.btSeq+1&15,r[1]=16,r.set(n,2);let o=r.length-4,s=Se(162,49,r.subarray(0,o));return new DataView(r.buffer).setUint32(o,s,!0),await e.device.sendReport(49,r),!0}let i=new Uint8Array(e.usbPayloadLength);return i.set(n,0),await e.device.sendReport(2,i),!0}async flushOutput(e={}){let t=this.getActiveHidSession();return!t||t.kind!=="dualsense"?!1:this.flushSessionOutput(t,e)}async setAudioConfig(e){let t=this.getActiveHidSession();return!t||t.kind!=="dualsense"?!1:(e.speakerVolume!==void 0&&(t.outState.speakerVolume=e.speakerVolume),e.headphoneVolume!==void 0&&(t.outState.headphoneVolume=e.headphoneVolume),e.audioRoute!==void 0&&(t.outState.audioRoute=e.audioRoute),e.speakerPreamp!==void 0&&(t.outState.speakerPreamp=e.speakerPreamp),this.flushSessionOutput(t,{includeAudioConfig:!0}))}async setTriggers(e,t,n){let i=this.getHidSessionForSlot(n);if(!i||i.kind!=="dualsense")return!1;let r=i.outState.leftTrigger,o=i.outState.rightTrigger,s=e?z(e):void 0,c=t?z(t):void 0;s&&(i.outState.leftTrigger=s),c&&(i.outState.rightTrigger=c);try{let l=await this.flushSessionOutput(i,{includeTriggers:!0});return l||(s&&i.outState.leftTrigger===s&&(i.outState.leftTrigger=r),c&&i.outState.rightTrigger===c&&(i.outState.rightTrigger=o)),l}catch(l){throw s&&i.outState.leftTrigger===s&&(i.outState.leftTrigger=r),c&&i.outState.rightTrigger===c&&(i.outState.rightTrigger=o),l}}async resetTriggers(e){if(this.stopGamepadRumble(e),e!==void 0){let n=this.getHidSessionForSlot(e);return!n||!n.device.opened||n.kind!=="dualsense"?!1:(n.outState.leftTrigger=z({type:"off"}),n.outState.rightTrigger=z({type:"off"}),this.flushSessionOutput(n,{includeTriggers:!0}).catch(()=>!1))}let t=!1;for(let n of this.hidSessions.values()){if(!n.device.opened||n.kind!=="dualsense")continue;n.outState.leftTrigger=z({type:"off"}),n.outState.rightTrigger=z({type:"off"}),await this.flushSessionOutput(n,{includeTriggers:!0}).catch(()=>!1)&&(t=!0)}return t}emergencyReset(){this.stopGamepadRumble();for(let e of this.hidSessions.values())if(e.device.opened){if(e.kind==="switch_pro"){this.clearSwitchRumbleTimers(e),this.sendSwitchRumbleBytes(e,q,q).catch(()=>{});continue}e.outState.leftTrigger=z({type:"off"}),e.outState.rightTrigger=z({type:"off"}),e.outState.legacyRumbleActive=!1,e.outState.legacyLeft=0,e.outState.legacyRight=0,e.outState.lightbar=[23,23,23],e.outState.muteLed="off",this.flushSessionOutput(e,{includeTriggers:!0,includeLeds:!0}).catch(()=>{})}}async setLightbar(e,t,n,i){let r=this.getHidSessionForSlot(i);return!r||r.kind!=="dualsense"?!1:(r.outState.lightbar=[e&255,t&255,n&255],this.flushSessionOutput(r,{includeLeds:!0}))}async setPlayerLeds(e,t){let n=this.getHidSessionForSlot(t);return!n||!n.device.opened?!1:n.kind==="switch_pro"?(await this.sendSwitchSubcommand(n,48,[e&15]),!0):(n.outState.playerLeds=e&31,this.flushSessionOutput(n,{includeLeds:!0}))}async setMuteLed(e,t){let n=this.getHidSessionForSlot(t);return!n||n.kind!=="dualsense"?!1:(n.outState.muteLed=e,this.flushSessionOutput(n,{includeLeds:!0}))}async pulseLegacyRumble(e=200,t=200,n=250,i){let r=this.getHidSessionForSlot(i);return!r||r.kind!=="dualsense"||!r.device.opened?!1:(r.legacyTimer&&(clearTimeout(r.legacyTimer),r.legacyTimer=null),r.outState.legacyRumbleActive=!0,r.outState.legacyLeft=e,r.outState.legacyRight=t,await this.flushSessionOutput(r,{}),new Promise(o=>{r.legacyTimer=setTimeout(async()=>{r.legacyTimer=null;try{r.outState.legacyLeft=0,r.outState.legacyRight=0,await this.flushSessionOutput(r,{}),r.outState.legacyRumbleActive=!1,await this.flushSessionOutput(r,{includeAudioConfig:!0})}catch{}o(!0)},n)}))}};var K={off:{type:"off"},weapon:{type:"weapon",startZone:2,endZone:5,strength:7},heavy_weapon:{type:"weapon",startZone:3,endZone:6,strength:8},bow:{type:"slope",startZone:1,endZone:8,startStrength:1,endStrength:7},abs:{type:"vibration",startZone:2,amplitude:6,frequencyHz:22},soft_wall:{type:"feedback",startZone:4,strength:4},rapid_pulse:{type:"vibration",startZone:1,amplitude:7,frequencyHz:14},precision_damp:{type:"feedback",startZone:2,strength:3}},ie={click:{freqHz:210,endFreqHz:140,durationMs:26,intensity:.45,wave:"triangle",triggerEmphasis:.65,switchHd:{highFreqHz:340,lowFreqHz:165,highWeight:.75,lowWeight:.25}},ratchet:{freqHz:180,endFreqHz:110,durationMs:22,intensity:.5,wave:"triangle",triggerEmphasis:.75,switchHd:{highFreqHz:320,lowFreqHz:155,highWeight:.8,lowWeight:.2}},wall_hit:{freqHz:135,endFreqHz:58,durationMs:65,intensity:.78,wave:"triangle",triggerEmphasis:.5,switchHd:{highFreqHz:290,lowFreqHz:130,highWeight:.55,lowWeight:.75}},marble_click:{freqHz:290,endFreqHz:210,durationMs:32,intensity:.62,wave:"sine",triggerEmphasis:.85,switchHd:{highFreqHz:380,lowFreqHz:190,highWeight:.85,lowWeight:.18}},recoil:{freqHz:115,endFreqHz:46,durationMs:75,intensity:.88,wave:"triangle",triggerEmphasis:1,switchHd:{highFreqHz:310,lowFreqHz:120,highWeight:.65,lowWeight:.85}},heavy_impact:{freqHz:75,endFreqHz:34,durationMs:140,intensity:.95,wave:"sine",triggerEmphasis:.7,switchHd:{highFreqHz:220,lowFreqHz:95,highWeight:.45,lowWeight:.95}},lock_unlock:{freqHz:95,endFreqHz:220,durationMs:120,intensity:.72,wave:"triangle",triggerEmphasis:.6,switchHd:{highFreqHz:350,lowFreqHz:150,highWeight:.7,lowWeight:.55}},splash:{freqHz:90,endFreqHz:48,durationMs:110,intensity:.6,wave:"sine",triggerEmphasis:.35,switchHd:{highFreqHz:250,lowFreqHz:120,highWeight:.5,lowWeight:.6}},boost:{freqHz:65,endFreqHz:165,durationMs:160,intensity:.75,wave:"sawtooth",triggerEmphasis:.85,switchHd:{highFreqHz:300,lowFreqHz:135,highWeight:.6,lowWeight:.75}},error_buzz:{freqHz:145,endFreqHz:115,durationMs:95,intensity:.65,wave:"square",triggerEmphasis:.45,switchHd:{highFreqHz:260,lowFreqHz:125,highWeight:.55,lowWeight:.65}}};function V(a){let e=Math.max(-1,Math.min(1,a.pan??0)),t=Math.max(0,Math.min(1,a.intensity)),n=Math.min(1,1-Math.max(0,e)),i=Math.min(1,1+Math.min(0,e)),r=a.highFreqHz??Math.max(160,Math.min(620,a.freqHz*1.9)),o=a.lowFreqHz??Math.max(60,Math.min(240,a.freqHz)),s=a.highWeight??(a.freqHz>=140?.78:.42),c=a.lowWeight??(a.freqHz<140?.82:.38),l=u=>{let d=t*u;if(!(d<.02))return{highFreqHz:r,highAmp:Math.min(.85,d*s*.85),lowFreqHz:o,lowAmp:Math.min(.85,d*c*.85)}};return{left:l(n),right:l(i),durationMs:Math.max(30,Math.min(2500,Math.round(a.durationMs)))}}function re(a){return a.allow4ChAudio===!1?!1:!!(a.audio&&a.audio.dsMode!=="none"&&a.audio.dsMaxChannelCount>=4)}function j(a,e){if(re(a)){a.audio.playHapticPulse(e);return}let t=a.hid.getCapabilityMatrixForSlot(a.slotId),n=Math.max(0,Math.min(1,e.intensity)),i=Math.max(25,Math.min(2500,Math.round(e.durationMs))),r=Math.max(-1,Math.min(1,e.pan??0));if(t.hd_rumble?.availability==="ready"){let c=V({pan:r,freqHz:e.freqHz,intensity:n,durationMs:i});a.hid.playSwitchHdRumble(c,a.slotId);return}if(t.impulse_triggers?.availability==="ready"){let c=Math.min(1,1-Math.max(0,r)),l=Math.min(1,1+Math.min(0,r)),u=e.freqHz>=120?.85:.45,d=e.freqHz<120?.78:.35;a.hid.playTriggerRumble(n*c*u,n*l*u,i,n*(e.freqHz>=120?.65:.35),n*d,a.slotId);return}let o=e.freqHz<120?n*.8:n*.3,s=e.freqHz>=120?n*.85:n*.4;a.hid.triggerGamepadRumbleFallback(s,o,i,a.slotId)}function ae(a,e){if(re(a)){a.audio.playHapticSweep(e);return}let t=a.hid.getCapabilityMatrixForSlot(a.slotId),n=Math.max(0,Math.min(1,e.intensity)),i=Math.max(40,Math.min(2500,Math.round(e.durationMs)));if(t.hd_rumble?.availability==="ready"){let r=Math.max(2,Math.min(6,Math.round(i/55))),o=Math.max(30,Math.round(i/r)),s=[];for(let c=0;c<r;c++){let l=r===1?0:c/(r-1),u=e.fromPan+(e.toPan-e.fromPan)*l,d=e.fromHz+(e.toHz-e.fromHz)*l;s.push({...V({pan:u,freqHz:d,intensity:n,durationMs:o}),delayMs:c*o})}a.hid.playSwitchHdRumbleSequence(s,a.slotId);return}if(t.impulse_triggers?.availability==="ready"){let r=(e.fromPan+e.toPan)*.5,o=Math.min(1,1-Math.max(0,r)),s=Math.min(1,1+Math.min(0,r));a.hid.playTriggerRumble(n*o*.7,n*s*.7,i,n*.5,n*.6,a.slotId);return}a.hid.triggerGamepadRumbleFallback(n*.55,n*.65,i,a.slotId)}function oe(a,e,t={}){let n=ie[e];if(!n)return;let i=Math.max(-1,Math.min(1,t.pan??0)),r=Math.max(0,Math.min(1,(t.intensity??1)*n.intensity));if(re(a)){a.audio.playHapticPulse({pan:i,freqHz:n.freqHz,endFreqHz:n.endFreqHz,durationMs:n.durationMs,intensity:r,wave:n.wave});return}let o=a.hid.getCapabilityMatrixForSlot(a.slotId);if(o.hd_rumble?.availability==="ready"&&n.switchHd){let s=V({pan:i,freqHz:n.freqHz,intensity:r,durationMs:n.durationMs,highFreqHz:n.switchHd.highFreqHz,lowFreqHz:n.switchHd.lowFreqHz,highWeight:n.switchHd.highWeight,lowWeight:n.switchHd.lowWeight});a.hid.playSwitchHdRumble(s,a.slotId);return}if(o.impulse_triggers?.availability==="ready"&&n.triggerEmphasis){let s=Math.min(1,1-Math.max(0,i)),c=Math.min(1,1+Math.min(0,i)),l=r*n.triggerEmphasis;a.hid.playTriggerRumble(l*s,l*c,Math.max(30,n.durationMs),r*.45,r*.55,a.slotId);return}j(a,{pan:i,freqHz:n.freqHz,endFreqHz:n.endFreqHz,durationMs:n.durationMs,intensity:r,wave:n.wave})}var Te=new Set(["cross","circle","square","triangle","l1","r1","l2Btn","r2Btn","l3","r3","up","down","left","right","create","options","ps","touchpadClick"]),se=new Set(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab"]);function ke(a){if(!a||typeof a!="object")return!1;let e=a;if(e.isContentEditable)return!0;let t=(e.tagName||"").toUpperCase();return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Ae(a,e,t,n,i){let r=e.source!=="keyboard_mouse";return a==="l2"?r?e.l2:0:a==="r2"?r?e.r2:0:a==="lx+"?r?Math.max(0,e.lx):0:a==="lx-"?r?Math.max(0,-e.lx):0:a==="ly+"?r?Math.max(0,e.ly):0:a==="ly-"?r?Math.max(0,-e.ly):0:a==="rx+"?r?Math.max(0,e.rx):0:a==="rx-"?r?Math.max(0,-e.rx):0:a==="ry+"?r?Math.max(0,e.ry):0:a==="ry-"?r?Math.max(0,-e.ry):0:Te.has(a)?r&&e.buttons[a]?1:0:a==="MouseLeft"||a==="MouseRight"||a==="MouseMiddle"?n.has(a)?1:0:t.has(a)?Math.max(1,i):0}function ce(a){let e=a.analogThreshold??.45,t=a.actions??{},n=a.axes??{},i=a.preventDefaultKeys!==!1,r=new Set;for(let m of Object.values(t))for(let S of m)se.has(S)&&r.add(S);for(let m of Object.values(n)){for(let S of m.negativeKeys??[])se.has(S)&&r.add(S);for(let S of m.positiveKeys??[])se.has(S)&&r.add(S)}let o=new Set,s=new Set,c=new Set,l=new Set,u=new Map,d=new Map,h=new Map;for(let m of Object.keys(t))u.set(m,{pressed:!1,justPressed:!1,justReleased:!1,heldMs:0,value:0});for(let m of Object.keys(n))h.set(m,0);let w=m=>m===0?"MouseLeft":m===1?"MouseMiddle":m===2?"MouseRight":null,y=m=>{let S=m;S.code&&(i&&r.has(S.code)&&!S.ctrlKey&&!S.metaKey&&!S.altKey&&!ke(S.target)&&S.preventDefault(),o.has(S.code)||s.add(S.code),o.add(S.code))},g=m=>{let S=m;S.code&&o.delete(S.code)},v=m=>{let p=w(m.button);p&&(c.has(p)||l.add(p),c.add(p))},T=m=>{let p=w(m.button);p&&c.delete(p)},f=()=>{o.clear(),s.clear(),c.clear(),l.clear()},x=a.attachWindowListeners!==!1&&typeof window<"u",M=a.mouseTarget??(typeof window<"u"?window:void 0);x&&(window.addEventListener("keydown",y),window.addEventListener("keyup",g),window.addEventListener("blur",f),M?.addEventListener("pointerdown",v),window.addEventListener("pointerup",T));let A={pressed:!1,justPressed:!1,justReleased:!1,heldMs:0,value:0};return{update(m,S=typeof performance<"u"?performance.now():Date.now()){let p=s.size>0?new Set([...o,...s]):o,b=l.size>0?new Set([...c,...l]):c;s.clear(),l.clear();for(let[k,P]of Object.entries(t)){let I=0;for(let E of P){let G=Ae(E,m,p,b,e);G>I&&(I=G)}let H=I>=e,R=u.get(k),B=H&&!R.pressed,D=!H&&R.pressed;B?d.set(k,S):H||d.delete(k);let L=d.get(k);R.pressed=H,R.justPressed=B,R.justReleased=D,R.heldMs=H&&L!==void 0?Math.max(0,S-L):0,R.value=Math.max(0,Math.min(1,I))}let C=m.source!=="keyboard_mouse";for(let[k,P]of Object.entries(n)){let I=0;if(P.stick&&C){let D=m[P.stick],L=P.deadzone??.08;I=F(D,L)}let H=0;C&&P.negativeButtons?.some(D=>m.buttons[D])&&(H-=1),C&&P.positiveButtons?.some(D=>m.buttons[D])&&(H+=1),P.negativeKeys?.some(D=>p.has(D))&&(H-=1),P.positiveKeys?.some(D=>p.has(D))&&(H+=1);let R=Math.abs(H)>Math.abs(I)?H:I,B=Math.max(-1,Math.min(1,R));h.set(k,P.invert?-B:B)}},action(m){return u.get(m)??A},isPressed(m){return u.get(m)?.pressed??!1},justPressed(m){return u.get(m)?.justPressed??!1},justReleased(m){return u.get(m)?.justReleased??!1},axis(m){return h.get(m)??0},setKeyDown(m,S){S?(o.has(m)||s.add(m),o.add(m)):o.delete(m)},setMouseButton(m,S){S?(c.has(m)||l.add(m),c.add(m)):c.delete(m)},dispose(){x&&(window.removeEventListener("keydown",y),window.removeEventListener("keyup",g),window.removeEventListener("blur",f),M?.removeEventListener("pointerdown",v),window.removeEventListener("pointerup",T)),o.clear(),s.clear(),c.clear(),l.clear(),d.clear()}}}var Pe={update(){},stop(){}};function le(a,e,t,n){let i=n&&!!(e&&e.dsMode!=="none"&&e.dsMaxChannelCount>=4),r=n&&!!(e&&e.dsMode!=="none"),o=a.getInputState(t),s=a.getCapabilityMatrixForSlot(t,{has4ChAudio:i,hasControllerSpeaker:r}),c=u=>s[u]?.availability==="ready",l="keyboard_mouse";return c("adaptive_triggers")&&i?l="dualsense_full_4ch":c("adaptive_triggers")?l="dualsense_hid_only":c("hd_rumble")?l="switch_pro_hid":c("impulse_triggers")?l="xbox_impulse":o.source==="gamepad"&&(l="standard_gamepad"),{slotId:t??a.getActiveSlotId(),tier:l,identity:o.identity,matrix:s,has:c,hasAdaptiveTriggers:c("adaptive_triggers"),hasImpulseTriggers:c("impulse_triggers"),hasHdRumble:c("hd_rumble"),hasDualRumble:c("dual_motor_rumble"),has4ChHaptics:i,hasControllerSpeaker:r,hasGyro:c("gyro"),hasTouchpad:c("touchpad")}}function ve(a,e){return[a.map(n=>`${n.id}:${n.source}:${n.identity.model}:${n.identity.transport}`).join(","),e.slotId??"",e.tier,e.hasAdaptiveTriggers?1:0,e.hasImpulseTriggers?1:0,e.hasHdRumble?1:0,e.has4ChHaptics?1:0,e.hasControllerSpeaker?1:0,e.hasGyro?1:0].join("|")}function Ie(a={}){let e=!a.hid,t=a.hid??new O,n=a.audio??null,i=!1,r=new Set,o=new Set,s=new Set,c=new Set;a.autoHotplug!==!1&&t.attachHidHotplug(),a.attachKeyboardFallback&&e&&t.attachKeyboardFallback();let l="",u=()=>{if(i)return;let f=t.getConnectedControllers(),x=le(t,n,void 0,!0),M=ve(f,x);if(M!==l){l=M;for(let A of c)try{A({slots:f,active:x})}catch{}}};l=ve(t.getConnectedControllers(),le(t,n,void 0,!0));let d=t.onStatusChange(()=>{u()}),h=()=>u(),w=()=>t.emergencyReset();typeof window<"u"&&(a.autoHotplug!==!1&&(window.addEventListener("gamepadconnected",h),window.addEventListener("gamepaddisconnected",h)),a.autoEmergencyReset!==!1&&(window.addEventListener("pagehide",w),window.addEventListener("beforeunload",w)));let y=null,g=a.capabilityPollMs??250;g>0&&typeof setInterval<"u"&&(y=setInterval(u,g));let v=f=>{let x=[23,23,23],M=0,A=null,m=()=>{if(f==="active")return{slotId:void 0,connected:!0,isPrimary:!0};if(typeof f=="number"){let C=t.getConnectedControllers()[f];if(!C)return{slotId:`__unassigned_${f}`,connected:!1,isPrimary:f===0};let k=t.getActiveSlotId();return{slotId:C.id,connected:!0,isPrimary:C.id===k||f===0}}let p=t.getActiveSlotId();return{slotId:f,connected:!0,isPrimary:f===p}},S=()=>{let p=m();return{hid:t,audio:n,slotId:p.slotId,allow4ChAudio:p.isPrimary}};return{getSlotId(){let p=m();return p.slotId===void 0?t.getActiveSlotId():p.connected?p.slotId:null},getCapabilities(){let p=m();return le(t,n,p.slotId,p.isPrimary)},input:{getState:()=>{let p=m();return t.getInputState(p.slotId)},applyDeadzone:F},triggers:{reset:()=>{if(i)return;let p=m();t.resetTriggers(p.slotId).catch(()=>{})},setLeft:p=>{if(i)return;let b=m();t.setTriggers(p,void 0,b.slotId).catch(()=>{})},setRight:p=>{if(i)return;let b=m();t.setTriggers(void 0,p,b.slotId).catch(()=>{})},setBoth:(p,b)=>{if(i)return;let C=m();t.setTriggers(p,b,C.slotId).catch(()=>{})},applyPreset:(p,b="both")=>{if(i)return;let C=K[p];if(!C)return;let k=m();b==="left"?t.setTriggers(C,void 0,k.slotId).catch(()=>{}):b==="right"?t.setTriggers(void 0,C,k.slotId).catch(()=>{}):t.setTriggers(C,C,k.slotId).catch(()=>{})},pulseImpulse:p=>{if(i)return;let b=m();t.playTriggerRumble(p.left??0,p.right??0,p.durationMs??80,p.weakGrip??0,p.strongGrip??0,b.slotId)}},haptics:{pulse:p=>{i||j(S(),p)},sweep:p=>{i||ae(S(),p)},rumble:p=>{if(i)return;let b=m();t.triggerGamepadRumbleFallback(p.weak,p.strong,p.durationMs,b.slotId)},hdRumble:p=>{if(i)return;let b=m();t.playSwitchHdRumble(p,b.slotId)},hdSequence:p=>{if(i)return;let b=m();t.playSwitchHdRumbleSequence(p,b.slotId)},playPreset:(p,b)=>{i||oe(S(),p,b)},createContinuous:p=>{if(i||!n)return Pe;let b=n.createContinuous(p);return r.add(b),{update:C=>{i||b.update(C)},stop:()=>{r.delete(b),b.stop()}}},playComboPreset:(p,b=0)=>{if(i)return;let C=m();if(n?.playComboPreset(p,b),!n||!C.isPrimary||n.dsMode==="none"||n.dsMaxChannelCount<4){let k=p==="shotgun"||p==="thunder"?.85:.4,P=p==="ratchet_tick"?30:120;j(S(),{pan:b,freqHz:p==="ratchet_tick"?190:95,durationMs:P,intensity:k})}},stop:()=>{let p=m();t.stopGamepadRumble(p.slotId)}},audio:{playPcTone:p=>{i||n?.playPcTone(p)},playPcNoise:p=>{i||n?.playPcNoiseBurst(p)},playControllerSpeakerTone:p=>{i||n?.playControllerSpeakerTone(p)}},lightbar:{setColor:(p,b,C)=>{if(i)return;let k=typeof performance<"u"?performance.now():Date.now();if(x[0]===p&&x[1]===b&&x[2]===C)return;if(A!==null){x=[p,b,C];return}if(k-M<30)return;M=k,x=[p,b,C];let P=m();t.setLightbar(p,b,C,P.slotId).catch(()=>{})},flash:(p,b,C,k=240)=>{if(i)return;A!==null&&(clearTimeout(A),o.delete(A),A=null);let P=m();t.setLightbar(p,b,C,P.slotId).catch(()=>{});let I=setTimeout(()=>{if(o.delete(I),A===I&&(A=null),!i){let H=x;t.setLightbar(H[0],H[1],H[2],P.slotId).catch(()=>{})}},k);A=I,o.add(I)}},createActions(p){let b=ce(p);return s.add(b),{...b,dispose(){s.delete(b),b.dispose()}}}}},T=v("active");return{hid:t,async connectWebHID(){let f=await t.connect();return u(),f},async reconnectAuthorized(){let f=await t.reconnectAuthorized();return u(),f},attachAudio(f){n=f,u()},getSlots(){return t.getConnectedControllers()},get active(){return T},player(f){return f===void 0||f==="active"?T:v(f)},onCapabilitiesChange(f){return c.add(f),()=>{c.delete(f)}},syncCapabilities:u,dispose(){if(!i){i=!0,y!==null&&(clearInterval(y),y=null),d(),c.clear(),typeof window<"u"&&(a.autoHotplug!==!1&&(window.removeEventListener("gamepadconnected",h),window.removeEventListener("gamepaddisconnected",h)),a.autoEmergencyReset!==!1&&(window.removeEventListener("pagehide",w),window.removeEventListener("beforeunload",w)));for(let f of o)clearTimeout(f);o.clear();for(let f of s)try{f.dispose()}catch{}s.clear();for(let f of r)try{f.stop()}catch{}r.clear(),t.stopGamepadRumble(),t.resetTriggers().catch(()=>{}),t.setLightbar(23,23,23).catch(()=>{}),e&&(a.autoHotplug!==!1&&t.detachHidHotplug(),a.attachKeyboardFallback&&t.detachKeyboardFallback())}}}}var de="http://127.0.0.1:5178",ue="ws://127.0.0.1:5178",W=class a{httpBase;wsBase;pcCtx=null;pcSinkId="";pcSinkLabel="PC Default Speakers";pcMasterGain=null;pcAnalysers=[];pcNoiseBuffer=null;dsMode="none";dsCtx=null;dsSinkId="";dsSinkLabel="";dsMaxChannelCount=2;dsActiveChannelCount=2;dsWs=null;dsWorklet=null;dsMerger=null;dsChGains=[];dsAnalysers=[];dsNoiseBuffer=null;pcGainValue=.8;dsSpeakerGainValue=.95;dsHapticGainValue=.95;audioMuted=!1;constructor(e={}){this.httpBase=(e.httpBase||de).replace(/\/+$/,""),this.wsBase=(e.wsBase||ue).replace(/\/+$/,"")}setAudioMuted(e){if(this.audioMuted=e,this.pcMasterGain&&this.pcCtx&&this.pcMasterGain.gain.setTargetAtTime(e?0:this.pcGainValue,this.pcCtx.currentTime,.015),this.dsChGains.length>=2&&this.dsCtx){let t=e?0:this.dsSpeakerGainValue;this.dsChGains[0].gain.setTargetAtTime(t,this.dsCtx.currentTime,.015),this.dsChGains[1].gain.setTargetAtTime(t,this.dsCtx.currentTime,.015)}}activeContinuous=new Set;companionToken="";intentionalWsClose=!1;reconnectAttempts=0;reconnectTimer=null;streamStateListeners=new Set;onCompanionStreamState(e){return this.streamStateListeners.add(e),()=>this.streamStateListeners.delete(e)}emitStreamState(e,t){for(let n of this.streamStateListeners)try{n(e,t)}catch{}}static isLoopbackOrigin(){if(typeof window>"u")return!0;let e=window.location.hostname;return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}static async getLoopbackPermissionState(){if(a.isLoopbackOrigin())return"local_exempt";if(typeof navigator>"u"||!navigator.permissions?.query)return"unknown";for(let e of["loopback-network","local-network-access"])try{let t=await navigator.permissions.query({name:e});if(t.state==="granted"||t.state==="prompt"||t.state==="denied")return t.state}catch{}return"unknown"}async loopbackFetch(e,t={}){let n={...t,targetAddressSpace:"loopback"};try{return await fetch(e,n)}catch(i){if(i instanceof TypeError&&!String(i.message).toLowerCase().includes("fetch"))return fetch(e,t);throw i}}static checkBrowserCapabilities(){if(typeof window>"u")return{hasWebAudio:!1,hasSetSinkId:!1,hasAudioWorklet:!1,isSecureContext:!0};let e=window.AudioContext||window.webkitAudioContext;return{hasWebAudio:!!e,hasSetSinkId:!!(e&&"setSinkId"in e.prototype),hasAudioWorklet:!!(e&&"audioWorklet"in e.prototype),isSecureContext:!!window.isSecureContext}}async probeCompanion(e=700){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await this.loopbackFetch(`${this.httpBase}/api/health`,{cache:"no-store",signal:t.signal});if(!i.ok)return{online:!1};let r=await i.json();return{online:!!r.ok,version:r.version,protocolVersion:typeof r.protocolVersion=="number"?r.protocolVersion:1,platform:r.platform}}catch{return{online:!1}}finally{clearTimeout(n)}}async acquireCompanionSession(){let e=await this.loopbackFetch(`${this.httpBase}/api/session`,{method:"POST",headers:{"X-Gamepadly-Client":"web"},cache:"no-store"});if(e.status===404)return this.companionToken="","";if(!e.ok)throw new Error(`Gamepadly Link rejected session request (HTTP ${e.status}).`);let t=await e.json();return this.companionToken=typeof t.token=="string"?t.token:"",this.companionToken}async listCompanionDevices(){let e=await this.loopbackFetch(`${this.httpBase}/api/devices`,{cache:"no-store"});if(!e.ok)throw new Error("Gamepadly Link companion did not respond.");let t=await e.json();return Array.isArray(t.devices)?t.devices:[]}async openWindowsSoundPanelViaCompanion(){try{let e=this.companionToken||await this.acquireCompanionSession(),t={};return e&&(t["X-Gamepadly-Token"]=e),(await this.loopbackFetch(`${this.httpBase}/api/open-sound-panel`,{method:"POST",headers:t})).ok}catch{return!1}}async unlockBrowserDeviceLabels(){if(!navigator.mediaDevices?.getUserMedia)return!1;try{let e=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});for(let t of e.getTracks())t.stop();return!0}catch{return!1}}async listBrowserOutputDevices(){return navigator.mediaDevices?.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audiooutput").map(t=>({deviceId:t.deviceId,label:t.label||(t.deviceId==="default"?"System Default":`Audio Output (${t.deviceId.slice(0,8)})`),isLikelyDualSense:/wireless controller|dualsense|ps5|dsx/i.test(t.label||"")})):[]}async initPcOutput(e="",t="PC Default Speakers"){let n=window.AudioContext||window.webkitAudioContext;this.pcCtx||(this.pcCtx=new n({latencyHint:"interactive"}));let i=this.pcCtx;return e&&typeof i.setSinkId=="function"&&await i.setSinkId(e),this.pcCtx.state==="suspended"&&await this.pcCtx.resume(),this.pcMasterGain||this.buildPcGraph(),this.pcSinkId=e,this.pcSinkLabel=t,{sinkId:this.pcSinkId,sinkLabel:this.pcSinkLabel,sampleRate:this.pcCtx.sampleRate}}buildPcGraph(){let e=this.pcCtx;this.pcMasterGain=e.createGain(),this.pcMasterGain.gain.value=this.audioMuted?0:this.pcGainValue;let t=e.createDynamicsCompressor();t.threshold.value=-4,t.knee.value=8,t.ratio.value=6;let n=e.createChannelSplitter(2),i=e.createAnalyser(),r=e.createAnalyser();i.fftSize=256,r.fftSize=256,i.smoothingTimeConstant=.55,r.smoothingTimeConstant=.55,this.pcMasterGain.connect(t),t.connect(e.destination),t.connect(n),n.connect(i,0),n.connect(r,1),this.pcAnalysers=[i,r],this.pcNoiseBuffer=this.createNoiseBuffer(e)}async openCompanionWebSocket(e){let t=await this.acquireCompanionSession(),n=new URLSearchParams;t&&n.set("token",t),e&&n.set("device",e);let i=n.toString(),r=`${this.wsBase}/ws/haptics${i?`?${i}`:""}`;return new Promise((o,s)=>{let c=new WebSocket(r);c.binaryType="arraybuffer";let l=setTimeout(()=>{c.close(),s(new Error("Gamepadly Link WASAPI handshake timeout."))},5e3);c.onmessage=u=>{if(typeof u.data=="string")try{let d=JSON.parse(u.data);d.type==="ready"?(clearTimeout(l),o({ws:c,ready:d})):d.type==="error"&&(clearTimeout(l),c.close(),s(new Error(d.message||"WASAPI renderer failed to initialize.")))}catch{}},c.onerror=()=>{clearTimeout(l),s(new Error("Failed to connect to Gamepadly Link WebSocket (check LNA loopback permission)."))}})}attachWsReconnectHandler(e,t){e.onclose=()=>{if(this.dsWs!==e)return;if(this.dsWs=null,this.intentionalWsClose||this.dsMode!=="companion"){this.emitStreamState("idle");return}if(this.reconnectAttempts>=3){this.emitStreamState("disconnected","Gamepadly Link connection lost. Click Connect to retry.");return}let n=800*Math.pow(2,this.reconnectAttempts);this.reconnectAttempts++,this.emitStreamState("reconnecting",`Reconnecting to Gamepadly Link (${this.reconnectAttempts}/3)...`),this.reconnectTimer=window.setTimeout(async()=>{if(this.reconnectTimer=null,!(this.intentionalWsClose||this.dsMode!=="companion"))try{let{ws:i}=await this.openCompanionWebSocket(t);this.dsWs=i,this.reconnectAttempts=0,this.attachWsReconnectHandler(i,t),this.emitStreamState("connected","Gamepadly Link reconnected.")}catch{this.reconnectAttempts<3?(this.attachWsReconnectHandler(e,t),e.onclose?.(new CloseEvent("close"))):this.emitStreamState("disconnected","Gamepadly Link offline.")}},n)}}async connectDualSenseCompanion(e="",t="DualSense WASAPI"){let n=window.AudioContext||window.webkitAudioContext;await this.teardownDsOutput(),this.intentionalWsClose=!1,this.reconnectAttempts=0;let{ws:i,ready:r}=await this.openCompanionWebSocket(e);this.dsWs=i,this.attachWsReconnectHandler(i,r.id||e),this.emitStreamState("connected");let o=r.sampleRate||48e3;this.dsCtx=new n({sampleRate:o,latencyHint:"interactive"}),this.dsCtx.state==="suspended"&&await this.dsCtx.resume(),await this.dsCtx.audioWorklet.addModule("/haptic-worklet.js"),this.dsMode="companion",this.dsSinkId=r.id||e,this.dsSinkLabel=r.name||t,this.dsMaxChannelCount=r.channels||4,this.dsActiveChannelCount=Math.min(4,this.dsMaxChannelCount),this.buildDsGraph(!1),this.dsWorklet=new AudioWorkletNode(this.dsCtx,"gamepadly-wasapi-capture",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],channelCount:4,channelCountMode:"explicit",channelInterpretation:"discrete"});let s=this.dsCtx.createGain();return s.gain.value=0,this.dsMerger.connect(this.dsWorklet),this.dsWorklet.connect(s),s.connect(this.dsCtx.destination),this.dsWorklet.port.onmessage=c=>{this.dsWs&&this.dsWs.readyState===WebSocket.OPEN&&this.dsWs.send(c.data)},{mode:"companion",sinkId:this.dsSinkId,sinkLabel:this.dsSinkLabel,sampleRate:this.dsCtx.sampleRate,maxChannelCount:this.dsMaxChannelCount,activeChannelCount:this.dsActiveChannelCount,isQuadraphonicReady:this.dsMaxChannelCount>=4,state:this.dsCtx.state}}async connectDualSenseBrowserSink(e,t){if(!e)throw new Error("DualSense audio output device ID is empty.");let n=window.AudioContext||window.webkitAudioContext;await this.teardownDsOutput();try{this.dsCtx=new n({latencyHint:"interactive",sinkId:e})}catch{this.dsCtx=new n({latencyHint:"interactive"})}let i=this.dsCtx;typeof i.setSinkId=="function"&&i.sinkId!==e&&await i.setSinkId(e),this.dsCtx.state==="suspended"&&await this.dsCtx.resume();let r=this.dsCtx.destination;this.dsMaxChannelCount=r.maxChannelCount;let o=this.dsMaxChannelCount>=4?4:Math.min(2,this.dsMaxChannelCount);return r.channelCountMode="explicit",r.channelInterpretation="discrete",r.channelCount=o,this.dsActiveChannelCount=r.channelCount,this.dsMode="setsinkid",this.dsSinkId=e,this.dsSinkLabel=t,this.buildDsGraph(!0),{mode:"setsinkid",sinkId:this.dsSinkId,sinkLabel:this.dsSinkLabel,sampleRate:this.dsCtx.sampleRate,maxChannelCount:this.dsMaxChannelCount,activeChannelCount:this.dsActiveChannelCount,isQuadraphonicReady:this.dsMaxChannelCount>=4,state:this.dsCtx.state}}buildDsGraph(e){let t=this.dsCtx;this.dsMerger=t.createChannelMerger(4),this.dsChGains=[],this.dsAnalysers=[];for(let n=0;n<4;n++){let i=t.createGain();i.gain.value=n<2?this.dsSpeakerGainValue:this.dsHapticGainValue;let r=i;if(n>=2){let c=t.createBiquadFilter();c.type="highpass",c.frequency.value=20,c.Q.value=.707,i.connect(c),r=c}let o=t.createDynamicsCompressor();o.threshold.value=-3,o.knee.value=6,o.ratio.value=12,o.attack.value=.0015,o.release.value=.05;let s=t.createAnalyser();s.fftSize=256,s.smoothingTimeConstant=.5,r.connect(o),o.connect(s),s.connect(this.dsMerger,0,n),this.dsChGains.push(i),this.dsAnalysers.push(s)}e&&this.dsMerger.connect(t.destination),this.dsNoiseBuffer=this.createNoiseBuffer(t)}async teardownDsOutput(){if(this.intentionalWsClose=!0,this.reconnectTimer!==null&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopAllContinuous(),this.dsWorklet){try{this.dsWorklet.port.onmessage=null,this.dsWorklet.disconnect()}catch{}this.dsWorklet=null}if(this.dsWs){try{this.dsWs.close()}catch{}this.dsWs=null}if(this.dsCtx){try{await this.dsCtx.close()}catch{}this.dsCtx=null}this.dsMerger=null,this.dsChGains=[],this.dsAnalysers=[],this.dsNoiseBuffer=null,this.dsMode="none"}createNoiseBuffer(e){let t=e.sampleRate*2,n=e.createBuffer(1,t,e.sampleRate),i=n.getChannelData(0);for(let r=0;r<t;r++)i[r]=Math.random()*2-1;return n}async resumeAll(){this.pcCtx||await this.initPcOutput("",this.pcSinkLabel),this.pcCtx&&this.pcCtx.state==="suspended"&&await this.pcCtx.resume(),this.dsCtx&&this.dsCtx.state==="suspended"&&await this.dsCtx.resume()}setGains(e){e.pc!==void 0&&(this.pcGainValue=Math.max(0,Math.min(1.4,e.pc)),this.pcMasterGain&&this.pcCtx&&this.pcMasterGain.gain.setTargetAtTime(this.pcGainValue,this.pcCtx.currentTime,.02)),e.dsSpeaker!==void 0&&(this.dsSpeakerGainValue=Math.max(0,Math.min(1.3,e.dsSpeaker)),this.dsChGains.length>=2&&this.dsCtx&&(this.dsChGains[0].gain.setTargetAtTime(this.dsSpeakerGainValue,this.dsCtx.currentTime,.02),this.dsChGains[1].gain.setTargetAtTime(this.dsSpeakerGainValue,this.dsCtx.currentTime,.02))),e.dsHaptic!==void 0&&(this.dsHapticGainValue=Math.max(0,Math.min(1.4,e.dsHaptic)),this.dsChGains.length>=4&&this.dsCtx&&(this.dsChGains[2].gain.setTargetAtTime(this.dsHapticGainValue,this.dsCtx.currentTime,.02),this.dsChGains[3].gain.setTargetAtTime(this.dsHapticGainValue,this.dsCtx.currentTime,.02)))}getWaveforms(){let e=t=>{if(!t)return null;let n=new Float32Array(t.fftSize);return t.getFloatTimeDomainData(n),n};return{pcL:e(this.pcAnalysers[0]),pcR:e(this.pcAnalysers[1]),dsCh0:e(this.dsAnalysers[0]),dsCh1:e(this.dsAnalysers[1]),dsCh2:e(this.dsAnalysers[2]),dsCh3:e(this.dsAnalysers[3])}}getHapticEnergy(){if(this.dsAnalysers.length<4)return{left:0,right:0};let e=t=>{let n=new Float32Array(t.fftSize);t.getFloatTimeDomainData(n);let i=0;for(let r=0;r<n.length;r++)i+=n[r]*n[r];return Math.min(1,Math.sqrt(i/n.length)*3.5)};return{left:e(this.dsAnalysers[2]),right:e(this.dsAnalysers[3])}}stopAllContinuous(){for(let e of Array.from(this.activeContinuous))try{e.stop()}catch{}this.activeContinuous.clear()}routePc(e,t=0,n=1){if(!this.pcCtx||!this.pcMasterGain)return;let i=this.pcCtx.createGain();i.gain.value=n;let r=this.pcCtx.createStereoPanner();r.pan.value=Math.max(-1,Math.min(1,t)),e.connect(i),i.connect(r),r.connect(this.pcMasterGain)}routeDsSpeakerMonoSafe(e,t=.9){if(!this.dsCtx||this.dsChGains.length<2)return;let n=this.dsCtx.createGain();n.gain.value=t,e.connect(n),n.connect(this.dsChGains[0]),n.connect(this.dsChGains[1])}routeDsVcm(e,t=0,n=1){if(!this.dsCtx||this.dsChGains.length<4)return;let i=Math.max(-1,Math.min(1,t)),r=this.dsCtx.createGain(),o=this.dsCtx.createGain();r.gain.value=Math.cos((i+1)*Math.PI/4)*n,o.gain.value=Math.sin((i+1)*Math.PI/4)*n,e.connect(r),e.connect(o),r.connect(this.dsChGains[2]),o.connect(this.dsChGains[3])}playPcTone(e){if(!this.pcCtx)return;let t=this.pcCtx,n=t.currentTime+(e.delayMs||0)/1e3,i=Math.max(.015,e.durationMs/1e3),r=t.createOscillator();r.type=e.wave||"sine",r.frequency.setValueAtTime(Math.max(20,e.freqHz),n),e.endFreqHz&&e.endFreqHz>0&&r.frequency.exponentialRampToValueAtTime(Math.max(20,e.endFreqHz),n+i);let o=t.createGain(),s=Math.max(.001,Math.min(1,e.intensity??.45));o.gain.setValueAtTime(1e-4,n),o.gain.linearRampToValueAtTime(s,n+Math.min(.012,i*.2)),o.gain.exponentialRampToValueAtTime(1e-4,n+i),r.connect(o),this.routePc(o,e.pan??0,1),r.start(n),r.stop(n+i+.02)}playPcNoiseBurst(e){if(!this.pcCtx||!this.pcNoiseBuffer)return;let t=this.pcCtx,n=t.currentTime+(e.delayMs||0)/1e3,i=Math.max(.02,e.durationMs/1e3),r=t.createBufferSource();r.buffer=this.pcNoiseBuffer;let o=t.createBiquadFilter();o.type=e.filterType||"bandpass",o.Q.value=e.q??2,o.frequency.setValueAtTime(e.freqHz,n),e.endFreqHz&&o.frequency.exponentialRampToValueAtTime(Math.max(30,e.endFreqHz),n+i);let s=t.createGain(),c=Math.max(.001,Math.min(1,e.intensity??.5));s.gain.setValueAtTime(1e-4,n),s.gain.linearRampToValueAtTime(c,n+Math.min(.015,i*.15)),s.gain.exponentialRampToValueAtTime(1e-4,n+i),r.connect(o),o.connect(s),this.routePc(s,e.pan??0,1),r.start(n),r.stop(n+i+.03)}playControllerSpeakerTone(e){if(!this.dsCtx||this.dsChGains.length<2){this.playPcTone({...e,intensity:(e.intensity??.5)*.45});return}let t=this.dsCtx,n=t.currentTime+(e.delayMs||0)/1e3,i=Math.max(.015,e.durationMs/1e3),r=t.createOscillator();r.type=e.wave||"triangle",r.frequency.setValueAtTime(Math.max(60,e.freqHz),n),e.endFreqHz&&e.endFreqHz>0&&r.frequency.exponentialRampToValueAtTime(Math.max(60,e.endFreqHz),n+i);let o=t.createGain(),s=Math.max(.001,Math.min(1,e.intensity??.75));o.gain.setValueAtTime(1e-4,n),o.gain.linearRampToValueAtTime(s,n+Math.min(.006,i*.18)),o.gain.exponentialRampToValueAtTime(1e-4,n+i),r.connect(o),this.routeDsSpeakerMonoSafe(o,.95),r.start(n),r.stop(n+i+.02)}playHapticPulse(e){if(!this.dsCtx||this.dsChGains.length<4)return;let t=this.dsCtx,n=t.currentTime+(e.delayMs||0)/1e3,i=Math.max(.012,e.durationMs/1e3),r=t.createOscillator();r.type=e.wave||"sine",r.frequency.setValueAtTime(Math.max(22,e.freqHz),n),e.endFreqHz&&e.endFreqHz>0&&r.frequency.exponentialRampToValueAtTime(Math.max(22,e.endFreqHz),n+i);let o=t.createGain(),s=Math.max(.001,Math.min(1,e.intensity));o.gain.setValueAtTime(1e-4,n),o.gain.linearRampToValueAtTime(s,n+Math.min(.004,i*.2)),o.gain.exponentialRampToValueAtTime(1e-4,n+i),r.connect(o),this.routeDsVcm(o,e.pan??0,1),r.start(n),r.stop(n+i+.02)}playHapticSweep(e){if(!this.dsCtx||this.dsChGains.length<4)return;let t=this.dsCtx,n=t.currentTime,i=Math.max(.04,e.durationMs/1e3),r=t.createOscillator();r.type=e.wave||"sine",r.frequency.setValueAtTime(Math.max(25,e.fromHz),n),r.frequency.exponentialRampToValueAtTime(Math.max(25,e.toHz),n+i);let o=Math.max(-1,Math.min(1,e.fromPan)),s=Math.max(-1,Math.min(1,e.toPan)),c=t.createGain(),l=t.createGain();c.gain.setValueAtTime(Math.cos((o+1)*Math.PI/4)*e.intensity,n),c.gain.linearRampToValueAtTime(Math.cos((s+1)*Math.PI/4)*e.intensity,n+i),l.gain.setValueAtTime(Math.sin((o+1)*Math.PI/4)*e.intensity,n),l.gain.linearRampToValueAtTime(Math.sin((s+1)*Math.PI/4)*e.intensity,n+i),r.connect(c),r.connect(l),c.connect(this.dsChGains[2]),l.connect(this.dsChGains[3]),r.start(n),r.stop(n+i+.02)}createContinuous(e){let t=!1,n=null,i=null,r=()=>{if(n){try{n.osc.stop(),n.noise?.stop(),n.master.disconnect(),n.spkGain.disconnect()}catch{}n=null}},o=()=>{if(i){try{i.osc.stop(),i.gain.disconnect()}catch{}i=null}},s=()=>{if(!t){if(n&&n.ctx!==this.dsCtx&&r(),!n&&this.dsCtx&&this.dsChGains.length>=4){let l=this.dsCtx,u=l.createOscillator(),d=l.createBiquadFilter(),h=l.createGain(),w=l.createGain(),y=l.createGain(),g=l.createGain();h.gain.value=1e-4,w.gain.value=.7,y.gain.value=.7,g.gain.value=1e-4;let T={ice:{wave:"triangle",f:240,filtF:310,spk:.25},metal:{wave:"sine",f:150,filtF:180,spk:.35},gravel:{wave:"sawtooth",f:82,filtF:150,spk:.2},grass:{wave:"sine",f:65,filtF:110,spk:.1},water:{wave:"sine",f:48,filtF:85,spk:.18},engine:{wave:"sawtooth",f:42,filtF:160,spk:.05},tension:{wave:"sawtooth",f:78,filtF:210,spk:.4}}[e];u.type=T.wave,u.frequency.value=T.f,d.type="lowpass",d.frequency.value=T.filtF;let f;if(this.dsNoiseBuffer&&(e==="water"||e==="gravel"||e==="ice")){f=l.createBufferSource(),f.buffer=this.dsNoiseBuffer,f.loop=!0;let x=l.createGain();x.gain.value=.45,f.connect(x),x.connect(d),f.start()}u.connect(d),d.connect(h),h.connect(w),h.connect(y),w.connect(this.dsChGains[2]),y.connect(this.dsChGains[3]),h.connect(g),g.connect(this.dsChGains[0]),g.connect(this.dsChGains[1]),g.gain.value=T.spk,u.start(),n={ctx:l,osc:u,noise:f,filter:d,master:h,gL:w,gR:y,spkGain:g}}if(i&&i.ctx!==this.pcCtx&&o(),!i&&this.pcCtx&&this.pcMasterGain&&(e==="engine"||e==="tension"||e==="water")){let l=this.pcCtx,u=l.createOscillator();u.type=e==="water"?"sine":"triangle",u.frequency.value=e==="engine"?75:e==="tension"?210:120;let d=l.createGain();d.gain.value=1e-4;let h=l.createStereoPanner();u.connect(d),d.connect(h),h.connect(this.pcMasterGain),u.start(),i={ctx:l,osc:u,gain:d,panner:h}}}};s();let c={update:({intensity:l=0,speed:u=.5,pan:d=0,freqScale:h=1}={})=>{if(t)return;l>.005&&s();let w=Math.max(1e-4,Math.min(1,l)),y=Math.max(-1,Math.min(1,d));if(n&&this.dsCtx&&n.ctx===this.dsCtx){let g=this.dsCtx.currentTime;n.master.gain.setTargetAtTime(w*.85,g,.025),n.gL.gain.setTargetAtTime(Math.cos((y+1)*Math.PI/4),g,.025),n.gR.gain.setTargetAtTime(Math.sin((y+1)*Math.PI/4),g,.025);let v=e==="tension"?68+u*150:e==="engine"?35+u*95:85+u*140;n.osc.frequency.setTargetAtTime(Math.max(25,v*h),g,.03)}if(i&&this.pcCtx&&i.ctx===this.pcCtx){let g=this.pcCtx.currentTime;i.gain.gain.setTargetAtTime(w*.22,g,.03),i.panner.pan.setTargetAtTime(y*.7,g,.03);let v=e==="tension"?180+u*260:70+u*160;i.osc.frequency.setTargetAtTime(Math.max(30,v*h),g,.03)}},stop:()=>{t||(t=!0,this.activeContinuous.delete(c),r(),o())}};return this.activeContinuous.add(c),c}playComboPreset(e,t=0){switch(e){case"ratchet_tick":this.playHapticPulse({pan:t,freqHz:215,endFreqHz:115,durationMs:18,intensity:.52,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:2100,endFreqHz:1150,durationMs:16,intensity:.45,wave:"triangle"});break;case"lock_sweet_spot":this.playHapticPulse({pan:-.45,freqHz:145,endFreqHz:68,durationMs:65,intensity:.95,wave:"sine"}),this.playHapticPulse({pan:.45,freqHz:285,endFreqHz:170,durationMs:48,intensity:.75,wave:"triangle",delayMs:14}),this.playControllerSpeakerTone({freqHz:1480,endFreqHz:860,durationMs:75,intensity:.85,wave:"sine"}),this.playPcTone({freqHz:440,endFreqHz:330,durationMs:110,intensity:.28,pan:t,wave:"sine"});break;case"lock_unlock":this.playHapticSweep({fromPan:-.95,toPan:.95,fromHz:65,toHz:185,durationMs:260,intensity:.95}),this.playControllerSpeakerTone({freqHz:980,endFreqHz:1560,durationMs:120,intensity:.85,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:1560,endFreqHz:2093,durationMs:180,intensity:.8,delayMs:120,wave:"sine"}),this.playPcNoiseBurst({durationMs:520,filterType:"lowpass",freqHz:280,endFreqHz:65,intensity:.85}),this.playPcTone({freqHz:523.25,endFreqHz:783.99,durationMs:360,intensity:.38,delayMs:90,wave:"triangle"});break;case"fish_bite":this.playHapticPulse({pan:t,freqHz:95,endFreqHz:42,durationMs:110,intensity:.95,wave:"sine"}),this.playHapticPulse({pan:-t*.5,freqHz:165,endFreqHz:75,durationMs:75,intensity:.8,delayMs:85}),this.playControllerSpeakerTone({freqHz:1250,endFreqHz:780,durationMs:95,intensity:.85,wave:"sawtooth"}),this.playPcNoiseBurst({durationMs:240,filterType:"bandpass",freqHz:1400,endFreqHz:500,intensity:.6,pan:t});break;case"fish_splash":this.playHapticSweep({fromPan:t,toPan:-t,fromHz:140,toHz:52,durationMs:220,intensity:.85}),this.playPcNoiseBurst({durationMs:420,filterType:"bandpass",freqHz:1800,endFreqHz:420,intensity:.72,pan:t}),this.playControllerSpeakerTone({freqHz:1600,endFreqHz:620,durationMs:110,intensity:.55,wave:"triangle"});break;case"pistol":this.playHapticPulse({pan:.2,freqHz:145,endFreqHz:42,durationMs:80,intensity:1}),this.playHapticPulse({pan:.6,freqHz:260,endFreqHz:135,durationMs:36,intensity:.68,delayMs:55,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:1850,endFreqHz:620,durationMs:48,intensity:.85,delayMs:50,wave:"triangle"}),this.playPcNoiseBurst({durationMs:190,filterType:"lowpass",freqHz:3200,endFreqHz:240,intensity:.75});break;case"shotgun":this.playHapticPulse({pan:0,freqHz:115,endFreqHz:28,durationMs:210,intensity:1}),this.playHapticPulse({pan:-.85,freqHz:210,endFreqHz:105,durationMs:50,intensity:.85,delayMs:260,wave:"sawtooth"}),this.playHapticPulse({pan:.85,freqHz:265,endFreqHz:130,durationMs:50,intensity:.85,delayMs:390,wave:"sawtooth"}),this.playControllerSpeakerTone({freqHz:1100,endFreqHz:520,durationMs:55,intensity:.85,delayMs:260,wave:"sawtooth"}),this.playControllerSpeakerTone({freqHz:1450,endFreqHz:740,durationMs:55,intensity:.85,delayMs:390,wave:"sawtooth"}),this.playPcNoiseBurst({durationMs:420,filterType:"lowpass",freqHz:2800,endFreqHz:110,intensity:.95});break;case"bow_release":this.playHapticPulse({pan:-.35,freqHz:240,endFreqHz:72,durationMs:150,intensity:.95,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:920,endFreqHz:360,durationMs:120,intensity:.85,wave:"triangle"}),this.playPcNoiseBurst({durationMs:210,filterType:"bandpass",freqHz:2200,endFreqHz:600,intensity:.55});break;case"thunder":this.playPcNoiseBurst({durationMs:1650,filterType:"lowpass",freqHz:520,endFreqHz:68,intensity:.95,pan:t}),this.playHapticPulse({pan:t,freqHz:82,endFreqHz:28,durationMs:950,intensity:1,wave:"sawtooth"});break}}async testPcSpeakersLoud(){await this.resumeAll(),this.playPcTone({freqHz:523.25,durationMs:240,intensity:.55,pan:-.85,wave:"sine"}),this.playPcTone({freqHz:659.25,durationMs:260,intensity:.55,pan:.85,delayMs:260,wave:"sine"})}async testDualSenseSpeakerLoud(){if(await this.resumeAll(),!this.dsCtx||this.dsChGains.length<2)throw new Error("DualSense 4-channel audio is not connected yet.");[880,1174.66,1318.51].forEach((t,n)=>{this.playControllerSpeakerTone({freqHz:t,durationMs:200,intensity:.95,delayMs:n*210,wave:"triangle"})})}async testDualSenseVcmLoud(){if(await this.resumeAll(),!this.dsCtx||this.dsChGains.length<4)throw new Error("DualSense 4-channel audio is not connected yet.");this.playHapticPulse({pan:-.95,freqHz:55,endFreqHz:180,durationMs:520,intensity:.95}),this.playHapticPulse({pan:.95,freqHz:180,endFreqHz:55,durationMs:520,intensity:.95,delayMs:560})}async runThreeLayerCalibration(e){await this.resumeAll(),e(1),this.playPcTone({freqHz:523.25,durationMs:320,intensity:.5,pan:-.9}),this.playPcTone({freqHz:659.25,durationMs:320,intensity:.5,pan:.9,delayMs:340}),setTimeout(()=>{e(2),this.playControllerSpeakerTone({freqHz:880,endFreqHz:1174.66,durationMs:480,intensity:.95,wave:"triangle"})},760),setTimeout(()=>{e(3),this.playHapticPulse({pan:-1,freqHz:45,endFreqHz:210,durationMs:650,intensity:.95})},1350),setTimeout(()=>{e(4),this.playHapticPulse({pan:1,freqHz:210,endFreqHz:45,durationMs:650,intensity:.95})},2100),setTimeout(()=>{e(5),this.playHapticSweep({fromPan:-1,toPan:1,fromHz:110,toHz:145,durationMs:850,intensity:.95}),this.playPcTone({freqHz:392,endFreqHz:523.25,durationMs:820,intensity:.35,wave:"triangle"})},2850),setTimeout(()=>e(6),3800)}};function Re(a){return new W(a)}var pe={platformer:{name:"Platformer (WASD / Arrows + Space Jump)",keys:{left:"ArrowLeft",right:"ArrowRight",up:"ArrowUp",down:"ArrowDown","lx-":"ArrowLeft","lx+":"ArrowRight","ly-":"ArrowUp","ly+":"ArrowDown",cross:{code:"Space",hapticOnPress:"click"},square:{code:"KeyZ",hapticOnPress:"recoil",hapticPan:.4},circle:{code:"KeyX",hapticOnPress:"click"},r2:{code:"ShiftLeft",hapticOnPress:"boost",hapticPan:.6},options:"Escape"},triggers:{right:"soft_wall"}},"arcade-4way":{name:"Arcade 4-Way (Grid / Puzzle / Snake / Tetris)",keys:{left:{code:"ArrowLeft",repeatMs:120,hapticOnPress:"ratchet",hapticPan:-.5},right:{code:"ArrowRight",repeatMs:120,hapticOnPress:"ratchet",hapticPan:.5},up:{code:"ArrowUp",repeatMs:120,hapticOnPress:"ratchet"},down:{code:"ArrowDown",repeatMs:90,hapticOnPress:"ratchet"},"lx-":{code:"ArrowLeft",repeatMs:140,hapticOnPress:"ratchet",hapticPan:-.5},"lx+":{code:"ArrowRight",repeatMs:140,hapticOnPress:"ratchet",hapticPan:.5},"ly-":{code:"ArrowUp",repeatMs:140,hapticOnPress:"ratchet"},"ly+":{code:"ArrowDown",repeatMs:100,hapticOnPress:"ratchet"},cross:{code:"Space",hapticOnPress:"click"},circle:"Escape",options:"Enter"}},racing:{name:"Racing (Steer + R2 Gas / L2 ABS Brake)",keys:{left:"ArrowLeft",right:"ArrowRight","lx-":{code:"ArrowLeft",threshold:.25},"lx+":{code:"ArrowRight",threshold:.25},r2:{code:"ArrowUp",threshold:.2},l2:{code:"ArrowDown",threshold:.2},cross:{code:"Space",hapticOnPress:"boost"},square:{code:"ShiftLeft",hapticOnPress:"ratchet"},options:"Escape"},triggers:{left:"abs",right:"bow"}},"twin-stick":{name:"Twin-Stick Shooter (Left Stick Move + Right Stick Aim + R2 Fire)",keys:{"lx-":"KeyA","lx+":"KeyD","ly-":"KeyW","ly+":"KeyS",left:"KeyA",right:"KeyD",up:"KeyW",down:"KeyS",cross:{code:"Space",hapticOnPress:"click"},square:{code:"KeyR",hapticOnPress:"ratchet"},options:"Escape"},pointer:{stick:"right",speedPxPerSec:720,deadzone:.14,clickButton:"r2",secondaryClickButton:"l2",hapticOnClick:"recoil"},triggers:{left:"precision_damp",right:"weapon"}}};var Be={Space:{key:" ",keyCode:32},Enter:{key:"Enter",keyCode:13},Escape:{key:"Escape",keyCode:27},Tab:{key:"Tab",keyCode:9},Backspace:{key:"Backspace",keyCode:8},ArrowLeft:{key:"ArrowLeft",keyCode:37},ArrowUp:{key:"ArrowUp",keyCode:38},ArrowRight:{key:"ArrowRight",keyCode:39},ArrowDown:{key:"ArrowDown",keyCode:40},ShiftLeft:{key:"Shift",keyCode:16},ShiftRight:{key:"Shift",keyCode:16},ControlLeft:{key:"Control",keyCode:17},AltLeft:{key:"Alt",keyCode:18}};function De(a){let e=Be[a.code];if(e)return{code:a.code,key:a.key??e.key,keyCode:a.keyCode??e.keyCode};if(/^Key[A-Z]$/.test(a.code)){let t=a.code.slice(3);return{code:a.code,key:a.key??t.toLowerCase(),keyCode:a.keyCode??t.charCodeAt(0)}}if(/^Digit[0-9]$/.test(a.code)){let t=a.code.slice(5);return{code:a.code,key:a.key??t,keyCode:a.keyCode??t.charCodeAt(0)}}return{code:a.code,key:a.key??a.code,keyCode:a.keyCode??0}}function qe(a){return(Array.isArray(a)?a:[a]).map(t=>typeof t=="string"?{code:t}:t)}function he(a,e){return a==="l2"?e.l2:a==="r2"?e.r2:a==="lx+"?Math.max(0,e.lx):a==="lx-"?Math.max(0,-e.lx):a==="ly+"?Math.max(0,e.ly):a==="ly-"?Math.max(0,-e.ly):a==="rx+"?Math.max(0,e.rx):a==="rx-"?Math.max(0,-e.rx):a==="ry+"?Math.max(0,e.ry):a==="ry-"?Math.max(0,-e.ry):e.buttons[a]?1:0}function Me(a){if(a)return typeof a=="string"?K[a]:a}function ze(a){return"active"in a&&"getSlots"in a}function Z(a,e,t,n=!1){if(typeof KeyboardEvent<"u"){let i=new KeyboardEvent(e,{key:t.key,code:t.code,bubbles:!0,cancelable:!0,repeat:n});try{Object.defineProperty(i,"keyCode",{value:t.keyCode}),Object.defineProperty(i,"which",{value:t.keyCode})}catch{}a.dispatchEvent(i);return}if(typeof Event<"u"){let i=new Event(e,{bubbles:!0,cancelable:!0});i.key=t.key,i.code=t.code,i.keyCode=t.keyCode,i.which=t.keyCode,i.repeat=n,a.dispatchEvent(i)}}function $(a,e,t,n,i,r){let o={bubbles:!0,cancelable:!0,clientX:t,clientY:n,button:i,buttons:r,pointerId:1,pointerType:"mouse",isPrimary:!0};typeof PointerEvent<"u"&&a.dispatchEvent(new PointerEvent(e,o));let s=e.replace("pointer","mouse");typeof MouseEvent<"u"&&a.dispatchEvent(new MouseEvent(s,o))}function st(a){let e=ze(a.player)?a.player:null,t=e?e.active:a.player,n=a.keyTarget??(typeof window<"u"?window:void 0),i=a.pointerTarget!==void 0?a.pointerTarget:typeof document<"u"?document.body:null,r=typeof a.profile=="string"?pe[a.profile]:a.profile,o=!1,s=0,c=0,l=new Map,u=new Map,d={x:0,y:0,down:!1,secondaryDown:!1,visible:!1},h=!1,w=(x,M)=>{typeof x=="string"?t.haptics.playPreset(x,M):t.haptics.pulse({...x,pan:M?.pan??x.pan,intensity:(M?.intensity??1)*x.intensity})},y=()=>{let x=Me(r.triggers?.left),M=Me(r.triggers?.right);x&&M?t.triggers.setBoth(x,M):x?t.triggers.setLeft(x):M?t.triggers.setRight(M):t.triggers.reset()},g=e?e.onCapabilitiesChange(()=>{o&&y()}):null,v=()=>{if(n)for(let{meta:x}of l.values())Z(n,"keyup",x,!1);if(l.clear(),u.clear(),i&&(d.down||d.secondaryDown)){let x=i.getBoundingClientRect?.()??{left:0,top:0};d.down&&$(i,"pointerup",x.left+d.x,x.top+d.y,0,0),d.secondaryDown&&$(i,"pointerup",x.left+d.x,x.top+d.y,2,0)}d.down=!1,d.secondaryDown=!1},T=(x,M=typeof performance<"u"?performance.now():Date.now())=>{let A=x!==void 0?Math.max(0,Math.min(.1,x)):c>0?Math.max(0,Math.min(.1,(M-c)/1e3)):.016666666666666666;c=M;let m=t.input.getState();if(!m.connected||m.source==="keyboard_mouse"){(l.size>0||d.down||d.secondaryDown)&&v();return}let S=new Map;for(let[p,b]of Object.entries(r.keys)){if(!b)continue;let C=p,k=he(C,m),P=qe(b);for(let I=0;I<P.length;I++){let H=P[I],R=H.threshold??.45,B=k>=R,D=`${C}:${H.code}:${I}`,L=u.get(D)??!1;if(u.set(D,B),B){let E=De(H);S.has(E.code)||S.set(E.code,{meta:E,repeatMs:H.repeatMs,repeatDelayMs:H.repeatDelayMs??220}),!L&&H.hapticOnPress&&w(H.hapticOnPress,{pan:H.hapticPan})}}}if(n){for(let[p,b]of l.entries())S.has(p)||(Z(n,"keyup",b.meta,!1),l.delete(p));for(let[p,b]of S.entries()){let C=l.get(p);C?b.repeatMs&&M>=C.nextRepeatAt&&(Z(n,"keydown",b.meta,!0),C.nextRepeatAt=M+b.repeatMs):(Z(n,"keydown",b.meta,!1),l.set(p,{meta:b.meta,nextRepeatAt:b.repeatMs?M+b.repeatDelayMs:Number.POSITIVE_INFINITY}))}}if(r.pointer&&i){let p=r.pointer,b=i.getBoundingClientRect?.()??{left:0,top:0,width:800,height:600},C=Math.max(1,b.width),k=Math.max(1,b.height);h||(d.x=C/2,d.y=k/2,h=!0);let P=p.deadzone??.14,I=F(p.stick==="left"?m.lx:m.rx,P),H=F(p.stick==="left"?m.ly:m.ry,P),R=p.speedPxPerSec??680,B=I!==0||H!==0;B&&(d.x=Math.max(0,Math.min(C,d.x+I*R*A)),d.y=Math.max(0,Math.min(k,d.y+H*R*A)),d.visible=!0);let D=p.clickButton??"r2",L=p.secondaryClickButton??"l2",E=he(D,m)>=.45,G=he(L,m)>=.45,X=(E?1:0)|(G?2:0),Y=b.left+d.x,Q=b.top+d.y;B&&$(i,"pointermove",Y,Q,-1,X),E!==d.down&&(d.down=E,d.visible=!0,$(i,E?"pointerdown":"pointerup",Y,Q,0,X),E&&p.hapticOnClick&&w(p.hapticOnClick)),G!==d.secondaryDown&&(d.secondaryDown=G,d.visible=!0,$(i,G?"pointerdown":"pointerup",Y,Q,2,X)),a.onCursorUpdate?.({...d})}},f=x=>{o&&(T(void 0,x),s=requestAnimationFrame(f))};return{start(){o||(o=!0,c=0,y(),a.autoRaf!==!1&&typeof requestAnimationFrame<"u"&&(s=requestAnimationFrame(f)))},stop(){o&&(o=!1,s&&typeof cancelAnimationFrame<"u"&&cancelAnimationFrame(s),s=0,v())},tick:T,setProfile(x){v(),r=typeof x=="string"?pe[x]:x,o&&y()},getCursor(){return{...d}},triggerHaptic:w,dispose(){this.stop(),g?.(),t.triggers.reset()}}}function lt(){let a=new Set,e=!1,t=n=>{if(e){try{n()}catch{}return()=>{}}return a.add(n),()=>{if(a.delete(n))try{n()}catch{}}};return{add:t,on(n,i,r,o){return n.addEventListener(i,r,o),t(()=>n.removeEventListener(i,r,o))},timeout(n,i){let r=setTimeout(()=>{a.delete(o),e||n()},i),o=()=>clearTimeout(r);return a.add(o),r},interval(n,i){let r=setInterval(()=>{e||n()},i);return a.add(()=>clearInterval(r)),r},dispose(){if(e)return;e=!0;let n=Array.from(a).reverse();a.clear();for(let i of n)try{i()}catch{}}}}function dt(a,e={}){let t=e.maxDpr??2,n=e.minWidth??320,i=e.minHeight??240,r=document.createElement("canvas");r.style.width="100%",r.style.height="100%",r.style.display="block",r.style.touchAction="none",e.cursor&&(r.style.cursor=e.cursor),a.innerHTML="",a.appendChild(r);let o=r.getContext("2d"),s=n,c=i,l=1,u=()=>{let w=a.getBoundingClientRect(),y=typeof window<"u"&&window.devicePixelRatio||1;l=Math.max(1,Math.min(t,y)),s=Math.max(n,Math.floor(w.width||n)),c=Math.max(i,Math.floor(w.height||i)),r.width=Math.floor(s*l),r.height=Math.floor(c*l),o.setTransform(l,0,0,l,0,0),e.onResize?.(s,c,l)};u();let d=null;typeof ResizeObserver<"u"&&(d=new ResizeObserver(()=>u()),d.observe(a));let h=()=>u();return typeof window<"u"&&window.addEventListener("resize",h),{canvas:r,ctx:o,get width(){return s},get height(){return c},get dpr(){return l},resize:u,dispose(){d?.disconnect(),d=null,typeof window<"u"&&window.removeEventListener("resize",h),r.parentElement===a&&a.removeChild(r)}}}function ut(a){let e=a.maxDelta??.05,t=a.fixedStep,n=a.autoPauseOnHidden!==!1,i=!1,r=!1,o=0,s=0,c=0,l=h=>{if(r){s=h;return}s===0&&(s=h);let w=Math.max(0,(h-s)/1e3);s=h;let y=Math.min(e,w);if(t&&t>0){c+=y;let g=0;for(;c>=t&&g<8;)a.onUpdate(t,h),c-=t,g++;a.onRender?.(c/t,h)}else a.onUpdate(y,h),a.onRender?.(1,h)},u=h=>{i&&(l(h),o=requestAnimationFrame(u))},d=()=>{!n||typeof document>"u"||document.hidden&&(s=0,c=0)};return n&&typeof document<"u"&&document.addEventListener("visibilitychange",d),{start(){i||(i=!0,s=0,c=0,typeof requestAnimationFrame<"u"&&(o=requestAnimationFrame(u)))},stop(){i&&(i=!1,o&&typeof cancelAnimationFrame<"u"&&cancelAnimationFrame(o),o=0)},pause(){r=!0,s=0},resume(){r=!1,s=0},isPaused(){return r},step:l,dispose(){this.stop(),n&&typeof document<"u"&&document.removeEventListener("visibilitychange",d)}}}export{pe as BUILTIN_BRIDGE_PROFILES,de as COMPANION_HTTP_BASE,ue as COMPANION_WS_BASE,O as ControllerManager,O as DualSenseControllerManager,ie as TACTILE_PRESETS,K as TRIGGER_PRESETS,W as ThreeLayerAudioEngine,F as applyDeadzone,V as buildSwitchHdFromPulse,Se as crc32WithSeed,ce as createActionTracker,dt as createCanvasStage,lt as createDisposables,N as createEmptyInput,ut as createGameLoop,Ie as createGamepadly,st as createKeyMouseBridge,Re as createLinkAudio,U as encodeSwitchHdRumbleSide,z as encodeTriggerEffect,ne as identifyGamepadFromId,j as routeHapticPulse,ae as routeHapticSweep,oe as routeTactilePreset};
1
+ var ft=[3302,3570],Le=1406,Ee=[8201],U=new Uint8Array([0,1,64,64]);function mt(a){if(!Number.isFinite(a)||a<=.01)return 0;let e=Math.min(.85,Math.max(0,a));return e>=.23?Math.min(100,Math.round(Math.log2(e*8.7)*32)):e>=.12?Math.round(Math.log2(e*17)*16):Math.max(1,Math.round(e/.12*16))}function de(a){if(!a||a.highAmp<=.01&&a.lowAmp<=.01)return U.slice();let e=Math.max(81.75,Math.min(1252.6,Number.isFinite(a.highFreqHz)?a.highFreqHz:320)),t=Math.max(40.88,Math.min(626.3,Number.isFinite(a.lowFreqHz)?a.lowFreqHz:160)),n=Math.round(Math.log2(e/10)*32),r=Math.round(Math.log2(t/10)*32),i=Math.max(0,Math.min(508,(n-96)*4)),o=Math.max(1,Math.min(127,r-64)),s=mt(a.highAmp),l=mt(a.lowAmp),d=Math.min(200,s*2),h=(l&1)!==0?128:0,u=Math.min(114,(l>>1)+64);return new Uint8Array([i&255,d+(i>>8&1)&255,(o|h)&255,u&255])}function V(a,e=.06){let t=Math.abs(a);if(t<=e)return 0;let n=(t-e)/(1-e);return Math.sign(a)*Math.max(0,Math.min(1,n))}function xt(a){return(a.match(/vendor:\s*([0-9a-f]{4})/)??a.match(/^([0-9a-f]{1,4})-[0-9a-f]{1,4}-/))?.[1]?.padStart(4,"0")}function qt(a){return(a.match(/product:\s*([0-9a-f]{4})/)??a.match(/^[0-9a-f]{1,4}-([0-9a-f]{1,4})-/))?.[1]?.padStart(4,"0")}function zt(a){let e=xt(a);if(e==="054c")return"sony";if(e==="045e")return"xbox";if(e==="057e")return"nintendo";if(!e){if(/xbox|xinput|microsoft/.test(a))return"xbox";if(/dualsense|dualshock|wireless controller/.test(a))return"sony";if(/nintendo|pro controller|joy-con|switch/.test(a))return"nintendo"}}function Ge(a){let e=(a||"").toLowerCase(),t=xt(e),n=qt(e),r=t?Number.parseInt(t,16):void 0,i=n?Number.parseInt(n,16):void 0,o=zt(e);return o==="sony"?/0df2|edge/.test(e)?{brand:"sony",model:"dualsense_edge",displayName:"DualSense Edge",rawId:a,vendorId:1356,productId:i??3570}:/0ce6|dualsense/.test(e)?{brand:"sony",model:"dualsense",displayName:"PlayStation DualSense",rawId:a,vendorId:1356,productId:i??3302}:/05c4|09cc|dualshock/.test(e)?{brand:"sony",model:"dualshock4",displayName:"DualShock 4",rawId:a,vendorId:1356,productId:i}:{brand:"sony",model:"dualsense",displayName:"PlayStation Controller",rawId:a,vendorId:1356,productId:i}:o==="xbox"?/0b12|0b13|0b20|0b21|0b22|series/.test(e)?{brand:"xbox",model:"xbox_series",displayName:"Xbox Wireless Controller",rawId:a,vendorId:1118,productId:i}:/028e|360/.test(e)?{brand:"xbox",model:"xbox_360",displayName:"Xbox 360 Controller",rawId:a,vendorId:1118,productId:i}:{brand:"xbox",model:"xbox_series",displayName:"Xbox Controller",rawId:a,vendorId:1118,productId:i}:o==="nintendo"?/2069|pro 2|switch 2/.test(e)?{brand:"nintendo",model:"switch2_pro",displayName:"Nintendo Switch 2 Pro Controller",rawId:a,vendorId:1406,productId:i??8297}:/joy-con|2006|2007/.test(e)?{brand:"nintendo",model:"joycon",displayName:"Nintendo Joy-Con",rawId:a,vendorId:1406,productId:i}:{brand:"nintendo",model:"switch_pro",displayName:"Nintendo Switch Pro Controller",rawId:a,vendorId:1406,productId:i??8201}:a?{brand:"generic",model:"generic",displayName:a.split("(")[0].trim()||a,rawId:a,vendorId:r,productId:i}:{brand:"none",model:"none",displayName:"No Controller Detected",rawId:""}}var _e=(()=>{let a=new Uint32Array(256);for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;a[e]=t>>>0}return a})();function vt(a,e,t){let n=4294967295;n=_e[(n^a)&255]^n>>>8,n=_e[(n^e)&255]^n>>>8;for(let r=0;r<t.length;r++)n=_e[(n^t[r])&255]^n>>>8;return(n^4294967295)>>>0}function K(a){let e=new Uint8Array(11);if(a.type==="off")return e[0]=5,e;if(a.type==="feedback"||a.type==="slope"){e[0]=33;let s=new Array(10).fill(0);if(a.type==="feedback"){let h=Math.max(0,Math.min(9,Math.round(a.startZone))),u=Math.max(1,Math.min(8,Math.round(a.strength)));for(let c=h;c<10;c++)s[c]=u}else{let h=Math.max(0,Math.min(8,Math.round(a.startZone))),u=Math.max(h+1,Math.min(9,Math.round(a.endZone)));for(let c=h;c<=u;c++){let m=(c-h)/(u-h);s[c]=Math.max(1,Math.min(8,Math.round(a.startStrength+m*(a.endStrength-a.startStrength))))}}let l=0,d=0;for(let h=0;h<10;h++){let u=s[h];u>0&&(l|=1<<h,d|=(u-1&7)<<3*h)}return e[1]=l&255,e[2]=l>>8&255,e[3]=d&255,e[4]=d>>8&255,e[5]=d>>16&255,e[6]=d>>24&255,e}if(a.type==="weapon"){let s=Math.max(2,Math.min(7,Math.round(a.startZone))),l=Math.max(s+1,Math.min(8,Math.round(a.endZone))),d=Math.max(1,Math.min(8,Math.round(a.strength))),h=1<<s|1<<l;return e[0]=37,e[1]=h&255,e[2]=h>>8&255,e[3]=d-1&7,e}let t=Math.max(0,Math.min(9,Math.round(a.startZone))),n=Math.max(1,Math.min(8,Math.round(a.amplitude))),r=Math.max(1,Math.min(255,Math.round(a.frequencyHz))),i=0,o=0;for(let s=t;s<10;s++)i|=1<<s,o|=(n-1&7)<<3*s;return e[0]=38,e[1]=i&255,e[2]=i>>8&255,e[3]=o&255,e[4]=o>>8&255,e[5]=o>>16&255,e[6]=o>>24&255,e[9]=r,e}function j(){return{connected:!1,source:"none",deviceName:"",isDualSense:!1,identity:{brand:"none",model:"none",displayName:"No Controller Detected",rawId:"",transport:"disconnected",source:"none"},lx:0,ly:0,rx:0,ry:0,l2:0,r2:0,buttons:{cross:!1,circle:!1,square:!1,triangle:!1,l1:!1,r1:!1,l2Btn:!1,r2Btn:!1,l3:!1,r3:!1,up:!1,down:!1,left:!1,right:!1,create:!1,options:!1,ps:!1,touchpadClick:!1,mute:!1,fnL:!1,fnR:!1,paddleL:!1,paddleR:!1},touch:{active:!1,x:.5,y:.5},touch2:{active:!1,x:.5,y:.5},gyro:{x:0,y:0,z:0},accel:{x:0,y:0,z:0},battery:{percent:0,charging:!1,full:!1,known:!1},observedReportHz:null}}function yt(){let a=()=>({center:2048,minDelta:1500,maxDelta:1500});return{lx:a(),ly:a(),rx:a(),ry:a()}}var gt=[4,10,21,27],bt=[1,3,7,15];function ie(a){return new Promise(e=>setTimeout(e,a))}function St(a=0){return{speakerVolume:100,headphoneVolume:100,audioRoute:"speaker",speakerPreamp:7,lightbar:[23,23,23],playerLeds:gt[a%gt.length],muteLed:"off",leftTrigger:K({type:"off"}),rightTrigger:K({type:"off"}),legacyRumbleActive:!1,legacyLeft:0,legacyRight:0}}var le=class a{hidSessions=new Map;nextHidSeq=1;activeSlotId=null;hidDisconnectAttached=!1;hidConnectAttached=!1;listeners=new Set;gamepadInputs=new Map;gamepadLastActivity=new Map;gamepadPrevBtnMask=new Map;fallbackInput=j();keysDown=new Set;kbmAttached=!1;boundConnect=e=>{this.handleConnect(e)};boundDisconnect=e=>this.handleDisconnect(e);boundKeyDown=e=>{this.keysDown.add(e.code)};boundKeyUp=e=>{this.keysDown.delete(e.code)};boundWindowBlur=()=>{this.keysDown.clear()};get device(){return this.getActiveHidSession()?.device??null}getHidDevice(e){return this.getHidSessionForSlot(e)?.device??null}get transport(){return this.getActiveHidSession()?.transport??"disconnected"}get firmwareInfo(){return this.getActiveHidSession()?.firmwareInfo}get hidDeviceCount(){return this.hidSessions.size}static isWebHIDSupported(){return typeof navigator<"u"&&"hid"in navigator}static isGamepadSupported(){return typeof navigator<"u"&&typeof navigator.getGamepads=="function"}isSupportedHidDevice(e){return e.vendorId===1356&&ft.includes(e.productId)||e.vendorId===Le&&Ee.includes(e.productId)}attachHidHotplug(){this.hidConnectAttached||!a.isWebHIDSupported()||(navigator.hid.addEventListener("connect",this.boundConnect),this.hidConnectAttached=!0)}detachHidHotplug(){!this.hidConnectAttached||!a.isWebHIDSupported()||(navigator.hid.removeEventListener("connect",this.boundConnect),this.hidConnectAttached=!1)}async handleConnect(e){if(this.isSupportedHidDevice(e.device))try{await this.attachDevice(e.device)}catch{}}attachKeyboardFallback(){this.kbmAttached||typeof window>"u"||(window.addEventListener("keydown",this.boundKeyDown),window.addEventListener("keyup",this.boundKeyUp),window.addEventListener("blur",this.boundWindowBlur),this.kbmAttached=!0)}detachKeyboardFallback(){!this.kbmAttached||typeof window>"u"||(window.removeEventListener("keydown",this.boundKeyDown),window.removeEventListener("keyup",this.boundKeyUp),window.removeEventListener("blur",this.boundWindowBlur),this.keysDown.clear(),this.kbmAttached=!1)}onStatusChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emit(e){for(let t of this.listeners)try{t(e)}catch(n){console.error("[core-hid] listener error:",n)}}getAllRawGamepads(){if(!a.isGamepadSupported())return[];let e=navigator.getGamepads(),t=[];for(let n of e)n&&n.connected&&t.push(n);return t}pollGamepadActivity(e){let t=0,n=Math.min(20,e.buttons.length);for(let i=0;i<n;i++)e.buttons[i]?.pressed&&(t|=1<<i);let r=this.gamepadPrevBtnMask.get(e.index)??0;if(this.gamepadPrevBtnMask.set(e.index,t),(t&~r)!==0){let i=performance.now();return this.gamepadLastActivity.set(e.index,i),i}return this.gamepadLastActivity.get(e.index)??0}getConnectedControllers(){let e=[],t=0,n=0,r=0;for(let s of this.hidSessions.values())s.device.opened&&(s.input.identity.model==="dualsense_edge"?t++:s.input.identity.model==="switch_pro"?r++:n++,e.push({id:s.id,playerNumber:e.length+1,source:"webhid",identity:{...s.input.identity},battery:{...s.input.battery},observedReportHz:s.input.observedReportHz,lastActivityAt:s.lastActivityAt}));let i=this.getAllRawGamepads(),o=new Set;for(let s of i){o.add(s.index);let l=Ge(s.id||"");if(l.model==="dualsense_edge"&&t>0){t--;continue}if(l.model==="dualsense"&&n>0){n--;continue}if(l.model==="switch_pro"&&r>0){r--;continue}let d=this.pollGamepadActivity(s);e.push({id:`gp-${s.index}`,playerNumber:e.length+1,source:"gamepad",identity:{...l,transport:"unknown",source:"gamepad"},battery:{percent:0,charging:!1,full:!1,known:!1},observedReportHz:null,lastActivityAt:d})}for(let s of this.gamepadPrevBtnMask.keys())o.has(s)||(this.gamepadPrevBtnMask.delete(s),this.gamepadLastActivity.delete(s));return e.length===0?this.activeSlotId=null:(!this.activeSlotId||!e.some(s=>s.id===this.activeSlotId))&&(this.activeSlotId=e[0].id),e}getActiveSlotId(){return this.getConnectedControllers(),this.activeSlotId}setActiveSlot(e){return this.getConnectedControllers().some(n=>n.id===e)?(this.activeSlotId!==e&&(this.activeSlotId=e,this.emit({type:"slots_changed",slotId:e})),!0):!1}getHidSessionForSlot(e){if(e!==void 0){let i=this.hidSessions.get(e);return i&&i.device.opened?i:null}let t=this.getConnectedControllers(),n=this.activeSlotId??t[0]?.id??null;if(!n)return null;let r=this.hidSessions.get(n);return r&&r.device.opened?r:null}getActiveHidSession(){return this.getHidSessionForSlot()}getGamepadForSlot(e){if(!a.isGamepadSupported())return null;if(e!==void 0){if(!e.startsWith("gp-"))return null;let r=Number(e.slice(3)),i=navigator.getGamepads()[r];return i&&i.connected?i:null}let t=this.getConnectedControllers(),n=this.activeSlotId??t[0]?.id??null;if(n&&n.startsWith("gp-")){let r=Number(n.slice(3)),i=navigator.getGamepads()[r];if(i&&i.connected)return i}if(n&&n.startsWith("hid-"))return null;for(let r of navigator.getGamepads())if(r&&r.connected)return r;return null}getActiveGamepad(){return this.getGamepadForSlot()}getGamepadActuatorEffects(e){let n=this.getGamepadForSlot(e)?.vibrationActuator;return n?Array.isArray(n.effects)&&n.effects.length>0?n.effects:typeof n.playEffect=="function"?["dual-rumble"]:[]:[]}hasTriggerRumbleSupport(e){return this.getGamepadActuatorEffects(e).includes("trigger-rumble")}hasDualRumbleSupport(e){return this.getGamepadActuatorEffects(e).includes("dual-rumble")||!!this.getGamepadForSlot(e)?.vibrationActuator?.playEffect}async connect(){if(!a.isWebHIDSupported())throw new Error("WebHID requires a Chromium browser (Chrome or Edge on desktop).");let e=await navigator.hid.requestDevice({filters:[...ft.map(n=>({vendorId:1356,productId:n})),...Ee.map(n=>({vendorId:Le,productId:n}))]});if(!e.length)return!1;let t=null;for(let n of e)t=await this.attachDevice(n);return t&&(this.activeSlotId=t,this.emit({type:"slots_changed",slotId:t})),!!t}async reconnectAuthorized(){if(!a.isWebHIDSupported())return!1;let t=(await navigator.hid.getDevices()).filter(r=>this.isSupportedHidDevice(r));if(!t.length)return!1;let n=!1;for(let r of t)try{await this.attachDevice(r),n=!0}catch{}return n}async readFirmwareInfoSafe(e){try{let t=await e.receiveFeatureReport(32);if(t.byteLength<44)return;let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),r=n[0]===32?1:0,i=(u,c)=>{let m="";for(let b=u;b<u+c&&b<n.length;b++){let y=n[b];y>=32&&y<=126&&(m+=String.fromCharCode(y))}return m.trim()},o=i(r+0,11),s=i(r+11,8),l=new DataView(t.buffer,t.byteOffset+r),d=l.byteLength>=28?l.getUint32(24,!0):0,h=l.byteLength>=32?l.getUint32(28,!0):0;return!o&&!d?void 0:{buildDate:o||"Unknown",buildTime:s||"",hwInfoHex:`0x${d.toString(16).padStart(8,"0")}`,fwVersionHex:`0x${h.toString(16).padStart(8,"0")}`}}catch{return}}async attachDevice(e){for(let b of this.hidSessions.values())if(b.device===e&&b.device.opened)return b.id;if(e.opened||await e.open(),e.vendorId===Le&&Ee.includes(e.productId))return this.attachSwitchProDevice(e);let n=!1,r=!1,i=47,o=77;for(let b of e.collections||[])for(let y of b.outputReports||[]){let S=Math.ceil((y.items||[]).reduce((v,g)=>v+(g.reportSize||0)*(g.reportCount||0),0)/8);y.reportId===2&&(n=!0,S>=47&&(i=S)),y.reportId===49&&(r=!0,S>=77&&(o=S))}let s=n?"usb":r?"bluetooth":"usb",l=e.productId===3570,d=await this.readFirmwareInfoSafe(e),h=`hid-${this.nextHidSeq++}`,u=l?"DualSense Edge":"PlayStation DualSense",c=j();c.connected=!0,c.source="webhid",c.isDualSense=!0,c.deviceName=e.productName||u,c.identity={brand:"sony",model:l?"dualsense_edge":"dualsense",displayName:u,rawId:e.productName||u,vendorId:e.vendorId,productId:e.productId,transport:s,source:"webhid",firmwareInfo:d};let m={id:h,kind:"dualsense",device:e,transport:s,firmwareInfo:d,usbPayloadLength:i,btPayloadLength:o,btSeq:0,switchSubcmdLength:48,switchRumbleLength:9,switchUsb80Length:1,switchPacketNum:0,switchCal:yt(),switchRumbleTimer:null,switchSeqTimers:[],reportTimes:[],input:c,outState:St(this.hidSessions.size),legacyTimer:null,lastActivityAt:performance.now(),prevBtnMask:0,boundInputReport:b=>this.handleInputReport(m,b)};return this.hidSessions.set(h,m),this.activeSlotId||(this.activeSlotId=h),this.getConnectedControllers(),e.addEventListener("inputreport",m.boundInputReport),!this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.addEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!0),await this.flushSessionOutput(m,{includeAudioConfig:!0,includeTriggers:!0,includeLeds:!0}),this.emit({type:"connected",slotId:h,deviceName:c.deviceName,productId:e.productId,transport:s,firmwareInfo:d}),h}async attachSwitchProDevice(e){let t=!1,n=48,r=9,i=1;for(let c of e.collections||[])for(let m of c.outputReports||[]){let b=Math.ceil((m.items||[]).reduce((y,S)=>y+(S.reportSize||0)*(S.reportCount||0),0)/8);m.reportId===128&&(t=!0,b>=1&&(i=b)),m.reportId===1&&b>=10&&(n=b),m.reportId===16&&b>=9&&(r=b)}let o=t?"usb":"bluetooth",s=`hid-${this.nextHidSeq++}`,l="Nintendo Switch Pro Controller",d=j();d.connected=!0,d.source="webhid",d.isDualSense=!1,d.deviceName=e.productName||l,d.identity={brand:"nintendo",model:"switch_pro",displayName:l,rawId:e.productName||l,vendorId:e.vendorId,productId:e.productId,transport:o,source:"webhid"};let h=this.hidSessions.size,u={id:s,kind:"switch_pro",device:e,transport:o,firmwareInfo:void 0,usbPayloadLength:47,btPayloadLength:77,btSeq:0,switchSubcmdLength:n,switchRumbleLength:r,switchUsb80Length:i,switchPacketNum:0,switchCal:yt(),switchRumbleTimer:null,switchSeqTimers:[],reportTimes:[],input:d,outState:St(h),legacyTimer:null,lastActivityAt:performance.now(),prevBtnMask:0,boundInputReport:c=>this.handleSwitchProInputReport(u,c)};return this.hidSessions.set(s,u),this.activeSlotId||(this.activeSlotId=s),this.getConnectedControllers(),e.addEventListener("inputreport",u.boundInputReport),!this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.addEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!0),await this.initSwitchProSession(u,h),this.emit({type:"connected",slotId:s,deviceName:d.deviceName,productId:e.productId,transport:o}),s}async sendSwitchUsbCmd(e,t){if(!e.device.opened)return;let n=new Uint8Array(Math.max(1,e.switchUsb80Length));n[0]=t&255,await e.device.sendReport(128,n)}async sendSwitchSubcommand(e,t,n=[]){if(!e.device.opened)return;let r=Math.max(10+n.length,e.switchSubcmdLength),i=new Uint8Array(r);i[0]=e.switchPacketNum&15,e.switchPacketNum=e.switchPacketNum+1&15,i.set(U,1),i.set(U,5),i[9]=t&255;for(let o=0;o<n.length;o++)i[10+o]=n[o]&255;await e.device.sendReport(1,i)}async sendSwitchRumbleBytes(e,t,n){if(!e.device.opened)return!1;let r=Math.max(9,e.switchRumbleLength),i=new Uint8Array(r);return i[0]=e.switchPacketNum&15,e.switchPacketNum=e.switchPacketNum+1&15,i.set(t.subarray(0,4),1),i.set(n.subarray(0,4),5),await e.device.sendReport(16,i),!0}clearSwitchRumbleTimers(e){e.switchRumbleTimer&&(clearTimeout(e.switchRumbleTimer),e.switchRumbleTimer=null);for(let t of e.switchSeqTimers)clearTimeout(t);e.switchSeqTimers=[]}async initSwitchProSession(e,t){try{e.transport==="usb"&&(await this.sendSwitchUsbCmd(e,2).catch(()=>{}),await ie(25),await this.sendSwitchUsbCmd(e,4).catch(()=>{}),await ie(25)),await this.sendSwitchSubcommand(e,3,[48]),await ie(20),await this.sendSwitchSubcommand(e,64,[1]),await ie(20),await this.sendSwitchSubcommand(e,72,[1]),await ie(20),await this.sendSwitchSubcommand(e,48,[bt[t%bt.length]]),await ie(20),await this.sendSwitchSubcommand(e,16,[61,96,0,0,18]).catch(()=>{}),await ie(20),await this.sendSwitchSubcommand(e,2).catch(()=>{})}catch{}}parseSwitchDeviceInfo(e,t){if(t.byteLength<17||t.getUint8(13)!==2)return;let n=t.getUint8(14),r=t.getUint8(15);if(n===0&&r===0)return;let i={buildDate:"",buildTime:"",hwInfoHex:"",fwVersionHex:`v${n}.${r}`};e.firmwareInfo=i,e.input.identity.firmwareInfo=i}parseSwitchStickCalibration(e,t){if(t.byteLength<37||t.getUint8(13)!==16||t.getUint32(14,!0)!==24637)return;let r=g=>{let f=t.getUint8(g),w=t.getUint8(g+1),k=t.getUint8(g+2);return[f|(w&15)<<8,w>>4&15|k<<4]},[i,o]=r(19),[s,l]=r(22),[d,h]=r(25),[u,c]=r(28),[m,b]=r(31),[y,S]=r(34),v=(g,f,w)=>g>=900&&g<=3200&&f>=400&&f<=2400&&w>=400&&w<=2400;v(s,d,i)&&v(l,h,o)&&(e.switchCal.lx={center:s,minDelta:d,maxDelta:i},e.switchCal.ly={center:l,minDelta:h,maxDelta:o}),v(u,m,y)&&v(c,b,S)&&(e.switchCal.rx={center:u,minDelta:m,maxDelta:y},e.switchCal.ry={center:c,minDelta:b,maxDelta:S})}handleSwitchProInputReport(e,t){let{reportId:n,data:r}=t;if(n===33&&(this.parseSwitchStickCalibration(e,r),this.parseSwitchDeviceInfo(e,r)),n!==48&&n!==33||r.byteLength<11)return;let i=e.input,o=performance.now();if(n===48&&(e.reportTimes.push(o),e.reportTimes.length>33&&e.reportTimes.shift(),e.reportTimes.length>=6)){let g=e.reportTimes[e.reportTimes.length-1]-e.reportTimes[0];g>10&&(i.observedReportHz=Math.round((e.reportTimes.length-1)*1e3/g))}let s=r.getUint8(1),l=Math.min(4,s>>5&7);i.battery.percent=l*25,i.battery.charging=!!(s&16),i.battery.full=l>=4,i.battery.known=!0;let d=r.getUint8(2),h=r.getUint8(3),u=r.getUint8(4);i.buttons.square=!!(d&1),i.buttons.triangle=!!(d&2),i.buttons.cross=!!(d&4),i.buttons.circle=!!(d&8),i.buttons.r1=!!(d&64),i.buttons.r2Btn=!!(d&128),i.buttons.create=!!(h&1),i.buttons.options=!!(h&2),i.buttons.r3=!!(h&4),i.buttons.l3=!!(h&8),i.buttons.ps=!!(h&16),i.buttons.touchpadClick=!!(h&32),i.buttons.down=!!(u&1),i.buttons.up=!!(u&2),i.buttons.right=!!(u&4),i.buttons.left=!!(u&8),i.buttons.l1=!!(u&64),i.buttons.l2Btn=!!(u&128),i.l2=i.buttons.l2Btn?1:0,i.r2=i.buttons.r2Btn?1:0;let c=d&207|(h&63)<<8|(u&207)<<16;(c&~e.prevBtnMask)!==0&&(e.lastActivityAt=o),e.prevBtnMask=c;let m=(g,f)=>{let w=g-f.center,k=w>=0?f.maxDelta:f.minDelta,p=k>0?w/k:0;return Math.max(-1,Math.min(1,p))},b=r.getUint8(5)|(r.getUint8(6)&15)<<8,y=r.getUint8(6)>>4&15|r.getUint8(7)<<4,S=r.getUint8(8)|(r.getUint8(9)&15)<<8,v=r.getUint8(9)>>4&15|r.getUint8(10)<<4;if(i.lx=m(b,e.switchCal.lx),i.ly=-m(y,e.switchCal.ly),i.rx=m(S,e.switchCal.rx),i.ry=-m(v,e.switchCal.ry),n===48&&r.byteLength>=48){let g=0,f=0,w=0,k=0,p=0,x=0;for(let H=0;H<3;H++){let M=12+H*12;g+=r.getInt16(M+0,!0),f+=r.getInt16(M+2,!0),w+=r.getInt16(M+4,!0),k+=r.getInt16(M+6,!0),p+=r.getInt16(M+8,!0),x+=r.getInt16(M+10,!0)}let C=g/3,A=f/3,R=w/3,I=k/3,P=p/3,D=x/3,T=H=>Math.max(-1,Math.min(1,H));i.accel.x=T(A/4096),i.accel.y=T(R/4096),i.accel.z=T(-C/4096),i.gyro.x=T(P/8192),i.gyro.y=T(D/8192),i.gyro.z=T(I/8192)}}async disconnect(e,t={}){let n=e??this.activeSlotId??Array.from(this.hidSessions.keys())[0];if(!n)return;let r=this.hidSessions.get(n);if(r){r.legacyTimer&&(clearTimeout(r.legacyTimer),r.legacyTimer=null),this.clearSwitchRumbleTimers(r);try{r.kind==="switch_pro"?await this.sendSwitchRumbleBytes(r,U,U):(r.outState.leftTrigger=K({type:"off"}),r.outState.rightTrigger=K({type:"off"}),r.outState.legacyRumbleActive=!1,r.outState.legacyLeft=0,r.outState.legacyRight=0,await this.flushSessionOutput(r,{includeTriggers:!0}))}catch{}r.device.removeEventListener("inputreport",r.boundInputReport);try{r.device.opened&&await r.device.close()}catch{}if(this.hidSessions.delete(n),this.hidSessions.size===0&&this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.removeEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!1),this.activeSlotId===n){let i=this.getConnectedControllers();this.activeSlotId=i[0]?.id??null}if(this.emit({type:"disconnected",slotId:n}),t.forget){let i=r.device;typeof i.forget=="function"&&await i.forget().catch(()=>{})}}}async disconnectAll(){let e=Array.from(this.hidSessions.keys());for(let t of e)await this.disconnect(t)}handleDisconnect(e){for(let[t,n]of this.hidSessions.entries())if(n.device===e.device){if(n.legacyTimer&&(clearTimeout(n.legacyTimer),n.legacyTimer=null),this.clearSwitchRumbleTimers(n),n.device.removeEventListener("inputreport",n.boundInputReport),this.hidSessions.delete(t),this.activeSlotId===t){let r=this.getConnectedControllers();this.activeSlotId=r[0]?.id??null}this.emit({type:"disconnected",slotId:t})}this.hidSessions.size===0&&this.hidDisconnectAttached&&typeof navigator<"u"&&navigator.hid&&(navigator.hid.removeEventListener("disconnect",this.boundDisconnect),this.hidDisconnectAttached=!1)}handleInputReport(e,t){let{reportId:n,data:r}=t,i=0;if(n===49&&r.byteLength>=40)i=1;else if(n!==1||r.byteLength<10)return;let o=e.input,s=performance.now();if(e.reportTimes.push(s),e.reportTimes.length>33&&e.reportTimes.shift(),e.reportTimes.length>=6){let y=e.reportTimes[e.reportTimes.length-1]-e.reportTimes[0];y>10&&(o.observedReportHz=Math.round((e.reportTimes.length-1)*1e3/y))}let l=y=>{let S=y>=128?(y-128)/127:(y-128)/128;return Math.max(-1,Math.min(1,S))};o.lx=l(r.getUint8(i+0)),o.ly=l(r.getUint8(i+1)),o.rx=l(r.getUint8(i+2)),o.ry=l(r.getUint8(i+3)),o.l2=r.getUint8(i+4)/255,o.r2=r.getUint8(i+5)/255;let d=r.getUint8(i+7),h=r.getUint8(i+8),u=r.getUint8(i+9),c=d&15;o.buttons.up=c===0||c===1||c===7,o.buttons.right=c===1||c===2||c===3,o.buttons.down=c===3||c===4||c===5,o.buttons.left=c===5||c===6||c===7,o.buttons.square=!!(d&16),o.buttons.cross=!!(d&32),o.buttons.circle=!!(d&64),o.buttons.triangle=!!(d&128),o.buttons.l1=!!(h&1),o.buttons.r1=!!(h&2),o.buttons.l2Btn=!!(h&4),o.buttons.r2Btn=!!(h&8),o.buttons.create=!!(h&16),o.buttons.options=!!(h&32),o.buttons.l3=!!(h&64),o.buttons.r3=!!(h&128),o.buttons.ps=!!(u&1),o.buttons.touchpadClick=!!(u&2),o.buttons.mute=!!(u&4),o.buttons.fnL=!!(u&16),o.buttons.fnR=!!(u&32),o.buttons.paddleL=!!(u&64),o.buttons.paddleR=!!(u&128);let m=d&240|(c<8?1:0)|h<<8|(u&247)<<16;(m&~e.prevBtnMask)!==0&&(e.lastActivityAt=s),e.prevBtnMask=m,r.byteLength>i+26&&(o.gyro.x=Math.max(-1,Math.min(1,r.getInt16(i+15,!0)/16384)),o.gyro.y=Math.max(-1,Math.min(1,r.getInt16(i+17,!0)/16384)),o.gyro.z=Math.max(-1,Math.min(1,r.getInt16(i+19,!0)/16384)),o.accel.x=Math.max(-1,Math.min(1,r.getInt16(i+21,!0)/8192)),o.accel.y=Math.max(-1,Math.min(1,r.getInt16(i+23,!0)/8192)),o.accel.z=Math.max(-1,Math.min(1,r.getInt16(i+25,!0)/8192)));let b=(y,S)=>{if(r.byteLength<=y+3)return;let g=(r.getUint8(y)&128)===0;if(S.active=g,g){let f=r.getUint8(y+1),w=r.getUint8(y+2),k=r.getUint8(y+3),p=f|(w&15)<<8,x=(w&240)>>4|k<<4;S.x=Math.max(0,Math.min(1,p/1919)),S.y=Math.max(0,Math.min(1,x/1079))}};if(b(i+32,o.touch),b(i+36,o.touch2),r.byteLength>i+52){let y=r.getUint8(i+52),S=y&15,v=y>>4&15;o.battery.charging=v===1,o.battery.full=v===2,o.battery.percent=v===2?100:Math.min(100,Math.round((S+.5)/10*100)),o.battery.known=!0}}populateGamepadInput(e,t){let n=i=>Math.max(-1,Math.min(1,Number.isFinite(i)?i:0)),r=Ge(e.id||"");return t.connected=!0,t.source="gamepad",t.deviceName=r.displayName,t.isDualSense=r.model==="dualsense"||r.model==="dualsense_edge",t.identity={...r,transport:"unknown",source:"gamepad"},t.lx=n(e.axes[0]??0),t.ly=n(e.axes[1]??0),t.rx=n(e.axes[2]??0),t.ry=n(e.axes[3]??0),t.l2=Math.max(0,Math.min(1,e.buttons[6]?.value??0)),t.r2=Math.max(0,Math.min(1,e.buttons[7]?.value??0)),t.buttons.cross=!!e.buttons[0]?.pressed,t.buttons.circle=!!e.buttons[1]?.pressed,t.buttons.square=!!e.buttons[2]?.pressed,t.buttons.triangle=!!e.buttons[3]?.pressed,t.buttons.l1=!!e.buttons[4]?.pressed,t.buttons.r1=!!e.buttons[5]?.pressed,t.buttons.l2Btn=!!e.buttons[6]?.pressed,t.buttons.r2Btn=!!e.buttons[7]?.pressed,t.buttons.create=!!e.buttons[8]?.pressed,t.buttons.options=!!e.buttons[9]?.pressed,t.buttons.l3=!!e.buttons[10]?.pressed,t.buttons.r3=!!e.buttons[11]?.pressed,t.buttons.up=!!e.buttons[12]?.pressed,t.buttons.down=!!e.buttons[13]?.pressed,t.buttons.left=!!e.buttons[14]?.pressed,t.buttons.right=!!e.buttons[15]?.pressed,t.buttons.ps=!!e.buttons[16]?.pressed,t.buttons.touchpadClick=!!e.buttons[17]?.pressed,t.touch.active=!1,t.touch2.active=!1,t.battery.known=!1,t.observedReportHz=null,t}getInputStateForSlot(e){let t=this.getHidSessionForSlot(e);if(t)return t.input;let n=this.getGamepadForSlot(e);if(n){let r=this.gamepadInputs.get(n.index);return r||(r=j(),this.gamepadInputs.set(n.index,r)),this.populateGamepadInput(n,r)}return j()}getInputState(e){if(e!==void 0)return this.getInputStateForSlot(e);let t=this.getActiveHidSession();if(t)return t.input;let n=this.getActiveGamepad();if(n)return this.populateGamepadInput(n,this.fallbackInput);let r=this.keysDown,i=(r.has("KeyD")||r.has("ArrowRight")?1:0)-(r.has("KeyA")||r.has("ArrowLeft")?1:0),o=(r.has("KeyS")||r.has("ArrowDown")?1:0)-(r.has("KeyW")||r.has("ArrowUp")?1:0),s=this.fallbackInput;return s.connected=!1,s.source="keyboard_mouse",s.deviceName="Keyboard & Mouse",s.isDualSense=!1,s.identity={brand:"none",model:"none",displayName:"Keyboard & Mouse",rawId:"",transport:"disconnected",source:"keyboard_mouse"},s.lx=i,s.ly=o,s.rx=0,s.ry=0,s.l2=r.has("ShiftLeft")||r.has("KeyQ")?1:0,s.r2=r.has("Space")||r.has("KeyE")?1:0,s.buttons.cross=r.has("Space")||r.has("Enter"),s.buttons.circle=r.has("KeyC")||r.has("Escape"),s.buttons.square=r.has("KeyR"),s.buttons.triangle=r.has("KeyF"),s.buttons.l1=r.has("KeyQ"),s.buttons.r1=r.has("KeyE"),s.buttons.l2Btn=s.l2>.5,s.buttons.r2Btn=s.r2>.5,s.buttons.l3=!1,s.buttons.r3=!1,s.buttons.up=r.has("ArrowUp")||r.has("KeyW"),s.buttons.down=r.has("ArrowDown")||r.has("KeyS"),s.buttons.left=r.has("ArrowLeft")||r.has("KeyA"),s.buttons.right=r.has("ArrowRight")||r.has("KeyD"),s.buttons.create=!1,s.buttons.options=!1,s.buttons.ps=!1,s.buttons.touchpadClick=!1,s.touch.active=!1,s.touch2.active=!1,s.battery.known=!1,s.observedReportHz=null,s}getCapabilityMatrixForSlot(e,t={}){let n=this.getInputState(e),r=n.identity,i=this.getHidSessionForSlot(e),o=i?.kind==="dualsense",s=i?.kind==="switch_pro",l=!!i,d=i?.transport??"unknown",h=a.isWebHIDSupported(),u=r.model==="dualsense"||r.model==="dualsense_edge",c=r.brand==="xbox",m=r.model==="switch_pro",b=r.brand==="nintendo",y=n.connected,S=this.hasTriggerRumbleSupport(e),v=this.hasDualRumbleSupport(e);if(!y){let g={inherent:!1,availability:"disconnected"};return{standard_input:g,analog_triggers:g,dual_motor_rumble:g,impulse_triggers:g,hd_rumble:g,adaptive_triggers:g,audio_haptics:g,controller_speaker:g,gyro:g,accelerometer:g,touchpad:g,lightbar:g,battery:g}}return{standard_input:{inherent:!0,availability:"ready"},analog_triggers:{inherent:!b,availability:b?"unsupported":"ready",reason:b?"Nintendo Pro/Joy-Con triggers are digital buttons":void 0},dual_motor_rumble:{inherent:!0,availability:l||v?"ready":"unsupported",reason:!l&&!v?"Browser Gamepad rumble actuator not exposed":void 0},impulse_triggers:{inherent:c,availability:c&&S?"ready":"unsupported",reason:c&&!S?"Requires Chrome/Edge 126+ with USB or Xbox Wireless Adapter (Windows Bluetooth often blocks trigger motors)":void 0},hd_rumble:{inherent:b,availability:b?s?"ready":m?h?"permission_required":"unsupported":"bridge_required":"unsupported",reason:m&&!s?h?"Connect Switch Pro via WebHID to unlock dual-band HD Rumble and 6-axis gyro":"WebHID requires desktop Chrome or Edge":void 0},adaptive_triggers:{inherent:u,availability:u?o?"ready":h?"permission_required":"unsupported":"unsupported",reason:u&&!o?h?"Click Unlock DualSense WebHID (works over USB & Bluetooth)":"WebHID requires desktop Chrome or Edge":void 0},audio_haptics:{inherent:u,availability:u?t.has4ChAudio?"ready":d==="bluetooth"?"configuration_required":"bridge_required":"unsupported",reason:u&&!t.has4ChAudio?d==="bluetooth"?"4-channel audio haptics require a wired USB-C connection on Windows":"Optional Gamepadly Link or USB 4ch audio routing required":void 0},controller_speaker:{inherent:u,availability:u?t.hasControllerSpeaker?"ready":d==="bluetooth"?"configuration_required":"bridge_required":"unsupported",reason:u&&!t.hasControllerSpeaker?"Requires wired USB-C DualSense audio output":void 0},gyro:{inherent:u||b,availability:u?o?"ready":h?"permission_required":"unsupported":m?s?"ready":h?"permission_required":"unsupported":b?"bridge_required":"unsupported"},accelerometer:{inherent:u||b,availability:u?o?"ready":h?"permission_required":"unsupported":m?s?"ready":h?"permission_required":"unsupported":b?"bridge_required":"unsupported"},touchpad:{inherent:u||r.model==="dualshock4",availability:u?o?"ready":h?"permission_required":"unsupported":"unsupported"},lightbar:{inherent:u||r.model==="dualshock4",availability:u?o?"ready":h?"permission_required":"unsupported":"unsupported"},battery:{inherent:!0,availability:u&&o||m&&s?"ready":"unknown"}}}getCapabilityMatrix(e={}){return this.getCapabilityMatrixForSlot(void 0,e)}async playSwitchHdRumble(e,t){let n=this.getHidSessionForSlot(t);if(!n||n.kind!=="switch_pro"||!n.device.opened)return!1;this.clearSwitchRumbleTimers(n);let r=de(e.left),i=de(e.right),o=Math.max(30,Math.min(2500,Math.round(e.durationMs??220)));try{await this.sendSwitchRumbleBytes(n,r,i)}catch{return!1}return n.switchRumbleTimer=setTimeout(()=>{n.switchRumbleTimer=null,this.sendSwitchRumbleBytes(n,U,U).catch(()=>{})},o),!0}async playSwitchHdRumbleSequence(e,t){let n=this.getHidSessionForSlot(t);if(!n||n.kind!=="switch_pro"||!n.device.opened||e.length===0)return!1;this.clearSwitchRumbleTimers(n);let r=0;for(let i of e){let o=Math.max(0,Math.round(i.delayMs)),s=Math.max(30,Math.min(1200,Math.round(i.durationMs??80)));o+s>r&&(r=o+s);let l=de(i.left),d=de(i.right);if(o===0)await this.sendSwitchRumbleBytes(n,l,d).catch(()=>{});else{let h=setTimeout(()=>{this.sendSwitchRumbleBytes(n,l,d).catch(()=>{})},o);n.switchSeqTimers.push(h)}}return n.switchRumbleTimer=setTimeout(()=>{n.switchRumbleTimer=null,n.switchSeqTimers=[],this.sendSwitchRumbleBytes(n,U,U).catch(()=>{})},r+15),!0}stopSwitchHdRumble(e){if(e!==void 0){let t=this.getHidSessionForSlot(e);t&&t.kind==="switch_pro"&&t.device.opened&&(this.clearSwitchRumbleTimers(t),this.sendSwitchRumbleBytes(t,U,U).catch(()=>{}));return}for(let t of this.hidSessions.values())t.kind!=="switch_pro"||!t.device.opened||(this.clearSwitchRumbleTimers(t),this.sendSwitchRumbleBytes(t,U,U).catch(()=>{}))}async playTriggerRumble(e,t,n,r=0,i=0,o){if(this.getHidSessionForSlot(o)?.kind==="switch_pro"){let v=Math.max(e,i),g=Math.max(t,r);return this.playSwitchHdRumble({left:v>.02?{highFreqHz:260,highAmp:v*.65,lowFreqHz:145,lowAmp:v*.7}:void 0,right:g>.02?{highFreqHz:340,highAmp:g*.7,lowFreqHz:170,lowAmp:g*.55}:void 0,durationMs:n},o)}let d=this.getGamepadForSlot(o)?.vibrationActuator;if(!d?.playEffect)return!1;let h=Math.max(20,Math.min(2500,Math.round(n))),u=Math.max(0,Math.min(1,e)),c=Math.max(0,Math.min(1,t)),m=Math.max(0,Math.min(1,r)),b=Math.max(0,Math.min(1,i));if(this.hasTriggerRumbleSupport(o))try{return await d.playEffect("trigger-rumble",{startDelay:0,duration:h,leftTrigger:u,rightTrigger:c,weakMagnitude:m,strongMagnitude:b}),!0}catch{}let y=Math.max(m,c*.65),S=Math.max(b,u*.65);return y>0||S>0?this.playDualRumble(y,S,h,o):!1}async playDualRumble(e,t,n,r){if(this.getHidSessionForSlot(r)?.kind==="switch_pro"){let l={highFreqHz:320,highAmp:Math.max(0,Math.min(.85,e*.8)),lowFreqHz:150,lowAmp:Math.max(0,Math.min(.85,t*.8))};return this.playSwitchHdRumble({left:l,right:l,durationMs:n},r)}let s=this.getGamepadForSlot(r)?.vibrationActuator;if(!s?.playEffect)return!1;try{return await s.playEffect("dual-rumble",{startDelay:0,duration:Math.max(20,Math.min(2500,Math.round(n))),strongMagnitude:Math.max(0,Math.min(1,t)),weakMagnitude:Math.max(0,Math.min(1,e))}),!0}catch{return!1}}stopGamepadRumble(e){if(this.stopSwitchHdRumble(e),!!a.isGamepadSupported()){if(e!==void 0){let t=this.getGamepadForSlot(e);t?.vibrationActuator?.reset&&t.vibrationActuator.reset().catch(()=>{});return}for(let t of this.getAllRawGamepads()){let n=t.vibrationActuator;n?.reset&&n.reset().catch(()=>{})}}}triggerGamepadRumbleFallback(e,t,n,r){let i=this.getHidSessionForSlot(r);if(i?.kind==="switch_pro"){this.playDualRumble(e,t,n,r);return}if(i?.kind==="dualsense"){this.pulseLegacyRumble(Math.round(Math.max(0,Math.min(1,t))*220),Math.round(Math.max(0,Math.min(1,e))*220),Math.max(25,Math.min(350,n)),r);return}this.playDualRumble(e,t,n,r)}buildCommonPayload(e,{includeAudioConfig:t=!1,includeTriggers:n=!1,includeLeds:r=!1}={}){let i=new Uint8Array(47),o=0,s=0;return e.legacyRumbleActive&&(o|=3,i[2]=Math.max(0,Math.min(255,Math.round(e.legacyRight))),i[3]=Math.max(0,Math.min(255,Math.round(e.legacyLeft)))),n&&(o|=12,i.set(e.rightTrigger.subarray(0,11),10),i.set(e.leftTrigger.subarray(0,11),21)),t&&(o|=176,s|=130,i[4]=Math.max(0,Math.min(127,e.headphoneVolume)),i[5]=Math.max(0,Math.min(255,e.speakerVolume)),i[6]=0,i[7]=e.audioRoute==="speaker"?48:e.audioRoute==="both"?32:0,i[9]=0,i[37]=e.speakerPreamp&7),r&&(s|=21,i[8]=e.muteLed==="on"?1:e.muteLed==="pulse"?2:0,i[38]=2,i[41]=2,i[42]=0,i[43]=e.playerLeds&31,i[44]=e.lightbar[0]&255,i[45]=e.lightbar[1]&255,i[46]=e.lightbar[2]&255),i[0]=o,i[1]=s,i}async flushSessionOutput(e,t={}){if(e.kind!=="dualsense"||!e.device.opened)return!1;let n=this.buildCommonPayload(e.outState,t);if(e.transport==="bluetooth"){let i=new Uint8Array(e.btPayloadLength);i[0]=(e.btSeq&15)<<4,e.btSeq=e.btSeq+1&15,i[1]=16,i.set(n,2);let o=i.length-4,s=vt(162,49,i.subarray(0,o));return new DataView(i.buffer).setUint32(o,s,!0),await e.device.sendReport(49,i),!0}let r=new Uint8Array(e.usbPayloadLength);return r.set(n,0),await e.device.sendReport(2,r),!0}async flushOutput(e={}){let t=this.getActiveHidSession();return!t||t.kind!=="dualsense"?!1:this.flushSessionOutput(t,e)}async setAudioConfig(e){let t=this.getActiveHidSession();return!t||t.kind!=="dualsense"?!1:(e.speakerVolume!==void 0&&(t.outState.speakerVolume=e.speakerVolume),e.headphoneVolume!==void 0&&(t.outState.headphoneVolume=e.headphoneVolume),e.audioRoute!==void 0&&(t.outState.audioRoute=e.audioRoute),e.speakerPreamp!==void 0&&(t.outState.speakerPreamp=e.speakerPreamp),this.flushSessionOutput(t,{includeAudioConfig:!0}))}async setTriggers(e,t,n){let r=this.getHidSessionForSlot(n);if(!r||r.kind!=="dualsense")return!1;let i=r.outState.leftTrigger,o=r.outState.rightTrigger,s=e?K(e):void 0,l=t?K(t):void 0;s&&(r.outState.leftTrigger=s),l&&(r.outState.rightTrigger=l);try{let d=await this.flushSessionOutput(r,{includeTriggers:!0});return d||(s&&r.outState.leftTrigger===s&&(r.outState.leftTrigger=i),l&&r.outState.rightTrigger===l&&(r.outState.rightTrigger=o)),d}catch(d){throw s&&r.outState.leftTrigger===s&&(r.outState.leftTrigger=i),l&&r.outState.rightTrigger===l&&(r.outState.rightTrigger=o),d}}async resetTriggers(e){if(this.stopGamepadRumble(e),e!==void 0){let n=this.getHidSessionForSlot(e);return!n||!n.device.opened||n.kind!=="dualsense"?!1:(n.outState.leftTrigger=K({type:"off"}),n.outState.rightTrigger=K({type:"off"}),this.flushSessionOutput(n,{includeTriggers:!0}).catch(()=>!1))}let t=!1;for(let n of this.hidSessions.values()){if(!n.device.opened||n.kind!=="dualsense")continue;n.outState.leftTrigger=K({type:"off"}),n.outState.rightTrigger=K({type:"off"}),await this.flushSessionOutput(n,{includeTriggers:!0}).catch(()=>!1)&&(t=!0)}return t}emergencyReset(){this.stopGamepadRumble();for(let e of this.hidSessions.values())if(e.device.opened){if(e.kind==="switch_pro"){this.clearSwitchRumbleTimers(e),this.sendSwitchRumbleBytes(e,U,U).catch(()=>{});continue}e.outState.leftTrigger=K({type:"off"}),e.outState.rightTrigger=K({type:"off"}),e.outState.legacyRumbleActive=!1,e.outState.legacyLeft=0,e.outState.legacyRight=0,e.outState.lightbar=[23,23,23],e.outState.muteLed="off",this.flushSessionOutput(e,{includeTriggers:!0,includeLeds:!0}).catch(()=>{})}}async setLightbar(e,t,n,r){let i=this.getHidSessionForSlot(r);return!i||i.kind!=="dualsense"?!1:(i.outState.lightbar=[e&255,t&255,n&255],this.flushSessionOutput(i,{includeLeds:!0}))}async setPlayerLeds(e,t){let n=this.getHidSessionForSlot(t);return!n||!n.device.opened?!1:n.kind==="switch_pro"?(await this.sendSwitchSubcommand(n,48,[e&15]),!0):(n.outState.playerLeds=e&31,this.flushSessionOutput(n,{includeLeds:!0}))}async setMuteLed(e,t){let n=this.getHidSessionForSlot(t);return!n||n.kind!=="dualsense"?!1:(n.outState.muteLed=e,this.flushSessionOutput(n,{includeLeds:!0}))}async pulseLegacyRumble(e=200,t=200,n=250,r){let i=this.getHidSessionForSlot(r);return!i||i.kind!=="dualsense"||!i.device.opened?!1:(i.legacyTimer&&(clearTimeout(i.legacyTimer),i.legacyTimer=null),i.outState.legacyRumbleActive=!0,i.outState.legacyLeft=e,i.outState.legacyRight=t,await this.flushSessionOutput(i,{}),new Promise(o=>{i.legacyTimer=setTimeout(async()=>{i.legacyTimer=null;try{i.outState.legacyLeft=0,i.outState.legacyRight=0,await this.flushSessionOutput(i,{}),i.outState.legacyRumbleActive=!1,await this.flushSessionOutput(i,{includeAudioConfig:!0})}catch{}o(!0)},n)}))}};var pe={off:{type:"off"},weapon:{type:"weapon",startZone:2,endZone:5,strength:7},heavy_weapon:{type:"weapon",startZone:3,endZone:6,strength:8},bow:{type:"slope",startZone:1,endZone:8,startStrength:1,endStrength:7},abs:{type:"vibration",startZone:2,amplitude:6,frequencyHz:22},soft_wall:{type:"feedback",startZone:4,strength:4},rapid_pulse:{type:"vibration",startZone:1,amplitude:7,frequencyHz:14},precision_damp:{type:"feedback",startZone:2,strength:3}},qe={click:{freqHz:210,endFreqHz:140,durationMs:26,intensity:.45,wave:"triangle",triggerEmphasis:.65,switchHd:{highFreqHz:340,lowFreqHz:165,highWeight:.75,lowWeight:.25}},ratchet:{freqHz:180,endFreqHz:110,durationMs:22,intensity:.5,wave:"triangle",triggerEmphasis:.75,switchHd:{highFreqHz:320,lowFreqHz:155,highWeight:.8,lowWeight:.2}},wall_hit:{freqHz:135,endFreqHz:58,durationMs:65,intensity:.78,wave:"triangle",triggerEmphasis:.5,switchHd:{highFreqHz:290,lowFreqHz:130,highWeight:.55,lowWeight:.75}},marble_click:{freqHz:290,endFreqHz:210,durationMs:32,intensity:.62,wave:"sine",triggerEmphasis:.85,switchHd:{highFreqHz:380,lowFreqHz:190,highWeight:.85,lowWeight:.18}},recoil:{freqHz:115,endFreqHz:46,durationMs:75,intensity:.88,wave:"triangle",triggerEmphasis:1,switchHd:{highFreqHz:310,lowFreqHz:120,highWeight:.65,lowWeight:.85}},heavy_impact:{freqHz:75,endFreqHz:34,durationMs:140,intensity:.95,wave:"sine",triggerEmphasis:.7,switchHd:{highFreqHz:220,lowFreqHz:95,highWeight:.45,lowWeight:.95}},lock_unlock:{freqHz:95,endFreqHz:220,durationMs:120,intensity:.72,wave:"triangle",triggerEmphasis:.6,switchHd:{highFreqHz:350,lowFreqHz:150,highWeight:.7,lowWeight:.55}},splash:{freqHz:90,endFreqHz:48,durationMs:110,intensity:.6,wave:"sine",triggerEmphasis:.35,switchHd:{highFreqHz:250,lowFreqHz:120,highWeight:.5,lowWeight:.6}},boost:{freqHz:65,endFreqHz:165,durationMs:160,intensity:.75,wave:"sawtooth",triggerEmphasis:.85,switchHd:{highFreqHz:300,lowFreqHz:135,highWeight:.6,lowWeight:.75}},error_buzz:{freqHz:145,endFreqHz:115,durationMs:95,intensity:.65,wave:"square",triggerEmphasis:.45,switchHd:{highFreqHz:260,lowFreqHz:125,highWeight:.55,lowWeight:.65}}};function he(a){let e=Math.max(-1,Math.min(1,a.pan??0)),t=Math.max(0,Math.min(1,a.intensity)),n=Math.min(1,1-Math.max(0,e)),r=Math.min(1,1+Math.min(0,e)),i=a.highFreqHz??Math.max(160,Math.min(620,a.freqHz*1.9)),o=a.lowFreqHz??Math.max(60,Math.min(240,a.freqHz)),s=a.highWeight??(a.freqHz>=140?.78:.42),l=a.lowWeight??(a.freqHz<140?.82:.38),d=h=>{let u=t*h;if(!(u<.02))return{highFreqHz:i,highAmp:Math.min(.85,u*s*.85),lowFreqHz:o,lowAmp:Math.min(.85,u*l*.85)}};return{left:d(n),right:d(r),durationMs:Math.max(30,Math.min(2500,Math.round(a.durationMs)))}}function ze(a){return a.allow4ChAudio===!1?!1:!!(a.audio&&a.audio.dsMode!=="none"&&a.audio.dsMaxChannelCount>=4)}function ce(a,e){if(ze(a)){a.audio.playHapticPulse(e);return}let t=a.hid.getCapabilityMatrixForSlot(a.slotId),n=Math.max(0,Math.min(1,e.intensity)),r=Math.max(25,Math.min(2500,Math.round(e.durationMs))),i=Math.max(-1,Math.min(1,e.pan??0));if(t.hd_rumble?.availability==="ready"){let l=he({pan:i,freqHz:e.freqHz,intensity:n,durationMs:r});a.hid.playSwitchHdRumble(l,a.slotId);return}if(t.impulse_triggers?.availability==="ready"){let l=Math.min(1,1-Math.max(0,i)),d=Math.min(1,1+Math.min(0,i)),h=e.freqHz>=120?.85:.45,u=e.freqHz<120?.78:.35;a.hid.playTriggerRumble(n*l*h,n*d*h,r,n*(e.freqHz>=120?.65:.35),n*u,a.slotId);return}let o=e.freqHz<120?n*.8:n*.3,s=e.freqHz>=120?n*.85:n*.4;a.hid.triggerGamepadRumbleFallback(s,o,r,a.slotId)}function Oe(a,e){if(ze(a)){a.audio.playHapticSweep(e);return}let t=a.hid.getCapabilityMatrixForSlot(a.slotId),n=Math.max(0,Math.min(1,e.intensity)),r=Math.max(40,Math.min(2500,Math.round(e.durationMs)));if(t.hd_rumble?.availability==="ready"){let i=Math.max(2,Math.min(6,Math.round(r/55))),o=Math.max(30,Math.round(r/i)),s=[];for(let l=0;l<i;l++){let d=i===1?0:l/(i-1),h=e.fromPan+(e.toPan-e.fromPan)*d,u=e.fromHz+(e.toHz-e.fromHz)*d;s.push({...he({pan:h,freqHz:u,intensity:n,durationMs:o}),delayMs:l*o})}a.hid.playSwitchHdRumbleSequence(s,a.slotId);return}if(t.impulse_triggers?.availability==="ready"){let i=(e.fromPan+e.toPan)*.5,o=Math.min(1,1-Math.max(0,i)),s=Math.min(1,1+Math.min(0,i));a.hid.playTriggerRumble(n*o*.7,n*s*.7,r,n*.5,n*.6,a.slotId);return}a.hid.triggerGamepadRumbleFallback(n*.55,n*.65,r,a.slotId)}function Fe(a,e,t={}){let n=qe[e];if(!n)return;let r=Math.max(-1,Math.min(1,t.pan??0)),i=Math.max(0,Math.min(1,(t.intensity??1)*n.intensity));if(ze(a)){a.audio.playHapticPulse({pan:r,freqHz:n.freqHz,endFreqHz:n.endFreqHz,durationMs:n.durationMs,intensity:i,wave:n.wave});return}let o=a.hid.getCapabilityMatrixForSlot(a.slotId);if(o.hd_rumble?.availability==="ready"&&n.switchHd){let s=he({pan:r,freqHz:n.freqHz,intensity:i,durationMs:n.durationMs,highFreqHz:n.switchHd.highFreqHz,lowFreqHz:n.switchHd.lowFreqHz,highWeight:n.switchHd.highWeight,lowWeight:n.switchHd.lowWeight});a.hid.playSwitchHdRumble(s,a.slotId);return}if(o.impulse_triggers?.availability==="ready"&&n.triggerEmphasis){let s=Math.min(1,1-Math.max(0,r)),l=Math.min(1,1+Math.min(0,r)),d=i*n.triggerEmphasis;a.hid.playTriggerRumble(d*s,d*l,Math.max(30,n.durationMs),i*.45,i*.55,a.slotId);return}ce(a,{pan:r,freqHz:n.freqHz,endFreqHz:n.endFreqHz,durationMs:n.durationMs,intensity:i,wave:n.wave})}var N={update(){},stop(){},get active(){return!1}};function wt(a,e,t){return Math.max(e,Math.min(t,a))}function Ot(a){let e=a>>>0;return()=>(e=e*1664525+1013904223>>>0,e/4294967296*2-1)}function Ft(a,e=48e3){let t=Math.max(8e3,Math.round(e)),n=Ot(a.length*9973+1337),i=Math.max(64,Math.round({footstep_ice:.09,footstep_metal:.14,footstep_gravel:.11,footstep_water:.16,zipper_tick:.032,spring_boing:.28,engine_hum:.5}[a]*t)),o=new Float32Array(i),s=new Float32Array(i),l=new Float32Array(i),d=new Float32Array(i),h=0,u=0,c=0;for(let m=0;m<i;m++){let b=m/t,y=m/i,S=n();h=h*.72+S*.28;let v=0,g=0;switch(a){case"footstep_ice":{let k=Math.pow(1-y,2.2)*Math.min(1,b/.003);u+=2*Math.PI*(240-y*90)/t,c+=2*Math.PI*(2400-y*950)/t,g=(Math.sin(u)*.65+(S-h)*.45)*k,v=(Math.sin(c)*.45+(S-h)*.65)*k;break}case"footstep_metal":{let k=Math.pow(1-y,1.8)*Math.min(1,b/.002),p=Math.pow(1-y,1.4)*Math.min(1,b/.002);u+=2*Math.PI*(148-y*35)/t,c+=2*Math.PI*1380/t,g=(Math.sin(u)*.78+Math.sin(u*2.13)*.22)*k,v=(Math.sin(c)*.55+Math.sin(c*1.47)*.35+(S-h)*.2)*p;break}case"footstep_gravel":{let k=Math.pow(1-y,1.9)*Math.min(1,b/.004),p=.55+.45*Math.sin(2*Math.PI*62*b);u+=2*Math.PI*(118+h*40)/t,g=(Math.sin(u)*.5+h*.65)*p*k,v=(S*.72+h*.28)*p*k;break}case"footstep_water":{let k=Math.sin(Math.PI*Math.pow(y,.7))*(1-y*.35);u+=2*Math.PI*(78-y*32)/t,c+=2*Math.PI*(520+y*640)/t,g=(Math.sin(u)*.75+h*.35)*k,v=(Math.sin(c)*.35+h*.6)*k;break}case"zipper_tick":{let k=Math.pow(1-y,2.8)*Math.min(1,b/.0015);u+=2*Math.PI*(260-y*110)/t,c+=2*Math.PI*(2850-y*900)/t,g=Math.sin(u)*k,v=(Math.sin(c)*.7+(S-h)*.3)*k;break}case"spring_boing":{let k=Math.pow(1-y,1.35)*Math.min(1,b/.004),p=Math.sin(2*Math.PI*19*b);u+=2*Math.PI*(68+y*115+p*18)/t,c+=2*Math.PI*(260+y*540+p*45)/t,g=Math.sin(u)*k*.92,v=Math.sin(c)*k*.78;break}case"engine_hum":{let p=Math.sin(2*Math.PI*48*b),x=Math.sin(2*Math.PI*96*b)*.45,C=Math.sin(2*Math.PI*144*b)*.22;g=(p+x+C)*.58,v=(x*.5+C*.5)*.35;break}}let f=wt(v,-.95,.95),w=wt(g,-.95,.95);o[m]=f,s[m]=f,l[m]=w,d[m]=w}return{sampleRate:t,channels:[o,s,l,d]}}var Nt=new Set(["cross","circle","square","triangle","l1","r1","l2Btn","r2Btn","l3","r3","up","down","left","right","create","options","ps","touchpadClick"]),Ne=new Set(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab"]);function Ut(a){if(!a||typeof a!="object")return!1;let e=a;if(e.isContentEditable)return!0;let t=(e.tagName||"").toUpperCase();return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Wt(a,e,t,n,r){let i=e.source!=="keyboard_mouse";return a==="l2"?i?e.l2:0:a==="r2"?i?e.r2:0:a==="lx+"?i?Math.max(0,e.lx):0:a==="lx-"?i?Math.max(0,-e.lx):0:a==="ly+"?i?Math.max(0,e.ly):0:a==="ly-"?i?Math.max(0,-e.ly):0:a==="rx+"?i?Math.max(0,e.rx):0:a==="rx-"?i?Math.max(0,-e.rx):0:a==="ry+"?i?Math.max(0,e.ry):0:a==="ry-"?i?Math.max(0,-e.ry):0:Nt.has(a)?i&&e.buttons[a]?1:0:a==="MouseLeft"||a==="MouseRight"||a==="MouseMiddle"?n.has(a)?1:0:t.has(a)?Math.max(1,r):0}function ue(a){let e=a.analogThreshold??.45,t=a.actions??{},n=a.axes??{},r=a.preventDefaultKeys!==!1,i=new Set;for(let p of Object.values(t))for(let x of p)Ne.has(x)&&i.add(x);for(let p of Object.values(n)){for(let x of p.negativeKeys??[])Ne.has(x)&&i.add(x);for(let x of p.positiveKeys??[])Ne.has(x)&&i.add(x)}let o=new Set,s=new Set,l=new Set,d=new Set,h=new Map,u=new Map,c=new Map;for(let p of Object.keys(t))h.set(p,{pressed:!1,justPressed:!1,justReleased:!1,heldMs:0,value:0});for(let p of Object.keys(n))c.set(p,0);let m=p=>p===0?"MouseLeft":p===1?"MouseMiddle":p===2?"MouseRight":null,b=p=>{let x=p;x.code&&(r&&i.has(x.code)&&!x.ctrlKey&&!x.metaKey&&!x.altKey&&!Ut(x.target)&&x.preventDefault(),o.has(x.code)||s.add(x.code),o.add(x.code))},y=p=>{let x=p;x.code&&o.delete(x.code)},S=p=>{let C=m(p.button);C&&(l.has(C)||d.add(C),l.add(C))},v=p=>{let C=m(p.button);C&&l.delete(C)},g=()=>{o.clear(),s.clear(),l.clear(),d.clear()},f=a.attachWindowListeners!==!1&&typeof window<"u",w=a.mouseTarget??(typeof window<"u"?window:void 0);f&&(window.addEventListener("keydown",b),window.addEventListener("keyup",y),window.addEventListener("blur",g),w?.addEventListener("pointerdown",S),window.addEventListener("pointerup",v));let k={pressed:!1,justPressed:!1,justReleased:!1,heldMs:0,value:0};return{update(p,x=typeof performance<"u"?performance.now():Date.now()){let C=s.size>0?new Set([...o,...s]):o,A=d.size>0?new Set([...l,...d]):l;s.clear(),d.clear();for(let[I,P]of Object.entries(t)){let D=0;for(let _ of P){let E=Wt(_,p,C,A,e);E>D&&(D=E)}let T=D>=e,H=h.get(I),M=T&&!H.pressed,B=!T&&H.pressed;M?u.set(I,x):T||u.delete(I);let O=u.get(I);H.pressed=T,H.justPressed=M,H.justReleased=B,H.heldMs=T&&O!==void 0?Math.max(0,x-O):0,H.value=Math.max(0,Math.min(1,D))}let R=p.source!=="keyboard_mouse";for(let[I,P]of Object.entries(n)){let D=0;if(P.stick&&R){let B=p[P.stick],O=P.deadzone??.08;D=V(B,O)}let T=0;R&&P.negativeButtons?.some(B=>p.buttons[B])&&(T-=1),R&&P.positiveButtons?.some(B=>p.buttons[B])&&(T+=1),P.negativeKeys?.some(B=>C.has(B))&&(T-=1),P.positiveKeys?.some(B=>C.has(B))&&(T+=1);let H=Math.abs(T)>Math.abs(D)?T:D,M=Math.max(-1,Math.min(1,H));c.set(I,P.invert?-M:M)}},action(p){return h.get(p)??k},isPressed(p){return h.get(p)?.pressed??!1},justPressed(p){return h.get(p)?.justPressed??!1},justReleased(p){return h.get(p)?.justReleased??!1},axis(p){return c.get(p)??0},setKeyDown(p,x){x?(o.has(p)||s.add(p),o.add(p)):o.delete(p)},setMouseButton(p,x){x?(l.has(p)||d.add(p),l.add(p)):l.delete(p)},dispose(){f&&(window.removeEventListener("keydown",b),window.removeEventListener("keyup",y),window.removeEventListener("blur",g),w?.removeEventListener("pointerdown",S),window.removeEventListener("pointerup",v)),o.clear(),s.clear(),l.clear(),d.clear(),u.clear()}}}function $(a,e,t){return Math.max(e,Math.min(t,a))}function Kt(a={}){let e=$(a.gyroWeight??.94,0,.995),t=Math.max(.5,a.gyroScaleRadPerSec??4.5),n=Math.max(.2,a.fullTiltRad??Math.PI/4),r=Math.max(.15,a.flickThreshold??.62),i=Math.max(80,a.flickCooldownMs??320),o=Math.max(.2,a.shakeDecay??2.4),s=$(a.shakeThreshold??.35,.05,.95),l=!1,d=!1,h=0,u=0,c=0,m=0,b=0,y=0,S=0,v=1,g=0,f=0,w=-1e9,k=0,p={active:!1,pitch:0,roll:0,yaw:0,pitchNorm:0,rollNorm:0,angularSpeed:0,linearAccelDelta:0,shakeIntensity:0,shaking:!1,justFlicked:!1,flickDirection:"none"};function x(){let C=$(h-m,-Math.PI/2,Math.PI/2),A=$(u-b,-Math.PI/2,Math.PI/2),R=c-y;p.active=d,p.pitch=C,p.roll=A,p.yaw=R,p.pitchNorm=$(C/n,-1,1),p.rollNorm=$(A/n,-1,1)}return{update(C,A,R=typeof performance<"u"?performance.now():Date.now()){let I=A!==void 0?$(A,.001,.1):k>0?$((R-k)/1e3,.001,.1):.016666666666666666;k=R;let{gx:P,gy:D,gz:T,ax:H,ay:M,az:B}={gx:C.gyro.x,gy:C.gyro.y,gz:C.gyro.z,ax:C.accel.x,ay:C.accel.y,az:C.accel.z},O=Math.hypot(H,M,B),_=Math.hypot(P,D,T);if(!(C.connected&&(O>.02||_>.002)))return d=!1,f=Math.max(0,f-o*I),p.active=!1,p.angularSpeed=0,p.linearAccelDelta=0,p.shakeIntensity=f,p.shaking=f>=s,p.justFlicked=!1,p.flickDirection="none",p;d=!0;let L=Math.atan2(-H,Math.hypot(M,B)||1e-4),G=Math.atan2(B,Math.hypot(H,M)||1e-4);if(!l)l=!0,h=G,u=L,c=0,S=H,v=M,g=B;else{let Y=O>.45&&O<1.65?e:.99;h=Y*(h+P*t*I)+(1-Y)*G,u=Y*(u+T*t*I)+(1-Y)*L;let se=Math.abs(D)>.012?D:0;c+=se*t*I}let q=.84;S=q*S+(1-q)*H,v=q*v+(1-q)*M,g=q*g+(1-q)*B;let F=H-S,W=M-v,Z=B-g,ae=Math.hypot(F,W,Z),J=$((ae*1.15+_*.72-.12)*1.35,0,1);J>f?f=Math.min(1,f+(J-f)*Math.min(1,I*16)):f=Math.max(0,f-o*I);let Se=_*.85+ae*.55,oe=!1,ee="none";if(Se>=r&&R-w>=i){w=R,oe=!0;let Y=Math.abs(P)+Math.abs(W)*.6,se=Math.abs(D)+Math.abs(T)*.7+Math.abs(F)*.6;Y>=se?ee=P+W*.5>=0?"up":"down":ee=D+T*.5-F*.4>=0?"right":"left"}return x(),p.angularSpeed=_,p.linearAccelDelta=ae,p.shakeIntensity=f,p.shaking=f>=s,p.justFlicked=oe,p.flickDirection=ee,p},getState(){return p},recenter(){m=h,b=u,y=c,x()},reset(){l=!1,d=!1,h=0,u=0,c=0,m=0,b=0,y=0,S=0,v=1,g=0,f=0,w=-1e9,k=0,p.active=!1,p.pitch=0,p.roll=0,p.yaw=0,p.pitchNorm=0,p.rollNorm=0,p.angularSpeed=0,p.linearAccelDelta=0,p.shakeIntensity=0,p.shaking=!1,p.justFlicked=!1,p.flickDirection="none"}}}function re(a,e,t){return Math.max(e,Math.min(t,a))}function jt(a={}){let e=Math.max(40,a.tapMaxMs??240),t=Math.max(.01,a.tapMaxMove??.06),n=Math.max(100,a.doubleTapWindowMs??320),r=Math.max(.2,a.swipeMinSpeed??1.15),i=Math.max(.03,a.swipeMinDistance??.12),o=re(a.velocitySmoothing??.45,.05,1),s=!1,l=.5,d=.5,h=.5,u=.5,c=0,m=0,b=!1,y=-1e9,S=.5,v=.5,g=!1,f=.5,w=.5,k=0,p=0,x=.5,C=.5,A=!1,R=0,I=0,P=!1,D=0,T=0,H=0,M={fingerCount:0,active:!1,x:.5,y:.5,justTouched:!1,justReleased:!1,dx:0,dy:0,totalDx:0,totalDy:0,vx:0,vy:0,speed:0,justTapped:!1,justDoubleTapped:!1,justTwoFingerTapped:!1,justSwiped:!1,swipeDirection:"none",pinchActive:!1,pinchDistance:0,pinchDelta:0,pinchScale:1,secondFinger:{active:!1,justTouched:!1,justReleased:!1,x:.5,y:.5,dx:0,dy:0},clicked:!1,justClicked:!1};return{update(B,O,_=typeof performance<"u"?performance.now():Date.now()){let E=O!==void 0?re(O,.001,.1):D>0?re((_-D)/1e3,.001,.1):.016666666666666666;D=_;let L=!!(B.connected&&B.touch.active),G=!!(B.connected&&B.touch2.active),q=re(B.touch.x,0,1),F=re(B.touch.y,0,1),W=re(B.touch2.x,0,1),Z=re(B.touch2.y,0,1),ae=L&&!s,J=!L&&s,Se=G&&!g,oe=!G&&g,ee=0,Y=0,se=!1,st=!1,lt=!1,ct=!1,ke="none";if(ae)h=q,u=F,c=_,m=0,b=G,T=0,H=0;else if(L){ee=q-l,Y=F-d,G&&(b=!0);let ne=Math.hypot(q-h,F-u);ne>m&&(m=ne);let De=ee/E,Be=Y/E;T=T*(1-o)+De*o,H=H*(1-o)+Be*o}else if(J){let ne=_-c,De=Math.hypot(l-h,d-u),Be=Math.hypot(T,H);if(ne<=e&&m<=t&&!b)se=!0,_-y<=n&&Math.hypot(l-S,d-v)<=t*2.5?(st=!0,y=-1e9):(y=_,S=l,v=d);else if(!b&&Be>=r&&De>=i){ct=!0;let pt=l-h,ht=d-u;Math.abs(pt)>=Math.abs(ht)?ke=pt>=0?"right":"left":ke=ht>=0?"down":"up"}}else T=0,H=0;let ut=0,dt=0;if(Se)x=W,C=Z,k=_,p=0;else if(G){ut=W-f,dt=Z-w;let ne=Math.hypot(W-x,Z-C);ne>p&&(p=ne)}(oe&&s&&_-k<=e&&p<=t&&m<=t||J&&oe&&_-c<=e&&_-k<=e&&m<=t&&p<=t)&&(lt=!0);let He=L&&G,te=0,Pe=0,Ie=1;He?(te=Math.hypot(W-q,Z-F),A?(Pe=te-I,Ie=te/Math.max(.02,R),I=te):(R=Math.max(.02,te),I=te,Pe=0,Ie=1)):(R=0,I=0);let Re=!!(B.connected&&B.buttons.touchpadClick),_t=Re&&!P;s=L,L&&(l=q,d=F),g=G,G&&(f=W,w=Z),A=He,P=Re;let Gt=L&&G?2:L||G?1:0;return M.fingerCount=Gt,M.active=L,M.x=L?q:l,M.y=L?F:d,M.justTouched=ae,M.justReleased=J,M.dx=ee,M.dy=Y,M.totalDx=L?q-h:0,M.totalDy=L?F-u:0,M.vx=L||J?T:0,M.vy=L||J?H:0,M.speed=Math.hypot(M.vx,M.vy),M.justTapped=se,M.justDoubleTapped=st,M.justTwoFingerTapped=lt,M.justSwiped=ct,M.swipeDirection=ke,M.pinchActive=He,M.pinchDistance=te,M.pinchDelta=Pe,M.pinchScale=Ie,M.secondFinger.active=G,M.secondFinger.justTouched=Se,M.secondFinger.justReleased=oe,M.secondFinger.x=G?W:f,M.secondFinger.y=G?Z:w,M.secondFinger.dx=ut,M.secondFinger.dy=dt,M.clicked=Re,M.justClicked=_t,M},getState(){return M},reset(){s=!1,g=!1,A=!1,P=!1,b=!1,y=-1e9,D=0,T=0,H=0,M.fingerCount=0,M.active=!1,M.justTouched=!1,M.justReleased=!1,M.dx=0,M.dy=0,M.totalDx=0,M.totalDy=0,M.vx=0,M.vy=0,M.speed=0,M.justTapped=!1,M.justDoubleTapped=!1,M.justTwoFingerTapped=!1,M.justSwiped=!1,M.swipeDirection="none",M.pinchActive=!1,M.pinchDistance=0,M.pinchDelta=0,M.pinchScale=1,M.secondFinger.active=!1,M.secondFinger.justTouched=!1,M.secondFinger.justReleased=!1,M.secondFinger.dx=0,M.secondFinger.dy=0,M.clicked=!1,M.justClicked=!1}}}var fe=class{anchors=new Map;cooldownUntil=0;notifyManualSelect(e,t){this.reanchorAll(e),this.cooldownUntil=t+280}evaluate(e,t,n){let r=new Set(e.map(l=>l.id));for(let l of this.anchors.keys())r.has(l)||this.anchors.delete(l);if(e.length===0)return{switchTo:null,triggeredSlotId:null};let i=null,o=0,s=null;for(let l of e){let d=this.anchors.get(l.id);if(!d){this.anchors.set(l.id,We(l));continue}let h=l.lastActivityAt>d.lastActivityAt,u=Math.hypot(l.lx,l.ly),c=Math.hypot(l.lx-d.lx,l.ly-d.ly),m=Math.hypot(l.rx,l.ry),b=Math.hypot(l.rx-d.rx,l.ry-d.ry),y=u>=.25&&c>=.22,S=m>=.25&&b>=.22,v=l.l2>=.25&&l.l2-d.l2>=.25,g=l.r2>=.25&&l.r2-d.r2>=.25,f=h||y||S||v||g;if(l.id===t||e.length===1){f?(s=l.id,this.anchors.set(l.id,We(l))):Ue(d,l,u,m);continue}if(n<this.cooldownUntil){f||Ue(d,l,u,m);continue}if(h){let w=10+(l.lastActivityAt-d.lastActivityAt)*1e-6;w>o&&(o=w,i=l.id)}else if(y||S||v||g){let w=Math.max(y?c:0,S?b:0,v?l.l2-d.l2:0,g?l.r2-d.r2:0);w>o&&(o=w,i=l.id)}else Ue(d,l,u,m)}return i?(this.reanchorAll(e),this.cooldownUntil=n+280,{switchTo:i,triggeredSlotId:i}):{switchTo:null,triggeredSlotId:s}}detectTargetSlot(e,t,n){return this.evaluate(e,t,n).switchTo}reanchorAll(e){for(let t of e)this.anchors.set(t.id,We(t))}};function Ue(a,e,t,n){t<Math.hypot(a.lx,a.ly)&&(a.lx=e.lx,a.ly=e.ly),n<Math.hypot(a.rx,a.ry)&&(a.rx=e.rx,a.ry=e.ry),e.l2<a.l2&&(a.l2=e.l2),e.r2<a.r2&&(a.r2=e.r2)}function We(a){return{lastActivityAt:a.lastActivityAt,lx:a.lx,ly:a.ly,rx:a.rx,ry:a.ry,l2:a.l2,r2:a.r2}}var Ke=class{mounted=!0;confirmedLeft="off";confirmedRight="off";pendingLeftSeq=0;pendingRightSeq=0;inFlightNonOff=0;uncertainTriggerState=!1;rumbleActive=!1;get leftPreset(){return this.confirmedLeft}get rightPreset(){return this.confirmedRight}get hasActiveTrigger(){return this.confirmedLeft!=="off"||this.confirmedRight!=="off"||this.inFlightNonOff>0||this.uncertainTriggerState}get needsCleanup(){return this.hasActiveTrigger||this.rumbleActive}markMounted(){this.mounted=!0}markRumbleActive(){this.rumbleActive=!0}async applyPreset(e,t,n,r){let i=n==="off",o=this.hasActiveTrigger,s=this.uncertainTriggerState||(t==="left"?this.confirmedLeft!=="off":t==="right"?this.confirmedRight!=="off":this.confirmedLeft!=="off"||this.confirmedRight!=="off"),l=t==="left"||t==="both"?++this.pendingLeftSeq:0,d=t==="right"||t==="both"?++this.pendingRightSeq:0;i||(this.inFlightNonOff+=1);let h=!1,u=!1;try{t==="both"?h=await e.setTriggers(r,r):t==="left"?h=await e.setTriggers(r,void 0):h=await e.setTriggers(void 0,r)}catch{h=!1,u=!0}finally{i||(this.inFlightNonOff=Math.max(0,this.inFlightNonOff-1))}let c=t==="right"||l===this.pendingLeftSeq,m=t==="left"||d===this.pendingRightSeq,b=!(c&&m);return this.mounted?(h?b?i||(this.uncertainTriggerState=!0):((t==="left"||t==="both")&&(this.confirmedLeft=n),(t==="right"||t==="both")&&(this.confirmedRight=n),this.confirmedLeft==="off"&&this.confirmedRight==="off"&&this.inFlightNonOff===0&&(this.uncertainTriggerState=!1)):u&&!i&&(this.uncertainTriggerState=!0),{ok:h,stale:b,unmounted:!1,hadActiveBefore:o,hadActiveTargetBefore:s,leftPreset:this.confirmedLeft,rightPreset:this.confirmedRight,needsReset:this.needsCleanup}):((!i&&(h||u)||i&&!h&&o)&&e.resetTriggers().catch(()=>{}),{ok:h,stale:b,unmounted:!0,hadActiveBefore:o,hadActiveTargetBefore:s,leftPreset:this.confirmedLeft,rightPreset:this.confirmedRight,needsReset:this.needsCleanup})}cleanupOnUnmount(e){return this.mounted=!1,this.needsCleanup?(this.confirmedLeft="off",this.confirmedRight="off",this.uncertainTriggerState=!1,this.rumbleActive=!1,e.resetTriggers().catch(()=>{}),!0):!1}cleanupOnSlotChange(e){return this.needsCleanup?(this.pendingLeftSeq+=1,this.pendingRightSeq+=1,this.confirmedLeft="off",this.confirmedRight="off",this.uncertainTriggerState=!1,this.rumbleActive=!1,e.resetTriggers().catch(()=>{}),!0):!1}};function je(a,e={}){let t=e.onChange??(()=>{}),n=e.autoHotplug!==!1,r=e.autoEmergencyReset!==!1,i=()=>typeof e.audio=="function"?e.audio():e.audio??null;n&&a.attachHidHotplug();let o=a.onStatusChange(()=>t("status")),s=()=>t("gamepad"),l=()=>{a.emergencyReset();let m=i();m?.stopAllContinuous?.(),e.teardownAudioOnExit&&m?.teardownDsOutput?.().catch(()=>{})},d=typeof window<"u";d&&(n&&(window.addEventListener("gamepadconnected",s),window.addEventListener("gamepaddisconnected",s)),r&&(window.addEventListener("pagehide",l),window.addEventListener("beforeunload",l)));let h=e.pollMs??250,u=h>0&&typeof setInterval<"u"?setInterval(()=>t("poll"),h):null,c=!1;return()=>{c||(c=!0,u!==null&&(clearInterval(u),u=null),o(),d&&(n&&(window.removeEventListener("gamepadconnected",s),window.removeEventListener("gamepaddisconnected",s)),r&&(window.removeEventListener("pagehide",l),window.removeEventListener("beforeunload",l))),n&&e.detachHotplugOnCleanup!==!1&&a.detachHidHotplug())}}var Vt={update(){},stop(){}};function Ve(a,e,t,n){let r=n&&!!(e&&e.dsMode!=="none"&&e.dsMaxChannelCount>=4),i=n&&!!(e&&e.dsMode!=="none"),o=a.getInputState(t),s=a.getCapabilityMatrixForSlot(t,{has4ChAudio:r,hasControllerSpeaker:i}),l=h=>s[h]?.availability==="ready",d="keyboard_mouse";return l("adaptive_triggers")&&r?d="dualsense_full_4ch":l("adaptive_triggers")?d="dualsense_hid_only":l("hd_rumble")?d="switch_pro_hid":l("impulse_triggers")?d="xbox_impulse":o.source==="gamepad"&&(d="standard_gamepad"),{slotId:t??a.getActiveSlotId(),tier:d,identity:o.identity,matrix:s,has:l,hasAdaptiveTriggers:l("adaptive_triggers"),hasImpulseTriggers:l("impulse_triggers"),hasHdRumble:l("hd_rumble"),hasDualRumble:l("dual_motor_rumble"),has4ChHaptics:r,hasControllerSpeaker:i,hasGyro:l("gyro"),hasTouchpad:l("touchpad")}}function Mt(a,e){return[a.map(n=>`${n.id}:${n.source}:${n.identity.model}:${n.identity.displayName}:${n.identity.transport}`).join(","),e.slotId??"",e.tier,e.hasAdaptiveTriggers?1:0,e.hasImpulseTriggers?1:0,e.hasHdRumble?1:0,e.has4ChHaptics?1:0,e.hasControllerSpeaker?1:0,e.hasGyro?1:0].join("|")}function Ye(a={}){let e=!a.hid,t=a.hid??new le,n=a.audio??null,r=a.samples??null,i=!1,o=new Set,s=new Set,l=new Set,d=new Set,h=new Set;a.attachKeyboardFallback&&e&&t.attachKeyboardFallback();let u="",c=()=>{if(i)return;let S=t.getConnectedControllers(),v=Ve(t,n,void 0,!0),g=Mt(S,v);if(g!==u){u=g;for(let f of h)try{f({slots:S,active:v})}catch{}}};u=Mt(t.getConnectedControllers(),Ve(t,n,void 0,!0));let m=je(t,{autoHotplug:a.autoHotplug,detachHotplugOnCleanup:e,autoEmergencyReset:a.autoEmergencyReset,teardownAudioOnExit:a.teardownAudioOnExit,audio:()=>n,pollMs:a.capabilityPollMs??250,onChange:c}),b=S=>{let v=[23,23,23],g=0,f=null,w=()=>{if(S==="active")return{slotId:void 0,connected:!0,isPrimary:!0};if(typeof S=="number"){let C=t.getConnectedControllers()[S];if(!C)return{slotId:`__unassigned_${S}`,connected:!1,isPrimary:S===0};let A=t.getActiveSlotId();return{slotId:C.id,connected:!0,isPrimary:C.id===A||S===0}}let p=t.getActiveSlotId();return{slotId:S,connected:!0,isPrimary:S===p}},k=()=>{let p=w();return{hid:t,audio:n,slotId:p.slotId,allow4ChAudio:p.isPrimary}};return{getSlotId(){let p=w();return p.slotId===void 0?t.getActiveSlotId():p.connected?p.slotId:null},getCapabilities(){let p=w();return Ve(t,n,p.slotId,p.isPrimary)},input:{getState:()=>{let p=w();return t.getInputState(p.slotId)},applyDeadzone:V},triggers:{reset:()=>{if(i)return;let p=w();t.resetTriggers(p.slotId).catch(()=>{})},setLeft:p=>{if(i)return;let x=w();t.setTriggers(p,void 0,x.slotId).catch(()=>{})},setRight:p=>{if(i)return;let x=w();t.setTriggers(void 0,p,x.slotId).catch(()=>{})},setBoth:(p,x)=>{if(i)return;let C=w();t.setTriggers(p,x,C.slotId).catch(()=>{})},applyPreset:(p,x="both")=>{if(i)return;let C=pe[p];if(!C)return;let A=w();x==="left"?t.setTriggers(C,void 0,A.slotId).catch(()=>{}):x==="right"?t.setTriggers(void 0,C,A.slotId).catch(()=>{}):t.setTriggers(C,C,A.slotId).catch(()=>{})},pulseImpulse:p=>{if(i)return;let x=w();t.playTriggerRumble(p.left??0,p.right??0,p.durationMs??80,p.weakGrip??0,p.strongGrip??0,x.slotId)}},haptics:{pulse:p=>{i||ce(k(),p)},sweep:p=>{i||Oe(k(),p)},rumble:p=>{if(i)return;let x=w();t.triggerGamepadRumbleFallback(p.weak,p.strong,p.durationMs,x.slotId)},hdRumble:p=>{if(i)return;let x=w();t.playSwitchHdRumble(p,x.slotId)},hdSequence:p=>{if(i)return;let x=w();t.playSwitchHdRumbleSequence(p,x.slotId)},playPreset:(p,x)=>{i||Fe(k(),p,x)},createContinuous:p=>{if(i||!n)return Vt;let x=n.createContinuous(p);return o.add(x),{update:C=>{i||x.update(C)},stop:()=>{o.delete(x),x.stop()}}},playComboPreset:(p,x=0)=>{if(i)return;let C=w();if(n?.playComboPreset(p,x),!n||!C.isPrimary||n.dsMode==="none"||n.dsMaxChannelCount<4){let A=p==="shotgun"||p==="thunder"?.85:.4,R=p==="ratchet_tick"?30:120;ce(k(),{pan:x,freqHz:p==="ratchet_tick"?190:95,durationMs:R,intensity:A})}},stop:()=>{let p=w();t.stopGamepadRumble(p.slotId)}},audio:{playPcTone:p=>{i||n?.playPcTone(p)},playPcNoise:p=>{i||n?.playPcNoiseBurst(p)},playControllerSpeakerTone:p=>{i||n?.playControllerSpeakerTone(p)},loadSample:(p,x)=>{let C=r??n;return i||!C?.loadSample?Promise.resolve(!1):C.loadSample(p,x)},hasSample:p=>{let x=r??n;return i||!x?.hasSample?!1:x.hasSample(p)},unloadSample:p=>{i||(r??n)?.unloadSample?.(p)},playSample:(p,x={})=>{if(i)return N;for(let M of s)M.active||s.delete(M);let C=w(),A=x.route??"pc",R=!!(n&&C.isPrimary&&n.dsMode!=="none"),I=!!(R&&n&&n.dsMaxChannelCount>=4);if((A==="vcm"||A==="quad")&&!I){let M=x.fallbackHaptic;ce(k(),{pan:x.pan??0,freqHz:M?.freqHz??145,durationMs:M?.durationMs??(x.loop?90:65),intensity:M?.intensity??Math.min(1,(x.gain??.85)*.72)})}let P=r??n;if(!P?.playSample)return N;let D=x;if(A!=="pc"&&!R){if(A==="vcm")return N;D={...x,route:"pc",gain:(x.gain??.85)*(A==="speaker"?.45:.5)}}let T=P.playSample(p,D);if(!T.active)return T;let H={get active(){return!i&&T.active},update:M=>{i||T.update(M)},stop:M=>{s.delete(H),T.stop(M)}};return s.add(H),H}},lightbar:{setColor:(p,x,C)=>{if(i)return;let A=typeof performance<"u"?performance.now():Date.now();if(v[0]===p&&v[1]===x&&v[2]===C)return;if(f!==null){v=[p,x,C];return}if(A-g<30)return;g=A,v=[p,x,C];let R=w();t.setLightbar(p,x,C,R.slotId).catch(()=>{})},flash:(p,x,C,A=240)=>{if(i)return;f!==null&&(clearTimeout(f),l.delete(f),f=null);let R=w();t.setLightbar(p,x,C,R.slotId).catch(()=>{});let I=setTimeout(()=>{if(l.delete(I),f===I&&(f=null),!i){let P=v;t.setLightbar(P[0],P[1],P[2],R.slotId).catch(()=>{})}},A);f=I,l.add(I)}},createActions(p){let x=ue(p);return d.add(x),{...x,dispose(){d.delete(x),x.dispose()}}}}},y=b("active");return{hid:t,async connectWebHID(){let S=await t.connect();return c(),S},async disconnectWebHID(S,v){await t.disconnect(S,v),c()},async reconnectAuthorized(){let S=await t.reconnectAuthorized();return c(),S},attachAudio(S){n=S,c()},getSlots(){return t.getConnectedControllers()},get active(){return y},player(S){return S===void 0||S==="active"?y:b(S)},onCapabilitiesChange(S){return h.add(S),()=>{h.delete(S)}},syncCapabilities:c,dispose(){if(!i){i=!0,m(),h.clear();for(let S of l)clearTimeout(S);l.clear();for(let S of d)try{S.dispose()}catch{}d.clear();for(let S of o)try{S.stop()}catch{}o.clear();for(let S of s)try{S.stop()}catch{}s.clear(),t.stopGamepadRumble(),t.resetTriggers().catch(()=>{}),t.setLightbar(23,23,23).catch(()=>{}),e&&a.attachKeyboardFallback&&t.detachKeyboardFallback()}}}}var $e="http://127.0.0.1:5178",Xe="ws://127.0.0.1:5178",Q=class a{httpBase;wsBase;pcCtx=null;pcSinkId="";pcSinkLabel="PC Default Speakers";pcMasterGain=null;pcAnalysers=[];pcNoiseBuffer=null;dsMode="none";dsCtx=null;dsSinkId="";dsSinkLabel="";dsMaxChannelCount=2;dsActiveChannelCount=2;dsWs=null;dsWorklet=null;dsMerger=null;dsChGains=[];dsAnalysers=[];dsNoiseBuffer=null;pcGainValue=.8;dsSpeakerGainValue=.95;dsHapticGainValue=.95;audioMuted=!1;constructor(e={}){this.httpBase=(e.httpBase||$e).replace(/\/+$/,""),this.wsBase=(e.wsBase||Xe).replace(/\/+$/,"")}setAudioMuted(e){if(this.audioMuted=e,this.pcMasterGain&&this.pcCtx&&this.pcMasterGain.gain.setTargetAtTime(e?0:this.pcGainValue,this.pcCtx.currentTime,.015),this.dsChGains.length>=2&&this.dsCtx){let t=e?0:this.dsSpeakerGainValue;this.dsChGains[0].gain.setTargetAtTime(t,this.dsCtx.currentTime,.015),this.dsChGains[1].gain.setTargetAtTime(t,this.dsCtx.currentTime,.015)}}activeContinuous=new Set;audioGraphListeners=new Set;onAudioGraphChange(e){return this.audioGraphListeners.add(e),()=>{this.audioGraphListeners.delete(e)}}getAudioRouting(){return{pcCtx:this.pcCtx,pcMasterGain:this.pcMasterGain,dsCtx:this.dsCtx,dsChGains:this.dsChGains}}emitAudioGraph(e){for(let t of this.audioGraphListeners)try{t(e)}catch{}}companionToken="";intentionalWsClose=!1;reconnectAttempts=0;reconnectTimer=null;streamStateListeners=new Set;onCompanionStreamState(e){return this.streamStateListeners.add(e),()=>this.streamStateListeners.delete(e)}emitStreamState(e,t){for(let n of this.streamStateListeners)try{n(e,t)}catch{}}static isLoopbackOrigin(){if(typeof window>"u")return!0;let e=window.location.hostname;return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}static async getLoopbackPermissionState(){if(a.isLoopbackOrigin())return"local_exempt";if(typeof navigator>"u"||!navigator.permissions?.query)return"unknown";for(let e of["loopback-network","local-network-access"])try{let t=await navigator.permissions.query({name:e});if(t.state==="granted"||t.state==="prompt"||t.state==="denied")return t.state}catch{}return"unknown"}async loopbackFetch(e,t={}){let n={...t,targetAddressSpace:"loopback"};try{return await fetch(e,n)}catch(r){if(r instanceof TypeError&&!String(r.message).toLowerCase().includes("fetch"))return fetch(e,t);throw r}}static checkBrowserCapabilities(){if(typeof window>"u")return{hasWebAudio:!1,hasSetSinkId:!1,hasAudioWorklet:!1,isSecureContext:!0};let e=window.AudioContext||window.webkitAudioContext;return{hasWebAudio:!!e,hasSetSinkId:!!(e&&"setSinkId"in e.prototype),hasAudioWorklet:!!(e&&"audioWorklet"in e.prototype),isSecureContext:!!window.isSecureContext}}async probeCompanion(e=700){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let r=await this.loopbackFetch(`${this.httpBase}/api/health`,{cache:"no-store",signal:t.signal});if(!r.ok)return{online:!1};let i=await r.json();return{online:!!i.ok,version:i.version,protocolVersion:typeof i.protocolVersion=="number"?i.protocolVersion:1,platform:i.platform}}catch{return{online:!1}}finally{clearTimeout(n)}}async acquireCompanionSession(){let e=await this.loopbackFetch(`${this.httpBase}/api/session`,{method:"POST",headers:{"X-Gamepadly-Client":"web"},cache:"no-store"});if(e.status===404)return this.companionToken="","";if(!e.ok)throw new Error(`Gamepadly Link rejected session request (HTTP ${e.status}).`);let t=await e.json();return this.companionToken=typeof t.token=="string"?t.token:"",this.companionToken}async listCompanionDevices(){let e=await this.loopbackFetch(`${this.httpBase}/api/devices`,{cache:"no-store"});if(!e.ok)throw new Error("Gamepadly Link companion did not respond.");let t=await e.json();return Array.isArray(t.devices)?t.devices:[]}async openWindowsSoundPanelViaCompanion(){try{let e=this.companionToken||await this.acquireCompanionSession(),t={};return e&&(t["X-Gamepadly-Token"]=e),(await this.loopbackFetch(`${this.httpBase}/api/open-sound-panel`,{method:"POST",headers:t})).ok}catch{return!1}}async unlockBrowserDeviceLabels(){if(!navigator.mediaDevices?.getUserMedia)return!1;try{let e=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});for(let t of e.getTracks())t.stop();return!0}catch{return!1}}async listBrowserOutputDevices(){return navigator.mediaDevices?.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audiooutput").map(t=>({deviceId:t.deviceId,label:t.label||(t.deviceId==="default"?"System Default":`Audio Output (${t.deviceId.slice(0,8)})`),isLikelyDualSense:/wireless controller|dualsense|ps5|dsx/i.test(t.label||"")})):[]}async initPcOutput(e="",t="PC Default Speakers"){let n=window.AudioContext||window.webkitAudioContext;this.pcCtx||(this.pcCtx=new n({latencyHint:"interactive"}));let r=this.pcCtx;return e&&typeof r.setSinkId=="function"&&await r.setSinkId(e),this.pcCtx.state==="suspended"&&await this.pcCtx.resume(),this.pcMasterGain||this.buildPcGraph(),this.pcSinkId=e,this.pcSinkLabel=t,{sinkId:this.pcSinkId,sinkLabel:this.pcSinkLabel,sampleRate:this.pcCtx.sampleRate}}buildPcGraph(){let e=this.pcCtx;this.pcMasterGain=e.createGain(),this.pcMasterGain.gain.value=this.audioMuted?0:this.pcGainValue;let t=e.createDynamicsCompressor();t.threshold.value=-4,t.knee.value=8,t.ratio.value=6;let n=e.createChannelSplitter(2),r=e.createAnalyser(),i=e.createAnalyser();r.fftSize=256,i.fftSize=256,r.smoothingTimeConstant=.55,i.smoothingTimeConstant=.55,this.pcMasterGain.connect(t),t.connect(e.destination),t.connect(n),n.connect(r,0),n.connect(i,1),this.pcAnalysers=[r,i],this.pcNoiseBuffer=this.createNoiseBuffer(e),this.emitAudioGraph("pc_ready")}async openCompanionWebSocket(e){let t=await this.acquireCompanionSession(),n=new URLSearchParams;t&&n.set("token",t),e&&n.set("device",e);let r=n.toString(),i=`${this.wsBase}/ws/haptics${r?`?${r}`:""}`;return new Promise((o,s)=>{let l=new WebSocket(i);l.binaryType="arraybuffer";let d=setTimeout(()=>{l.close(),s(new Error("Gamepadly Link WASAPI handshake timeout."))},5e3);l.onmessage=h=>{if(typeof h.data=="string")try{let u=JSON.parse(h.data);u.type==="ready"?(clearTimeout(d),o({ws:l,ready:u})):u.type==="error"&&(clearTimeout(d),l.close(),s(new Error(u.message||"WASAPI renderer failed to initialize.")))}catch{}},l.onerror=()=>{clearTimeout(d),s(new Error("Failed to connect to Gamepadly Link WebSocket (check LNA loopback permission)."))}})}attachWsReconnectHandler(e,t){e.onclose=()=>{if(this.dsWs!==e)return;if(this.dsWs=null,this.intentionalWsClose||this.dsMode!=="companion"){this.emitStreamState("idle");return}if(this.reconnectAttempts>=3){this.emitStreamState("disconnected","Gamepadly Link connection lost. Click Connect to retry.");return}let n=800*Math.pow(2,this.reconnectAttempts);this.reconnectAttempts++,this.emitStreamState("reconnecting",`Reconnecting to Gamepadly Link (${this.reconnectAttempts}/3)...`),this.reconnectTimer=window.setTimeout(async()=>{if(this.reconnectTimer=null,!(this.intentionalWsClose||this.dsMode!=="companion"))try{let{ws:r}=await this.openCompanionWebSocket(t);this.dsWs=r,this.reconnectAttempts=0,this.attachWsReconnectHandler(r,t),this.emitStreamState("connected","Gamepadly Link reconnected.")}catch{this.reconnectAttempts<3?(this.attachWsReconnectHandler(e,t),e.onclose?.(new CloseEvent("close"))):this.emitStreamState("disconnected","Gamepadly Link offline.")}},n)}}async connectDualSenseCompanion(e="",t="DualSense WASAPI"){let n=window.AudioContext||window.webkitAudioContext;await this.teardownDsOutput(),this.intentionalWsClose=!1,this.reconnectAttempts=0;let{ws:r,ready:i}=await this.openCompanionWebSocket(e);this.dsWs=r,this.attachWsReconnectHandler(r,i.id||e),this.emitStreamState("connected");let o=i.sampleRate||48e3;this.dsCtx=new n({sampleRate:o,latencyHint:"interactive"}),this.dsCtx.state==="suspended"&&await this.dsCtx.resume(),await this.dsCtx.audioWorklet.addModule("/haptic-worklet.js"),this.dsMode="companion",this.dsSinkId=i.id||e,this.dsSinkLabel=i.name||t,this.dsMaxChannelCount=i.channels||4,this.dsActiveChannelCount=Math.min(4,this.dsMaxChannelCount),this.buildDsGraph(!1),this.dsWorklet=new AudioWorkletNode(this.dsCtx,"gamepadly-wasapi-capture",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],channelCount:4,channelCountMode:"explicit",channelInterpretation:"discrete"});let s=this.dsCtx.createGain();return s.gain.value=0,this.dsMerger.connect(this.dsWorklet),this.dsWorklet.connect(s),s.connect(this.dsCtx.destination),this.dsWorklet.port.onmessage=l=>{this.dsWs&&this.dsWs.readyState===WebSocket.OPEN&&this.dsWs.send(l.data)},{mode:"companion",sinkId:this.dsSinkId,sinkLabel:this.dsSinkLabel,sampleRate:this.dsCtx.sampleRate,maxChannelCount:this.dsMaxChannelCount,activeChannelCount:this.dsActiveChannelCount,isQuadraphonicReady:this.dsMaxChannelCount>=4,state:this.dsCtx.state}}async connectDualSenseBrowserSink(e,t){if(!e)throw new Error("DualSense audio output device ID is empty.");let n=window.AudioContext||window.webkitAudioContext;await this.teardownDsOutput();try{this.dsCtx=new n({latencyHint:"interactive",sinkId:e})}catch{this.dsCtx=new n({latencyHint:"interactive"})}let r=this.dsCtx;typeof r.setSinkId=="function"&&r.sinkId!==e&&await r.setSinkId(e),this.dsCtx.state==="suspended"&&await this.dsCtx.resume();let i=this.dsCtx.destination;this.dsMaxChannelCount=i.maxChannelCount;let o=this.dsMaxChannelCount>=4?4:Math.min(2,this.dsMaxChannelCount);return i.channelCountMode="explicit",i.channelInterpretation="discrete",i.channelCount=o,this.dsActiveChannelCount=i.channelCount,this.dsMode="setsinkid",this.dsSinkId=e,this.dsSinkLabel=t,this.buildDsGraph(!0),{mode:"setsinkid",sinkId:this.dsSinkId,sinkLabel:this.dsSinkLabel,sampleRate:this.dsCtx.sampleRate,maxChannelCount:this.dsMaxChannelCount,activeChannelCount:this.dsActiveChannelCount,isQuadraphonicReady:this.dsMaxChannelCount>=4,state:this.dsCtx.state}}buildDsGraph(e){let t=this.dsCtx;this.dsMerger=t.createChannelMerger(4),this.dsChGains=[],this.dsAnalysers=[];for(let n=0;n<4;n++){let r=t.createGain();r.gain.value=n<2?this.dsSpeakerGainValue:this.dsHapticGainValue;let i=r;if(n>=2){let l=t.createBiquadFilter();l.type="highpass",l.frequency.value=20,l.Q.value=.707,r.connect(l),i=l}let o=t.createDynamicsCompressor();o.threshold.value=-3,o.knee.value=6,o.ratio.value=12,o.attack.value=.0015,o.release.value=.05;let s=t.createAnalyser();s.fftSize=256,s.smoothingTimeConstant=.5,i.connect(o),o.connect(s),s.connect(this.dsMerger,0,n),this.dsChGains.push(r),this.dsAnalysers.push(s)}e&&this.dsMerger.connect(t.destination),this.dsNoiseBuffer=this.createNoiseBuffer(t),this.emitAudioGraph("ds_ready")}async teardownDsOutput(){if(this.intentionalWsClose=!0,this.reconnectTimer!==null&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopAllContinuous(),this.emitAudioGraph("ds_teardown"),this.dsWorklet){try{this.dsWorklet.port.onmessage=null,this.dsWorklet.disconnect()}catch{}this.dsWorklet=null}if(this.dsWs){try{this.dsWs.close()}catch{}this.dsWs=null}if(this.dsCtx){try{await this.dsCtx.close()}catch{}this.dsCtx=null}this.dsMerger=null,this.dsChGains=[],this.dsAnalysers=[],this.dsNoiseBuffer=null,this.dsMode="none"}createNoiseBuffer(e){let t=e.sampleRate*2,n=e.createBuffer(1,t,e.sampleRate),r=n.getChannelData(0);for(let i=0;i<t;i++)r[i]=Math.random()*2-1;return n}async resumeAll(){this.pcCtx||await this.initPcOutput("",this.pcSinkLabel),this.pcCtx&&this.pcCtx.state==="suspended"&&await this.pcCtx.resume(),this.dsCtx&&this.dsCtx.state==="suspended"&&await this.dsCtx.resume()}setGains(e){e.pc!==void 0&&(this.pcGainValue=Math.max(0,Math.min(1.4,e.pc)),this.pcMasterGain&&this.pcCtx&&this.pcMasterGain.gain.setTargetAtTime(this.pcGainValue,this.pcCtx.currentTime,.02)),e.dsSpeaker!==void 0&&(this.dsSpeakerGainValue=Math.max(0,Math.min(1.3,e.dsSpeaker)),this.dsChGains.length>=2&&this.dsCtx&&(this.dsChGains[0].gain.setTargetAtTime(this.dsSpeakerGainValue,this.dsCtx.currentTime,.02),this.dsChGains[1].gain.setTargetAtTime(this.dsSpeakerGainValue,this.dsCtx.currentTime,.02))),e.dsHaptic!==void 0&&(this.dsHapticGainValue=Math.max(0,Math.min(1.4,e.dsHaptic)),this.dsChGains.length>=4&&this.dsCtx&&(this.dsChGains[2].gain.setTargetAtTime(this.dsHapticGainValue,this.dsCtx.currentTime,.02),this.dsChGains[3].gain.setTargetAtTime(this.dsHapticGainValue,this.dsCtx.currentTime,.02)))}getWaveforms(){let e=t=>{if(!t)return null;let n=new Float32Array(t.fftSize);return t.getFloatTimeDomainData(n),n};return{pcL:e(this.pcAnalysers[0]),pcR:e(this.pcAnalysers[1]),dsCh0:e(this.dsAnalysers[0]),dsCh1:e(this.dsAnalysers[1]),dsCh2:e(this.dsAnalysers[2]),dsCh3:e(this.dsAnalysers[3])}}getHapticEnergy(){if(this.dsAnalysers.length<4)return{left:0,right:0};let e=t=>{let n=new Float32Array(t.fftSize);t.getFloatTimeDomainData(n);let r=0;for(let i=0;i<n.length;i++)r+=n[i]*n[i];return Math.min(1,Math.sqrt(r/n.length)*3.5)};return{left:e(this.dsAnalysers[2]),right:e(this.dsAnalysers[3])}}stopAllContinuous(){for(let e of Array.from(this.activeContinuous))try{e.stop()}catch{}this.activeContinuous.clear()}routePc(e,t=0,n=1){if(!this.pcCtx||!this.pcMasterGain)return;let r=this.pcCtx.createGain();r.gain.value=n;let i=this.pcCtx.createStereoPanner();i.pan.value=Math.max(-1,Math.min(1,t)),e.connect(r),r.connect(i),i.connect(this.pcMasterGain)}routeDsSpeakerMonoSafe(e,t=.9){if(!this.dsCtx||this.dsChGains.length<2)return;let n=this.dsCtx.createGain();n.gain.value=t,e.connect(n),n.connect(this.dsChGains[0]),n.connect(this.dsChGains[1])}routeDsVcm(e,t=0,n=1){if(!this.dsCtx||this.dsChGains.length<4)return;let r=Math.max(-1,Math.min(1,t)),i=this.dsCtx.createGain(),o=this.dsCtx.createGain();i.gain.value=Math.cos((r+1)*Math.PI/4)*n,o.gain.value=Math.sin((r+1)*Math.PI/4)*n,e.connect(i),e.connect(o),i.connect(this.dsChGains[2]),o.connect(this.dsChGains[3])}playPcTone(e){if(!this.pcCtx)return;let t=this.pcCtx,n=t.currentTime+(e.delayMs||0)/1e3,r=Math.max(.015,e.durationMs/1e3),i=t.createOscillator();i.type=e.wave||"sine",i.frequency.setValueAtTime(Math.max(20,e.freqHz),n),e.endFreqHz&&e.endFreqHz>0&&i.frequency.exponentialRampToValueAtTime(Math.max(20,e.endFreqHz),n+r);let o=t.createGain(),s=Math.max(.001,Math.min(1,e.intensity??.45));o.gain.setValueAtTime(1e-4,n),o.gain.linearRampToValueAtTime(s,n+Math.min(.012,r*.2)),o.gain.exponentialRampToValueAtTime(1e-4,n+r),i.connect(o),this.routePc(o,e.pan??0,1),i.start(n),i.stop(n+r+.02)}playPcNoiseBurst(e){if(!this.pcCtx||!this.pcNoiseBuffer)return;let t=this.pcCtx,n=t.currentTime+(e.delayMs||0)/1e3,r=Math.max(.02,e.durationMs/1e3),i=t.createBufferSource();i.buffer=this.pcNoiseBuffer;let o=t.createBiquadFilter();o.type=e.filterType||"bandpass",o.Q.value=e.q??2,o.frequency.setValueAtTime(e.freqHz,n),e.endFreqHz&&o.frequency.exponentialRampToValueAtTime(Math.max(30,e.endFreqHz),n+r);let s=t.createGain(),l=Math.max(.001,Math.min(1,e.intensity??.5));s.gain.setValueAtTime(1e-4,n),s.gain.linearRampToValueAtTime(l,n+Math.min(.015,r*.15)),s.gain.exponentialRampToValueAtTime(1e-4,n+r),i.connect(o),o.connect(s),this.routePc(s,e.pan??0,1),i.start(n),i.stop(n+r+.03)}playControllerSpeakerTone(e){if(!this.dsCtx||this.dsChGains.length<2){this.playPcTone({...e,intensity:(e.intensity??.5)*.45});return}let t=this.dsCtx,n=t.currentTime+(e.delayMs||0)/1e3,r=Math.max(.015,e.durationMs/1e3),i=t.createOscillator();i.type=e.wave||"triangle",i.frequency.setValueAtTime(Math.max(60,e.freqHz),n),e.endFreqHz&&e.endFreqHz>0&&i.frequency.exponentialRampToValueAtTime(Math.max(60,e.endFreqHz),n+r);let o=t.createGain(),s=Math.max(.001,Math.min(1,e.intensity??.75));o.gain.setValueAtTime(1e-4,n),o.gain.linearRampToValueAtTime(s,n+Math.min(.006,r*.18)),o.gain.exponentialRampToValueAtTime(1e-4,n+r),i.connect(o),this.routeDsSpeakerMonoSafe(o,.95),i.start(n),i.stop(n+r+.02)}playHapticPulse(e){if(!this.dsCtx||this.dsChGains.length<4)return;let t=this.dsCtx,n=t.currentTime+(e.delayMs||0)/1e3,r=Math.max(.012,e.durationMs/1e3),i=t.createOscillator();i.type=e.wave||"sine",i.frequency.setValueAtTime(Math.max(22,e.freqHz),n),e.endFreqHz&&e.endFreqHz>0&&i.frequency.exponentialRampToValueAtTime(Math.max(22,e.endFreqHz),n+r);let o=t.createGain(),s=Math.max(.001,Math.min(1,e.intensity));o.gain.setValueAtTime(1e-4,n),o.gain.linearRampToValueAtTime(s,n+Math.min(.004,r*.2)),o.gain.exponentialRampToValueAtTime(1e-4,n+r),i.connect(o),this.routeDsVcm(o,e.pan??0,1),i.start(n),i.stop(n+r+.02)}playHapticSweep(e){if(!this.dsCtx||this.dsChGains.length<4)return;let t=this.dsCtx,n=t.currentTime,r=Math.max(.04,e.durationMs/1e3),i=t.createOscillator();i.type=e.wave||"sine",i.frequency.setValueAtTime(Math.max(25,e.fromHz),n),i.frequency.exponentialRampToValueAtTime(Math.max(25,e.toHz),n+r);let o=Math.max(-1,Math.min(1,e.fromPan)),s=Math.max(-1,Math.min(1,e.toPan)),l=t.createGain(),d=t.createGain();l.gain.setValueAtTime(Math.cos((o+1)*Math.PI/4)*e.intensity,n),l.gain.linearRampToValueAtTime(Math.cos((s+1)*Math.PI/4)*e.intensity,n+r),d.gain.setValueAtTime(Math.sin((o+1)*Math.PI/4)*e.intensity,n),d.gain.linearRampToValueAtTime(Math.sin((s+1)*Math.PI/4)*e.intensity,n+r),i.connect(l),i.connect(d),l.connect(this.dsChGains[2]),d.connect(this.dsChGains[3]),i.start(n),i.stop(n+r+.02)}createContinuous(e){let t=!1,n=null,r=null,i=()=>{if(n){try{n.osc.stop(),n.noise?.stop(),n.master.disconnect(),n.spkGain.disconnect()}catch{}n=null}},o=()=>{if(r){try{r.osc.stop(),r.gain.disconnect()}catch{}r=null}},s=()=>{if(!t){if(n&&n.ctx!==this.dsCtx&&i(),!n&&this.dsCtx&&this.dsChGains.length>=4){let d=this.dsCtx,h=d.createOscillator(),u=d.createBiquadFilter(),c=d.createGain(),m=d.createGain(),b=d.createGain(),y=d.createGain();c.gain.value=1e-4,m.gain.value=.7,b.gain.value=.7,y.gain.value=1e-4;let v={ice:{wave:"triangle",f:240,filtF:310,spk:.25},metal:{wave:"sine",f:150,filtF:180,spk:.35},gravel:{wave:"sawtooth",f:82,filtF:150,spk:.2},grass:{wave:"sine",f:65,filtF:110,spk:.1},water:{wave:"sine",f:48,filtF:85,spk:.18},engine:{wave:"sawtooth",f:42,filtF:160,spk:.05},tension:{wave:"sawtooth",f:78,filtF:210,spk:.4}}[e];h.type=v.wave,h.frequency.value=v.f,u.type="lowpass",u.frequency.value=v.filtF;let g;if(this.dsNoiseBuffer&&(e==="water"||e==="gravel"||e==="ice")){g=d.createBufferSource(),g.buffer=this.dsNoiseBuffer,g.loop=!0;let f=d.createGain();f.gain.value=.45,g.connect(f),f.connect(u),g.start()}h.connect(u),u.connect(c),c.connect(m),c.connect(b),m.connect(this.dsChGains[2]),b.connect(this.dsChGains[3]),c.connect(y),y.connect(this.dsChGains[0]),y.connect(this.dsChGains[1]),y.gain.value=v.spk,h.start(),n={ctx:d,osc:h,noise:g,filter:u,master:c,gL:m,gR:b,spkGain:y}}if(r&&r.ctx!==this.pcCtx&&o(),!r&&this.pcCtx&&this.pcMasterGain&&(e==="engine"||e==="tension"||e==="water")){let d=this.pcCtx,h=d.createOscillator();h.type=e==="water"?"sine":"triangle",h.frequency.value=e==="engine"?75:e==="tension"?210:120;let u=d.createGain();u.gain.value=1e-4;let c=d.createStereoPanner();h.connect(u),u.connect(c),c.connect(this.pcMasterGain),h.start(),r={ctx:d,osc:h,gain:u,panner:c}}}};s();let l={update:({intensity:d=0,speed:h=.5,pan:u=0,freqScale:c=1}={})=>{if(t)return;d>.005&&s();let m=Math.max(1e-4,Math.min(1,d)),b=Math.max(-1,Math.min(1,u));if(n&&this.dsCtx&&n.ctx===this.dsCtx){let y=this.dsCtx.currentTime;n.master.gain.setTargetAtTime(m*.85,y,.025),n.gL.gain.setTargetAtTime(Math.cos((b+1)*Math.PI/4),y,.025),n.gR.gain.setTargetAtTime(Math.sin((b+1)*Math.PI/4),y,.025);let S=e==="tension"?68+h*150:e==="engine"?35+h*95:85+h*140;n.osc.frequency.setTargetAtTime(Math.max(25,S*c),y,.03)}if(r&&this.pcCtx&&r.ctx===this.pcCtx){let y=this.pcCtx.currentTime;r.gain.gain.setTargetAtTime(m*.22,y,.03),r.panner.pan.setTargetAtTime(b*.7,y,.03);let S=e==="tension"?180+h*260:70+h*160;r.osc.frequency.setTargetAtTime(Math.max(30,S*c),y,.03)}},stop:()=>{t||(t=!0,this.activeContinuous.delete(l),i(),o())}};return this.activeContinuous.add(l),l}playComboPreset(e,t=0){switch(e){case"ratchet_tick":this.playHapticPulse({pan:t,freqHz:215,endFreqHz:115,durationMs:18,intensity:.52,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:2100,endFreqHz:1150,durationMs:16,intensity:.45,wave:"triangle"});break;case"lock_sweet_spot":this.playHapticPulse({pan:-.45,freqHz:145,endFreqHz:68,durationMs:65,intensity:.95,wave:"sine"}),this.playHapticPulse({pan:.45,freqHz:285,endFreqHz:170,durationMs:48,intensity:.75,wave:"triangle",delayMs:14}),this.playControllerSpeakerTone({freqHz:1480,endFreqHz:860,durationMs:75,intensity:.85,wave:"sine"}),this.playPcTone({freqHz:440,endFreqHz:330,durationMs:110,intensity:.28,pan:t,wave:"sine"});break;case"lock_unlock":this.playHapticSweep({fromPan:-.95,toPan:.95,fromHz:65,toHz:185,durationMs:260,intensity:.95}),this.playControllerSpeakerTone({freqHz:980,endFreqHz:1560,durationMs:120,intensity:.85,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:1560,endFreqHz:2093,durationMs:180,intensity:.8,delayMs:120,wave:"sine"}),this.playPcNoiseBurst({durationMs:520,filterType:"lowpass",freqHz:280,endFreqHz:65,intensity:.85}),this.playPcTone({freqHz:523.25,endFreqHz:783.99,durationMs:360,intensity:.38,delayMs:90,wave:"triangle"});break;case"fish_bite":this.playHapticPulse({pan:t,freqHz:95,endFreqHz:42,durationMs:110,intensity:.95,wave:"sine"}),this.playHapticPulse({pan:-t*.5,freqHz:165,endFreqHz:75,durationMs:75,intensity:.8,delayMs:85}),this.playControllerSpeakerTone({freqHz:1250,endFreqHz:780,durationMs:95,intensity:.85,wave:"sawtooth"}),this.playPcNoiseBurst({durationMs:240,filterType:"bandpass",freqHz:1400,endFreqHz:500,intensity:.6,pan:t});break;case"fish_splash":this.playHapticSweep({fromPan:t,toPan:-t,fromHz:140,toHz:52,durationMs:220,intensity:.85}),this.playPcNoiseBurst({durationMs:420,filterType:"bandpass",freqHz:1800,endFreqHz:420,intensity:.72,pan:t}),this.playControllerSpeakerTone({freqHz:1600,endFreqHz:620,durationMs:110,intensity:.55,wave:"triangle"});break;case"pistol":this.playHapticPulse({pan:.2,freqHz:145,endFreqHz:42,durationMs:80,intensity:1}),this.playHapticPulse({pan:.6,freqHz:260,endFreqHz:135,durationMs:36,intensity:.68,delayMs:55,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:1850,endFreqHz:620,durationMs:48,intensity:.85,delayMs:50,wave:"triangle"}),this.playPcNoiseBurst({durationMs:190,filterType:"lowpass",freqHz:3200,endFreqHz:240,intensity:.75});break;case"shotgun":this.playHapticPulse({pan:0,freqHz:115,endFreqHz:28,durationMs:210,intensity:1}),this.playHapticPulse({pan:-.85,freqHz:210,endFreqHz:105,durationMs:50,intensity:.85,delayMs:260,wave:"sawtooth"}),this.playHapticPulse({pan:.85,freqHz:265,endFreqHz:130,durationMs:50,intensity:.85,delayMs:390,wave:"sawtooth"}),this.playControllerSpeakerTone({freqHz:1100,endFreqHz:520,durationMs:55,intensity:.85,delayMs:260,wave:"sawtooth"}),this.playControllerSpeakerTone({freqHz:1450,endFreqHz:740,durationMs:55,intensity:.85,delayMs:390,wave:"sawtooth"}),this.playPcNoiseBurst({durationMs:420,filterType:"lowpass",freqHz:2800,endFreqHz:110,intensity:.95});break;case"bow_release":this.playHapticPulse({pan:-.35,freqHz:240,endFreqHz:72,durationMs:150,intensity:.95,wave:"triangle"}),this.playControllerSpeakerTone({freqHz:920,endFreqHz:360,durationMs:120,intensity:.85,wave:"triangle"}),this.playPcNoiseBurst({durationMs:210,filterType:"bandpass",freqHz:2200,endFreqHz:600,intensity:.55});break;case"thunder":this.playPcNoiseBurst({durationMs:1650,filterType:"lowpass",freqHz:520,endFreqHz:68,intensity:.95,pan:t}),this.playHapticPulse({pan:t,freqHz:82,endFreqHz:28,durationMs:950,intensity:1,wave:"sawtooth"});break}}async testPcSpeakersLoud(){await this.resumeAll(),this.playPcTone({freqHz:523.25,durationMs:240,intensity:.55,pan:-.85,wave:"sine"}),this.playPcTone({freqHz:659.25,durationMs:260,intensity:.55,pan:.85,delayMs:260,wave:"sine"})}async testDualSenseSpeakerLoud(){if(await this.resumeAll(),!this.dsCtx||this.dsChGains.length<2)throw new Error("DualSense 4-channel audio is not connected yet.");[880,1174.66,1318.51].forEach((t,n)=>{this.playControllerSpeakerTone({freqHz:t,durationMs:200,intensity:.95,delayMs:n*210,wave:"triangle"})})}async testDualSenseVcmLoud(){if(await this.resumeAll(),!this.dsCtx||this.dsChGains.length<4)throw new Error("DualSense 4-channel audio is not connected yet.");this.playHapticPulse({pan:-.95,freqHz:55,endFreqHz:180,durationMs:520,intensity:.95}),this.playHapticPulse({pan:.95,freqHz:180,endFreqHz:55,durationMs:520,intensity:.95,delayMs:560})}async runThreeLayerCalibration(e){await this.resumeAll(),e(1),this.playPcTone({freqHz:523.25,durationMs:320,intensity:.5,pan:-.9}),this.playPcTone({freqHz:659.25,durationMs:320,intensity:.5,pan:.9,delayMs:340}),setTimeout(()=>{e(2),this.playControllerSpeakerTone({freqHz:880,endFreqHz:1174.66,durationMs:480,intensity:.95,wave:"triangle"})},760),setTimeout(()=>{e(3),this.playHapticPulse({pan:-1,freqHz:45,endFreqHz:210,durationMs:650,intensity:.95})},1350),setTimeout(()=>{e(4),this.playHapticPulse({pan:1,freqHz:210,endFreqHz:45,durationMs:650,intensity:.95})},2100),setTimeout(()=>{e(5),this.playHapticSweep({fromPan:-1,toPan:1,fromHz:110,toHz:145,durationMs:850,intensity:.95}),this.playPcTone({freqHz:392,endFreqHz:523.25,durationMs:820,intensity:.35,wave:"triangle"})},2850),setTimeout(()=>e(6),3800)}};var xe="gamepadly-link://start";function Ze(){return typeof navigator>"u"?!1:/Windows/i.test(navigator.userAgent)&&!/Firefox\//i.test(navigator.userAgent)}function Je(a=xe){if(typeof document>"u"||!document.body)return;let e=document.createElement("a");e.href=a,e.style.display="none",document.body.appendChild(e),e.click(),document.body.removeChild(e)}function Ct(a){return a instanceof Error?a.message:String(a)}async function Yt(a,e,t){let n=!1,r=null,i=()=>{n=!0},o=()=>{let d=r;r=null,d?.()},s=typeof window<"u";s&&(window.addEventListener("blur",i),window.addEventListener("focus",o));let l={online:!1};try{Je(e);let d=Date.now();for(;await new Promise(u=>{let c=setTimeout(()=>{r=null,u()},450);r=()=>{clearTimeout(c),u()}}),l=await a.probeCompanion(700),!l.online;){let h=n||t?12e3:3600;if(Date.now()-d>=h)break}}finally{s&&(window.removeEventListener("blur",i),window.removeEventListener("focus",o))}return l}async function At(a,e={}){let t={online:!1},n=[];try{await a.initPcOutput().catch(()=>{}),t=await a.probeCompanion(900);let r=e.autoLaunch??Ze();if(!t.online&&(e.forceLaunch||r)){e.onLaunchingChange?.(!0);try{t=await Yt(a,e.launchUri??xe,!!e.forceLaunch)}finally{e.onLaunchingChange?.(!1)}}if(!t.online)return{ok:!1,error:"link_not_running",health:t,devices:n};n=await a.listCompanionDevices().catch(()=>[]);let i=(e.deviceId?n.find(s=>s.id===e.deviceId):void 0)??n.find(s=>s.isDualSense&&s.channels>=4)??n.find(s=>s.isDualSense);return{ok:!0,bind:await a.connectDualSenseCompanion(i?.id||e.deviceId||"",i?.name||"DualSense WASAPI"),health:t,devices:n}}catch(r){return{ok:!1,error:"failed",message:Ct(r),health:t,devices:n}}}async function Tt(a,e={}){try{if(!Q.checkBrowserCapabilities().hasSetSinkId)return{ok:!1,error:"no_set_sink_id"};await a.initPcOutput().catch(()=>{}),await a.unlockBrowserDeviceLabels();let t=await a.listBrowserOutputDevices(),n=(e.deviceId?t.find(i=>i.deviceId===e.deviceId):void 0)??t.find(i=>i.isLikelyDualSense&&i.deviceId!=="default"&&i.deviceId!=="communications")??t.find(i=>i.isLikelyDualSense);return n?{ok:!0,bind:await a.connectDualSenseBrowserSink(n.deviceId,n.label)}:{ok:!1,error:"dualsense_audio_not_found"}}catch(t){return{ok:!1,error:"failed",message:Ct(t)}}}function ve(a){let e=new Map,t=new Set,n=!1,r=()=>a.getAudioRouting();function i(u,c){let m=Math.max(1,Math.min(4,c.channels.length)),b=Math.max(1,c.channels[0]?.length??1),y=u.createBuffer(m,b,Math.max(8e3,Math.round(c.sampleRate)));for(let S=0;S<m;S++){let v=y.getChannelData(S),g=c.channels[S]??c.channels[0];g&&v.set(g.length===b?g:g.subarray(0,b))}return y}function o(u,c){if(n)return Promise.resolve(null);let m=e.get(u),b=r(),y=c==="pc"?b.pcCtx:b.dsCtx;if(!m||!y)return Promise.resolve(null);if(c==="pc"&&m.pcCtxRef===y&&m.pcBuffer)return Promise.resolve(m.pcBuffer);if(c==="ds"&&m.dsCtxRef===y&&m.dsBuffer)return Promise.resolve(m.dsBuffer);if(m.rawPcm){let v=i(y,m.rawPcm);return c==="pc"?(m.pcCtxRef=y,m.pcBuffer=v):(m.dsCtxRef=y,m.dsBuffer=v),Promise.resolve(v)}if(!m.rawEncoded||c==="pc"&&m.pcDecoding||c==="ds"&&m.dsDecoding)return Promise.resolve(null);c==="pc"?m.pcDecoding=!0:m.dsDecoding=!0;let S=m.rawEncoded.slice(0);return y.decodeAudioData(S).then(v=>{if(n||e.get(u)!==m)return null;let g=r();return c==="pc"&&g.pcCtx===y?(m.pcCtxRef=y,m.pcBuffer=v):c==="ds"&&g.dsCtx===y&&(m.dsCtxRef=y,m.dsBuffer=v),v}).catch(()=>null).finally(()=>{c==="pc"?m.pcDecoding=!1:m.dsDecoding=!1})}function s(u){for(let c of e.keys())o(c,u)}function l(u,c){let m=e.get(u),b=r(),y=c==="pc"?b.pcCtx:b.dsCtx;if(!m||!y)return null;if(c==="pc"){if(m.pcCtxRef===y&&m.pcBuffer)return m.pcBuffer}else if(m.dsCtxRef===y&&m.dsBuffer)return m.dsBuffer;if(m.rawPcm){let S=i(y,m.rawPcm);return c==="pc"?(m.pcCtxRef=y,m.pcBuffer=S):(m.dsCtxRef=y,m.dsBuffer=S),S}return o(u,c),null}function d(u=0){for(let c of Array.from(t))try{c.stop(u)}catch{}t.clear()}let h=typeof a.onAudioGraphChange=="function"?a.onAudioGraphChange(u=>{if(!n){if(u==="pc_ready")s("pc");else if(u==="ds_ready")s("ds");else if(u==="ds_teardown"){d(0);for(let c of e.values())c.dsCtxRef=null,c.dsBuffer=null,c.dsDecoding=!1}}}):()=>{};return{async loadSample(u,c){if(n||!u)return!1;try{if(typeof c=="string"){let y=await fetch(c);if(!y.ok)return!1;let S=await y.arrayBuffer();e.set(u,{rawEncoded:S})}else if(c instanceof ArrayBuffer)e.set(u,{rawEncoded:c.slice(0)});else if(c&&Array.isArray(c.channels)&&c.channels.length>0)e.set(u,{rawPcm:{sampleRate:c.sampleRate,channels:c.channels.map(y=>new Float32Array(y))}});else return!1;let m=r(),b=[];return m.pcCtx&&b.push(o(u,"pc")),m.dsCtx&&b.push(o(u,"ds")),b.length>0&&await Promise.all(b),!0}catch{return!1}},hasSample(u){return e.has(u)},unloadSample(u){e.delete(u)},playSample(u,c={}){if(n)return N;let m=c.route??"pc",b=Math.max(-1,Math.min(1,c.pan??0)),y=Math.max(.001,Math.min(1.5,c.gain??.85)),S=Math.max(.25,Math.min(4,c.playbackRate??1)),v=!!c.loop,g=Math.max(0,(c.delayMs??0)/1e3),f=r(),w=!!(f.dsCtx&&f.dsChGains.length>=4),k=!!(f.dsCtx&&f.dsChGains.length>=2),p="pc",x=m,C=1;if(m==="vcm"){if(!w)return N;p="ds"}else if(m==="speaker")if(k)p="ds";else if(f.pcCtx&&f.pcMasterGain)p="pc",x="pc",C=.45;else return N;else if(m==="quad")if(w)p="ds";else if(f.pcCtx&&f.pcMasterGain)p="pc",x="pc",C=.5;else return N;else{if(!f.pcCtx||!f.pcMasterGain)return N;p="pc"}let A=p==="pc"?f.pcCtx:f.dsCtx,R=l(u,p);if(!R)return N;let I=A.createBufferSource();I.buffer=R,I.loop=v,I.playbackRate.value=S;let P=A.createGain();P.gain.value=y*C;let D=null,T=null,H=null,M=[I,P];if(x==="pc")D=A.createStereoPanner(),D.pan.value=b,I.connect(P),P.connect(D),D.connect(f.pcMasterGain),M.push(D);else if(x==="speaker")I.connect(P),P.connect(f.dsChGains[0]),P.connect(f.dsChGains[1]);else if(x==="vcm")T=A.createGain(),H=A.createGain(),T.gain.value=Math.cos((b+1)*Math.PI/4),H.gain.value=Math.sin((b+1)*Math.PI/4),I.connect(P),P.connect(T),P.connect(H),T.connect(f.dsChGains[2]),H.connect(f.dsChGains[3]),M.push(T,H);else if(R.numberOfChannels>=4){let E=A.createChannelSplitter(4),L=A.createGain();L.gain.value=.5,T=A.createGain(),H=A.createGain(),T.gain.value=Math.cos((b+1)*Math.PI/4)*Math.SQRT2,H.gain.value=Math.sin((b+1)*Math.PI/4)*Math.SQRT2,I.connect(P),P.connect(E),E.connect(L,0),E.connect(L,1),L.connect(f.dsChGains[0]),L.connect(f.dsChGains[1]),E.connect(T,2),E.connect(H,3),T.connect(f.dsChGains[2]),H.connect(f.dsChGains[3]),M.push(E,L,T,H)}else{let E=A.createGain();E.gain.value=.35,T=A.createGain(),H=A.createGain(),T.gain.value=Math.cos((b+1)*Math.PI/4),H.gain.value=Math.sin((b+1)*Math.PI/4),I.connect(P),P.connect(E),E.connect(f.dsChGains[0]),E.connect(f.dsChGains[1]),P.connect(T),P.connect(H),T.connect(f.dsChGains[2]),H.connect(f.dsChGains[3]),M.push(E,T,H)}let B=!0,O=()=>{if(B){B=!1,t.delete(_);for(let E of M)try{E.disconnect()}catch{}}},_={get active(){return B},update:({pan:E,gain:L,playbackRate:G}={})=>{if(!B)return;let q=A.currentTime;if(L!==void 0){let F=Math.max(1e-4,Math.min(1.5,L))*C;P.gain.setTargetAtTime(F,q,.02)}if(G!==void 0){let F=Math.max(.25,Math.min(4,G));I.playbackRate.setTargetAtTime(F,q,.025)}if(E!==void 0){let F=Math.max(-1,Math.min(1,E));if(D&&D.pan.setTargetAtTime(F,q,.02),T&&H){let W=x==="quad"&&R.numberOfChannels>=4?Math.SQRT2:1;T.gain.setTargetAtTime(Math.cos((F+1)*Math.PI/4)*W,q,.02),H.gain.setTargetAtTime(Math.sin((F+1)*Math.PI/4)*W,q,.02)}}},stop:(E=0)=>{if(!B)return;let L=A.currentTime;if(E>4){let G=Math.min(2,E/1e3);try{P.gain.cancelScheduledValues(L),P.gain.setValueAtTime(Math.max(1e-4,P.gain.value),L),P.gain.exponentialRampToValueAtTime(1e-4,L+G),I.stop(L+G+.015)}catch{O()}}else{try{I.stop()}catch{}O()}}};return I.onended=()=>{O()},t.add(_),I.start(A.currentTime+g),_},stopAll:d,dispose(){n||(n=!0,h(),d(0),e.clear())}}}function $t(a){let e=new Q(a),t=ve(e);return Object.assign(e,{loadSample:t.loadSample,hasSample:t.hasSample,unloadSample:t.unloadSample,playSample:t.playSample,stopAllSamples:t.stopAll})}function kt(a,e=a.destination){let t=a.createGain();t.connect(e);let n=!1;return{output:t,getAudioRouting:()=>({pcCtx:n?null:a,pcMasterGain:n?null:t,dsCtx:null,dsChGains:[]}),dispose(){if(!n){n=!0;try{t.disconnect()}catch{}}}}}var we=/wireless controller|dualsense|ps5/i;function Pt(){return typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia&&typeof window<"u"&&!!(window.AudioContext||window.webkitAudioContext)}function Qe(a){return{video:!1,audio:{...a?{deviceId:{exact:a}}:{},echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}}function et(a){if(a)for(let e of a.getTracks())try{e.stop()}catch{}}async function Ht(){if(navigator.mediaDevices?.enumerateDevices)try{return(await navigator.mediaDevices.enumerateDevices()).find(e=>e.kind==="audioinput"&&we.test(e.label||""))}catch{return}}async function me(a={}){if(!Pt())return"unsupported";let e=window.AudioContext||window.webkitAudioContext,t=!a.deviceId&&a.preferControllerMic!==!1,n=null;try{let r=t?await Ht():void 0;try{n=await navigator.mediaDevices.getUserMedia(Qe(a.deviceId??r?.deviceId))}catch(u){if(!r)throw u;n=await navigator.mediaDevices.getUserMedia(Qe())}if(t&&!we.test(n.getAudioTracks()[0]?.label||"")){let u=await Ht(),c=n.getAudioTracks()[0]?.getSettings?.().deviceId;if(u?.deviceId&&u.deviceId!==c)try{let m=await navigator.mediaDevices.getUserMedia(Qe(u.deviceId));et(n),n=m}catch{}}let i=new e;i.state==="suspended"&&await i.resume();let o=i.createMediaStreamSource(n),s=i.createAnalyser();s.fftSize=a.fftSize??512,s.smoothingTimeConstant=a.smoothing??.55,o.connect(s);let l=n.getAudioTracks()[0]?.label||"",d=n,h=!1;return{ctx:i,analyser:s,stream:d,label:l,usingControllerMic:we.test(l),close(){if(!h){h=!0;try{o.disconnect()}catch{}et(d),i.close().catch(()=>{})}}}}catch{return et(n),"denied"}}function tt(a){if(a.length===0)return 0;let e=0;for(let t=0;t<a.length;t++){let n=(a[t]-128)/128;e+=n*n}return Math.sqrt(e/a.length)}function X(a,e,t){return Math.max(e,Math.min(t,a))}function It(a,e,t,n,r={}){let i=r.rmsThreshold??.035,o=r.flatnessThreshold??.28,s=0;for(let C=0;C<e.length;C++){let A=(e[C]-128)/128;s+=A*A}let l=e.length>0?Math.sqrt(s/e.length):0,d=t/Math.max(1,n),h=Math.max(1,Math.floor(80/d)),u=Math.min(a.length-1,Math.ceil(1600/d)),c=Math.max(1,u-h+1),m=0,b=0,y=0;for(let C=h;C<=u;C++){let A=Math.max(1e-4,a[C]/255);m+=A,b+=Math.log(A),a[C]>18&&y++}let S=m/c,v=Math.exp(b/c),g=S>1e-4?X(v/S,0,1):0,f=y/c;if(l<i)return{rms:l,flatness:g,rawIntensity:0};let w=X((l-i)/Math.max(.05,.28-i),0,1),k=X((g-o*.65)/Math.max(.15,.78-o*.65),0,1),p=X(f/.45,0,1),x=X(w*(.25+.75*k*p),0,1);return{rms:l,flatness:g,rawIntensity:x}}function nt(a={}){let e=X(a.rmsThreshold??.035,.005,.5),t=X(a.flatnessThreshold??.28,.05,.9),n=X(a.blowingThreshold??.22,.05,.95),r=X(a.smoothing??.28,.05,1),i=a.fftSize??512,o=null,s=null,l=null,d=null,h=0,u=0,c={status:"idle",intensity:0,blowing:!1,sustainedMs:0,peakIntensity:0,rms:0,flatness:0,deviceLabel:"",usingControllerMic:!1};function m(){u++,o?.close(),o=null,s=null,l=null,d=null,h=0,c.status=c.status==="denied"||c.status==="unsupported"?c.status:"idle",c.intensity=0,c.blowing=!1,c.sustainedMs=0,c.rms=0,c.flatness=0,c.deviceLabel="",c.usingControllerMic=!1}return{async start(){m();let b=u;c.peakIntensity=0;let y=await me({preferControllerMic:a.preferControllerMic,deviceId:a.deviceId,fftSize:i,smoothing:.55});return b!==u?(typeof y!="string"&&y.close(),!1):typeof y=="string"?(c.status=y,!1):(o=y,s=y.analyser,l=new Uint8Array(new ArrayBuffer(s.frequencyBinCount)),d=new Uint8Array(new ArrayBuffer(s.fftSize)),c.status="active",c.deviceLabel=y.label||"Microphone",c.usingControllerMic=y.usingControllerMic,!0)},stop:m,sample(b=typeof performance<"u"?performance.now():Date.now()){if(c.status!=="active"||!o||!s||!l||!d)return c;s.getByteFrequencyData(l),s.getByteTimeDomainData(d);let y=It(l,d,o.ctx.sampleRate,s.fftSize,{rmsThreshold:e,flatnessThreshold:t}),S=y.rawIntensity;c.intensity=c.intensity+(S-c.intensity)*r,c.intensity<.005&&(c.intensity=0),c.intensity>c.peakIntensity&&(c.peakIntensity=c.intensity),c.rms=y.rms,c.flatness=y.flatness;let v=c.intensity>=n;return v?(c.blowing||(h=b),c.sustainedMs=Math.max(0,b-h)):(h=0,c.sustainedMs=0),c.blowing=v,c},getState(){return c},dispose(){m()}}}function Xt(a={}){let e=a.gain??2.6,t=null,n=null,r=0,i={status:"idle",level:0,peak:0,rms:0,deviceLabel:"",usingControllerMic:!1},o=()=>{r++,t?.close(),t=null,n=null,i.status==="active"&&(i.status="idle"),i.level=0,i.rms=0};return{async start(){o();let s=r,l=await me({fftSize:256,smoothing:.65,...a});return s!==r?(typeof l!="string"&&l.close(),!1):typeof l=="string"?(i.status=l,!1):(t=l,n=new Uint8Array(new ArrayBuffer(l.analyser.fftSize)),i.status="active",i.peak=0,i.deviceLabel=l.label,i.usingControllerMic=l.usingControllerMic,!0)},sample(){return!t||!n||(t.analyser.getByteTimeDomainData(n),i.rms=tt(n),i.level=Math.min(1,i.rms*e),i.level>i.peak&&(i.peak=i.level)),i},getState:()=>i,stop:o,dispose:o}}function Zt(a){return a}var Jt={update(){},stop(){}};function Rt(a){return{getBestScore:()=>{if(typeof localStorage>"u")return 0;try{let e=localStorage.getItem(a);return e&&Number(e)||0}catch{return 0}},saveBestScore:e=>{if(!(typeof localStorage>"u"))try{let t=Number(localStorage.getItem(a)||0);e>t&&localStorage.setItem(a,String(Math.round(e)))}catch{}}}}function Qt(a){let{gameId:e,locale:t,getPlayerSeats:n}=a,r=Ye(a.hub),i=r.active,o=j();o.source="keyboard_mouse",o.deviceName="Keyboard & Mouse",o.identity={brand:"none",model:"none",displayName:"Keyboard & Mouse",rawId:"",transport:"disconnected",source:"keyboard_mouse"};let s=j(),l=a.isolateKeyboardFallback===!1?v=>v:v=>v.source==="keyboard_mouse"?o:v,d=new Map,h=v=>{let g=d.get(v);return g||(g=r.player(v),d.set(v,g)),g},u=r.player("__unassigned_seat__"),c=v=>{let g=()=>{let f=n?.();if(!f)return r.player(v);let w=f[v]??null;return w?h(w):null};return{getSlotId:()=>g()?.getSlotId()??null,getCapabilities:()=>{let f=g();return f?f.getCapabilities():{...u.getCapabilities(),slotId:null}},input:{getState:()=>{let f=g();return f?l(f.input.getState()):s},applyDeadzone:V},triggers:{reset:()=>g()?.triggers.reset(),setLeft:f=>g()?.triggers.setLeft(f),setRight:f=>g()?.triggers.setRight(f),setBoth:(f,w)=>g()?.triggers.setBoth(f,w),applyPreset:(f,w)=>g()?.triggers.applyPreset(f,w),pulseImpulse:f=>g()?.triggers.pulseImpulse(f)},haptics:{pulse:f=>g()?.haptics.pulse(f),sweep:f=>g()?.haptics.sweep(f),rumble:f=>g()?.haptics.rumble(f),hdRumble:f=>g()?.haptics.hdRumble(f),hdSequence:f=>g()?.haptics.hdSequence(f),playPreset:(f,w)=>g()?.haptics.playPreset(f,w),createContinuous:f=>g()?.haptics.createContinuous(f)??Jt,playComboPreset:(f,w)=>g()?.haptics.playComboPreset(f,w),stop:()=>g()?.haptics.stop()},audio:{playPcTone:f=>g()?.audio.playPcTone(f),playPcNoise:f=>g()?.audio.playPcNoise(f),playControllerSpeakerTone:f=>g()?.audio.playControllerSpeakerTone(f),loadSample:(f,w)=>i.audio.loadSample(f,w),hasSample:f=>i.audio.hasSample(f),unloadSample:f=>i.audio.unloadSample(f),playSample:(f,w)=>g()?.audio.playSample(f,w)??N},lightbar:{setColor:(f,w,k)=>g()?.lightbar.setColor(f,w,k),flash:(f,w,k,p)=>g()?.lightbar.flash(f,w,k,p)},createActions:f=>(g()??i).createActions(f)}},m=new Set,b=new Set,y={gameId:e,locale:t,showcase:a.showcase,getCapabilities:()=>i.getCapabilities(),onCapabilitiesChange:v=>{m.add(v);let g=r.onCapabilitiesChange(v);return()=>{m.delete(v),g()}},players:{getSlots:()=>r.getSlots(),get:v=>typeof v=="number"&&n?c(v):typeof v=="string"?h(v):r.player(v)},input:{getState:()=>l(i.input.getState()),applyDeadzone:i.input.applyDeadzone},triggers:i.triggers,haptics:i.haptics,audio:i.audio,lightbar:i.lightbar,createActions:v=>i.createActions(v),createMicBlowSensor:v=>{let g=nt(v);return b.add(g),{start:()=>g.start(),sample:f=>g.sample(f),getState:()=>g.getState(),stop:()=>g.stop(),dispose:()=>{b.delete(g),g.dispose()}}},storage:a.storage??Rt(`${a.storageKeyPrefix??"gamepadly:best:"}${e}`)},S=!1;return{sdk:y,hub:r,notifyPlayerSeatsChanged:()=>{if(S)return;let v={slots:r.getSlots(),active:i.getCapabilities()};for(let g of m)try{g(v)}catch{}},dispose:()=>{if(!S){S=!0;for(let v of b)try{v.dispose()}catch{}b.clear(),m.clear(),d.clear(),r.dispose()}}}}var en=["standard_input","analog_triggers","dual_motor_rumble","impulse_triggers","hd_rumble","adaptive_triggers","audio_haptics","controller_speaker","gyro","accelerometer","touchpad","lightbar","battery"],tn={sony:{model:"dualsense",displayName:"DualSense Wireless Controller",tier:"dualsense_full_4ch",caps:["standard_input","analog_triggers","dual_motor_rumble","adaptive_triggers","audio_haptics","controller_speaker","gyro","accelerometer","touchpad","lightbar","battery"]},nintendo:{model:"switch_pro",displayName:"Switch Pro Controller",tier:"switch_pro_hid",caps:["standard_input","hd_rumble","gyro","accelerometer","battery"]},xbox:{model:"xbox_series",displayName:"Xbox Wireless Controller",tier:"xbox_impulse",caps:["standard_input","analog_triggers","dual_motor_rumble","impulse_triggers"]},generic:{model:"generic",displayName:"Standard Gamepad",tier:"standard_gamepad",caps:["standard_input","analog_triggers","dual_motor_rumble"]},none:{model:"none",displayName:"Keyboard & Mouse",tier:"keyboard_mouse",caps:[]}};function nn(a,e,t,n){let r={};for(let o of en)r[o]={inherent:n.has(o),availability:n.has(o)?"ready":"unsupported"};let i=o=>n.has(o);return{slotId:a,tier:t,identity:e.identity,matrix:r,has:i,hasAdaptiveTriggers:i("adaptive_triggers"),hasImpulseTriggers:i("impulse_triggers"),hasHdRumble:i("hd_rumble"),hasDualRumble:i("dual_motor_rumble"),has4ChHaptics:i("audio_haptics"),hasControllerSpeaker:i("controller_speaker"),hasGyro:i("gyro"),hasTouchpad:i("touchpad")}}var z=()=>{};function it(a={},e=0){let t=a.brand??"generic",n=tn[t],r=a.slotId??`gp-${e}`,i=t!=="none",o=j();o.connected=i,o.source=i?"gamepad":"keyboard_mouse",o.deviceName=a.displayName??n.displayName,o.identity={...o.identity,brand:t,model:n.model,displayName:a.displayName??n.displayName,transport:i?"usb":"disconnected",source:i?"gamepad":"keyboard_mouse"};let s=new Set(n.caps);return{state:o,getSlotId:()=>i?r:null,getCapabilities:()=>nn(i?r:null,o,n.tier,s),input:{getState:()=>o,applyDeadzone:V},triggers:{reset:z,setLeft:z,setRight:z,setBoth:z,applyPreset:z,pulseImpulse:z},haptics:{pulse:z,sweep:z,rumble:z,hdRumble:z,hdSequence:z,playPreset:z,createContinuous:()=>({update:z,stop:z}),playComboPreset:z,stop:z},audio:{playPcTone:z,playPcNoise:z,playControllerSpeakerTone:z,loadSample:async()=>!1,hasSample:()=>!1,unloadSample:z,playSample:()=>N},lightbar:{setColor:z,flash:z},createActions:l=>ue(l)}}var Dt={status:"idle",intensity:0,blowing:!1,sustainedMs:0,peakIntensity:0,rms:0,flatness:0,deviceLabel:"",usingControllerMic:!1};function rn(){return{start:async()=>!1,stop:z,sample:()=>({...Dt}),getState:()=>({...Dt}),dispose:z}}function an(a){let t=(a.players??[{}]).map((l,d)=>it(l,d)),n=it({brand:"none",slotId:"__keyboard__"}),r=t[0]??n,i=t.filter(l=>l.state.connected).map((l,d)=>({id:l.getSlotId()??`gp-${d}`,playerNumber:d+1,source:"gamepad",identity:l.state.identity,battery:{percent:100,charging:!1,full:!1,known:!1},observedReportHz:null,lastActivityAt:0})),o=a.bestScore??0,s={getBestScore:()=>o,saveBestScore:l=>{l>o&&(o=Math.round(l))}};return{gameId:a.gameId,locale:a.locale,showcase:a.showcase,mockPlayers:t,getCapabilities:()=>r.getCapabilities(),onCapabilitiesChange:()=>()=>{},players:{getSlots:()=>i.map(l=>({...l})),get:l=>typeof l=="number"?t[l]??n:t.find(d=>d.getSlotId()===l)??n},input:r.input,triggers:r.triggers,haptics:r.haptics,audio:r.audio,lightbar:r.lightbar,createActions:l=>ue(l),createMicBlowSensor:()=>rn(),storage:s}}function Bt(a,e){let t=Math.max(1,e);return Array.from({length:t},(n,r)=>a[r]?.id??null)}function on(a,e,t,n){let r=Math.max(1,n);if(e.length===0)return Bt(t,r);let i=new Map(t.map(c=>[c.id,c])),o=new Map(e.map(c=>[c.id,c])),s=new Set(e.map(c=>c.id)),l=Array.from({length:r},(c,m)=>a[m]??null),d=new Set,h=[];for(let c=0;c<r;c++){let m=l[c];m&&(i.has(m)&&!d.has(m)?d.add(m):h.push(c))}let u=t.filter(c=>!s.has(c.id)&&!d.has(c.id));for(let c of h){let m=l[c],b=m?o.get(m)?.brand:void 0,y=b?u.findIndex(S=>S.brand===b&&!d.has(S.id)):-1;if(y>=0){let S=u.splice(y,1)[0];l[c]=S.id,d.add(S.id)}else l[c]=null}for(let c of u){let m=l.indexOf(null);if(m===-1)break;l[m]=c.id,d.add(c.id)}return l}function sn(a,e,t){let n=Math.max(1,t),r=Array.from({length:n},(s,l)=>a[l]??null),i=r.indexOf(e);if(i>=0)return r[i]=null,r;let o=r.indexOf(null);return o>=0?(r[o]=e,r):[...r.slice(1),e]}var ln=72;var cn=.72,un=12;function Me(){return{sectors:new Float32Array(72),coveragePct:0,avgErrorPct:null,maxMag:0}}function Ce(a,e,t){let n=Math.hypot(e,t);if(n>a.maxMag&&(a.maxMag=n),n<.72)return;let r=Math.atan2(t,e);r<0&&(r+=Math.PI*2);let i=Math.min(71,Math.floor(r/(Math.PI*2)*72));if(n>a.sectors[i]){a.sectors[i]=n;let o=0,s=0;for(let l=0;l<72;l++)a.sectors[l]>0&&(o++,s+=Math.abs(a.sectors[l]-1));a.coveragePct=Math.round(o/72*100),a.avgErrorPct=o>=12?Number((s/o*100).toFixed(1)):null}}function dn(a,e,t,n){let r=[];for(let i=0;i<72;i++){let o=a[i];if(o<=0)continue;let s=(i+.5)/72*Math.PI*2,l=Math.min(1.22,o),d=e+Math.cos(s)*n*l,h=t+Math.sin(s)*n*l;r.push(`${r.length===0?"M":"L"}${d.toFixed(1)},${h.toFixed(1)}`)}return r.length>=24&&r.push("Z"),r.join(" ")}var rt=Object.freeze({mildOffset:.03,driftOffset:.08,mildJitter:.015,driftJitter:.03});function Ae(){return{inRestSince:null,sessionActive:!1,sessionMinX:0,sessionMaxX:0,sessionMinY:0,sessionMaxY:0,settled:!1,peakOffset:0,peakJitter:0}}function Lt(a,e,t,n=rt){return a?e>=n.driftOffset||t>=n.driftJitter?"drift":e>=n.mildOffset||t>=n.mildJitter?"mild":"normal":"waiting"}var ye=class{left=Ae();right=Ae();restMaxMag;settleMs;thresholds;constructor(e={}){this.restMaxMag=e.restMaxMagnitude??.22,this.settleMs=e.settleMs??350,this.thresholds={...rt,...e.thresholds}}updateAxis(e,t,n,r){let i=Math.hypot(t,n);if(i>=this.restMaxMag){e.inRestSince=null,e.sessionActive=!1;return}if(e.inRestSince===null){e.inRestSince=r,e.sessionActive=!1;return}if(r-e.inRestSince<this.settleMs)return;e.sessionActive?(t<e.sessionMinX&&(e.sessionMinX=t),t>e.sessionMaxX&&(e.sessionMaxX=t),n<e.sessionMinY&&(e.sessionMinY=n),n>e.sessionMaxY&&(e.sessionMaxY=n)):(e.sessionActive=!0,e.sessionMinX=t,e.sessionMaxX=t,e.sessionMinY=n,e.sessionMaxY=n),e.settled=!0,i>e.peakOffset&&(e.peakOffset=i);let o=Math.max(e.sessionMaxX-e.sessionMinX,e.sessionMaxY-e.sessionMinY);o>e.peakJitter&&(e.peakJitter=o)}update(e,t,n,r,i){this.updateAxis(this.left,e,t,i),this.updateAxis(this.right,n,r,i)}snapshotAxis(e){let t=Number(e.peakOffset.toFixed(4)),n=Number(e.peakJitter.toFixed(4));return{settled:e.settled,peakOffset:t,peakJitter:n,verdict:Lt(e.settled,t,n,this.thresholds)}}getSnapshot(){return{left:this.snapshotAxis(this.left),right:this.snapshotAxis(this.right)}}reset(){this.left=Ae(),this.right=Ae()}},ge=class{states=new Map;counts=new Map;releaseMaxMs;pressIntervalMaxMs;constructor(e={}){this.releaseMaxMs=e.releaseMaxMs??55,this.pressIntervalMaxMs=e.pressIntervalMaxMs??90}update(e,t){for(let[n,r]of Object.entries(e)){let i=this.states.get(n);if(!i){i={pressed:r,lastPressAt:r?t:0,lastReleaseAt:0},this.states.set(n,i);continue}r&&!i.pressed?(i.lastReleaseAt>0&&i.lastPressAt>0&&t-i.lastReleaseAt<=this.releaseMaxMs&&t-i.lastPressAt<=this.pressIntervalMaxMs&&this.counts.set(n,(this.counts.get(n)??0)+1),i.lastPressAt=t):!r&&i.pressed&&(i.lastReleaseAt=t),i.pressed=r}}getBouncedButtons(){return Array.from(this.counts.keys())}reset(){this.states.clear(),this.counts.clear()}};function pn(a){let{source:e,brandFilter:t}=a,n=a.setActiveSlot??(h=>void e.setActiveSlot(h)),r=new fe,i=new Map,o=[],s=t?`__none_${t}__`:"__none__",l=()=>({circularity:{left:Me(),right:Me()},drift:new ye(a.drift),bounce:new ge(a.bounce),tested:new Set}),d=h=>{let u=i.get(h);return u||(u=l(),i.set(h,u)),u};return{update(h){let u=e.getConnectedControllers(),c=t?u.filter(w=>w.identity.brand===t):u,m=t?u.filter(w=>w.identity.brand!==t):[],b=e.getActiveSlotId(),y=b;t&&(c.length===0?y=null:(!b||!c.some(w=>w.id===b))&&(y=c[0].id,n(y)));let S=!1;if(c.length>0){o=c.map(p=>{let x=e.getInputState(p.id);return{id:p.id,lastActivityAt:p.lastActivityAt,lx:x.lx,ly:x.ly,rx:x.rx,ry:x.ry,l2:x.l2,r2:x.r2}});let{switchTo:w,triggeredSlotId:k}=r.evaluate(o,y,h);w&&w!==y&&(y=w,n(w)),S=k!==null}else o=[];let v=y??(t?`__none_${t}__`:"__none__");s=v;let g=d(v),f=y?e.getInputState(y):t?j():e.getInputState();if(f.connected){Ce(g.circularity.left,f.lx,f.ly),Ce(g.circularity.right,f.rx,f.ry),g.drift.update(f.lx,f.ly,f.rx,f.ry,h),g.bounce.update(f.buttons,h);for(let[w,k]of Object.entries(f.buttons))k&&g.tested.add(w)}return{now:h,slots:c,otherSlots:m,activeSlotId:y,slotKey:v,input:f,triggered:S,diagnostics:g}},selectSlot(h,u){r.notifyManualSelect(o,u),n(h)},resetActive(){i.set(s,l())},getDiagnostics:d}}var at={platformer:{name:"Platformer (WASD / Arrows + Space Jump)",keys:{left:"ArrowLeft",right:"ArrowRight",up:"ArrowUp",down:"ArrowDown","lx-":"ArrowLeft","lx+":"ArrowRight","ly-":"ArrowUp","ly+":"ArrowDown",cross:{code:"Space",hapticOnPress:"click"},square:{code:"KeyZ",hapticOnPress:"recoil",hapticPan:.4},circle:{code:"KeyX",hapticOnPress:"click"},r2:{code:"ShiftLeft",hapticOnPress:"boost",hapticPan:.6},options:"Escape"},triggers:{right:"soft_wall"}},"arcade-4way":{name:"Arcade 4-Way (Grid / Puzzle / Snake / Tetris)",keys:{left:{code:"ArrowLeft",repeatMs:120,hapticOnPress:"ratchet",hapticPan:-.5},right:{code:"ArrowRight",repeatMs:120,hapticOnPress:"ratchet",hapticPan:.5},up:{code:"ArrowUp",repeatMs:120,hapticOnPress:"ratchet"},down:{code:"ArrowDown",repeatMs:90,hapticOnPress:"ratchet"},"lx-":{code:"ArrowLeft",repeatMs:140,hapticOnPress:"ratchet",hapticPan:-.5},"lx+":{code:"ArrowRight",repeatMs:140,hapticOnPress:"ratchet",hapticPan:.5},"ly-":{code:"ArrowUp",repeatMs:140,hapticOnPress:"ratchet"},"ly+":{code:"ArrowDown",repeatMs:100,hapticOnPress:"ratchet"},cross:{code:"Space",hapticOnPress:"click"},circle:"Escape",options:"Enter"}},racing:{name:"Racing (Steer + R2 Gas / L2 ABS Brake)",keys:{left:"ArrowLeft",right:"ArrowRight","lx-":{code:"ArrowLeft",threshold:.25},"lx+":{code:"ArrowRight",threshold:.25},r2:{code:"ArrowUp",threshold:.2},l2:{code:"ArrowDown",threshold:.2},cross:{code:"Space",hapticOnPress:"boost"},square:{code:"ShiftLeft",hapticOnPress:"ratchet"},options:"Escape"},triggers:{left:"abs",right:"bow"}},"twin-stick":{name:"Twin-Stick Shooter (Left Stick Move + Right Stick Aim + R2 Fire)",keys:{"lx-":"KeyA","lx+":"KeyD","ly-":"KeyW","ly+":"KeyS",left:"KeyA",right:"KeyD",up:"KeyW",down:"KeyS",cross:{code:"Space",hapticOnPress:"click"},square:{code:"KeyR",hapticOnPress:"ratchet"},options:"Escape"},pointer:{stick:"right",speedPxPerSec:720,deadzone:.14,clickButton:"r2",secondaryClickButton:"l2",hapticOnClick:"recoil"},triggers:{left:"precision_damp",right:"weapon"}}};var hn={Space:{key:" ",keyCode:32},Enter:{key:"Enter",keyCode:13},Escape:{key:"Escape",keyCode:27},Tab:{key:"Tab",keyCode:9},Backspace:{key:"Backspace",keyCode:8},ArrowLeft:{key:"ArrowLeft",keyCode:37},ArrowUp:{key:"ArrowUp",keyCode:38},ArrowRight:{key:"ArrowRight",keyCode:39},ArrowDown:{key:"ArrowDown",keyCode:40},ShiftLeft:{key:"Shift",keyCode:16},ShiftRight:{key:"Shift",keyCode:16},ControlLeft:{key:"Control",keyCode:17},AltLeft:{key:"Alt",keyCode:18}};function fn(a){let e=hn[a.code];if(e)return{code:a.code,key:a.key??e.key,keyCode:a.keyCode??e.keyCode};if(/^Key[A-Z]$/.test(a.code)){let t=a.code.slice(3);return{code:a.code,key:a.key??t.toLowerCase(),keyCode:a.keyCode??t.charCodeAt(0)}}if(/^Digit[0-9]$/.test(a.code)){let t=a.code.slice(5);return{code:a.code,key:a.key??t,keyCode:a.keyCode??t.charCodeAt(0)}}return{code:a.code,key:a.key??a.code,keyCode:a.keyCode??0}}function mn(a){return(Array.isArray(a)?a:[a]).map(t=>typeof t=="string"?{code:t}:t)}function ot(a,e){return a==="l2"?e.l2:a==="r2"?e.r2:a==="lx+"?Math.max(0,e.lx):a==="lx-"?Math.max(0,-e.lx):a==="ly+"?Math.max(0,e.ly):a==="ly-"?Math.max(0,-e.ly):a==="rx+"?Math.max(0,e.rx):a==="rx-"?Math.max(0,-e.rx):a==="ry+"?Math.max(0,e.ry):a==="ry-"?Math.max(0,-e.ry):e.buttons[a]?1:0}function Et(a){if(a)return typeof a=="string"?pe[a]:a}function yn(a){return"active"in a&&"getSlots"in a}function Te(a,e,t,n=!1){if(typeof KeyboardEvent<"u"){let r=new KeyboardEvent(e,{key:t.key,code:t.code,bubbles:!0,cancelable:!0,repeat:n});try{Object.defineProperty(r,"keyCode",{value:t.keyCode}),Object.defineProperty(r,"which",{value:t.keyCode})}catch{}a.dispatchEvent(r);return}if(typeof Event<"u"){let r=new Event(e,{bubbles:!0,cancelable:!0});r.key=t.key,r.code=t.code,r.keyCode=t.keyCode,r.which=t.keyCode,r.repeat=n,a.dispatchEvent(r)}}function be(a,e,t,n,r,i){let o={bubbles:!0,cancelable:!0,clientX:t,clientY:n,button:r,buttons:i,pointerId:1,pointerType:"mouse",isPrimary:!0};typeof PointerEvent<"u"&&a.dispatchEvent(new PointerEvent(e,o));let s=e.replace("pointer","mouse");typeof MouseEvent<"u"&&a.dispatchEvent(new MouseEvent(s,o))}function Yi(a){let e=yn(a.player)?a.player:null,t=e?e.active:a.player,n=a.keyTarget??(typeof window<"u"?window:void 0),r=a.pointerTarget!==void 0?a.pointerTarget:typeof document<"u"?document.body:null,i=typeof a.profile=="string"?at[a.profile]:a.profile,o=!1,s=0,l=0,d=new Map,h=new Map,u={x:0,y:0,down:!1,secondaryDown:!1,visible:!1},c=!1,m=(f,w)=>{typeof f=="string"?t.haptics.playPreset(f,w):t.haptics.pulse({...f,pan:w?.pan??f.pan,intensity:(w?.intensity??1)*f.intensity})},b=()=>{let f=Et(i.triggers?.left),w=Et(i.triggers?.right);f&&w?t.triggers.setBoth(f,w):f?t.triggers.setLeft(f):w?t.triggers.setRight(w):t.triggers.reset()},y=e?e.onCapabilitiesChange(()=>{o&&b()}):null,S=()=>{if(n)for(let{meta:f}of d.values())Te(n,"keyup",f,!1);if(d.clear(),h.clear(),r&&(u.down||u.secondaryDown)){let f=r.getBoundingClientRect?.()??{left:0,top:0};u.down&&be(r,"pointerup",f.left+u.x,f.top+u.y,0,0),u.secondaryDown&&be(r,"pointerup",f.left+u.x,f.top+u.y,2,0)}u.down=!1,u.secondaryDown=!1},v=(f,w=typeof performance<"u"?performance.now():Date.now())=>{let k=f!==void 0?Math.max(0,Math.min(.1,f)):l>0?Math.max(0,Math.min(.1,(w-l)/1e3)):.016666666666666666;l=w;let p=t.input.getState();if(!p.connected||p.source==="keyboard_mouse"){(d.size>0||u.down||u.secondaryDown)&&S();return}let x=new Map;for(let[C,A]of Object.entries(i.keys)){if(!A)continue;let R=C,I=ot(R,p),P=mn(A);for(let D=0;D<P.length;D++){let T=P[D],H=T.threshold??.45,M=I>=H,B=`${R}:${T.code}:${D}`,O=h.get(B)??!1;if(h.set(B,M),M){let _=fn(T);x.has(_.code)||x.set(_.code,{meta:_,repeatMs:T.repeatMs,repeatDelayMs:T.repeatDelayMs??220}),!O&&T.hapticOnPress&&m(T.hapticOnPress,{pan:T.hapticPan})}}}if(n){for(let[C,A]of d.entries())x.has(C)||(Te(n,"keyup",A.meta,!1),d.delete(C));for(let[C,A]of x.entries()){let R=d.get(C);R?A.repeatMs&&w>=R.nextRepeatAt&&(Te(n,"keydown",A.meta,!0),R.nextRepeatAt=w+A.repeatMs):(Te(n,"keydown",A.meta,!1),d.set(C,{meta:A.meta,nextRepeatAt:A.repeatMs?w+A.repeatDelayMs:Number.POSITIVE_INFINITY}))}}if(i.pointer&&r){let C=i.pointer,A=r.getBoundingClientRect?.()??{left:0,top:0,width:800,height:600},R=Math.max(1,A.width),I=Math.max(1,A.height);c||(u.x=R/2,u.y=I/2,c=!0);let P=C.deadzone??.14,D=V(C.stick==="left"?p.lx:p.rx,P),T=V(C.stick==="left"?p.ly:p.ry,P),H=C.speedPxPerSec??680,M=D!==0||T!==0;M&&(u.x=Math.max(0,Math.min(R,u.x+D*H*k)),u.y=Math.max(0,Math.min(I,u.y+T*H*k)),u.visible=!0);let B=C.clickButton??"r2",O=C.secondaryClickButton??"l2",_=ot(B,p)>=.45,E=ot(O,p)>=.45,L=(_?1:0)|(E?2:0),G=A.left+u.x,q=A.top+u.y;M&&be(r,"pointermove",G,q,-1,L),_!==u.down&&(u.down=_,u.visible=!0,be(r,_?"pointerdown":"pointerup",G,q,0,L),_&&C.hapticOnClick&&m(C.hapticOnClick)),E!==u.secondaryDown&&(u.secondaryDown=E,u.visible=!0,be(r,E?"pointerdown":"pointerup",G,q,2,L)),a.onCursorUpdate?.({...u})}},g=f=>{o&&(v(void 0,f),s=requestAnimationFrame(g))};return{start(){o||(o=!0,l=0,b(),a.autoRaf!==!1&&typeof requestAnimationFrame<"u"&&(s=requestAnimationFrame(g)))},stop(){o&&(o=!1,s&&typeof cancelAnimationFrame<"u"&&cancelAnimationFrame(s),s=0,S())},tick:v,setProfile(f){S(),i=typeof f=="string"?at[f]:f,o&&b()},getCursor(){return{...u}},triggerHaptic:m,dispose(){this.stop(),y?.(),t.triggers.reset()}}}function Xi(){let a=new Set,e=!1,t=n=>{if(e){try{n()}catch{}return()=>{}}return a.add(n),()=>{if(a.delete(n))try{n()}catch{}}};return{add:t,on(n,r,i,o){return n.addEventListener(r,i,o),t(()=>n.removeEventListener(r,i,o))},timeout(n,r){let i=setTimeout(()=>{a.delete(o),e||n()},r),o=()=>clearTimeout(i);return a.add(o),i},interval(n,r){let i=setInterval(()=>{e||n()},r);return a.add(()=>clearInterval(i)),i},dispose(){if(e)return;e=!0;let n=Array.from(a).reverse();a.clear();for(let r of n)try{r()}catch{}}}}function Zi(a,e={}){let t=e.maxDpr??2,n=e.minWidth??320,r=e.minHeight??240,i=document.createElement("canvas");i.style.width="100%",i.style.height="100%",i.style.display="block",i.style.touchAction="none",e.cursor&&(i.style.cursor=e.cursor),a.innerHTML="",a.appendChild(i);let o=i.getContext("2d"),s=n,l=r,d=1,h=()=>{let m=a.getBoundingClientRect(),b=typeof window<"u"&&window.devicePixelRatio||1;d=Math.max(1,Math.min(t,b)),s=Math.max(n,Math.floor(m.width||n)),l=Math.max(r,Math.floor(m.height||r)),i.width=Math.floor(s*d),i.height=Math.floor(l*d),o.setTransform(d,0,0,d,0,0),e.onResize?.(s,l,d)};h();let u=null;typeof ResizeObserver<"u"&&(u=new ResizeObserver(()=>h()),u.observe(a));let c=()=>h();return typeof window<"u"&&window.addEventListener("resize",c),{canvas:i,ctx:o,get width(){return s},get height(){return l},get dpr(){return d},resize:h,dispose(){u?.disconnect(),u=null,typeof window<"u"&&window.removeEventListener("resize",c),i.parentElement===a&&a.removeChild(i)}}}function Ji(a){let e=a.maxDelta??.05,t=a.fixedStep,n=a.autoPauseOnHidden!==!1,r=!1,i=!1,o=0,s=0,l=0,d=c=>{if(i){s=c;return}s===0&&(s=c);let m=Math.max(0,(c-s)/1e3);s=c;let b=Math.min(e,m);if(t&&t>0){l+=b;let y=0;for(;l>=t&&y<8;)a.onUpdate(t,c),l-=t,y++;a.onRender?.(l/t,c)}else a.onUpdate(b,c),a.onRender?.(1,c)},h=c=>{r&&(d(c),o=requestAnimationFrame(h))},u=()=>{!n||typeof document>"u"||document.hidden&&(s=0,l=0)};return n&&typeof document<"u"&&document.addEventListener("visibilitychange",u),{start(){r||(r=!0,s=0,l=0,typeof requestAnimationFrame<"u"&&(o=requestAnimationFrame(h)))},stop(){r&&(r=!1,o&&typeof cancelAnimationFrame<"u"&&cancelAnimationFrame(o),o=0)},pause(){i=!0,s=0},resume(){i=!1,s=0},isPaused(){return i},step:d,dispose(){this.stop(),n&&typeof document<"u"&&document.removeEventListener("visibilitychange",u)}}}export{at as BUILTIN_BRIDGE_PROFILES,ge as ButtonBounceTracker,cn as CIRCULARITY_MIN_RIM_MAGNITUDE,un as CIRCULARITY_MIN_SECTORS,ln as CIRCULARITY_SECTORS,$e as COMPANION_HTTP_BASE,Xe as COMPANION_WS_BASE,we as CONTROLLER_MIC_RE,le as ControllerManager,rt as DEFAULT_DRIFT_THRESHOLDS,le as DualSenseControllerManager,xe as LINK_PROTOCOL_START_URI,N as NOOP_SAMPLE_HANDLE,fe as SlotAutoSwitcher,ye as StickDriftTracker,qe as TACTILE_PRESETS,pe as TRIGGER_PRESETS,Q as ThreeLayerAudioEngine,Ke as TriggerFeedbackController,It as analyzeBlowSpectrum,V as applyDeadzone,je as attachControllerLifecycle,dn as buildSectorPath,he as buildSwitchHdFromPulse,Lt as classifyRestVerdict,Tt as connectDualSenseViaBrowser,At as connectDualSenseViaCompanion,vt as crc32WithSeed,ue as createActionTracker,Zi as createCanvasStage,Me as createCircularity,pn as createControllerTelemetry,Xi as createDisposables,j as createEmptyInput,Qt as createGameHost,Ji as createGameLoop,Ye as createGamepadly,Bt as createInitialSeats,Yi as createKeyMouseBridge,$t as createLinkAudio,Rt as createLocalBestScoreStorage,nt as createMicBlowSensor,Xt as createMicLevelMeter,an as createMockGameSDK,it as createMockPlayerHandle,Kt as createMotionTracker,kt as createPcAudioRouting,ve as createSampleBank,Ft as createTactileBuffer,jt as createTouchpadGestures,Zt as defineGame,de as encodeSwitchHdRumbleSide,K as encodeTriggerEffect,Ge as identifyGamepadFromId,Pt as isMicInputSupported,Je as launchLinkViaProtocol,me as openMicInput,on as reconcileSeats,ce as routeHapticPulse,Oe as routeHapticSweep,Fe as routeTactilePreset,Ze as shouldAutoLaunchLink,tt as timeDomainRms,sn as toggleSeatAssignment,Ce as updateCircularity};
@@ -0,0 +1,26 @@
1
+ /**
2
+ * True 360° stick circularity measurement: the stick's outer travel is binned into 72 five-degree
3
+ * sectors and the reported error is the mean radial deviation from the unit circle across every
4
+ * sampled sector, never a single peak value. Feed it raw (0% deadzone) axes.
5
+ */
6
+ /** 5-degree angular sectors for true 360-degree circularity measurement. */
7
+ export declare const CIRCULARITY_SECTORS = 72;
8
+ /** Samples below this radius are ignored (the stick is not at its outer rim). */
9
+ export declare const CIRCULARITY_MIN_RIM_MAGNITUDE = 0.72;
10
+ /** Minimum filled sectors before `avgErrorPct` is reported. */
11
+ export declare const CIRCULARITY_MIN_SECTORS = 12;
12
+ export interface CircularityStats {
13
+ /** Peak radius seen per sector (`0` = not yet swept). */
14
+ sectors: Float32Array;
15
+ /** Share of the 72 sectors swept so far (0..100). */
16
+ coveragePct: number;
17
+ /** Mean |r - 1| over swept sectors in percent, `null` until enough sectors are swept. */
18
+ avgErrorPct: number | null;
19
+ /** Largest radius seen anywhere (including inside the rim band). */
20
+ maxMag: number;
21
+ }
22
+ export declare function createCircularity(): CircularityStats;
23
+ export declare function updateCircularity(c: CircularityStats, x: number, y: number): void;
24
+ /** SVG path (`M…L…Z`) of the swept rim, centred on `(cx, cy)` with unit circle = `radius`. */
25
+ export declare function buildSectorPath(sectors: Float32Array, cx: number, cy: number, radius: number): string;
26
+ //# sourceMappingURL=circularity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"circularity.d.ts","sourceRoot":"","sources":["../../src/diagnostics/circularity.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,4EAA4E;AAC5E,eAAO,MAAM,mBAAmB,KAAK,CAAC;AAEtC,iFAAiF;AACjF,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAClD,+DAA+D;AAC/D,eAAO,MAAM,uBAAuB,KAAK,CAAC;AAE1C,MAAM,WAAW,gBAAgB;IAC/B,yDAAyD;IACzD,OAAO,EAAE,YAAY,CAAC;IACtB,qDAAqD;IACrD,WAAW,EAAE,MAAM,CAAC;IACpB,yFAAyF;IACzF,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,oEAAoE;IACpE,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,wBAAgB,iBAAiB,IAAI,gBAAgB,CAOpD;AAED,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,gBAAgB,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAoBjF;AAED,8FAA8F;AAC9F,wBAAgB,eAAe,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAarG"}