@gamepadly/sdk 0.0.0-stage → 0.1.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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -2
  3. package/SECURITY.md +19 -0
  4. package/dist/bridge/index.d.ts +50 -0
  5. package/dist/bridge/index.d.ts.map +1 -0
  6. package/dist/bridge/index.js +422 -0
  7. package/dist/bridge/index.js.map +7 -0
  8. package/dist/bridge/profiles.d.ts +51 -0
  9. package/dist/bridge/profiles.d.ts.map +1 -0
  10. package/dist/browser.d.ts +15 -0
  11. package/dist/browser.d.ts.map +1 -0
  12. package/dist/browser.js +4140 -0
  13. package/dist/browser.js.map +7 -0
  14. package/dist/browser.min.js +1 -0
  15. package/dist/chunks/chunk-BEBDNL5B.js +1850 -0
  16. package/dist/chunks/chunk-BEBDNL5B.js.map +7 -0
  17. package/dist/haptics/presets.d.ts +35 -0
  18. package/dist/haptics/presets.d.ts.map +1 -0
  19. package/dist/haptics/router.d.ts +102 -0
  20. package/dist/haptics/router.d.ts.map +1 -0
  21. package/dist/hid/index.d.ts +323 -0
  22. package/dist/hid/index.d.ts.map +1 -0
  23. package/dist/hub.d.ts +112 -0
  24. package/dist/hub.d.ts.map +1 -0
  25. package/dist/index.d.ts +15 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +747 -0
  28. package/dist/index.js.map +7 -0
  29. package/dist/input/actions.d.ts +59 -0
  30. package/dist/input/actions.d.ts.map +1 -0
  31. package/dist/link/engine.d.ts +213 -0
  32. package/dist/link/engine.d.ts.map +1 -0
  33. package/dist/link/index.d.ts +8 -0
  34. package/dist/link/index.d.ts.map +1 -0
  35. package/dist/link/index.js +944 -0
  36. package/dist/link/index.js.map +7 -0
  37. package/dist/loop/index.d.ts +69 -0
  38. package/dist/loop/index.d.ts.map +1 -0
  39. package/dist/loop/index.js +214 -0
  40. package/dist/loop/index.js.map +7 -0
  41. package/package.json +79 -4
@@ -0,0 +1,1850 @@
1
+ // src/hid/index.ts
2
+ var SONY_VENDOR_ID = 1356;
3
+ var DUALSENSE_PIDS = [3302, 3570];
4
+ var NINTENDO_VENDOR_ID = 1406;
5
+ var SWITCH_PRO_PIDS = [8201];
6
+ var SWITCH_NEUTRAL_RUMBLE = new Uint8Array([0, 1, 64, 64]);
7
+ function encodeSwitchAmpStep(rawAmp) {
8
+ if (!Number.isFinite(rawAmp) || rawAmp <= 0.01) return 0;
9
+ const amp = Math.min(0.85, Math.max(0, rawAmp));
10
+ if (amp >= 0.23) {
11
+ return Math.min(100, Math.round(Math.log2(amp * 8.7) * 32));
12
+ }
13
+ if (amp >= 0.12) {
14
+ return Math.round(Math.log2(amp * 17) * 16);
15
+ }
16
+ return Math.max(1, Math.round(amp / 0.12 * 16));
17
+ }
18
+ function encodeSwitchHdRumbleSide(side) {
19
+ if (!side || side.highAmp <= 0.01 && side.lowAmp <= 0.01) {
20
+ return SWITCH_NEUTRAL_RUMBLE.slice();
21
+ }
22
+ const hfHz = Math.max(81.75, Math.min(1252.6, Number.isFinite(side.highFreqHz) ? side.highFreqHz : 320));
23
+ const lfHz = Math.max(40.88, Math.min(626.3, Number.isFinite(side.lowFreqHz) ? side.lowFreqHz : 160));
24
+ const encodedHf = Math.round(Math.log2(hfHz / 10) * 32);
25
+ const encodedLf = Math.round(Math.log2(lfHz / 10) * 32);
26
+ const hf = Math.max(0, Math.min(508, (encodedHf - 96) * 4));
27
+ const lf = Math.max(1, Math.min(127, encodedLf - 64));
28
+ const hfStep = encodeSwitchAmpStep(side.highAmp);
29
+ const lfStep = encodeSwitchAmpStep(side.lowAmp);
30
+ const hfAmpByte = Math.min(200, hfStep * 2);
31
+ const lfAmpParity = (lfStep & 1) !== 0 ? 128 : 0;
32
+ const lfAmpLo = Math.min(114, (lfStep >> 1) + 64);
33
+ return new Uint8Array([
34
+ hf & 255,
35
+ hfAmpByte + (hf >> 8 & 1) & 255,
36
+ (lf | lfAmpParity) & 255,
37
+ lfAmpLo & 255
38
+ ]);
39
+ }
40
+ function applyDeadzone(value, threshold = 0.06) {
41
+ const abs = Math.abs(value);
42
+ if (abs <= threshold) return 0;
43
+ const scaled = (abs - threshold) / (1 - threshold);
44
+ return Math.sign(value) * Math.max(0, Math.min(1, scaled));
45
+ }
46
+ function parseGamepadVendorId(lower) {
47
+ return (lower.match(/vendor:\s*([0-9a-f]{4})/) ?? lower.match(/^([0-9a-f]{1,4})-[0-9a-f]{1,4}-/))?.[1]?.padStart(4, "0");
48
+ }
49
+ function detectGamepadBrand(lower) {
50
+ const vendor = parseGamepadVendorId(lower);
51
+ if (vendor === "054c") return "sony";
52
+ if (vendor === "045e") return "xbox";
53
+ if (vendor === "057e") return "nintendo";
54
+ if (vendor) return void 0;
55
+ if (/xbox|xinput|microsoft/.test(lower)) return "xbox";
56
+ if (/dualsense|dualshock|wireless controller/.test(lower)) return "sony";
57
+ if (/nintendo|pro controller|joy-con|switch/.test(lower)) return "nintendo";
58
+ return void 0;
59
+ }
60
+ function identifyGamepadFromId(rawId) {
61
+ const lower = (rawId || "").toLowerCase();
62
+ const brand = detectGamepadBrand(lower);
63
+ if (brand === "sony") {
64
+ if (/0df2|edge/.test(lower)) {
65
+ return { brand: "sony", model: "dualsense_edge", displayName: "DualSense Edge", rawId, vendorId: 1356, productId: 3570 };
66
+ }
67
+ if (/0ce6|dualsense/.test(lower)) {
68
+ return { brand: "sony", model: "dualsense", displayName: "PlayStation DualSense", rawId, vendorId: 1356, productId: 3302 };
69
+ }
70
+ if (/05c4|09cc|dualshock/.test(lower)) {
71
+ return { brand: "sony", model: "dualshock4", displayName: "DualShock 4", rawId, vendorId: 1356 };
72
+ }
73
+ return { brand: "sony", model: "dualsense", displayName: "PlayStation Controller", rawId, vendorId: 1356 };
74
+ }
75
+ if (brand === "xbox") {
76
+ if (/0b12|0b13|0b20|0b21|0b22|series/.test(lower)) {
77
+ return { brand: "xbox", model: "xbox_series", displayName: "Xbox Wireless Controller", rawId, vendorId: 1118 };
78
+ }
79
+ if (/028e|360/.test(lower)) {
80
+ return { brand: "xbox", model: "xbox_360", displayName: "Xbox 360 Controller", rawId, vendorId: 1118 };
81
+ }
82
+ return { brand: "xbox", model: "xbox_series", displayName: "Xbox Controller", rawId, vendorId: 1118 };
83
+ }
84
+ if (brand === "nintendo") {
85
+ if (/2069|pro 2|switch 2/.test(lower)) {
86
+ return { brand: "nintendo", model: "switch2_pro", displayName: "Nintendo Switch 2 Pro Controller", rawId, vendorId: 1406, productId: 8297 };
87
+ }
88
+ if (/joy-con|2006|2007/.test(lower)) {
89
+ return { brand: "nintendo", model: "joycon", displayName: "Nintendo Joy-Con", rawId, vendorId: 1406 };
90
+ }
91
+ return { brand: "nintendo", model: "switch_pro", displayName: "Nintendo Switch Pro Controller", rawId, vendorId: 1406, productId: 8201 };
92
+ }
93
+ if (rawId) {
94
+ return { brand: "generic", model: "generic", displayName: rawId.split("(")[0].trim() || rawId, rawId };
95
+ }
96
+ return { brand: "none", model: "none", displayName: "No Controller Detected", rawId: "" };
97
+ }
98
+ var CRC32_TABLE = (() => {
99
+ const table = new Uint32Array(256);
100
+ for (let i = 0; i < 256; i++) {
101
+ let c = i;
102
+ for (let k = 0; k < 8; k++) {
103
+ c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
104
+ }
105
+ table[i] = c >>> 0;
106
+ }
107
+ return table;
108
+ })();
109
+ function crc32WithSeed(seedByte, reportId, bytes) {
110
+ let crc = 4294967295;
111
+ crc = CRC32_TABLE[(crc ^ seedByte) & 255] ^ crc >>> 8;
112
+ crc = CRC32_TABLE[(crc ^ reportId) & 255] ^ crc >>> 8;
113
+ for (let i = 0; i < bytes.length; i++) {
114
+ crc = CRC32_TABLE[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
115
+ }
116
+ return (crc ^ 4294967295) >>> 0;
117
+ }
118
+ function encodeTriggerEffect(spec) {
119
+ const out = new Uint8Array(11);
120
+ if (spec.type === "off") {
121
+ out[0] = 5;
122
+ return out;
123
+ }
124
+ if (spec.type === "feedback" || spec.type === "slope") {
125
+ out[0] = 33;
126
+ const forces = new Array(10).fill(0);
127
+ if (spec.type === "feedback") {
128
+ const s2 = Math.max(0, Math.min(9, Math.round(spec.startZone)));
129
+ const f = Math.max(1, Math.min(8, Math.round(spec.strength)));
130
+ for (let i = s2; i < 10; i++) forces[i] = f;
131
+ } else {
132
+ const s2 = Math.max(0, Math.min(8, Math.round(spec.startZone)));
133
+ const e = Math.max(s2 + 1, Math.min(9, Math.round(spec.endZone)));
134
+ for (let i = s2; i <= e; i++) {
135
+ const t = (i - s2) / (e - s2);
136
+ forces[i] = Math.max(
137
+ 1,
138
+ Math.min(8, Math.round(spec.startStrength + t * (spec.endStrength - spec.startStrength)))
139
+ );
140
+ }
141
+ }
142
+ let activeZones2 = 0;
143
+ let forceZones = 0;
144
+ for (let i = 0; i < 10; i++) {
145
+ const f = forces[i];
146
+ if (f > 0) {
147
+ activeZones2 |= 1 << i;
148
+ forceZones |= (f - 1 & 7) << 3 * i;
149
+ }
150
+ }
151
+ out[1] = activeZones2 & 255;
152
+ out[2] = activeZones2 >> 8 & 255;
153
+ out[3] = forceZones & 255;
154
+ out[4] = forceZones >> 8 & 255;
155
+ out[5] = forceZones >> 16 & 255;
156
+ out[6] = forceZones >> 24 & 255;
157
+ return out;
158
+ }
159
+ if (spec.type === "weapon") {
160
+ const s2 = Math.max(2, Math.min(7, Math.round(spec.startZone)));
161
+ const e = Math.max(s2 + 1, Math.min(8, Math.round(spec.endZone)));
162
+ const f = Math.max(1, Math.min(8, Math.round(spec.strength)));
163
+ const startEnd = 1 << s2 | 1 << e;
164
+ out[0] = 37;
165
+ out[1] = startEnd & 255;
166
+ out[2] = startEnd >> 8 & 255;
167
+ out[3] = f - 1 & 7;
168
+ return out;
169
+ }
170
+ const s = Math.max(0, Math.min(9, Math.round(spec.startZone)));
171
+ const a = Math.max(1, Math.min(8, Math.round(spec.amplitude)));
172
+ const freq = Math.max(1, Math.min(255, Math.round(spec.frequencyHz)));
173
+ let activeZones = 0;
174
+ let ampZones = 0;
175
+ for (let i = s; i < 10; i++) {
176
+ activeZones |= 1 << i;
177
+ ampZones |= (a - 1 & 7) << 3 * i;
178
+ }
179
+ out[0] = 38;
180
+ out[1] = activeZones & 255;
181
+ out[2] = activeZones >> 8 & 255;
182
+ out[3] = ampZones & 255;
183
+ out[4] = ampZones >> 8 & 255;
184
+ out[5] = ampZones >> 16 & 255;
185
+ out[6] = ampZones >> 24 & 255;
186
+ out[9] = freq;
187
+ return out;
188
+ }
189
+ function createEmptyInput() {
190
+ return {
191
+ connected: false,
192
+ source: "none",
193
+ deviceName: "",
194
+ isDualSense: false,
195
+ identity: {
196
+ brand: "none",
197
+ model: "none",
198
+ displayName: "No Controller Detected",
199
+ rawId: "",
200
+ transport: "disconnected",
201
+ source: "none"
202
+ },
203
+ lx: 0,
204
+ ly: 0,
205
+ rx: 0,
206
+ ry: 0,
207
+ l2: 0,
208
+ r2: 0,
209
+ buttons: {
210
+ cross: false,
211
+ circle: false,
212
+ square: false,
213
+ triangle: false,
214
+ l1: false,
215
+ r1: false,
216
+ l2Btn: false,
217
+ r2Btn: false,
218
+ l3: false,
219
+ r3: false,
220
+ up: false,
221
+ down: false,
222
+ left: false,
223
+ right: false,
224
+ create: false,
225
+ options: false,
226
+ ps: false,
227
+ touchpadClick: false
228
+ },
229
+ touch: { active: false, x: 0.5, y: 0.5 },
230
+ touch2: { active: false, x: 0.5, y: 0.5 },
231
+ gyro: { x: 0, y: 0, z: 0 },
232
+ accel: { x: 0, y: 0, z: 0 },
233
+ battery: { percent: 0, charging: false, full: false, known: false },
234
+ observedReportHz: null
235
+ };
236
+ }
237
+ function createDefaultSwitchCal() {
238
+ const def = () => ({ center: 2048, minDelta: 1500, maxDelta: 1500 });
239
+ return { lx: def(), ly: def(), rx: def(), ry: def() };
240
+ }
241
+ var PS5_PLAYER_LED_PATTERNS = [4, 10, 21, 27];
242
+ var SWITCH_PLAYER_LED_PATTERNS = [1, 3, 7, 15];
243
+ function sleepMs(ms) {
244
+ return new Promise((resolve) => setTimeout(resolve, ms));
245
+ }
246
+ function createDefaultOutState(playerIndex = 0) {
247
+ return {
248
+ speakerVolume: 100,
249
+ headphoneVolume: 100,
250
+ audioRoute: "speaker",
251
+ speakerPreamp: 7,
252
+ lightbar: [23, 23, 23],
253
+ playerLeds: PS5_PLAYER_LED_PATTERNS[playerIndex % PS5_PLAYER_LED_PATTERNS.length],
254
+ leftTrigger: encodeTriggerEffect({ type: "off" }),
255
+ rightTrigger: encodeTriggerEffect({ type: "off" }),
256
+ legacyRumbleActive: false,
257
+ legacyLeft: 0,
258
+ legacyRight: 0
259
+ };
260
+ }
261
+ var DualSenseControllerManager = class _DualSenseControllerManager {
262
+ hidSessions = /* @__PURE__ */ new Map();
263
+ nextHidSeq = 1;
264
+ activeSlotId = null;
265
+ hidDisconnectAttached = false;
266
+ hidConnectAttached = false;
267
+ listeners = /* @__PURE__ */ new Set();
268
+ // Per-gamepad input snapshots & activity tracking (supports P1-P4 simultaneous polling)
269
+ gamepadInputs = /* @__PURE__ */ new Map();
270
+ gamepadLastActivity = /* @__PURE__ */ new Map();
271
+ gamepadPrevBtnMask = /* @__PURE__ */ new Map();
272
+ // Fallback buffer for single-slot Gamepad API & Keyboard/Mouse snapshots
273
+ fallbackInput = createEmptyInput();
274
+ keysDown = /* @__PURE__ */ new Set();
275
+ kbmAttached = false;
276
+ boundConnect = (e) => {
277
+ void this.handleConnect(e);
278
+ };
279
+ boundDisconnect = (e) => this.handleDisconnect(e);
280
+ boundKeyDown = (e) => {
281
+ this.keysDown.add(e.code);
282
+ };
283
+ boundKeyUp = (e) => {
284
+ this.keysDown.delete(e.code);
285
+ };
286
+ boundWindowBlur = () => {
287
+ this.keysDown.clear();
288
+ };
289
+ /** Active slot's WebHID device (null if active slot is a Gamepad API controller or disconnected). */
290
+ get device() {
291
+ return this.getActiveHidSession()?.device ?? null;
292
+ }
293
+ /** Active slot's WebHID transport (or 'disconnected' when active slot is not WebHID). */
294
+ get transport() {
295
+ return this.getActiveHidSession()?.transport ?? "disconnected";
296
+ }
297
+ /** Active slot's read-only DualSense firmware metadata, if available. */
298
+ get firmwareInfo() {
299
+ return this.getActiveHidSession()?.firmwareInfo;
300
+ }
301
+ /** Count of currently open WebHID sessions (multi-DualSense support). */
302
+ get hidDeviceCount() {
303
+ return this.hidSessions.size;
304
+ }
305
+ static isWebHIDSupported() {
306
+ return typeof navigator !== "undefined" && "hid" in navigator;
307
+ }
308
+ static isGamepadSupported() {
309
+ return typeof navigator !== "undefined" && typeof navigator.getGamepads === "function";
310
+ }
311
+ isSupportedHidDevice(device) {
312
+ return device.vendorId === SONY_VENDOR_ID && DUALSENSE_PIDS.includes(device.productId) || device.vendorId === NINTENDO_VENDOR_ID && SWITCH_PRO_PIDS.includes(device.productId);
313
+ }
314
+ /**
315
+ * Listens for previously authorized DualSense / Switch Pro devices re-connecting over USB or Bluetooth
316
+ * while the page is open, automatically re-attaching WebHID with zero browser prompts.
317
+ */
318
+ attachHidHotplug() {
319
+ if (this.hidConnectAttached || !_DualSenseControllerManager.isWebHIDSupported()) return;
320
+ navigator.hid.addEventListener("connect", this.boundConnect);
321
+ this.hidConnectAttached = true;
322
+ }
323
+ detachHidHotplug() {
324
+ if (!this.hidConnectAttached || !_DualSenseControllerManager.isWebHIDSupported()) return;
325
+ navigator.hid.removeEventListener("connect", this.boundConnect);
326
+ this.hidConnectAttached = false;
327
+ }
328
+ async handleConnect(e) {
329
+ if (!this.isSupportedHidDevice(e.device)) return;
330
+ try {
331
+ await this.attachDevice(e.device);
332
+ } catch {
333
+ }
334
+ }
335
+ attachKeyboardFallback() {
336
+ if (this.kbmAttached || typeof window === "undefined") return;
337
+ window.addEventListener("keydown", this.boundKeyDown);
338
+ window.addEventListener("keyup", this.boundKeyUp);
339
+ window.addEventListener("blur", this.boundWindowBlur);
340
+ this.kbmAttached = true;
341
+ }
342
+ detachKeyboardFallback() {
343
+ if (!this.kbmAttached || typeof window === "undefined") return;
344
+ window.removeEventListener("keydown", this.boundKeyDown);
345
+ window.removeEventListener("keyup", this.boundKeyUp);
346
+ window.removeEventListener("blur", this.boundWindowBlur);
347
+ this.keysDown.clear();
348
+ this.kbmAttached = false;
349
+ }
350
+ onStatusChange(fn) {
351
+ this.listeners.add(fn);
352
+ return () => this.listeners.delete(fn);
353
+ }
354
+ emit(evt) {
355
+ for (const fn of this.listeners) {
356
+ try {
357
+ fn(evt);
358
+ } catch (err) {
359
+ console.error("[core-hid] listener error:", err);
360
+ }
361
+ }
362
+ }
363
+ getAllRawGamepads() {
364
+ if (!_DualSenseControllerManager.isGamepadSupported()) return [];
365
+ const pads = navigator.getGamepads();
366
+ const out = [];
367
+ for (const p of pads) {
368
+ if (p && p.connected) out.push(p);
369
+ }
370
+ return out;
371
+ }
372
+ pollGamepadActivity(pad) {
373
+ let mask = 0;
374
+ const len = Math.min(20, pad.buttons.length);
375
+ for (let i = 0; i < len; i++) {
376
+ if (pad.buttons[i]?.pressed) mask |= 1 << i;
377
+ }
378
+ const prev = this.gamepadPrevBtnMask.get(pad.index) ?? 0;
379
+ this.gamepadPrevBtnMask.set(pad.index, mask);
380
+ if ((mask & ~prev) !== 0) {
381
+ const now = performance.now();
382
+ this.gamepadLastActivity.set(pad.index, now);
383
+ return now;
384
+ }
385
+ return this.gamepadLastActivity.get(pad.index) ?? 0;
386
+ }
387
+ /**
388
+ * Returns all connected controllers across WebHID and Gamepad API, automatically
389
+ * deduplicating DualSense and Switch Pro controllers that appear in both APIs simultaneously.
390
+ */
391
+ getConnectedControllers() {
392
+ const slots = [];
393
+ let edgeHidCount = 0;
394
+ let stdHidCount = 0;
395
+ let switchProHidCount = 0;
396
+ for (const session of this.hidSessions.values()) {
397
+ if (!session.device.opened) continue;
398
+ if (session.input.identity.model === "dualsense_edge") edgeHidCount++;
399
+ else if (session.input.identity.model === "switch_pro") switchProHidCount++;
400
+ else stdHidCount++;
401
+ slots.push({
402
+ id: session.id,
403
+ playerNumber: slots.length + 1,
404
+ source: "webhid",
405
+ identity: { ...session.input.identity },
406
+ battery: { ...session.input.battery },
407
+ observedReportHz: session.input.observedReportHz,
408
+ lastActivityAt: session.lastActivityAt
409
+ });
410
+ }
411
+ const rawPads = this.getAllRawGamepads();
412
+ const activePadIndices = /* @__PURE__ */ new Set();
413
+ for (const pad of rawPads) {
414
+ activePadIndices.add(pad.index);
415
+ const baseId = identifyGamepadFromId(pad.id || "");
416
+ if (baseId.model === "dualsense_edge" && edgeHidCount > 0) {
417
+ edgeHidCount--;
418
+ continue;
419
+ }
420
+ if (baseId.model === "dualsense" && stdHidCount > 0) {
421
+ stdHidCount--;
422
+ continue;
423
+ }
424
+ if (baseId.model === "switch_pro" && switchProHidCount > 0) {
425
+ switchProHidCount--;
426
+ continue;
427
+ }
428
+ const lastActivityAt = this.pollGamepadActivity(pad);
429
+ slots.push({
430
+ id: `gp-${pad.index}`,
431
+ playerNumber: slots.length + 1,
432
+ source: "gamepad",
433
+ identity: {
434
+ ...baseId,
435
+ transport: "unknown",
436
+ source: "gamepad"
437
+ },
438
+ battery: { percent: 0, charging: false, full: false, known: false },
439
+ observedReportHz: null,
440
+ lastActivityAt
441
+ });
442
+ }
443
+ for (const idx of this.gamepadPrevBtnMask.keys()) {
444
+ if (!activePadIndices.has(idx)) {
445
+ this.gamepadPrevBtnMask.delete(idx);
446
+ this.gamepadLastActivity.delete(idx);
447
+ }
448
+ }
449
+ if (slots.length === 0) {
450
+ this.activeSlotId = null;
451
+ } else if (!this.activeSlotId || !slots.some((s) => s.id === this.activeSlotId)) {
452
+ this.activeSlotId = slots[0].id;
453
+ }
454
+ return slots;
455
+ }
456
+ getActiveSlotId() {
457
+ this.getConnectedControllers();
458
+ return this.activeSlotId;
459
+ }
460
+ setActiveSlot(slotId) {
461
+ const slots = this.getConnectedControllers();
462
+ if (!slots.some((s) => s.id === slotId)) return false;
463
+ if (this.activeSlotId !== slotId) {
464
+ this.activeSlotId = slotId;
465
+ this.emit({ type: "slots_changed", slotId });
466
+ }
467
+ return true;
468
+ }
469
+ getHidSessionForSlot(slotId) {
470
+ if (slotId !== void 0) {
471
+ const session2 = this.hidSessions.get(slotId);
472
+ return session2 && session2.device.opened ? session2 : null;
473
+ }
474
+ const slots = this.getConnectedControllers();
475
+ const targetId = this.activeSlotId ?? slots[0]?.id ?? null;
476
+ if (!targetId) return null;
477
+ const session = this.hidSessions.get(targetId);
478
+ return session && session.device.opened ? session : null;
479
+ }
480
+ getActiveHidSession() {
481
+ return this.getHidSessionForSlot();
482
+ }
483
+ getGamepadForSlot(slotId) {
484
+ if (!_DualSenseControllerManager.isGamepadSupported()) return null;
485
+ if (slotId !== void 0) {
486
+ if (!slotId.startsWith("gp-")) return null;
487
+ const idx = Number(slotId.slice(3));
488
+ const pad = navigator.getGamepads()[idx];
489
+ return pad && pad.connected ? pad : null;
490
+ }
491
+ const slots = this.getConnectedControllers();
492
+ const targetId = this.activeSlotId ?? slots[0]?.id ?? null;
493
+ if (targetId && targetId.startsWith("gp-")) {
494
+ const idx = Number(targetId.slice(3));
495
+ const pad = navigator.getGamepads()[idx];
496
+ if (pad && pad.connected) return pad;
497
+ }
498
+ if (targetId && targetId.startsWith("hid-")) {
499
+ return null;
500
+ }
501
+ for (const p of navigator.getGamepads()) {
502
+ if (p && p.connected) return p;
503
+ }
504
+ return null;
505
+ }
506
+ getActiveGamepad() {
507
+ return this.getGamepadForSlot();
508
+ }
509
+ getGamepadActuatorEffects(slotId) {
510
+ const pad = this.getGamepadForSlot(slotId);
511
+ const act = pad?.vibrationActuator;
512
+ if (!act) return [];
513
+ if (Array.isArray(act.effects) && act.effects.length > 0) return act.effects;
514
+ if (typeof act.playEffect === "function") return ["dual-rumble"];
515
+ return [];
516
+ }
517
+ hasTriggerRumbleSupport(slotId) {
518
+ return this.getGamepadActuatorEffects(slotId).includes("trigger-rumble");
519
+ }
520
+ hasDualRumbleSupport(slotId) {
521
+ const effects = this.getGamepadActuatorEffects(slotId);
522
+ return effects.includes("dual-rumble") || Boolean(this.getGamepadForSlot(slotId)?.vibrationActuator?.playEffect);
523
+ }
524
+ /**
525
+ * Opens the browser WebHID device picker to connect (or append) a DualSense / DualSense Edge
526
+ * or Nintendo Switch Pro controller. Existing connected controllers remain active and untouched.
527
+ */
528
+ async connect() {
529
+ if (!_DualSenseControllerManager.isWebHIDSupported()) {
530
+ throw new Error("WebHID requires a Chromium browser (Chrome or Edge on desktop).");
531
+ }
532
+ const devices = await navigator.hid.requestDevice({
533
+ filters: [
534
+ ...DUALSENSE_PIDS.map((productId) => ({ vendorId: SONY_VENDOR_ID, productId })),
535
+ ...SWITCH_PRO_PIDS.map((productId) => ({ vendorId: NINTENDO_VENDOR_ID, productId }))
536
+ ]
537
+ });
538
+ if (!devices.length) return false;
539
+ let attachedId = null;
540
+ for (const dev of devices) {
541
+ attachedId = await this.attachDevice(dev);
542
+ }
543
+ if (attachedId) {
544
+ this.activeSlotId = attachedId;
545
+ this.emit({ type: "slots_changed", slotId: attachedId });
546
+ }
547
+ return Boolean(attachedId);
548
+ }
549
+ /**
550
+ * Silently re-attaches all previously authorized DualSense & Switch Pro WebHID devices (zero browser prompts).
551
+ */
552
+ async reconnectAuthorized() {
553
+ if (!_DualSenseControllerManager.isWebHIDSupported()) return false;
554
+ const devices = await navigator.hid.getDevices();
555
+ const matches = devices.filter((d) => this.isSupportedHidDevice(d));
556
+ if (!matches.length) return false;
557
+ let attachedAny = false;
558
+ for (const dev of matches) {
559
+ try {
560
+ await this.attachDevice(dev);
561
+ attachedAny = true;
562
+ } catch {
563
+ }
564
+ }
565
+ return attachedAny;
566
+ }
567
+ async readFirmwareInfoSafe(device) {
568
+ try {
569
+ const view = await device.receiveFeatureReport(32);
570
+ if (view.byteLength < 44) return void 0;
571
+ const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
572
+ const offset = bytes[0] === 32 ? 1 : 0;
573
+ const decodeAscii = (start, len) => {
574
+ let s = "";
575
+ for (let i = start; i < start + len && i < bytes.length; i++) {
576
+ const ch = bytes[i];
577
+ if (ch >= 32 && ch <= 126) s += String.fromCharCode(ch);
578
+ }
579
+ return s.trim();
580
+ };
581
+ const buildDate = decodeAscii(offset + 0, 11);
582
+ const buildTime = decodeAscii(offset + 11, 8);
583
+ const dv = new DataView(view.buffer, view.byteOffset + offset);
584
+ const hwInfo = dv.byteLength >= 28 ? dv.getUint32(24, true) : 0;
585
+ const fwVersion = dv.byteLength >= 32 ? dv.getUint32(28, true) : 0;
586
+ if (!buildDate && !hwInfo) return void 0;
587
+ return {
588
+ buildDate: buildDate || "Unknown",
589
+ buildTime: buildTime || "",
590
+ hwInfoHex: `0x${hwInfo.toString(16).padStart(8, "0")}`,
591
+ fwVersionHex: `0x${fwVersion.toString(16).padStart(8, "0")}`
592
+ };
593
+ } catch {
594
+ return void 0;
595
+ }
596
+ }
597
+ async attachDevice(device) {
598
+ for (const existing of this.hidSessions.values()) {
599
+ if (existing.device === device && existing.device.opened) {
600
+ return existing.id;
601
+ }
602
+ }
603
+ if (!device.opened) await device.open();
604
+ const isSwitchPro = device.vendorId === NINTENDO_VENDOR_ID && SWITCH_PRO_PIDS.includes(device.productId);
605
+ if (isSwitchPro) {
606
+ return this.attachSwitchProDevice(device);
607
+ }
608
+ let hasUsb02 = false;
609
+ let hasBt31 = false;
610
+ let usbPayloadLength = 47;
611
+ let btPayloadLength = 77;
612
+ for (const col of device.collections || []) {
613
+ for (const rep of col.outputReports || []) {
614
+ const byteLen = Math.ceil(
615
+ (rep.items || []).reduce((acc, it) => acc + (it.reportSize || 0) * (it.reportCount || 0), 0) / 8
616
+ );
617
+ if (rep.reportId === 2) {
618
+ hasUsb02 = true;
619
+ if (byteLen >= 47) usbPayloadLength = byteLen;
620
+ }
621
+ if (rep.reportId === 49) {
622
+ hasBt31 = true;
623
+ if (byteLen >= 77) btPayloadLength = byteLen;
624
+ }
625
+ }
626
+ }
627
+ const transport = hasUsb02 ? "usb" : hasBt31 ? "bluetooth" : "usb";
628
+ const isEdge = device.productId === 3570;
629
+ const firmwareInfo = await this.readFirmwareInfoSafe(device);
630
+ const slotId = `hid-${this.nextHidSeq++}`;
631
+ const displayName = isEdge ? "DualSense Edge" : "PlayStation DualSense";
632
+ const input = createEmptyInput();
633
+ input.connected = true;
634
+ input.source = "webhid";
635
+ input.isDualSense = true;
636
+ input.deviceName = device.productName || displayName;
637
+ input.identity = {
638
+ brand: "sony",
639
+ model: isEdge ? "dualsense_edge" : "dualsense",
640
+ displayName,
641
+ rawId: device.productName || displayName,
642
+ vendorId: device.vendorId,
643
+ productId: device.productId,
644
+ transport,
645
+ source: "webhid",
646
+ firmwareInfo
647
+ };
648
+ const session = {
649
+ id: slotId,
650
+ kind: "dualsense",
651
+ device,
652
+ transport,
653
+ firmwareInfo,
654
+ usbPayloadLength,
655
+ btPayloadLength,
656
+ btSeq: 0,
657
+ switchSubcmdLength: 48,
658
+ switchRumbleLength: 9,
659
+ switchUsb80Length: 1,
660
+ switchPacketNum: 0,
661
+ switchCal: createDefaultSwitchCal(),
662
+ switchRumbleTimer: null,
663
+ switchSeqTimers: [],
664
+ reportTimes: [],
665
+ input,
666
+ outState: createDefaultOutState(this.hidSessions.size),
667
+ legacyTimer: null,
668
+ lastActivityAt: performance.now(),
669
+ prevBtnMask: 0,
670
+ boundInputReport: (e) => this.handleInputReport(session, e)
671
+ };
672
+ this.hidSessions.set(slotId, session);
673
+ if (!this.activeSlotId) {
674
+ this.activeSlotId = slotId;
675
+ }
676
+ this.getConnectedControllers();
677
+ device.addEventListener("inputreport", session.boundInputReport);
678
+ if (!this.hidDisconnectAttached && typeof navigator !== "undefined" && navigator.hid) {
679
+ navigator.hid.addEventListener("disconnect", this.boundDisconnect);
680
+ this.hidDisconnectAttached = true;
681
+ }
682
+ await this.flushSessionOutput(session, { includeAudioConfig: true, includeTriggers: true, includeLeds: true });
683
+ this.emit({
684
+ type: "connected",
685
+ slotId,
686
+ deviceName: input.deviceName,
687
+ productId: device.productId,
688
+ transport,
689
+ firmwareInfo
690
+ });
691
+ return slotId;
692
+ }
693
+ async attachSwitchProDevice(device) {
694
+ let hasUsb80 = false;
695
+ let switchSubcmdLength = 48;
696
+ let switchRumbleLength = 9;
697
+ let switchUsb80Length = 1;
698
+ for (const col of device.collections || []) {
699
+ for (const rep of col.outputReports || []) {
700
+ const byteLen = Math.ceil(
701
+ (rep.items || []).reduce((acc, it) => acc + (it.reportSize || 0) * (it.reportCount || 0), 0) / 8
702
+ );
703
+ if (rep.reportId === 128) {
704
+ hasUsb80 = true;
705
+ if (byteLen >= 1) switchUsb80Length = byteLen;
706
+ }
707
+ if (rep.reportId === 1 && byteLen >= 10) {
708
+ switchSubcmdLength = byteLen;
709
+ }
710
+ if (rep.reportId === 16 && byteLen >= 9) {
711
+ switchRumbleLength = byteLen;
712
+ }
713
+ }
714
+ }
715
+ const transport = hasUsb80 ? "usb" : "bluetooth";
716
+ const slotId = `hid-${this.nextHidSeq++}`;
717
+ const displayName = "Nintendo Switch Pro Controller";
718
+ const input = createEmptyInput();
719
+ input.connected = true;
720
+ input.source = "webhid";
721
+ input.isDualSense = false;
722
+ input.deviceName = device.productName || displayName;
723
+ input.identity = {
724
+ brand: "nintendo",
725
+ model: "switch_pro",
726
+ displayName,
727
+ rawId: device.productName || displayName,
728
+ vendorId: device.vendorId,
729
+ productId: device.productId,
730
+ transport,
731
+ source: "webhid"
732
+ };
733
+ const playerIndex = this.hidSessions.size;
734
+ const session = {
735
+ id: slotId,
736
+ kind: "switch_pro",
737
+ device,
738
+ transport,
739
+ firmwareInfo: void 0,
740
+ usbPayloadLength: 47,
741
+ btPayloadLength: 77,
742
+ btSeq: 0,
743
+ switchSubcmdLength,
744
+ switchRumbleLength,
745
+ switchUsb80Length,
746
+ switchPacketNum: 0,
747
+ switchCal: createDefaultSwitchCal(),
748
+ switchRumbleTimer: null,
749
+ switchSeqTimers: [],
750
+ reportTimes: [],
751
+ input,
752
+ outState: createDefaultOutState(playerIndex),
753
+ legacyTimer: null,
754
+ lastActivityAt: performance.now(),
755
+ prevBtnMask: 0,
756
+ boundInputReport: (e) => this.handleSwitchProInputReport(session, e)
757
+ };
758
+ this.hidSessions.set(slotId, session);
759
+ if (!this.activeSlotId) {
760
+ this.activeSlotId = slotId;
761
+ }
762
+ this.getConnectedControllers();
763
+ device.addEventListener("inputreport", session.boundInputReport);
764
+ if (!this.hidDisconnectAttached && typeof navigator !== "undefined" && navigator.hid) {
765
+ navigator.hid.addEventListener("disconnect", this.boundDisconnect);
766
+ this.hidDisconnectAttached = true;
767
+ }
768
+ await this.initSwitchProSession(session, playerIndex);
769
+ this.emit({
770
+ type: "connected",
771
+ slotId,
772
+ deviceName: input.deviceName,
773
+ productId: device.productId,
774
+ transport
775
+ });
776
+ return slotId;
777
+ }
778
+ async sendSwitchUsbCmd(session, cmd) {
779
+ if (!session.device.opened) return;
780
+ const payload = new Uint8Array(Math.max(1, session.switchUsb80Length));
781
+ payload[0] = cmd & 255;
782
+ await session.device.sendReport(128, payload);
783
+ }
784
+ async sendSwitchSubcommand(session, subcmd, args = []) {
785
+ if (!session.device.opened) return;
786
+ const len = Math.max(10 + args.length, session.switchSubcmdLength);
787
+ const payload = new Uint8Array(len);
788
+ payload[0] = session.switchPacketNum & 15;
789
+ session.switchPacketNum = session.switchPacketNum + 1 & 15;
790
+ payload.set(SWITCH_NEUTRAL_RUMBLE, 1);
791
+ payload.set(SWITCH_NEUTRAL_RUMBLE, 5);
792
+ payload[9] = subcmd & 255;
793
+ for (let i = 0; i < args.length; i++) {
794
+ payload[10 + i] = args[i] & 255;
795
+ }
796
+ await session.device.sendReport(1, payload);
797
+ }
798
+ async sendSwitchRumbleBytes(session, left4, right4) {
799
+ if (!session.device.opened) return false;
800
+ const len = Math.max(9, session.switchRumbleLength);
801
+ const payload = new Uint8Array(len);
802
+ payload[0] = session.switchPacketNum & 15;
803
+ session.switchPacketNum = session.switchPacketNum + 1 & 15;
804
+ payload.set(left4.subarray(0, 4), 1);
805
+ payload.set(right4.subarray(0, 4), 5);
806
+ await session.device.sendReport(16, payload);
807
+ return true;
808
+ }
809
+ clearSwitchRumbleTimers(session) {
810
+ if (session.switchRumbleTimer) {
811
+ clearTimeout(session.switchRumbleTimer);
812
+ session.switchRumbleTimer = null;
813
+ }
814
+ for (const t of session.switchSeqTimers) {
815
+ clearTimeout(t);
816
+ }
817
+ session.switchSeqTimers = [];
818
+ }
819
+ async initSwitchProSession(session, playerIndex) {
820
+ try {
821
+ if (session.transport === "usb") {
822
+ await this.sendSwitchUsbCmd(session, 2).catch(() => {
823
+ });
824
+ await sleepMs(25);
825
+ await this.sendSwitchUsbCmd(session, 4).catch(() => {
826
+ });
827
+ await sleepMs(25);
828
+ }
829
+ await this.sendSwitchSubcommand(session, 3, [48]);
830
+ await sleepMs(20);
831
+ await this.sendSwitchSubcommand(session, 64, [1]);
832
+ await sleepMs(20);
833
+ await this.sendSwitchSubcommand(session, 72, [1]);
834
+ await sleepMs(20);
835
+ await this.sendSwitchSubcommand(session, 48, [
836
+ SWITCH_PLAYER_LED_PATTERNS[playerIndex % SWITCH_PLAYER_LED_PATTERNS.length]
837
+ ]);
838
+ await sleepMs(20);
839
+ await this.sendSwitchSubcommand(session, 16, [61, 96, 0, 0, 18]).catch(() => {
840
+ });
841
+ } catch {
842
+ }
843
+ }
844
+ parseSwitchStickCalibration(session, data) {
845
+ if (data.byteLength < 37) return;
846
+ if (data.getUint8(13) !== 16) return;
847
+ const addr = data.getUint32(14, true);
848
+ if (addr !== 24637) return;
849
+ const u12Pair = (o) => {
850
+ const b0 = data.getUint8(o);
851
+ const b1 = data.getUint8(o + 1);
852
+ const b2 = data.getUint8(o + 2);
853
+ return [b0 | (b1 & 15) << 8, b1 >> 4 & 15 | b2 << 4];
854
+ };
855
+ const [lxMax, lyMax] = u12Pair(19);
856
+ const [lxCtr, lyCtr] = u12Pair(22);
857
+ const [lxMin, lyMin] = u12Pair(25);
858
+ const [rxCtr, ryCtr] = u12Pair(28);
859
+ const [rxMin, ryMin] = u12Pair(31);
860
+ const [rxMax, ryMax] = u12Pair(34);
861
+ const validAxis = (center, minD, maxD) => center >= 900 && center <= 3200 && minD >= 400 && minD <= 2400 && maxD >= 400 && maxD <= 2400;
862
+ if (validAxis(lxCtr, lxMin, lxMax) && validAxis(lyCtr, lyMin, lyMax)) {
863
+ session.switchCal.lx = { center: lxCtr, minDelta: lxMin, maxDelta: lxMax };
864
+ session.switchCal.ly = { center: lyCtr, minDelta: lyMin, maxDelta: lyMax };
865
+ }
866
+ if (validAxis(rxCtr, rxMin, rxMax) && validAxis(ryCtr, ryMin, ryMax)) {
867
+ session.switchCal.rx = { center: rxCtr, minDelta: rxMin, maxDelta: rxMax };
868
+ session.switchCal.ry = { center: ryCtr, minDelta: ryMin, maxDelta: ryMax };
869
+ }
870
+ }
871
+ handleSwitchProInputReport(session, event) {
872
+ const { reportId, data } = event;
873
+ if (reportId === 33) {
874
+ this.parseSwitchStickCalibration(session, data);
875
+ }
876
+ if (reportId !== 48 && reportId !== 33 || data.byteLength < 11) {
877
+ return;
878
+ }
879
+ const input = session.input;
880
+ const now = performance.now();
881
+ if (reportId === 48) {
882
+ session.reportTimes.push(now);
883
+ if (session.reportTimes.length > 33) session.reportTimes.shift();
884
+ if (session.reportTimes.length >= 6) {
885
+ const spanMs = session.reportTimes[session.reportTimes.length - 1] - session.reportTimes[0];
886
+ if (spanMs > 10) {
887
+ input.observedReportHz = Math.round((session.reportTimes.length - 1) * 1e3 / spanMs);
888
+ }
889
+ }
890
+ }
891
+ const battByte = data.getUint8(1);
892
+ const bars = Math.min(4, battByte >> 5 & 7);
893
+ input.battery.percent = bars * 25;
894
+ input.battery.charging = Boolean(battByte & 16);
895
+ input.battery.full = bars >= 4;
896
+ input.battery.known = true;
897
+ const bRight = data.getUint8(2);
898
+ const bShared = data.getUint8(3);
899
+ const bLeft = data.getUint8(4);
900
+ input.buttons.square = Boolean(bRight & 1);
901
+ input.buttons.triangle = Boolean(bRight & 2);
902
+ input.buttons.cross = Boolean(bRight & 4);
903
+ input.buttons.circle = Boolean(bRight & 8);
904
+ input.buttons.r1 = Boolean(bRight & 64);
905
+ input.buttons.r2Btn = Boolean(bRight & 128);
906
+ input.buttons.create = Boolean(bShared & 1);
907
+ input.buttons.options = Boolean(bShared & 2);
908
+ input.buttons.r3 = Boolean(bShared & 4);
909
+ input.buttons.l3 = Boolean(bShared & 8);
910
+ input.buttons.ps = Boolean(bShared & 16);
911
+ input.buttons.touchpadClick = Boolean(bShared & 32);
912
+ input.buttons.down = Boolean(bLeft & 1);
913
+ input.buttons.up = Boolean(bLeft & 2);
914
+ input.buttons.right = Boolean(bLeft & 4);
915
+ input.buttons.left = Boolean(bLeft & 8);
916
+ input.buttons.l1 = Boolean(bLeft & 64);
917
+ input.buttons.l2Btn = Boolean(bLeft & 128);
918
+ input.l2 = input.buttons.l2Btn ? 1 : 0;
919
+ input.r2 = input.buttons.r2Btn ? 1 : 0;
920
+ const btnMask = bRight & 207 | (bShared & 63) << 8 | (bLeft & 207) << 16;
921
+ if ((btnMask & ~session.prevBtnMask) !== 0) {
922
+ session.lastActivityAt = now;
923
+ }
924
+ session.prevBtnMask = btnMask;
925
+ const normAxis = (raw, cal) => {
926
+ const diff = raw - cal.center;
927
+ const denom = diff >= 0 ? cal.maxDelta : cal.minDelta;
928
+ const v = denom > 0 ? diff / denom : 0;
929
+ return Math.max(-1, Math.min(1, v));
930
+ };
931
+ const lxRaw = data.getUint8(5) | (data.getUint8(6) & 15) << 8;
932
+ const lyRaw = data.getUint8(6) >> 4 & 15 | data.getUint8(7) << 4;
933
+ const rxRaw = data.getUint8(8) | (data.getUint8(9) & 15) << 8;
934
+ const ryRaw = data.getUint8(9) >> 4 & 15 | data.getUint8(10) << 4;
935
+ input.lx = normAxis(lxRaw, session.switchCal.lx);
936
+ input.ly = -normAxis(lyRaw, session.switchCal.ly);
937
+ input.rx = normAxis(rxRaw, session.switchCal.rx);
938
+ input.ry = -normAxis(ryRaw, session.switchCal.ry);
939
+ if (reportId === 48 && data.byteLength >= 48) {
940
+ let sumAx = 0;
941
+ let sumAy = 0;
942
+ let sumAz = 0;
943
+ let sumGx = 0;
944
+ let sumGy = 0;
945
+ let sumGz = 0;
946
+ for (let s = 0; s < 3; s++) {
947
+ const base = 12 + s * 12;
948
+ sumAx += data.getInt16(base + 0, true);
949
+ sumAy += data.getInt16(base + 2, true);
950
+ sumAz += data.getInt16(base + 4, true);
951
+ sumGx += data.getInt16(base + 6, true);
952
+ sumGy += data.getInt16(base + 8, true);
953
+ sumGz += data.getInt16(base + 10, true);
954
+ }
955
+ const avgAx = sumAx / 3;
956
+ const avgAy = sumAy / 3;
957
+ const avgAz = sumAz / 3;
958
+ const avgGx = sumGx / 3;
959
+ const avgGy = sumGy / 3;
960
+ const avgGz = sumGz / 3;
961
+ const clamp1 = (v) => Math.max(-1, Math.min(1, v));
962
+ input.accel.x = clamp1(avgAy / 4096);
963
+ input.accel.y = clamp1(avgAz / 4096);
964
+ input.accel.z = clamp1(-avgAx / 4096);
965
+ input.gyro.x = clamp1(avgGy / 8192);
966
+ input.gyro.y = clamp1(avgGz / 8192);
967
+ input.gyro.z = clamp1(avgGx / 8192);
968
+ }
969
+ }
970
+ /**
971
+ * Disconnects a specific WebHID controller slot, or the active WebHID slot when `slotId` is omitted.
972
+ */
973
+ async disconnect(slotId) {
974
+ const targetId = slotId ?? this.activeSlotId ?? Array.from(this.hidSessions.keys())[0];
975
+ if (!targetId) return;
976
+ const session = this.hidSessions.get(targetId);
977
+ if (!session) return;
978
+ if (session.legacyTimer) {
979
+ clearTimeout(session.legacyTimer);
980
+ session.legacyTimer = null;
981
+ }
982
+ this.clearSwitchRumbleTimers(session);
983
+ try {
984
+ if (session.kind === "switch_pro") {
985
+ await this.sendSwitchRumbleBytes(session, SWITCH_NEUTRAL_RUMBLE, SWITCH_NEUTRAL_RUMBLE);
986
+ } else {
987
+ session.outState.leftTrigger = encodeTriggerEffect({ type: "off" });
988
+ session.outState.rightTrigger = encodeTriggerEffect({ type: "off" });
989
+ session.outState.legacyRumbleActive = false;
990
+ session.outState.legacyLeft = 0;
991
+ session.outState.legacyRight = 0;
992
+ await this.flushSessionOutput(session, { includeTriggers: true });
993
+ }
994
+ } catch {
995
+ }
996
+ session.device.removeEventListener("inputreport", session.boundInputReport);
997
+ try {
998
+ if (session.device.opened) await session.device.close();
999
+ } catch {
1000
+ }
1001
+ this.hidSessions.delete(targetId);
1002
+ if (this.hidSessions.size === 0 && this.hidDisconnectAttached && typeof navigator !== "undefined" && navigator.hid) {
1003
+ navigator.hid.removeEventListener("disconnect", this.boundDisconnect);
1004
+ this.hidDisconnectAttached = false;
1005
+ }
1006
+ if (this.activeSlotId === targetId) {
1007
+ const remaining = this.getConnectedControllers();
1008
+ this.activeSlotId = remaining[0]?.id ?? null;
1009
+ }
1010
+ this.emit({ type: "disconnected", slotId: targetId });
1011
+ }
1012
+ async disconnectAll() {
1013
+ const ids = Array.from(this.hidSessions.keys());
1014
+ for (const id of ids) {
1015
+ await this.disconnect(id);
1016
+ }
1017
+ }
1018
+ handleDisconnect(e) {
1019
+ for (const [slotId, session] of this.hidSessions.entries()) {
1020
+ if (session.device === e.device) {
1021
+ if (session.legacyTimer) {
1022
+ clearTimeout(session.legacyTimer);
1023
+ session.legacyTimer = null;
1024
+ }
1025
+ this.clearSwitchRumbleTimers(session);
1026
+ session.device.removeEventListener("inputreport", session.boundInputReport);
1027
+ this.hidSessions.delete(slotId);
1028
+ if (this.activeSlotId === slotId) {
1029
+ const remaining = this.getConnectedControllers();
1030
+ this.activeSlotId = remaining[0]?.id ?? null;
1031
+ }
1032
+ this.emit({ type: "disconnected", slotId });
1033
+ }
1034
+ }
1035
+ if (this.hidSessions.size === 0 && this.hidDisconnectAttached && typeof navigator !== "undefined" && navigator.hid) {
1036
+ navigator.hid.removeEventListener("disconnect", this.boundDisconnect);
1037
+ this.hidDisconnectAttached = false;
1038
+ }
1039
+ }
1040
+ handleInputReport(session, event) {
1041
+ const { reportId, data } = event;
1042
+ let offset = 0;
1043
+ if (reportId === 49 && data.byteLength >= 40) {
1044
+ offset = 1;
1045
+ } else if (reportId !== 1 || data.byteLength < 10) {
1046
+ return;
1047
+ }
1048
+ const input = session.input;
1049
+ const now = performance.now();
1050
+ session.reportTimes.push(now);
1051
+ if (session.reportTimes.length > 33) session.reportTimes.shift();
1052
+ if (session.reportTimes.length >= 6) {
1053
+ const spanMs = session.reportTimes[session.reportTimes.length - 1] - session.reportTimes[0];
1054
+ if (spanMs > 10) {
1055
+ input.observedReportHz = Math.round((session.reportTimes.length - 1) * 1e3 / spanMs);
1056
+ }
1057
+ }
1058
+ const normRaw = (v) => {
1059
+ const n = v >= 128 ? (v - 128) / 127 : (v - 128) / 128;
1060
+ return Math.max(-1, Math.min(1, n));
1061
+ };
1062
+ input.lx = normRaw(data.getUint8(offset + 0));
1063
+ input.ly = normRaw(data.getUint8(offset + 1));
1064
+ input.rx = normRaw(data.getUint8(offset + 2));
1065
+ input.ry = normRaw(data.getUint8(offset + 3));
1066
+ input.l2 = data.getUint8(offset + 4) / 255;
1067
+ input.r2 = data.getUint8(offset + 5) / 255;
1068
+ const btn0 = data.getUint8(offset + 7);
1069
+ const btn1 = data.getUint8(offset + 8);
1070
+ const btn2 = data.getUint8(offset + 9);
1071
+ const dpad = btn0 & 15;
1072
+ input.buttons.up = dpad === 0 || dpad === 1 || dpad === 7;
1073
+ input.buttons.right = dpad === 1 || dpad === 2 || dpad === 3;
1074
+ input.buttons.down = dpad === 3 || dpad === 4 || dpad === 5;
1075
+ input.buttons.left = dpad === 5 || dpad === 6 || dpad === 7;
1076
+ input.buttons.square = Boolean(btn0 & 16);
1077
+ input.buttons.cross = Boolean(btn0 & 32);
1078
+ input.buttons.circle = Boolean(btn0 & 64);
1079
+ input.buttons.triangle = Boolean(btn0 & 128);
1080
+ input.buttons.l1 = Boolean(btn1 & 1);
1081
+ input.buttons.r1 = Boolean(btn1 & 2);
1082
+ input.buttons.l2Btn = Boolean(btn1 & 4);
1083
+ input.buttons.r2Btn = Boolean(btn1 & 8);
1084
+ input.buttons.create = Boolean(btn1 & 16);
1085
+ input.buttons.options = Boolean(btn1 & 32);
1086
+ input.buttons.l3 = Boolean(btn1 & 64);
1087
+ input.buttons.r3 = Boolean(btn1 & 128);
1088
+ input.buttons.ps = Boolean(btn2 & 1);
1089
+ input.buttons.touchpadClick = Boolean(btn2 & 2);
1090
+ const btnMask = btn0 & 240 | (dpad < 8 ? 1 : 0) | btn1 << 8 | (btn2 & 3) << 16;
1091
+ if ((btnMask & ~session.prevBtnMask) !== 0) {
1092
+ session.lastActivityAt = now;
1093
+ }
1094
+ session.prevBtnMask = btnMask;
1095
+ if (data.byteLength > offset + 26) {
1096
+ input.gyro.x = Math.max(-1, Math.min(1, data.getInt16(offset + 15, true) / 16384));
1097
+ input.gyro.y = Math.max(-1, Math.min(1, data.getInt16(offset + 17, true) / 16384));
1098
+ input.gyro.z = Math.max(-1, Math.min(1, data.getInt16(offset + 19, true) / 16384));
1099
+ input.accel.x = Math.max(-1, Math.min(1, data.getInt16(offset + 21, true) / 8192));
1100
+ input.accel.y = Math.max(-1, Math.min(1, data.getInt16(offset + 23, true) / 8192));
1101
+ input.accel.z = Math.max(-1, Math.min(1, data.getInt16(offset + 25, true) / 8192));
1102
+ }
1103
+ const parseFinger = (base, target) => {
1104
+ if (data.byteLength <= base + 3) return;
1105
+ const contact = data.getUint8(base);
1106
+ const touching = (contact & 128) === 0;
1107
+ target.active = touching;
1108
+ if (touching) {
1109
+ const b0 = data.getUint8(base + 1);
1110
+ const b1 = data.getUint8(base + 2);
1111
+ const b2 = data.getUint8(base + 3);
1112
+ const tx = b0 | (b1 & 15) << 8;
1113
+ const ty = (b1 & 240) >> 4 | b2 << 4;
1114
+ target.x = Math.max(0, Math.min(1, tx / 1919));
1115
+ target.y = Math.max(0, Math.min(1, ty / 1079));
1116
+ }
1117
+ };
1118
+ parseFinger(offset + 32, input.touch);
1119
+ parseFinger(offset + 36, input.touch2);
1120
+ if (data.byteLength > offset + 52) {
1121
+ const battByte = data.getUint8(offset + 52);
1122
+ const level = battByte & 15;
1123
+ const state = battByte >> 4 & 15;
1124
+ input.battery.percent = Math.min(100, Math.round((level + 0.5) / 10 * 100));
1125
+ input.battery.charging = state === 1;
1126
+ input.battery.full = state === 2;
1127
+ input.battery.known = true;
1128
+ }
1129
+ }
1130
+ populateGamepadInput(pad, out) {
1131
+ const clamp = (v) => Math.max(-1, Math.min(1, Number.isFinite(v) ? v : 0));
1132
+ const baseId = identifyGamepadFromId(pad.id || "");
1133
+ out.connected = true;
1134
+ out.source = "gamepad";
1135
+ out.deviceName = baseId.displayName;
1136
+ out.isDualSense = baseId.model === "dualsense" || baseId.model === "dualsense_edge";
1137
+ out.identity = {
1138
+ ...baseId,
1139
+ transport: "unknown",
1140
+ source: "gamepad"
1141
+ };
1142
+ out.lx = clamp(pad.axes[0] ?? 0);
1143
+ out.ly = clamp(pad.axes[1] ?? 0);
1144
+ out.rx = clamp(pad.axes[2] ?? 0);
1145
+ out.ry = clamp(pad.axes[3] ?? 0);
1146
+ out.l2 = Math.max(0, Math.min(1, pad.buttons[6]?.value ?? 0));
1147
+ out.r2 = Math.max(0, Math.min(1, pad.buttons[7]?.value ?? 0));
1148
+ out.buttons.cross = Boolean(pad.buttons[0]?.pressed);
1149
+ out.buttons.circle = Boolean(pad.buttons[1]?.pressed);
1150
+ out.buttons.square = Boolean(pad.buttons[2]?.pressed);
1151
+ out.buttons.triangle = Boolean(pad.buttons[3]?.pressed);
1152
+ out.buttons.l1 = Boolean(pad.buttons[4]?.pressed);
1153
+ out.buttons.r1 = Boolean(pad.buttons[5]?.pressed);
1154
+ out.buttons.l2Btn = Boolean(pad.buttons[6]?.pressed);
1155
+ out.buttons.r2Btn = Boolean(pad.buttons[7]?.pressed);
1156
+ out.buttons.create = Boolean(pad.buttons[8]?.pressed);
1157
+ out.buttons.options = Boolean(pad.buttons[9]?.pressed);
1158
+ out.buttons.l3 = Boolean(pad.buttons[10]?.pressed);
1159
+ out.buttons.r3 = Boolean(pad.buttons[11]?.pressed);
1160
+ out.buttons.up = Boolean(pad.buttons[12]?.pressed);
1161
+ out.buttons.down = Boolean(pad.buttons[13]?.pressed);
1162
+ out.buttons.left = Boolean(pad.buttons[14]?.pressed);
1163
+ out.buttons.right = Boolean(pad.buttons[15]?.pressed);
1164
+ out.buttons.ps = Boolean(pad.buttons[16]?.pressed);
1165
+ out.buttons.touchpadClick = Boolean(pad.buttons[17]?.pressed);
1166
+ out.touch.active = false;
1167
+ out.touch2.active = false;
1168
+ out.battery.known = false;
1169
+ out.observedReportHz = null;
1170
+ return out;
1171
+ }
1172
+ /**
1173
+ * Returns a live input snapshot for a specific controller slot (e.g. `hid-1` or `gp-0`).
1174
+ * Returns a disconnected empty snapshot when that slot is not currently connected.
1175
+ */
1176
+ getInputStateForSlot(slotId) {
1177
+ const hidSession = this.getHidSessionForSlot(slotId);
1178
+ if (hidSession) return hidSession.input;
1179
+ const pad = this.getGamepadForSlot(slotId);
1180
+ if (pad) {
1181
+ let buf = this.gamepadInputs.get(pad.index);
1182
+ if (!buf) {
1183
+ buf = createEmptyInput();
1184
+ this.gamepadInputs.set(pad.index, buf);
1185
+ }
1186
+ return this.populateGamepadInput(pad, buf);
1187
+ }
1188
+ return createEmptyInput();
1189
+ }
1190
+ getInputState(slotId) {
1191
+ if (slotId !== void 0) {
1192
+ return this.getInputStateForSlot(slotId);
1193
+ }
1194
+ const activeHid = this.getActiveHidSession();
1195
+ if (activeHid) {
1196
+ return activeHid.input;
1197
+ }
1198
+ const pad = this.getActiveGamepad();
1199
+ if (pad) {
1200
+ return this.populateGamepadInput(pad, this.fallbackInput);
1201
+ }
1202
+ const k = this.keysDown;
1203
+ const lx = (k.has("KeyD") || k.has("ArrowRight") ? 1 : 0) - (k.has("KeyA") || k.has("ArrowLeft") ? 1 : 0);
1204
+ const ly = (k.has("KeyS") || k.has("ArrowDown") ? 1 : 0) - (k.has("KeyW") || k.has("ArrowUp") ? 1 : 0);
1205
+ const out = this.fallbackInput;
1206
+ out.connected = false;
1207
+ out.source = "keyboard_mouse";
1208
+ out.deviceName = "Keyboard & Mouse";
1209
+ out.isDualSense = false;
1210
+ out.identity = {
1211
+ brand: "none",
1212
+ model: "none",
1213
+ displayName: "Keyboard & Mouse",
1214
+ rawId: "",
1215
+ transport: "disconnected",
1216
+ source: "keyboard_mouse"
1217
+ };
1218
+ out.lx = lx;
1219
+ out.ly = ly;
1220
+ out.rx = 0;
1221
+ out.ry = 0;
1222
+ out.l2 = k.has("ShiftLeft") || k.has("KeyQ") ? 1 : 0;
1223
+ out.r2 = k.has("Space") || k.has("KeyE") ? 1 : 0;
1224
+ out.buttons.cross = k.has("Space") || k.has("Enter");
1225
+ out.buttons.circle = k.has("KeyC") || k.has("Escape");
1226
+ out.buttons.square = k.has("KeyR");
1227
+ out.buttons.triangle = k.has("KeyF");
1228
+ out.buttons.l1 = k.has("KeyQ");
1229
+ out.buttons.r1 = k.has("KeyE");
1230
+ out.buttons.l2Btn = out.l2 > 0.5;
1231
+ out.buttons.r2Btn = out.r2 > 0.5;
1232
+ out.buttons.l3 = false;
1233
+ out.buttons.r3 = false;
1234
+ out.buttons.up = k.has("ArrowUp") || k.has("KeyW");
1235
+ out.buttons.down = k.has("ArrowDown") || k.has("KeyS");
1236
+ out.buttons.left = k.has("ArrowLeft") || k.has("KeyA");
1237
+ out.buttons.right = k.has("ArrowRight") || k.has("KeyD");
1238
+ out.buttons.create = false;
1239
+ out.buttons.options = false;
1240
+ out.buttons.ps = false;
1241
+ out.buttons.touchpadClick = false;
1242
+ out.touch.active = false;
1243
+ out.touch2.active = false;
1244
+ out.battery.known = false;
1245
+ out.observedReportHz = null;
1246
+ return out;
1247
+ }
1248
+ /**
1249
+ * Computes a real-time capability matrix for the active controller slot (or a specific `slotId`).
1250
+ */
1251
+ getCapabilityMatrixForSlot(slotId, opts = {}) {
1252
+ const state = this.getInputState(slotId);
1253
+ const id = state.identity;
1254
+ const activeHid = this.getHidSessionForSlot(slotId);
1255
+ const isDsHid = activeHid?.kind === "dualsense";
1256
+ const isSwitchProHid = activeHid?.kind === "switch_pro";
1257
+ const isHid = Boolean(activeHid);
1258
+ const activeTransport = activeHid?.transport ?? "unknown";
1259
+ const hasWebHid = _DualSenseControllerManager.isWebHIDSupported();
1260
+ const isDS = id.model === "dualsense" || id.model === "dualsense_edge";
1261
+ const isXbox = id.brand === "xbox";
1262
+ const isSwitchPro = id.model === "switch_pro";
1263
+ const isNintendo = id.brand === "nintendo";
1264
+ const connected = state.connected;
1265
+ const hasTrigRumble = this.hasTriggerRumbleSupport(slotId);
1266
+ const hasDualRumble = this.hasDualRumbleSupport(slotId);
1267
+ if (!connected) {
1268
+ const disc = { inherent: false, availability: "disconnected" };
1269
+ return {
1270
+ standard_input: disc,
1271
+ analog_triggers: disc,
1272
+ dual_motor_rumble: disc,
1273
+ impulse_triggers: disc,
1274
+ hd_rumble: disc,
1275
+ adaptive_triggers: disc,
1276
+ audio_haptics: disc,
1277
+ controller_speaker: disc,
1278
+ gyro: disc,
1279
+ accelerometer: disc,
1280
+ touchpad: disc,
1281
+ lightbar: disc,
1282
+ battery: disc
1283
+ };
1284
+ }
1285
+ return {
1286
+ standard_input: { inherent: true, availability: "ready" },
1287
+ analog_triggers: {
1288
+ inherent: !isNintendo,
1289
+ availability: isNintendo ? "unsupported" : "ready",
1290
+ reason: isNintendo ? "Nintendo Pro/Joy-Con triggers are digital buttons" : void 0
1291
+ },
1292
+ dual_motor_rumble: {
1293
+ inherent: true,
1294
+ availability: isHid ? "ready" : hasDualRumble ? "ready" : "unsupported",
1295
+ reason: !isHid && !hasDualRumble ? "Browser Gamepad rumble actuator not exposed" : void 0
1296
+ },
1297
+ impulse_triggers: {
1298
+ inherent: isXbox,
1299
+ availability: isXbox ? hasTrigRumble ? "ready" : "unsupported" : "unsupported",
1300
+ reason: isXbox && !hasTrigRumble ? "Requires Chrome/Edge 126+ with USB or Xbox Wireless Adapter (Windows Bluetooth often blocks trigger motors)" : void 0
1301
+ },
1302
+ hd_rumble: {
1303
+ inherent: isNintendo,
1304
+ availability: !isNintendo ? "unsupported" : isSwitchProHid ? "ready" : isSwitchPro ? hasWebHid ? "permission_required" : "unsupported" : "bridge_required",
1305
+ reason: isSwitchPro && !isSwitchProHid ? hasWebHid ? "Connect Switch Pro via WebHID to unlock dual-band HD Rumble and 6-axis gyro" : "WebHID requires desktop Chrome or Edge" : void 0
1306
+ },
1307
+ adaptive_triggers: {
1308
+ inherent: isDS,
1309
+ availability: !isDS ? "unsupported" : isDsHid ? "ready" : hasWebHid ? "permission_required" : "unsupported",
1310
+ reason: isDS && !isDsHid ? hasWebHid ? "Click Unlock DualSense WebHID (works over USB & Bluetooth)" : "WebHID requires desktop Chrome or Edge" : void 0
1311
+ },
1312
+ audio_haptics: {
1313
+ inherent: isDS,
1314
+ availability: !isDS ? "unsupported" : opts.has4ChAudio ? "ready" : activeTransport === "bluetooth" ? "configuration_required" : "bridge_required",
1315
+ reason: isDS && !opts.has4ChAudio ? activeTransport === "bluetooth" ? "4-channel audio haptics require a wired USB-C connection on Windows" : "Optional Gamepadly Link or USB 4ch audio routing required" : void 0
1316
+ },
1317
+ controller_speaker: {
1318
+ inherent: isDS,
1319
+ availability: !isDS ? "unsupported" : opts.hasControllerSpeaker ? "ready" : activeTransport === "bluetooth" ? "configuration_required" : "bridge_required",
1320
+ reason: isDS && !opts.hasControllerSpeaker ? "Requires wired USB-C DualSense audio output" : void 0
1321
+ },
1322
+ gyro: {
1323
+ inherent: isDS || isNintendo,
1324
+ availability: isDS ? isDsHid ? "ready" : hasWebHid ? "permission_required" : "unsupported" : isSwitchPro ? isSwitchProHid ? "ready" : hasWebHid ? "permission_required" : "unsupported" : isNintendo ? "bridge_required" : "unsupported"
1325
+ },
1326
+ accelerometer: {
1327
+ inherent: isDS || isNintendo,
1328
+ availability: isDS ? isDsHid ? "ready" : hasWebHid ? "permission_required" : "unsupported" : isSwitchPro ? isSwitchProHid ? "ready" : hasWebHid ? "permission_required" : "unsupported" : isNintendo ? "bridge_required" : "unsupported"
1329
+ },
1330
+ touchpad: {
1331
+ inherent: isDS || id.model === "dualshock4",
1332
+ availability: isDS ? isDsHid ? "ready" : hasWebHid ? "permission_required" : "unsupported" : "unsupported"
1333
+ },
1334
+ lightbar: {
1335
+ inherent: isDS || id.model === "dualshock4",
1336
+ availability: isDS ? isDsHid ? "ready" : hasWebHid ? "permission_required" : "unsupported" : "unsupported"
1337
+ },
1338
+ battery: {
1339
+ inherent: true,
1340
+ availability: isDS && isDsHid || isSwitchPro && isSwitchProHid ? "ready" : "unknown"
1341
+ }
1342
+ };
1343
+ }
1344
+ getCapabilityMatrix(opts = {}) {
1345
+ return this.getCapabilityMatrixForSlot(void 0, opts);
1346
+ }
1347
+ /**
1348
+ * Drives Nintendo Switch Pro dual-band HD Rumble (LRA) over WebHID Report 0x10.
1349
+ * Automatically returns both motors to neutral off after `durationMs`.
1350
+ */
1351
+ async playSwitchHdRumble(spec, slotId) {
1352
+ const session = this.getHidSessionForSlot(slotId);
1353
+ if (!session || session.kind !== "switch_pro" || !session.device.opened) return false;
1354
+ this.clearSwitchRumbleTimers(session);
1355
+ const left4 = encodeSwitchHdRumbleSide(spec.left);
1356
+ const right4 = encodeSwitchHdRumbleSide(spec.right);
1357
+ const dur = Math.max(30, Math.min(2500, Math.round(spec.durationMs ?? 220)));
1358
+ try {
1359
+ await this.sendSwitchRumbleBytes(session, left4, right4);
1360
+ } catch {
1361
+ return false;
1362
+ }
1363
+ session.switchRumbleTimer = setTimeout(() => {
1364
+ session.switchRumbleTimer = null;
1365
+ void this.sendSwitchRumbleBytes(session, SWITCH_NEUTRAL_RUMBLE, SWITCH_NEUTRAL_RUMBLE).catch(() => {
1366
+ });
1367
+ }, dur);
1368
+ return true;
1369
+ }
1370
+ /**
1371
+ * Plays a timed sequence of Switch Pro HD Rumble steps (e.g., ice-cube sweep or L/R stereo pulse).
1372
+ */
1373
+ async playSwitchHdRumbleSequence(steps, slotId) {
1374
+ const session = this.getHidSessionForSlot(slotId);
1375
+ if (!session || session.kind !== "switch_pro" || !session.device.opened || steps.length === 0) {
1376
+ return false;
1377
+ }
1378
+ this.clearSwitchRumbleTimers(session);
1379
+ let maxEndMs = 0;
1380
+ for (const step of steps) {
1381
+ const startAt = Math.max(0, Math.round(step.delayMs));
1382
+ const dur = Math.max(30, Math.min(1200, Math.round(step.durationMs ?? 80)));
1383
+ if (startAt + dur > maxEndMs) maxEndMs = startAt + dur;
1384
+ const left4 = encodeSwitchHdRumbleSide(step.left);
1385
+ const right4 = encodeSwitchHdRumbleSide(step.right);
1386
+ if (startAt === 0) {
1387
+ await this.sendSwitchRumbleBytes(session, left4, right4).catch(() => {
1388
+ });
1389
+ } else {
1390
+ const t = setTimeout(() => {
1391
+ void this.sendSwitchRumbleBytes(session, left4, right4).catch(() => {
1392
+ });
1393
+ }, startAt);
1394
+ session.switchSeqTimers.push(t);
1395
+ }
1396
+ }
1397
+ session.switchRumbleTimer = setTimeout(() => {
1398
+ session.switchRumbleTimer = null;
1399
+ session.switchSeqTimers = [];
1400
+ void this.sendSwitchRumbleBytes(session, SWITCH_NEUTRAL_RUMBLE, SWITCH_NEUTRAL_RUMBLE).catch(() => {
1401
+ });
1402
+ }, maxEndMs + 15);
1403
+ return true;
1404
+ }
1405
+ stopSwitchHdRumble(slotId) {
1406
+ if (slotId !== void 0) {
1407
+ const session = this.getHidSessionForSlot(slotId);
1408
+ if (session && session.kind === "switch_pro" && session.device.opened) {
1409
+ this.clearSwitchRumbleTimers(session);
1410
+ void this.sendSwitchRumbleBytes(session, SWITCH_NEUTRAL_RUMBLE, SWITCH_NEUTRAL_RUMBLE).catch(() => {
1411
+ });
1412
+ }
1413
+ return;
1414
+ }
1415
+ for (const session of this.hidSessions.values()) {
1416
+ if (session.kind !== "switch_pro" || !session.device.opened) continue;
1417
+ this.clearSwitchRumbleTimers(session);
1418
+ void this.sendSwitchRumbleBytes(session, SWITCH_NEUTRAL_RUMBLE, SWITCH_NEUTRAL_RUMBLE).catch(() => {
1419
+ });
1420
+ }
1421
+ }
1422
+ /**
1423
+ * Native Xbox Series Impulse Triggers (Chrome/Edge 126+, zero WebHID / zero install).
1424
+ * Automatically maps to HD Rumble when the targeted slot is a WebHID Switch Pro.
1425
+ */
1426
+ async playTriggerRumble(leftTrigger, rightTrigger, durationMs, weakMagnitude = 0, strongMagnitude = 0, slotId) {
1427
+ const activeHid = this.getHidSessionForSlot(slotId);
1428
+ if (activeHid?.kind === "switch_pro") {
1429
+ const lAmp = Math.max(leftTrigger, strongMagnitude);
1430
+ const rAmp = Math.max(rightTrigger, weakMagnitude);
1431
+ return this.playSwitchHdRumble(
1432
+ {
1433
+ left: lAmp > 0.02 ? { highFreqHz: 260, highAmp: lAmp * 0.65, lowFreqHz: 145, lowAmp: lAmp * 0.7 } : void 0,
1434
+ right: rAmp > 0.02 ? { highFreqHz: 340, highAmp: rAmp * 0.7, lowFreqHz: 170, lowAmp: rAmp * 0.55 } : void 0,
1435
+ durationMs
1436
+ },
1437
+ slotId
1438
+ );
1439
+ }
1440
+ const pad = this.getGamepadForSlot(slotId);
1441
+ const act = pad?.vibrationActuator;
1442
+ if (!act?.playEffect) return false;
1443
+ const dur = Math.max(20, Math.min(2500, Math.round(durationMs)));
1444
+ const lt = Math.max(0, Math.min(1, leftTrigger));
1445
+ const rt = Math.max(0, Math.min(1, rightTrigger));
1446
+ const weak = Math.max(0, Math.min(1, weakMagnitude));
1447
+ const strong = Math.max(0, Math.min(1, strongMagnitude));
1448
+ if (this.hasTriggerRumbleSupport(slotId)) {
1449
+ try {
1450
+ await act.playEffect("trigger-rumble", {
1451
+ startDelay: 0,
1452
+ duration: dur,
1453
+ leftTrigger: lt,
1454
+ rightTrigger: rt,
1455
+ weakMagnitude: weak,
1456
+ strongMagnitude: strong
1457
+ });
1458
+ return true;
1459
+ } catch {
1460
+ }
1461
+ }
1462
+ const fallbackWeak = Math.max(weak, rt * 0.65);
1463
+ const fallbackStrong = Math.max(strong, lt * 0.65);
1464
+ if (fallbackWeak > 0 || fallbackStrong > 0) {
1465
+ return this.playDualRumble(fallbackWeak, fallbackStrong, dur, slotId);
1466
+ }
1467
+ return false;
1468
+ }
1469
+ /**
1470
+ * Standard Gamepad API dual-rumble for Xbox / Switch / Generic controllers.
1471
+ * Automatically uses true HD Rumble when the targeted slot is a WebHID Switch Pro.
1472
+ */
1473
+ async playDualRumble(weakMagnitude, strongMagnitude, durationMs, slotId) {
1474
+ const activeHid = this.getHidSessionForSlot(slotId);
1475
+ if (activeHid?.kind === "switch_pro") {
1476
+ const side = {
1477
+ highFreqHz: 320,
1478
+ highAmp: Math.max(0, Math.min(0.85, weakMagnitude * 0.8)),
1479
+ lowFreqHz: 150,
1480
+ lowAmp: Math.max(0, Math.min(0.85, strongMagnitude * 0.8))
1481
+ };
1482
+ return this.playSwitchHdRumble({ left: side, right: side, durationMs }, slotId);
1483
+ }
1484
+ const pad = this.getGamepadForSlot(slotId);
1485
+ const act = pad?.vibrationActuator;
1486
+ if (!act?.playEffect) return false;
1487
+ try {
1488
+ await act.playEffect("dual-rumble", {
1489
+ startDelay: 0,
1490
+ duration: Math.max(20, Math.min(2500, Math.round(durationMs))),
1491
+ strongMagnitude: Math.max(0, Math.min(1, strongMagnitude)),
1492
+ weakMagnitude: Math.max(0, Math.min(1, weakMagnitude))
1493
+ });
1494
+ return true;
1495
+ } catch {
1496
+ return false;
1497
+ }
1498
+ }
1499
+ stopGamepadRumble(slotId) {
1500
+ this.stopSwitchHdRumble(slotId);
1501
+ if (!_DualSenseControllerManager.isGamepadSupported()) return;
1502
+ if (slotId !== void 0) {
1503
+ const pad = this.getGamepadForSlot(slotId);
1504
+ if (pad?.vibrationActuator?.reset) {
1505
+ void pad.vibrationActuator.reset().catch(() => {
1506
+ });
1507
+ }
1508
+ return;
1509
+ }
1510
+ for (const pad of this.getAllRawGamepads()) {
1511
+ const act = pad.vibrationActuator;
1512
+ if (act?.reset) {
1513
+ void act.reset().catch(() => {
1514
+ });
1515
+ }
1516
+ }
1517
+ }
1518
+ /**
1519
+ * Backwards-compatible helper used when 4ch VCM audio is not active.
1520
+ */
1521
+ triggerGamepadRumbleFallback(weakMagnitude, strongMagnitude, durationMs, slotId) {
1522
+ const activeHid = this.getHidSessionForSlot(slotId);
1523
+ if (activeHid?.kind === "switch_pro") {
1524
+ void this.playDualRumble(weakMagnitude, strongMagnitude, durationMs, slotId);
1525
+ return;
1526
+ }
1527
+ if (activeHid?.kind === "dualsense") {
1528
+ void this.pulseLegacyRumble(
1529
+ Math.round(Math.max(0, Math.min(1, strongMagnitude)) * 220),
1530
+ Math.round(Math.max(0, Math.min(1, weakMagnitude)) * 220),
1531
+ Math.max(25, Math.min(350, durationMs)),
1532
+ slotId
1533
+ );
1534
+ return;
1535
+ }
1536
+ void this.playDualRumble(weakMagnitude, strongMagnitude, durationMs, slotId);
1537
+ }
1538
+ buildCommonPayload(outState, { includeAudioConfig = false, includeTriggers = false, includeLeds = false } = {}) {
1539
+ const common = new Uint8Array(47);
1540
+ let flag0 = 0;
1541
+ let flag1 = 0;
1542
+ if (outState.legacyRumbleActive) {
1543
+ flag0 |= 1 | 2;
1544
+ common[2] = Math.max(0, Math.min(255, Math.round(outState.legacyRight)));
1545
+ common[3] = Math.max(0, Math.min(255, Math.round(outState.legacyLeft)));
1546
+ }
1547
+ if (includeTriggers) {
1548
+ flag0 |= 4 | 8;
1549
+ common.set(outState.rightTrigger.subarray(0, 11), 10);
1550
+ common.set(outState.leftTrigger.subarray(0, 11), 21);
1551
+ }
1552
+ if (includeAudioConfig) {
1553
+ flag0 |= 16 | 32 | 128;
1554
+ flag1 |= 2 | 128;
1555
+ common[4] = Math.max(0, Math.min(127, outState.headphoneVolume));
1556
+ common[5] = Math.max(0, Math.min(255, outState.speakerVolume));
1557
+ common[6] = 0;
1558
+ common[7] = outState.audioRoute === "speaker" ? 48 : outState.audioRoute === "both" ? 32 : 0;
1559
+ common[9] = 0;
1560
+ common[37] = outState.speakerPreamp & 7;
1561
+ }
1562
+ if (includeLeds) {
1563
+ flag1 |= 4 | 16;
1564
+ common[38] = 2;
1565
+ common[41] = 2;
1566
+ common[42] = 0;
1567
+ common[43] = outState.playerLeds & 31;
1568
+ common[44] = outState.lightbar[0] & 255;
1569
+ common[45] = outState.lightbar[1] & 255;
1570
+ common[46] = outState.lightbar[2] & 255;
1571
+ }
1572
+ common[0] = flag0;
1573
+ common[1] = flag1;
1574
+ return common;
1575
+ }
1576
+ async flushSessionOutput(session, opts = {}) {
1577
+ if (session.kind !== "dualsense" || !session.device.opened) return false;
1578
+ const common = this.buildCommonPayload(session.outState, opts);
1579
+ if (session.transport === "bluetooth") {
1580
+ const payload2 = new Uint8Array(session.btPayloadLength);
1581
+ payload2[0] = (session.btSeq & 15) << 4;
1582
+ session.btSeq = session.btSeq + 1 & 15;
1583
+ payload2[1] = 16;
1584
+ payload2.set(common, 2);
1585
+ const crcOffset = payload2.length - 4;
1586
+ const crc = crc32WithSeed(162, 49, payload2.subarray(0, crcOffset));
1587
+ new DataView(payload2.buffer).setUint32(crcOffset, crc, true);
1588
+ await session.device.sendReport(49, payload2);
1589
+ return true;
1590
+ }
1591
+ const payload = new Uint8Array(session.usbPayloadLength);
1592
+ payload.set(common, 0);
1593
+ await session.device.sendReport(2, payload);
1594
+ return true;
1595
+ }
1596
+ async flushOutput(opts = {}) {
1597
+ const session = this.getActiveHidSession();
1598
+ if (!session || session.kind !== "dualsense") return false;
1599
+ return this.flushSessionOutput(session, opts);
1600
+ }
1601
+ async setAudioConfig(cfg) {
1602
+ const session = this.getActiveHidSession();
1603
+ if (!session || session.kind !== "dualsense") return false;
1604
+ if (cfg.speakerVolume !== void 0) session.outState.speakerVolume = cfg.speakerVolume;
1605
+ if (cfg.headphoneVolume !== void 0) session.outState.headphoneVolume = cfg.headphoneVolume;
1606
+ if (cfg.audioRoute !== void 0) session.outState.audioRoute = cfg.audioRoute;
1607
+ if (cfg.speakerPreamp !== void 0) session.outState.speakerPreamp = cfg.speakerPreamp;
1608
+ return this.flushSessionOutput(session, { includeAudioConfig: true });
1609
+ }
1610
+ async setTriggers(left, right, slotId) {
1611
+ const session = this.getHidSessionForSlot(slotId);
1612
+ if (!session || session.kind !== "dualsense") return false;
1613
+ const prevLeft = session.outState.leftTrigger;
1614
+ const prevRight = session.outState.rightTrigger;
1615
+ const nextLeft = left ? encodeTriggerEffect(left) : void 0;
1616
+ const nextRight = right ? encodeTriggerEffect(right) : void 0;
1617
+ if (nextLeft) session.outState.leftTrigger = nextLeft;
1618
+ if (nextRight) session.outState.rightTrigger = nextRight;
1619
+ try {
1620
+ const ok = await this.flushSessionOutput(session, { includeTriggers: true });
1621
+ if (!ok) {
1622
+ if (nextLeft && session.outState.leftTrigger === nextLeft) session.outState.leftTrigger = prevLeft;
1623
+ if (nextRight && session.outState.rightTrigger === nextRight) session.outState.rightTrigger = prevRight;
1624
+ }
1625
+ return ok;
1626
+ } catch (err) {
1627
+ if (nextLeft && session.outState.leftTrigger === nextLeft) session.outState.leftTrigger = prevLeft;
1628
+ if (nextRight && session.outState.rightTrigger === nextRight) session.outState.rightTrigger = prevRight;
1629
+ throw err;
1630
+ }
1631
+ }
1632
+ async resetTriggers(slotId) {
1633
+ this.stopGamepadRumble(slotId);
1634
+ if (slotId !== void 0) {
1635
+ const session = this.getHidSessionForSlot(slotId);
1636
+ if (!session || !session.device.opened || session.kind !== "dualsense") return false;
1637
+ session.outState.leftTrigger = encodeTriggerEffect({ type: "off" });
1638
+ session.outState.rightTrigger = encodeTriggerEffect({ type: "off" });
1639
+ return this.flushSessionOutput(session, { includeTriggers: true }).catch(() => false);
1640
+ }
1641
+ let resetAny = false;
1642
+ for (const session of this.hidSessions.values()) {
1643
+ if (!session.device.opened || session.kind !== "dualsense") continue;
1644
+ session.outState.leftTrigger = encodeTriggerEffect({ type: "off" });
1645
+ session.outState.rightTrigger = encodeTriggerEffect({ type: "off" });
1646
+ const ok = await this.flushSessionOutput(session, { includeTriggers: true }).catch(() => false);
1647
+ if (ok) resetAny = true;
1648
+ }
1649
+ return resetAny;
1650
+ }
1651
+ /**
1652
+ * Fire-and-forget safety reset across ALL connected WebHID and Gamepad controllers
1653
+ * used inside `pagehide` / `beforeunload` so no controller ever stays stuck with stiff triggers or rumble.
1654
+ */
1655
+ emergencyReset() {
1656
+ this.stopGamepadRumble();
1657
+ for (const session of this.hidSessions.values()) {
1658
+ if (!session.device.opened) continue;
1659
+ if (session.kind === "switch_pro") {
1660
+ this.clearSwitchRumbleTimers(session);
1661
+ void this.sendSwitchRumbleBytes(session, SWITCH_NEUTRAL_RUMBLE, SWITCH_NEUTRAL_RUMBLE).catch(() => {
1662
+ });
1663
+ continue;
1664
+ }
1665
+ session.outState.leftTrigger = encodeTriggerEffect({ type: "off" });
1666
+ session.outState.rightTrigger = encodeTriggerEffect({ type: "off" });
1667
+ session.outState.legacyRumbleActive = false;
1668
+ session.outState.legacyLeft = 0;
1669
+ session.outState.legacyRight = 0;
1670
+ session.outState.lightbar = [23, 23, 23];
1671
+ void this.flushSessionOutput(session, { includeTriggers: true, includeLeds: true }).catch(() => {
1672
+ });
1673
+ }
1674
+ }
1675
+ async setLightbar(r, g, b, slotId) {
1676
+ const session = this.getHidSessionForSlot(slotId);
1677
+ if (!session || session.kind !== "dualsense") return false;
1678
+ session.outState.lightbar = [r & 255, g & 255, b & 255];
1679
+ return this.flushSessionOutput(session, { includeLeds: true });
1680
+ }
1681
+ async pulseLegacyRumble(left = 200, right = 200, durationMs = 250, slotId) {
1682
+ const session = this.getHidSessionForSlot(slotId);
1683
+ if (!session || session.kind !== "dualsense" || !session.device.opened) return false;
1684
+ if (session.legacyTimer) {
1685
+ clearTimeout(session.legacyTimer);
1686
+ session.legacyTimer = null;
1687
+ }
1688
+ session.outState.legacyRumbleActive = true;
1689
+ session.outState.legacyLeft = left;
1690
+ session.outState.legacyRight = right;
1691
+ await this.flushSessionOutput(session, {});
1692
+ return new Promise((resolve) => {
1693
+ session.legacyTimer = setTimeout(async () => {
1694
+ session.legacyTimer = null;
1695
+ try {
1696
+ session.outState.legacyLeft = 0;
1697
+ session.outState.legacyRight = 0;
1698
+ await this.flushSessionOutput(session, {});
1699
+ session.outState.legacyRumbleActive = false;
1700
+ await this.flushSessionOutput(session, { includeAudioConfig: true });
1701
+ } catch {
1702
+ }
1703
+ resolve(true);
1704
+ }, durationMs);
1705
+ });
1706
+ }
1707
+ };
1708
+
1709
+ // src/haptics/presets.ts
1710
+ var TRIGGER_PRESETS = {
1711
+ off: { type: "off" },
1712
+ weapon: { type: "weapon", startZone: 2, endZone: 5, strength: 7 },
1713
+ heavy_weapon: { type: "weapon", startZone: 3, endZone: 6, strength: 8 },
1714
+ bow: { type: "slope", startZone: 1, endZone: 8, startStrength: 1, endStrength: 7 },
1715
+ abs: { type: "vibration", startZone: 2, amplitude: 6, frequencyHz: 22 },
1716
+ soft_wall: { type: "feedback", startZone: 4, strength: 4 },
1717
+ rapid_pulse: { type: "vibration", startZone: 1, amplitude: 7, frequencyHz: 14 },
1718
+ precision_damp: { type: "feedback", startZone: 2, strength: 3 }
1719
+ };
1720
+ var TACTILE_PRESETS = {
1721
+ click: {
1722
+ freqHz: 210,
1723
+ endFreqHz: 140,
1724
+ durationMs: 26,
1725
+ intensity: 0.45,
1726
+ wave: "triangle",
1727
+ triggerEmphasis: 0.65,
1728
+ switchHd: { highFreqHz: 340, lowFreqHz: 165, highWeight: 0.75, lowWeight: 0.25 }
1729
+ },
1730
+ ratchet: {
1731
+ freqHz: 180,
1732
+ endFreqHz: 110,
1733
+ durationMs: 22,
1734
+ intensity: 0.5,
1735
+ wave: "triangle",
1736
+ triggerEmphasis: 0.75,
1737
+ switchHd: { highFreqHz: 320, lowFreqHz: 155, highWeight: 0.8, lowWeight: 0.2 }
1738
+ },
1739
+ wall_hit: {
1740
+ freqHz: 135,
1741
+ endFreqHz: 58,
1742
+ durationMs: 65,
1743
+ intensity: 0.78,
1744
+ wave: "triangle",
1745
+ triggerEmphasis: 0.5,
1746
+ switchHd: { highFreqHz: 290, lowFreqHz: 130, highWeight: 0.55, lowWeight: 0.75 }
1747
+ },
1748
+ marble_click: {
1749
+ freqHz: 290,
1750
+ endFreqHz: 210,
1751
+ durationMs: 32,
1752
+ intensity: 0.62,
1753
+ wave: "sine",
1754
+ triggerEmphasis: 0.85,
1755
+ switchHd: { highFreqHz: 380, lowFreqHz: 190, highWeight: 0.85, lowWeight: 0.18 }
1756
+ },
1757
+ recoil: {
1758
+ freqHz: 115,
1759
+ endFreqHz: 46,
1760
+ durationMs: 75,
1761
+ intensity: 0.88,
1762
+ wave: "triangle",
1763
+ triggerEmphasis: 1,
1764
+ switchHd: { highFreqHz: 310, lowFreqHz: 120, highWeight: 0.65, lowWeight: 0.85 }
1765
+ },
1766
+ heavy_impact: {
1767
+ freqHz: 75,
1768
+ endFreqHz: 34,
1769
+ durationMs: 140,
1770
+ intensity: 0.95,
1771
+ wave: "sine",
1772
+ triggerEmphasis: 0.7,
1773
+ switchHd: { highFreqHz: 220, lowFreqHz: 95, highWeight: 0.45, lowWeight: 0.95 }
1774
+ },
1775
+ lock_unlock: {
1776
+ freqHz: 95,
1777
+ endFreqHz: 220,
1778
+ durationMs: 120,
1779
+ intensity: 0.72,
1780
+ wave: "triangle",
1781
+ triggerEmphasis: 0.6,
1782
+ switchHd: { highFreqHz: 350, lowFreqHz: 150, highWeight: 0.7, lowWeight: 0.55 }
1783
+ },
1784
+ splash: {
1785
+ freqHz: 90,
1786
+ endFreqHz: 48,
1787
+ durationMs: 110,
1788
+ intensity: 0.6,
1789
+ wave: "sine",
1790
+ triggerEmphasis: 0.35,
1791
+ switchHd: { highFreqHz: 250, lowFreqHz: 120, highWeight: 0.5, lowWeight: 0.6 }
1792
+ },
1793
+ boost: {
1794
+ freqHz: 65,
1795
+ endFreqHz: 165,
1796
+ durationMs: 160,
1797
+ intensity: 0.75,
1798
+ wave: "sawtooth",
1799
+ triggerEmphasis: 0.85,
1800
+ switchHd: { highFreqHz: 300, lowFreqHz: 135, highWeight: 0.6, lowWeight: 0.75 }
1801
+ },
1802
+ error_buzz: {
1803
+ freqHz: 145,
1804
+ endFreqHz: 115,
1805
+ durationMs: 95,
1806
+ intensity: 0.65,
1807
+ wave: "square",
1808
+ triggerEmphasis: 0.45,
1809
+ switchHd: { highFreqHz: 260, lowFreqHz: 125, highWeight: 0.55, lowWeight: 0.65 }
1810
+ }
1811
+ };
1812
+ function buildSwitchHdFromPulse(opts) {
1813
+ const pan = Math.max(-1, Math.min(1, opts.pan ?? 0));
1814
+ const intensity = Math.max(0, Math.min(1, opts.intensity));
1815
+ const leftGain = Math.min(1, 1 - Math.max(0, pan));
1816
+ const rightGain = Math.min(1, 1 + Math.min(0, pan));
1817
+ const highFreqHz = opts.highFreqHz ?? Math.max(160, Math.min(620, opts.freqHz * 1.9));
1818
+ const lowFreqHz = opts.lowFreqHz ?? Math.max(60, Math.min(240, opts.freqHz));
1819
+ const highBias = opts.highWeight ?? (opts.freqHz >= 140 ? 0.78 : 0.42);
1820
+ const lowBias = opts.lowWeight ?? (opts.freqHz < 140 ? 0.82 : 0.38);
1821
+ const mkSide = (gain) => {
1822
+ const scaled = intensity * gain;
1823
+ if (scaled < 0.02) return void 0;
1824
+ return {
1825
+ highFreqHz,
1826
+ highAmp: Math.min(0.85, scaled * highBias * 0.85),
1827
+ lowFreqHz,
1828
+ lowAmp: Math.min(0.85, scaled * lowBias * 0.85)
1829
+ };
1830
+ };
1831
+ return {
1832
+ left: mkSide(leftGain),
1833
+ right: mkSide(rightGain),
1834
+ durationMs: Math.max(30, Math.min(2500, Math.round(opts.durationMs)))
1835
+ };
1836
+ }
1837
+
1838
+ export {
1839
+ encodeSwitchHdRumbleSide,
1840
+ applyDeadzone,
1841
+ identifyGamepadFromId,
1842
+ crc32WithSeed,
1843
+ encodeTriggerEffect,
1844
+ createEmptyInput,
1845
+ DualSenseControllerManager,
1846
+ TRIGGER_PRESETS,
1847
+ TACTILE_PRESETS,
1848
+ buildSwitchHdFromPulse
1849
+ };
1850
+ //# sourceMappingURL=chunk-BEBDNL5B.js.map