@cldmv/node-android-tv-remote 2.2.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,17 +14,17 @@ Every remote is an event source: operations report through structured `log` even
14
14
 
15
15
  ## ✨ What's New
16
16
 
17
- ### Latest: v2.2.1 (November 2026)
17
+ ### Latest: v3.0.0 (November 2026)
18
18
 
19
- - **`engines.node` is now `>=22.12.0` ([#89](https://github.com/CLDMV/node-android-tv-remote/pull/89))** — v2.2.0 declared `>=22.22.0`, the floor of the development toolchain rather than of the package. The runtime floor is now the one `@devicefarmer/adbkit` 4 and `commander` 15 declare; `require()` needs Node.js 22.13.0 or later. The 22.22.0 toolchain floor moves to `devEngines`, so it only applies when working on this repository. The exported API and behavior are unchanged.
20
- - [View full v2.2.1 Changelog](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/changelog/v2/v2.2.1.md)
19
+ - **Generic CommonJS shim ([#121](https://github.com/CLDMV/node-android-tv-remote/pull/121))** — `require("@cldmv/node-android-tv-remote")` now returns the module object, the same exports `import` gives, instead of the `createRemote` function. Use `const { createRemote } = require("@cldmv/node-android-tv-remote")`; `.createRemote`, `.createAndroidTVRemote` and `.default` keep working. ESM `import` is unchanged.
20
+ - [View full v3.0.0 Changelog](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/changelog/v3/v3.0.0.md)
21
21
 
22
22
  ### Recent Releases
23
23
 
24
+ - **v2.3.0** (November 2026) — talks to the device through `@cldmv/droidsock` instead of `@devicefarmer/adbkit`, so the `adb` tool is no longer needed; `engines.node` is `>=22.15.0` ([Changelog](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/changelog/v2/v2.3.0.md))
25
+ - **v2.2.1** (November 2026) — `engines.node` lowered to `>=22.12.0`, the runtime floor; the 22.22.0 toolchain floor moves to `devEngines` ([Changelog](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/changelog/v2/v2.2.1.md))
24
26
  - **v2.2.0** (November 2026) — library layout with a tsup build into `dist/`, `@devicefarmer/adbkit` 4, `waitBootComplete(timeout)` rejects at its timeout, and `screencap()` reports the file saved only once written; declared Node.js `>=22.22.0` ([Changelog](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/changelog/v2/v2.2.0.md))
25
27
  - **v2.1.9** (October 2026) — `brace-expansion` security fix in the dev toolchain and dev-tooling bumps; no runtime change ([Changelog](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/changelog/v2/v2.1.9.md))
26
- - **v2.1.8** (October 2026) — independent event emitters per remote, an unheard `error` no longer crashes the process, `npm run setup-device` works again, relicensed under Apache-2.0 ([Changelog](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/changelog/v2/v2.1.8.md))
27
- - **v2.1.7** (October 2026) — CommonJS entry loads the ESM build directly, fails clearly without `require(esm)`, and exports `createAndroidTVRemote` ([Changelog](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/changelog/v2/v2.1.7.md))
28
28
 
29
29
  > **Note:** v2.1.1 through v2.1.6 were released on GitHub but never published to npm; npm went from v2.1.0 straight to v2.1.7. See the changelogs for what changed in between, including the Node.js 20.9.0 floor from v2.1.1.
30
30
 
@@ -52,9 +52,8 @@ Every remote is an event source: operations report through structured `log` even
52
52
 
53
53
  ### Requirements
54
54
 
55
- - **Node.js >=22.12.0** (the package's `engines` floor; adbkit 4 and its `commander` 15 dependency need it). `require()` loads the ESM build through Node's `require(esm)`, so `require()` needs Node.js >=22.13.0, where `require(esm)` runs without warnings.
55
+ - **Node.js 22.15.0 or higher** (the package's `engines` floor, set by `@cldmv/droidsock`). `require()` loads the ESM build through Node's `require(esm)`, which runs without warnings on that floor.
56
56
  - Developing this package needs Node.js 22.22.0 or later (`devEngines`).
57
- - The **Android Debug Bridge (ADB)** binary installed and available in your system PATH (see below). A `postinstall` check prints install instructions when `adb` is missing.
58
57
  - `sharp` installs a platform-specific prebuilt binary; the install environment must be able to fetch it.
59
58
 
60
59
  ### Install
@@ -63,7 +62,9 @@ Every remote is an event source: operations report through structured `log` even
63
62
  npm install @cldmv/node-android-tv-remote
64
63
  ```
65
64
 
66
- ### Install ADB
65
+ ### Install ADB (optional)
66
+
67
+ The remote talks to the device over its own ADB client (`@cldmv/droidsock`), so the `adb` command-line tool and its server are **not** required. Install them only if you want `adb` for your own use, such as the `setup-device` steps below.
67
68
 
68
69
  #### Windows
69
70
 
@@ -101,7 +102,7 @@ npm install @cldmv/node-android-tv-remote
101
102
  import createRemote from "@cldmv/node-android-tv-remote";
102
103
 
103
104
  // CommonJS
104
- const createRemote = require("@cldmv/node-android-tv-remote");
105
+ const { createRemote } = require("@cldmv/node-android-tv-remote");
105
106
 
106
107
  // Create remote (async function)
107
108
  const remote = await createRemote({ ip: "192.168.1.100" });
@@ -434,8 +435,8 @@ See [Keyboard Keys](https://github.com/CLDMV/node-android-tv-remote/blob/master/
434
435
  Contributions are welcome — open an issue or a pull request on [GitHub](https://github.com/CLDMV/node-android-tv-remote).
435
436
 
436
437
  ```bash
437
- npm test # Vitest against src/, then build and run the CommonJS entry tests against dist/
438
- npm run build # tsup: src/index.mjs → dist/index.mjs, src/index.cjs copied to dist/index.cjs
438
+ npm test # Vitest against src/, the CommonJS entry tests and the suite again against the build in dist/
439
+ npm run build # esbuild, one minified file per src/ module in dist/ (JSON copied, src/index.cjs copied verbatim)
439
440
  npm run lint # ESLint
440
441
  npm run format # Prettier
441
442
  ```
@@ -448,7 +449,7 @@ node --conditions=node-android-tv-remote-dev app.mjs
448
449
  export NODE_OPTIONS=--conditions=node-android-tv-remote-dev
449
450
  ```
450
451
 
451
- The test suite sets the condition itself, so `npm test` always runs against `src/`.
452
+ The test suite sets the condition itself, so `npm test` runs against `src/`; `npm run test:dist` builds and runs the same suite against `dist/`.
452
453
 
453
454
  [![Contributors]][contributors_url] [![Sponsor shinrai]][sponsor_url]
454
455
 
@@ -0,0 +1,73 @@
1
+ {
2
+ "a": "a",
3
+ "b": "b",
4
+ "c": "c",
5
+ "d": "d",
6
+ "e": "e",
7
+ "f": "f",
8
+ "g": "g",
9
+ "h": "h",
10
+ "i": "i",
11
+ "j": "j",
12
+ "k": "k",
13
+ "l": "l",
14
+ "m": "m",
15
+ "n": "n",
16
+ "o": "o",
17
+ "p": "p",
18
+ "q": "q",
19
+ "r": "r",
20
+ "s": "s",
21
+ "t": "t",
22
+ "u": "u",
23
+ "v": "v",
24
+ "w": "w",
25
+ "x": "x",
26
+ "y": "y",
27
+ "z": "z",
28
+ "0": "0",
29
+ "1": "1",
30
+ "2": "2",
31
+ "3": "3",
32
+ "4": "4",
33
+ "5": "5",
34
+ "6": "6",
35
+ "7": "7",
36
+ "8": "8",
37
+ "9": "9",
38
+ "space": " ",
39
+ "comma": ",",
40
+ "period": ".",
41
+ "semicolon": ";",
42
+ "apostrophe": "'",
43
+ "slash": "/",
44
+ "backslash": "\\",
45
+ "leftBracket": "[",
46
+ "rightBracket": "]",
47
+ "minus": "-",
48
+ "equals": "=",
49
+ "grave": "`",
50
+ "tab": "\t",
51
+ "enter": "\n",
52
+ "exclamation": "!",
53
+ "at": "@",
54
+ "hash": "#",
55
+ "dollar": "$",
56
+ "percent": "%",
57
+ "caret": "^",
58
+ "ampersand": "&",
59
+ "asterisk": "*",
60
+ "leftParen": "(",
61
+ "rightParen": ")",
62
+ "underscore": "_",
63
+ "plus": "+",
64
+ "leftBrace": "{",
65
+ "rightBrace": "}",
66
+ "pipe": "|",
67
+ "colon": ":",
68
+ "quote": "\"",
69
+ "lessThan": "<",
70
+ "greaterThan": ">",
71
+ "question": "?",
72
+ "tilde": "~"
73
+ }
@@ -0,0 +1,275 @@
1
+ {
2
+ "unknown": 0,
3
+ "softLeft": 1,
4
+ "softRight": 2,
5
+ "home": 3,
6
+ "back": 4,
7
+ "call": 5,
8
+ "endcall": 6,
9
+ "0": 7,
10
+ "1": 8,
11
+ "2": 9,
12
+ "3": 10,
13
+ "4": 11,
14
+ "5": 12,
15
+ "6": 13,
16
+ "7": 14,
17
+ "8": 15,
18
+ "9": 16,
19
+ "star": 17,
20
+ "pound": 18,
21
+ "dpadUp": 19,
22
+ "dpadDown": 20,
23
+ "dpadLeft": 21,
24
+ "dpadRight": 22,
25
+ "dpadCenter": 23,
26
+ "volumeUp": 24,
27
+ "volumeDown": 25,
28
+ "power": 26,
29
+ "camera": 27,
30
+ "clear": 28,
31
+ "a": 29,
32
+ "b": 30,
33
+ "c": 31,
34
+ "d": 32,
35
+ "e": 33,
36
+ "f": 34,
37
+ "g": 35,
38
+ "h": 36,
39
+ "i": 37,
40
+ "j": 38,
41
+ "k": 39,
42
+ "l": 40,
43
+ "m": 41,
44
+ "n": 42,
45
+ "o": 43,
46
+ "p": 44,
47
+ "q": 45,
48
+ "r": 46,
49
+ "s": 47,
50
+ "t": 48,
51
+ "u": 49,
52
+ "v": 50,
53
+ "w": 51,
54
+ "x": 52,
55
+ "y": 53,
56
+ "z": 54,
57
+ "comma": 55,
58
+ "period": 56,
59
+ "altLeft": 57,
60
+ "altRight": 58,
61
+ "shiftLeft": 59,
62
+ "shiftRight": 60,
63
+ "tab": 61,
64
+ "space": 62,
65
+ "sym": 63,
66
+ "explorer": 64,
67
+ "envelope": 65,
68
+ "enter": 66,
69
+ "del": 67,
70
+ "grave": 68,
71
+ "minus": 69,
72
+ "equals": 70,
73
+ "leftBracket": 71,
74
+ "rightBracket": 72,
75
+ "backslash": 73,
76
+ "semicolon": 74,
77
+ "apostrophe": 75,
78
+ "slash": 76,
79
+ "at": 77,
80
+ "num": 78,
81
+ "headsethook": 79,
82
+ "focus": 80,
83
+ "plus": 81,
84
+ "menu": 82,
85
+ "notification": 83,
86
+ "search": 84,
87
+ "playPause": 85,
88
+ "stop": 86,
89
+ "next": 87,
90
+ "previous": 88,
91
+ "rewind": 89,
92
+ "fastForward": 90,
93
+ "mute": 91,
94
+ "pageUp": 92,
95
+ "pageDown": 93,
96
+ "pictsymbols": 94,
97
+ "switchCharset": 95,
98
+ "buttonA": 96,
99
+ "buttonB": 97,
100
+ "buttonC": 98,
101
+ "buttonX": 99,
102
+ "buttonY": 100,
103
+ "buttonZ": 101,
104
+ "buttonL1": 102,
105
+ "buttonR1": 103,
106
+ "buttonL2": 104,
107
+ "buttonR2": 105,
108
+ "buttonThumbl": 106,
109
+ "buttonThumbr": 107,
110
+ "buttonStart": 108,
111
+ "buttonSelect": 109,
112
+ "buttonMode": 110,
113
+ "escape": 111,
114
+ "forward": 125,
115
+ "mediaPlay": 126,
116
+ "mediaPause": 127,
117
+ "mediaClose": 128,
118
+ "mediaEject": 129,
119
+ "mediaRecord": 130,
120
+ "f1": 131,
121
+ "f2": 132,
122
+ "f3": 133,
123
+ "f4": 134,
124
+ "f5": 135,
125
+ "f6": 136,
126
+ "f7": 137,
127
+ "f8": 138,
128
+ "f9": 139,
129
+ "f10": 140,
130
+ "f11": 141,
131
+ "f12": 142,
132
+ "numLock": 143,
133
+ "numpad0": 144,
134
+ "numpad1": 145,
135
+ "numpad2": 146,
136
+ "numpad3": 147,
137
+ "numpad4": 148,
138
+ "numpad5": 149,
139
+ "numpad6": 150,
140
+ "numpad7": 151,
141
+ "numpad8": 152,
142
+ "numpad9": 153,
143
+ "numpadDivide": 154,
144
+ "numpadMultiply": 155,
145
+ "numpadSubtract": 156,
146
+ "numpadAdd": 157,
147
+ "numpadDot": 158,
148
+ "numpadComma": 159,
149
+ "numpadEnter": 160,
150
+ "numpadEquals": 161,
151
+ "numpadLeftParen": 162,
152
+ "numpadRightParen": 163,
153
+ "volumeMute": 164,
154
+ "info": 165,
155
+ "channelUp": 166,
156
+ "channelDown": 167,
157
+ "zoomIn": 168,
158
+ "zoomOut": 169,
159
+ "tv": 170,
160
+ "window": 171,
161
+ "guide": 172,
162
+ "dvr": 173,
163
+ "bookmark": 174,
164
+ "captions": 175,
165
+ "settings": 176,
166
+ "tvPower": 177,
167
+ "tvInput": 178,
168
+ "stbPower": 179,
169
+ "stbInput": 180,
170
+ "avrPower": 181,
171
+ "avrInput": 182,
172
+ "progRed": 183,
173
+ "progGreen": 184,
174
+ "progYellow": 185,
175
+ "progBlue": 186,
176
+ "appSwitch": 187,
177
+ "button1": 188,
178
+ "button2": 189,
179
+ "button3": 190,
180
+ "button4": 191,
181
+ "button5": 192,
182
+ "button6": 193,
183
+ "button7": 194,
184
+ "button8": 195,
185
+ "button9": 196,
186
+ "button10": 197,
187
+ "button11": 198,
188
+ "button12": 199,
189
+ "button13": 200,
190
+ "button14": 201,
191
+ "button15": 202,
192
+ "button16": 203,
193
+ "languageSwitch": 204,
194
+ "mannerMode": 205,
195
+ "3dMode": 206,
196
+ "contacts": 207,
197
+ "calendar": 208,
198
+ "music": 209,
199
+ "calculator": 210,
200
+ "zenkakuHankaku": 211,
201
+ "eisu": 212,
202
+ "muhenkan": 213,
203
+ "henkan": 214,
204
+ "kana": 215,
205
+ "assist": 219,
206
+ "brightnessDown": 220,
207
+ "brightnessUp": 221,
208
+ "mediaAudioTrack": 222,
209
+ "sleep": 223,
210
+ "wakeup": 224,
211
+ "pairing": 225,
212
+ "mediaTopMenu": 226,
213
+ "11": 227,
214
+ "12": 228,
215
+ "lastChannel": 229,
216
+ "tvDataService": 230,
217
+ "voiceAssist": 231,
218
+ "tvRadioService": 232,
219
+ "tvTeletext": 233,
220
+ "tvNumberEntry": 234,
221
+ "tvTerrestrialAnalog": 235,
222
+ "tvTerrestrialDigital": 236,
223
+ "tvSatellite": 237,
224
+ "tvSatelliteBs": 238,
225
+ "tvSatelliteCs": 239,
226
+ "tvSatelliteService": 240,
227
+ "tvNetwork": 241,
228
+ "tvAntennaCable": 242,
229
+ "tvInputHdmi1": 243,
230
+ "tvInputHdmi2": 244,
231
+ "tvInputHdmi3": 245,
232
+ "tvInputHdmi4": 246,
233
+ "tvInputComposite1": 247,
234
+ "tvInputComposite2": 248,
235
+ "tvInputComponent1": 249,
236
+ "tvInputComponent2": 250,
237
+ "tvInputVga1": 251,
238
+ "tvAudioDescription": 252,
239
+ "tvAudioDescriptionMixUp": 253,
240
+ "tvAudioDescriptionMixDown": 254,
241
+ "tvZoomMode": 255,
242
+ "tvContentsMenu": 256,
243
+ "tvMediaContextMenu": 257,
244
+ "tvTimerProgramming": 258,
245
+ "help": 259,
246
+ "navigatePrevious": 260,
247
+ "navigateNext": 261,
248
+ "navigateIn": 262,
249
+ "navigateOut": 263,
250
+ "stemPrimary": 264,
251
+ "stem1": 265,
252
+ "stem2": 266,
253
+ "stem3": 267,
254
+ "dpadUpLeft": 268,
255
+ "dpadDownLeft": 269,
256
+ "dpadUpRight": 270,
257
+ "dpadDownRight": 271,
258
+ "mediaSkipForward": 272,
259
+ "mediaSkipBackward": 273,
260
+ "mediaStepForward": 274,
261
+ "mediaStepBackward": 275,
262
+ "softSleep": 276,
263
+ "cut": 277,
264
+ "copy": 278,
265
+ "paste": 279,
266
+ "systemNavigationUp": 280,
267
+ "systemNavigationDown": 281,
268
+ "systemNavigationLeft": 282,
269
+ "systemNavigationRight": 283,
270
+ "azmNetflix": 290,
271
+ "azmPrime": 291,
272
+ "azmDirecttv": 292,
273
+ "azmPeacock": 296,
274
+ "azmGuide": 297
275
+ }
@@ -0,0 +1,86 @@
1
+ [
2
+ "home",
3
+ "wakeup",
4
+ "back",
5
+ "recall",
6
+ "menu",
7
+ "ok",
8
+ "select",
9
+ "up",
10
+ "down",
11
+ "left",
12
+ "right",
13
+ "play",
14
+ "pause",
15
+ "playPause",
16
+ "stop",
17
+ "next",
18
+ "previous",
19
+ "fastForward",
20
+ "rewind",
21
+ "volumeUp",
22
+ "volumeDown",
23
+ "volumeMute",
24
+ "channelUp",
25
+ "channelDown",
26
+ "info",
27
+ "guide",
28
+ "settings",
29
+ "apps",
30
+ "caption",
31
+ "bookmark",
32
+ "help",
33
+ "power",
34
+ "input",
35
+ "mute",
36
+ "search",
37
+ "number0",
38
+ "number1",
39
+ "number2",
40
+ "number3",
41
+ "number4",
42
+ "number5",
43
+ "number6",
44
+ "number7",
45
+ "number8",
46
+ "number9",
47
+ "numpad0",
48
+ "numpad1",
49
+ "numpad2",
50
+ "numpad3",
51
+ "numpad4",
52
+ "numpad5",
53
+ "numpad6",
54
+ "numpad7",
55
+ "numpad8",
56
+ "numpad9",
57
+ "numpadDivide",
58
+ "numpadMultiply",
59
+ "numpadSubtract",
60
+ "numpadAdd",
61
+ "numpadDot",
62
+ "numpadComma",
63
+ "enter",
64
+ "numpadEnter",
65
+ "numpadEquals",
66
+ "numpadLeftParen",
67
+ "numpadRightParen",
68
+ "pageUp",
69
+ "pageDown",
70
+ "mediaPlay",
71
+ "mediaPause",
72
+ "mediaClose",
73
+ "mediaEject",
74
+ "mediaRecord",
75
+ "mediaSkipForward",
76
+ "mediaSkipBackward",
77
+ "mediaStepForward",
78
+ "mediaStepBackward",
79
+ "mediaAudioTrack",
80
+ "mediaTopMenu",
81
+ "azmNetflix",
82
+ "azmPrime",
83
+ "azmDirecttv",
84
+ "azmPeacock",
85
+ "azmGuide"
86
+ ]
package/dist/index.cjs CHANGED
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  *
3
3
  * @Project: @cldmv/node-android-tv-remote
4
- * @Filename: /src/index.cjs
4
+ * @Filename: src/index.cjs
5
5
  * @Date: 2025-10-15T10:29:19-07:00 (1760549359)
6
6
  * @Author: Nate Corcoran <CLDMV>
7
7
  * @Email: <Shinrai@users.noreply.github.com>
8
8
  * -----
9
9
  * @Last modified by: Nate Corcoran <CLDMV> (Shinrai@users.noreply.github.com)
10
- * @Last modified time: 2026-11-01T16:31:25-08:00 (1793579485)
10
+ * @Last modified time: 2026-11-28T09:59:04-08:00 (1795888744)
11
11
  * -----
12
12
  * @Copyright: Copyright (c) 2013-2026 Catalyzed Motivation Inc. All rights reserved.
13
13
  *
@@ -16,31 +16,31 @@
16
16
  /**
17
17
  * CommonJS entry point for @cldmv/node-android-tv-remote
18
18
  *
19
- * A thin, synchronous wrapper around the ESM entry: it loads the sibling index.mjs through
20
- * Node's require(esm) and maps it to the historical CommonJS shape (`module.exports` is
21
- * createRemote, with createRemote / createAndroidTVRemote / default on it).
19
+ * The generic CLDMV shim: a thin, synchronous wrapper around the ESM entry that loads the sibling index.mjs through
20
+ * Node's require(esm). The ESM entry exports two distinct values (createRemote, also the default, and createAndroidTVRemote),
21
+ * so require() returns the module object: `{ __esModule, default: createRemote, createRemote, createAndroidTVRemote }`.
22
22
  *
23
- * tsup.config.mjs copies this file verbatim to dist/index.cjs, so it is never bundled.
24
- * Its `require("./index.mjs")` resolves to src/index.mjs in a checkout and to the bundle
25
- * in dist/.
23
+ * scripts/build.mjs copies this file verbatim to dist/index.cjs, so it is never transformed.
24
+ * Its `require("./index.mjs")` resolves to src/index.mjs in a checkout and to dist/index.mjs.
26
25
  *
27
26
  * @module @cldmv/node-android-tv-remote
28
27
  */
29
28
  "use strict";
30
29
 
31
- // Node.js versions without require(esm) (before 20.19 / 22.12) would fail with a bare ERR_REQUIRE_ESM, so fail
32
- // early with a message that says what to do instead.
33
30
  if (!process.features?.require_module) {
34
31
  const error = new Error(
35
- `@cldmv/node-android-tv-remote: require() needs Node.js >=22.13.0 (this is ${process.version}). On older Node.js, load the package with import() instead.`
32
+ `@cldmv/node-android-tv-remote: require() needs Node.js >=22.15.0 (this is ${process.version}). On older Node.js, load the package with import() instead.`
36
33
  );
37
34
  error.code = "ERR_REQUIRE_ESM";
38
35
  throw error;
39
36
  }
40
37
 
41
- const { default: createRemote, createAndroidTVRemote } = require("./index.mjs");
42
-
43
- module.exports = createRemote;
44
- module.exports.createRemote = createRemote;
45
- module.exports.createAndroidTVRemote = createAndroidTVRemote;
46
- module.exports.default = createRemote;
38
+ // Same exports as `import`. One distinct exported value (aliases of it count once) comes back as that value,
39
+ // so require(x)(...) works; anything else comes back as the module object ({ default, ...named }).
40
+ const esm = require("./index.mjs");
41
+ const values = new Set(
42
+ Object.keys(esm)
43
+ .filter((key) => key !== "__esModule")
44
+ .map((key) => esm[key])
45
+ );
46
+ module.exports = values.size === 1 ? values.values().next().value : esm;
package/dist/index.mjs CHANGED
@@ -1,3 +1,2 @@
1
- var $e=Object.defineProperty;var d=(c,a)=>$e(c,"name",{value:a,configurable:!0});import ue from"@devicefarmer/adbkit";import{EventEmitter as Oe}from"events";import{debuglog as Re}from"node:util";import{createWriteStream as de}from"fs";import{Transform as Be}from"node:stream";import{pipeline as ze}from"node:stream/promises";import xe from"sharp";var i={unknown:0,softLeft:1,softRight:2,home:3,back:4,call:5,endcall:6,"0":7,"1":8,"2":9,"3":10,"4":11,"5":12,"6":13,"7":14,"8":15,"9":16,star:17,pound:18,dpadUp:19,dpadDown:20,dpadLeft:21,dpadRight:22,dpadCenter:23,volumeUp:24,volumeDown:25,power:26,camera:27,clear:28,a:29,b:30,c:31,d:32,e:33,f:34,g:35,h:36,i:37,j:38,k:39,l:40,m:41,n:42,o:43,p:44,q:45,r:46,s:47,t:48,u:49,v:50,w:51,x:52,y:53,z:54,comma:55,period:56,altLeft:57,altRight:58,shiftLeft:59,shiftRight:60,tab:61,space:62,sym:63,explorer:64,envelope:65,enter:66,del:67,grave:68,minus:69,equals:70,leftBracket:71,rightBracket:72,backslash:73,semicolon:74,apostrophe:75,slash:76,at:77,num:78,headsethook:79,focus:80,plus:81,menu:82,notification:83,search:84,playPause:85,stop:86,next:87,previous:88,rewind:89,fastForward:90,mute:91,pageUp:92,pageDown:93,pictsymbols:94,switchCharset:95,buttonA:96,buttonB:97,buttonC:98,buttonX:99,buttonY:100,buttonZ:101,buttonL1:102,buttonR1:103,buttonL2:104,buttonR2:105,buttonThumbl:106,buttonThumbr:107,buttonStart:108,buttonSelect:109,buttonMode:110,escape:111,forward:125,mediaPlay:126,mediaPause:127,mediaClose:128,mediaEject:129,mediaRecord:130,f1:131,f2:132,f3:133,f4:134,f5:135,f6:136,f7:137,f8:138,f9:139,f10:140,f11:141,f12:142,numLock:143,numpad0:144,numpad1:145,numpad2:146,numpad3:147,numpad4:148,numpad5:149,numpad6:150,numpad7:151,numpad8:152,numpad9:153,numpadDivide:154,numpadMultiply:155,numpadSubtract:156,numpadAdd:157,numpadDot:158,numpadComma:159,numpadEnter:160,numpadEquals:161,numpadLeftParen:162,numpadRightParen:163,volumeMute:164,info:165,channelUp:166,channelDown:167,zoomIn:168,zoomOut:169,tv:170,window:171,guide:172,dvr:173,bookmark:174,captions:175,settings:176,tvPower:177,tvInput:178,stbPower:179,stbInput:180,avrPower:181,avrInput:182,progRed:183,progGreen:184,progYellow:185,progBlue:186,appSwitch:187,button1:188,button2:189,button3:190,button4:191,button5:192,button6:193,button7:194,button8:195,button9:196,button10:197,button11:198,button12:199,button13:200,button14:201,button15:202,button16:203,languageSwitch:204,mannerMode:205,"3dMode":206,contacts:207,calendar:208,music:209,calculator:210,zenkakuHankaku:211,eisu:212,muhenkan:213,henkan:214,kana:215,assist:219,brightnessDown:220,brightnessUp:221,mediaAudioTrack:222,sleep:223,wakeup:224,pairing:225,mediaTopMenu:226,"11":227,"12":228,lastChannel:229,tvDataService:230,voiceAssist:231,tvRadioService:232,tvTeletext:233,tvNumberEntry:234,tvTerrestrialAnalog:235,tvTerrestrialDigital:236,tvSatellite:237,tvSatelliteBs:238,tvSatelliteCs:239,tvSatelliteService:240,tvNetwork:241,tvAntennaCable:242,tvInputHdmi1:243,tvInputHdmi2:244,tvInputHdmi3:245,tvInputHdmi4:246,tvInputComposite1:247,tvInputComposite2:248,tvInputComponent1:249,tvInputComponent2:250,tvInputVga1:251,tvAudioDescription:252,tvAudioDescriptionMixUp:253,tvAudioDescriptionMixDown:254,tvZoomMode:255,tvContentsMenu:256,tvMediaContextMenu:257,tvTimerProgramming:258,help:259,navigatePrevious:260,navigateNext:261,navigateIn:262,navigateOut:263,stemPrimary:264,stem1:265,stem2:266,stem3:267,dpadUpLeft:268,dpadDownLeft:269,dpadUpRight:270,dpadDownRight:271,mediaSkipForward:272,mediaSkipBackward:273,mediaStepForward:274,mediaStepBackward:275,softSleep:276,cut:277,copy:278,paste:279,systemNavigationUp:280,systemNavigationDown:281,systemNavigationLeft:282,systemNavigationRight:283,azmNetflix:290,azmPrime:291,azmDirecttv:292,azmPeacock:296,azmGuide:297};var F={a:"a",b:"b",c:"c",d:"d",e:"e",f:"f",g:"g",h:"h",i:"i",j:"j",k:"k",l:"l",m:"m",n:"n",o:"o",p:"p",q:"q",r:"r",s:"s",t:"t",u:"u",v:"v",w:"w",x:"x",y:"y",z:"z","0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9",space:" ",comma:",",period:".",semicolon:";",apostrophe:"'",slash:"/",backslash:"\\",leftBracket:"[",rightBracket:"]",minus:"-",equals:"=",grave:"`",tab:" ",enter:`
2
- `,exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftParen:"(",rightParen:")",underscore:"_",plus:"+",leftBrace:"{",rightBrace:"}",pipe:"|",colon:":",quote:'"',lessThan:"<",greaterThan:">",question:"?",tilde:"~"};var ce=["home","wakeup","back","recall","menu","ok","select","up","down","left","right","play","pause","playPause","stop","next","previous","fastForward","rewind","volumeUp","volumeDown","volumeMute","channelUp","channelDown","info","guide","settings","apps","caption","bookmark","help","power","input","mute","search","number0","number1","number2","number3","number4","number5","number6","number7","number8","number9","numpad0","numpad1","numpad2","numpad3","numpad4","numpad5","numpad6","numpad7","numpad8","numpad9","numpadDivide","numpadMultiply","numpadSubtract","numpadAdd","numpadDot","numpadComma","enter","numpadEnter","numpadEquals","numpadLeftParen","numpadRightParen","pageUp","pageDown","mediaPlay","mediaPause","mediaClose","mediaEject","mediaRecord","mediaSkipForward","mediaSkipBackward","mediaStepForward","mediaStepBackward","mediaAudioTrack","mediaTopMenu","azmNetflix","azmPrime","azmDirecttv","azmPeacock","azmGuide"];var Q=ue.Adb??ue;function $(c){return function(...a){let y=typeof a[a.length-1]=="function"?a.pop():null,z=c.apply(this,a);if(y)z.then(u=>y(null,u)).catch(u=>y(u));else return z}}d($,"wrapAsync");var Fe=Re("android-tv-remote");function Me(){let c=new Oe;function a(u,O,E="android-tv-remote",h=null){c.emit("log",{level:u,message:O,source:E,timestamp:new Date().toISOString(),...h&&{data:h}})}d(a,"emitLog");function y(u,O="android-tv-remote",E=null){let h=u.message||"";if(h.includes("libspng")||h.includes("pngload_buffer")||h.includes("read error")){a("debug",`PNG processing error (likely post-disconnect): ${h}`,O);return}let f={error:u,source:O,message:E||u.message,timestamp:new Date().toISOString()};if(c.listenerCount("error")>0){c.emit("error",f);return}Fe("unhandled error from %s: %s",O,f.message),a("error",f.message,O,{error:u})}d(y,"emitError");function z(u){return y(u,"handleDisconnectError"),u.message&&(u.message.includes("device unauthorized")||u.message.includes("failed to authenticate"))&&(y(u,"handleDisconnectError","Device unauthorized - authentication required"),a("error","Your device is unauthorized or failed to authenticate. Please check your TV and accept the authorization dialog to allow this system to connect via ADB.","handleDisconnectError"),a("info","If you do not see a prompt, try disconnecting and reconnecting the device, or reboot your TV.","handleDisconnectError"),a("info","If the problem persists, remove the device from the list of authorized ADB devices in Developer Options and try again.","handleDisconnectError"),a("info","Tip: In Developer Options on your TV, try toggling 'ADB Debugging' off and then back on. This often resolves authentication issues.","handleDisconnectError")),u.message&&(u.message.includes("actively refused")||u.message.includes("No connection could be made"))&&(y(u,"handleDisconnectError","Connection refused - ADB not enabled"),a("error","The device refused the connection. To enable ADB, follow these steps on your Android TV or Fire TV:","handleDisconnectError"),a("info","1. Open Settings > Device Preferences > About (or My Fire TV > About)","handleDisconnectError"),a("info","2. Scroll to 'Build' and press OK 7 times to enable Developer Options","handleDisconnectError"),a("info","3. Go back to Settings > Device Preferences > Developer Options","handleDisconnectError"),a("info","4. Enable 'Developer Options' if needed, then enable 'ADB Debugging' and 'Apps from Unknown Sources'","handleDisconnectError"),a("info","5. Ensure your TV and computer are on the same network","handleDisconnectError"),a("info","6. On your computer, run: adb connect <device-ip>:5555","handleDisconnectError"),a("info","7. Accept the authorization prompt on your TV","handleDisconnectError"),a("info","If you do not see 'Developer Options', repeat step 2 until it appears.","handleDisconnectError")),u}return d(z,"handleDisconnectError"),{emitter:c,emitLog:a,emitError:y,handleDisconnectError:z}}d(Me,"createEventChannel");function Ue(c,a){return/^[a-z]$/.test(a)?a.toUpperCase():{1:"!",2:"@",3:"#",4:"$",5:"%",6:"^",7:"&",8:"*",9:"(",0:")","-":"_","=":"+","[":"{","]":"}","\\":"|",";":":","'":'"',",":"<",".":">","/":"?","`":"~"}[a]||a}d(Ue,"getShiftedCharacter");async function G(c){if(!c||typeof c!="object"||!c.ip)throw new Error("Missing required 'ip' property in RemoteConfig.");let a=c.ip,y=c.port||5555,z=c.inputDevice||"/dev/input/event0",u=a+":"+y,O=typeof c.connectTimeout=="number"?c.connectTimeout:1e4,E=Q.createClient({timeout:O}),h=E.getDevice(u),{emitter:f,emitLog:n,emitError:S,handleDisconnectError:ee}=Me(),g=!1,x=new Set;function L(e,t="android-tv-remote",o=null){let r=e.message||"";if(!g&&(r.includes("libspng")||r.includes("pngload_buffer")||r.includes("read error"))){n("debug",`PNG processing error (post-disconnect): ${r}`,t);return}S(e,t,o)}d(L,"localEmitError");let H=c.autoConnect!==!1,me=c.autoDisconnect===!0,pe=typeof c.disconnectTimeout=="number"?c.disconnectTimeout:10,fe=typeof c.connectionCheckInterval=="number"?c.connectionCheckInterval:1e4,M=null,U=null,P=c.quiet!==!1,ge=c.maintainConnection!==!1,he=typeof c.heartbeatInterval=="number"?c.heartbeatInterval:2e4,N=null,we=7e3,_,Z,te=new Promise((e,t)=>{if(_=e,Z=t,!H){_(void 0);return}(async()=>{try{if(await ie(!0)==="connected")g=!0,P||n("info",`Already connected to ${u} (on init)`,"initPromise"),X(),_(void 0);else if(await q(),g)_(void 0);else{let r=new Error("Failed to connect to device on initialization.");S(r,"initPromise","Auto-connect failed during initialization"),Z(r)}}catch(o){S(o instanceof Error?o:new Error(String(o)),"initPromise","Exception during initialization"),Z(o)}})()}),ne=Promise.race([te,new Promise((e,t)=>{setTimeout(()=>{t(new Error("ADB initPromise timed out"))},we)})]);ne.catch(()=>{});function Y(){me&&(U&&clearTimeout(U),U=setTimeout(()=>{g&&re()},pe*1e3))}d(Y,"resetDisconnectTimer");function X(){ge&&(N&&clearInterval(N),N=setInterval(()=>{g&&h.shell("echo heartbeat").catch(()=>{})},he),be())}d(X,"startHeartbeat");function be(){M&&clearInterval(M),M=setInterval(async()=>{if(g)try{let e=await E.listDevices(),t=u;e.some(r=>r.id===t)||(n("warn",`Device ${t} not found in adb devices list. Attempting reconnect...`,"connectionCheck"),g=!1,await q())}catch(e){let t=e instanceof Error?e:new Error(String(e));n("warn",`Error checking device connection: ${t.message}`,"connectionCheck")}},fe)}d(be,"startConnectionCheck");function oe(){N&&(clearInterval(N),N=null),M&&(clearInterval(M),M=null)}d(oe,"stopHeartbeat");function R(){return!H||g?Promise.resolve():q()}d(R,"ensureConnected");function q(){return g?(P||n("info",`Already connected to ${u}`,"connect"),Promise.resolve()):E.connect(a,y).then(()=>{g=!0,P||n("info",`Connected to ${u}`,"connect"),X()}).catch(e=>e.message&&e.message.includes("already connected")?(P||n("warn","Device already connected","connect"),g=!0,X(),!0):ee(e))}d(q,"connect");let ve=$(q);async function re(){if(U&&(clearTimeout(U),U=null),oe(),x.size>0){P||n("info",`\u{1F504} [DISCONNECT] Waiting for ${x.size} background operations to complete...`,"disconnect");let e=performance.now();try{await Promise.allSettled([...x]);let t=performance.now();P||n("info",`\u2705 [DISCONNECT] All background operations completed in ${(t-e).toFixed(2)}ms`,"disconnect")}catch(t){let o=performance.now();n("warn",`\u26A0\uFE0F [DISCONNECT] Some background operations failed after ${(o-e).toFixed(2)}ms: ${t.message}`,"disconnect")}}else P||n("info","\u2705 [DISCONNECT] No background operations to wait for","disconnect");try{return await E.disconnect(a,y),g=!1,P||n("info",`Disconnected from ${u}`,"disconnect"),!0}catch(e){return e.message&&e.message.includes("disconnected")?(P||n("warn","Device already disconnected before explicit disconnect call","disconnect"),g=!1,!0):ee(e)}}d(re,"disconnect");let ye=$(re);function w(e){return R().then(()=>(Y(),h.shell("input keyevent "+e)))}d(w,"inputKeycode");let De=$(w);function ke(e){let t="sendevent "+z+" 1 "+e+" 1 && sleep 1 && sendevent "+z+" 1 "+e+" 0";return R().then(()=>(Y(),h.shell(t)))}d(ke,"inputKeycodeLongPress");let T=$(ke);function V(e){let t=e.replace(/ /g,"%s");return R().then(()=>(Y(),h.shell('input text "'+t+'"')))}d(V,"inputText");let Se=$(V);async function ie(e=!1){if(!e)return g?"connected":"disconnected";try{let t=await E.listDevices(),o=u,r=t.some(s=>s.id===o);return g=r,r?"connected":"disconnected"}catch{return g=!1,"unknown"}}d(ie,"getConnectionStatus");function Pe(){return!!g}d(Pe,"isConnected");function Te(){return!this||!this.keyboard||!this.keyboard.key?[]:Object.keys(this.keyboard.key).filter(e=>typeof this.keyboard.key[e]=="function")}d(Te,"getKeyboardKeys");function Ae(){return!this||!this.press?[]:Object.keys(this.press).filter(e=>e!=="long"&&typeof this.press[e]=="function")}d(Ae,"getPressCommands");let K=null,W={initPromise:ne,on(e,t){return f.on(e,t),W},off(e,t){return f.off(e,t),W},once(e,t){return f.once(e,t),W},emit(e,...t){return f.emit(e,...t)},getConnectionStatus:ie,getKeyboardKeys(){return Te.call(W)},getPressCommands(){return Ae.call(W)},get isConnected(){return Pe()},get lastScreencapData(){return K},async setSettings(e="set"){try{n("info",`=== ${e==="set"?"Configuring":"Retrieving"} Android TV settings ===`,"setSettings"),await R();let t=[{ns:"system",key:"screen_off_timeout",value:2147483647},{ns:"secure",key:"sleep_timeout",value:0},{ns:"global",key:"stay_on_while_plugged_in",value:3}];for(let o of t){let r=e==="set"?`settings put ${o.ns} ${o.key} ${o.value}`:`settings get ${o.ns} ${o.key}`,s=await h.shell(r).then(Q.util.readAll);P||(e==="set"?n("info",`Set ${o.ns} ${o.key} to ${o.value}`,"setSettings"):n("info",`${o.ns} ${o.key}: ${s.toString().trim()}`,"setSettings"))}if(e==="set"){n("info","Setting additional display and power settings","setSettings");let o=["settings put system screen_brightness_mode 0","settings put system screen_brightness 255","svc power stayon true"];for(let r of o)P||n("info",`Running: ${r}`,"setSettings"),await h.shell(r)}n("info",`\u2705 Android TV settings ${e==="set"?"configured":"retrieved"} successfully`,"setSettings")}catch(t){throw L(t,"setSettings",`Failed to ${e==="set"?"configure":"retrieve"} Android TV settings`),t}},async ensureAwake(){try{n("info","=== Starting ensureAwake sequence ===","ensureAwake"),await R();let e=d(m=>{let D=m.match(/^\s*mIsPowered=([a-zA-Z0-9]+)/m),A=m.match(/^\s*mWakefulness=([a-zA-Z0-9]+)/m),v=m.match(/^\s*mDisplayReady=([a-zA-Z0-9]+)/m);return{mIsPowered:D?D[1]:"unknown",mWakefulness:A?A[1]:"unknown",mDisplayReady:v?v[1]:"unknown"}},"parsePowerState"),t=d(async()=>{let m=await h.shell("dumpsys power").then(Q.util.readAll).then(D=>D.toString());return e(m)},"getCurrentPowerState"),o=d((m,D="")=>{let A=D?`${D} `:"";n("info",`${A}Power State:`,"ensureAwake"),n("info",` mIsPowered: ${m.mIsPowered}`,"ensureAwake"),n("info",` mWakefulness: ${m.mWakefulness}`,"ensureAwake"),n("info",` mDisplayReady: ${m.mDisplayReady}`,"ensureAwake")},"emitPowerState"),r=await t();o(r,"Initial");let s=[];if(r.mIsPowered!=="true"?(n("info",`Device not powered (${r.mIsPowered}), will send POWER keycode`,"ensureAwake"),s.push({keycode:i.power,reason:"power on device"})):n("info","\u2705 Device already powered","ensureAwake"),r.mWakefulness!=="Awake"?(n("info",`Device not awake (${r.mWakefulness}), will send WAKEUP keycode`,"ensureAwake"),s.push({keycode:i.wakeUp,reason:"wake up device"})):n("info","\u2705 Device already awake","ensureAwake"),r.mDisplayReady!=="true"?(n("info",`Display not ready (${r.mDisplayReady}), will send POWER keycode`,"ensureAwake"),s.push({keycode:i.power,reason:"ensure display ready"})):n("info","\u2705 Display already ready","ensureAwake"),s.length>0){n("info",`Sending ${s.length} keycode(s)...`,"ensureAwake");for(let m of s)n("info",`Sending keycode ${m.keycode} to ${m.reason}`,"ensureAwake"),await w(m.keycode),await new Promise(D=>setTimeout(D,500));n("info","Waiting for commands to take effect...","ensureAwake"),await new Promise(m=>setTimeout(m,3e3))}let l=await t();o(l,"Final");let b=[];if(l.mIsPowered!=="true"&&b.push(`Device still not powered: ${l.mIsPowered}`),l.mWakefulness!=="Awake"&&b.push(`Device still not awake: ${l.mWakefulness}`),l.mDisplayReady!=="true"&&b.push(`Display still not ready: ${l.mDisplayReady}`),b.length===0)return n("info","\u{1F389} ensureAwake completed successfully - device is fully ready","ensureAwake"),!0;for(let m of b)n("warn",m,"ensureAwake");return S(new Error(`ensureAwake failed with ${b.length} persistent issue(s): ${b.join(", ")}`),"ensureAwake","Device may not be fully responsive"),!1}catch(e){throw S(e,"ensureAwake","Failed to ensure device is awake"),e}},connect:ve,disconnect:ye,inputKeycode:De,async reboot(){try{n("info","=== Starting device reboot ===","reboot"),await R(),n("info","Sending reboot command to device","reboot");let e;try{e=await h.reboot(),n("info","\u2705 Reboot command completed normally","reboot")}catch(t){if(t.message&&t.message.includes("timeout"))n("info","\u2705 Reboot command sent (connection timeout is expected during reboot)","reboot"),e=!0;else throw t}return n("warn","Device will reboot shortly and connection will be lost","reboot"),setTimeout(()=>{n("info","Device should be rebooting now - connection will be terminated","reboot"),g=!1,oe()},1e3),n("info","=== Device reboot initiated ===","reboot"),e}catch(e){throw S(e,"reboot","Failed to reboot device"),e.message&&e.message.includes("unauthorized")?n("error","Device unauthorized - ensure ADB debugging is enabled and device is authorized","reboot"):e.message&&e.message.includes("device not found")?n("error","Device not found - check IP address and ADB connection","reboot"):e.message&&e.message.includes("permission")?n("error","Permission denied - reboot may require root access on some devices","reboot"):e.message&&e.message.includes("timeout")&&n("warn","Reboot command timed out - this may be normal behavior during reboot","reboot"),e}},async screencap(e={}){let t=performance.now(),{width:o,height:r,filepath:s}=e;try{n("info","=== Taking device screenshot ===","screencap"),f.emit("screencap-start",{timestamp:new Date().toISOString(),options:{width:o,height:r,filepath:s}}),await R(),n("info","Capturing screenshot using native screencap utility","screencap");let l=await h.screencap(),b=performance.now();n("info",`\u2705 Screenshot captured successfully (${(b-t).toFixed(2)}ms)`,"screencap"),f.emit("screencap-captured",{timestamp:new Date().toISOString(),captureTime:b-t});let m=o||r;if(s&&!m){let v=(async()=>{try{let p=performance.now();n("info",`\u{1F4BE} [BACKGROUND] Starting direct save to: ${s}`,"screencap");let I=performance.now(),C=de(s);K=l,n("info","\u{1F504} [BACKGROUND] Piping stream to file...","screencap"),l.pipe(C),n("info","\u23F3 [BACKGROUND] Waiting for write stream to finish...","screencap"),await new Promise((ae,J)=>{C.on("finish",()=>{n("info",`\u2705 [BACKGROUND] Write stream finished for ${s}`,"screencap"),ae()}),C.on("error",se=>{n("error",`\u274C [BACKGROUND] Write stream error for ${s}: ${se.message}`,"screencap"),J(se)})});let k=performance.now()-I,B=performance.now()-p,j=performance.now()-t;n("info",`\u2705 Screenshot saved directly to ${s}`,"screencap"),n("info",`\u26A1 Direct pipe timing: ${k.toFixed(2)}ms (no Sharp processing!)`,"screencap"),f.emit("screencap-saved",{timestamp:new Date().toISOString(),filepath:s,timing:{adbStream:b-t,directPipe:k,fileOperation:B,total:j}}),f.emit("screencap-complete",{timestamp:new Date().toISOString(),filepath:s,processed:!1,timing:{adbStream:b-t,directPipe:k,fileOperation:B,total:j}})}catch(p){n("error",`\u{1F4A5} [BACKGROUND] Direct pipe error: ${p.message}`,"screencap"),L(p,"screencap",`Failed to save screenshot directly to ${s}: ${p.message}`)}finally{n("info",`\u{1F9F9} [BACKGROUND] Cleaning up background operation for ${s}`,"screencap"),x.delete(v)}})();x.add(v),n("info","Direct PNG pipe started in background","screencap");return}if(!m&&!s)return K=l,n("info","Raw PNG stream ready (no processing needed)","screencap"),f.emit("screencap-ready",{timestamp:new Date().toISOString(),processed:!1,totalTime:b-t}),f.emit("screencap-complete",{timestamp:new Date().toISOString(),totalTime:b-t,processed:!1}),l;n("info","Processing screenshot image...","screencap"),f.emit("screencap-processing",{timestamp:new Date().toISOString(),width:o,height:r,filepath:s});let D=performance.now(),A=xe();if(o||r){let v={fit:"inside",withoutEnlargement:!0};o&&(v.width=o),r&&(v.height=r),A=A.resize(v),n("info",`Resizing to ${o||"auto"}x${r||"auto"}`,"screencap")}if(A=A.png({compressionLevel:1,progressive:!1}),s){let v=(async()=>{try{let p=performance.now(),I=[],C=new Be({transform(j,ae,J){I.push(j),J(null,j)}});await ze(l,A,C,de(s)),K=Buffer.concat(I);let k=performance.now()-p,B=performance.now()-t;n("info",`\u2705 Screenshot saved to ${s}`,"screencap"),n("info",`\u23F1\uFE0F File save timing: ${k.toFixed(2)}ms, Total: ${B.toFixed(2)}ms`,"screencap"),f.emit("screencap-saved",{timestamp:new Date().toISOString(),filepath:s,timing:{fileOperation:k,total:B}}),f.emit("screencap-complete",{timestamp:new Date().toISOString(),filepath:s,processed:!0,width:o,height:r,timing:{fileOperation:k,total:B}})}catch(p){n("error",`\u{1F4A5} [BACKGROUND SHARP] File save error: ${p.message}`,"screencap"),n("error",`\u{1F4A5} [BACKGROUND SHARP] Error stack: ${p.stack}`,"screencap"),!g&&p.message&&(p.message.includes("libspng")||p.message.includes("pngload_buffer")||p.message.includes("read error"))?n("debug",`PNG processing error after disconnection (suppressed): ${s}`,"screencap"):L(p,"screencap",`Failed to save screenshot to ${s}: ${p.message}`)}finally{n("info",`\u{1F9F9} [BACKGROUND SHARP] Cleaning up background operation for ${s}`,"screencap"),x.delete(v)}})();x.add(v),n("info","Screenshot processing started in background","screencap");return}else{let v=l.pipe(A),p=performance.now(),I=b-t,C=p-D,k=p-t;n("debug",`\u{1F50D} Timing variables: captureTime=${b}, startTime=${t}, processEndTime=${p}, processStartTime=${D}`,"screencap"),n("info","PNG stream processed and ready","screencap");try{n("info",`\u23F1\uFE0F Timing breakdown: Capture=${I.toFixed(2)}ms, Sharp=${C.toFixed(2)}ms, Total=${k.toFixed(2)}ms`,"screencap")}catch(B){n("error",`\u26A0\uFE0F Timing log error in stream processing: ${B.message}. Variables: streamCaptureTime=${I}, sharpProcessTime=${C}, totalTime=${k}`,"screencap")}return f.emit("screencap-ready",{timestamp:new Date().toISOString(),processed:!0,width:o,height:r,timing:{capture:I,sharpProcess:C,total:k}}),f.emit("screencap-complete",{timestamp:new Date().toISOString(),processed:!0,width:o,height:r,timing:{capture:I,sharpProcess:C,total:k}}),K=v,v}}catch(l){throw L(l,"screencap","Failed to capture screenshot"),l.message&&l.message.includes("unauthorized")?n("error","Device unauthorized - ensure ADB debugging is enabled and device is authorized","screencap"):l.message&&l.message.includes("device not found")?n("error","Device not found - check IP address and ADB connection","screencap"):l.message&&l.message.includes("screencap")?n("warn","Screencap utility may not be available - automatic fallback to framebuffer attempted","screencap"):l.message&&l.message.includes("ENOENT")&&n("error",`File path error: ${l.message}`,"screencap"),l}},async thumbnail(e={}){let t={width:240,...e};return n("info",`\u{1F4F8} Taking thumbnail screenshot (${t.width}x${t.height||"auto"})`,"thumbnail"),await this.screencap(t)},async waitBootComplete(e=6e4){try{n("info","=== Waiting for device boot completion ===","waitBootComplete"),await R(),n("info",`Monitoring boot status (timeout: ${e}ms)`,"waitBootComplete");let t=await h.waitBootComplete({signal:AbortSignal.timeout(e)});return n("info","\u2705 Device boot completed successfully","waitBootComplete"),n("info","Device is now ready for operations","waitBootComplete"),t}catch(t){throw S(t,"waitBootComplete","Failed while waiting for boot completion"),t.message&&t.message.includes("unauthorized")?n("error","Device unauthorized - ensure ADB debugging is enabled and device is authorized","waitBootComplete"):t.message&&t.message.includes("device not found")?n("error","Device not found - check IP address and ADB connection","waitBootComplete"):t.message&&t.message.includes("timeout")?n("error",`Boot completion timeout after ${e}ms - device may still be starting`,"waitBootComplete"):t.message&&t.message.includes("connection")&&n("error","Connection lost while waiting for boot completion","waitBootComplete"),t}},press:(()=>{let e={},t={};return ce.forEach(o=>{e[o]=$(function(){if(o==="ok"||o==="select")return w(i.dpadCenter||i.ok);if(o==="up")return w(i.dpadUp);if(o==="down")return w(i.dpadDown);if(o==="left")return w(i.dpadLeft);if(o==="right")return w(i.dpadRight);if(o==="play")return w(i.mediaPlay||i.playPause);if(o==="pause")return w(i.mediaPause||i.playPause);if(o==="volumeMute"||o==="mute")return w(i.volumeMute||i.mute);if(o==="input")return w(i.tvInput);if(o.startsWith("number")){let r=o.replace("number","");return w(i[r])}return w(i[o])}),t[o]=$(function(){if(o==="ok"||o==="select")return T(i.dpadCenter||i.ok);if(o==="up")return T(i.dpadUp);if(o==="down")return T(i.dpadDown);if(o==="left")return T(i.dpadLeft);if(o==="right")return T(i.dpadRight);if(o==="play")return T(i.mediaPlay||i.playPause);if(o==="pause")return T(i.mediaPause||i.playPause);if(o==="volumeMute"||o==="mute")return T(i.volumeMute||i.mute);if(o==="input")return T(i.tvInput);if(o.startsWith("number")){let r=o.replace("number","");return T(i[r])}return T(i[o])})}),e.long=t,e})(),keyboard:{text:Se,key:Object.assign($(function(e,t){if(t=t||{},!F[e]){let r=new Error("Unknown keyboard key: "+e);return S(r,"keyboard.key",`Unknown keyboard key: ${e}`),Promise.reject(r)}if(!t.forceKeycode)return V(F[e]);if(i[e])return w(i[e]);let o=new Error("No keycode available for key: "+e);return S(o,"keyboard.key",`No keycode available for key: ${e}`),Promise.reject(o)}),{...(()=>{let e={};return Object.keys(F).forEach(t=>{e[t]=$(function(o){if(o=o||{},!o.forceKeycode)return V(F[t]);if(i[t])return w(i[t]);let r=new Error("No keycode available for key: "+t);return S(r,"keyboard.key",`No keycode available for key: ${t}`),Promise.reject(r)}),i[t]&&(e[t].keycode=$(function(){return w(i[t])}))}),e})(),shift:(()=>{let e={};return Object.keys(F).forEach(t=>{let o=F[t],r=Ue(t,o);r!==o&&(e[t]=$(function(){return V(r)}))}),e})()})}};if(H)try{await te}catch(e){S(e,"createRemote","Auto-connect failed during initialization")}return W}d(G,"createRemote");async function le(c){return await G(c)}d(le,"createAndroidTVRemote");G.create=le;export{le as createAndroidTVRemote,G as createRemote,G as default};
3
- //# sourceMappingURL=index.mjs.map
1
+ import{default as o}from"./lib/android-tv-remote.mjs";import{default as a,createAndroidTVRemote as d}from"./lib/android-tv-remote.mjs";export{d as createAndroidTVRemote,a as createRemote,o as default};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1,2 @@
1
+ var ve=Object.defineProperty;var d=(u,s)=>ve(u,"name",{value:s,configurable:!0});import De from"@cldmv/droidsock";import{EventEmitter as Se}from"events";import{debuglog as $e}from"node:util";import{createWriteStream as re}from"fs";import{Readable as ke,Transform as Te}from"node:stream";import{pipeline as Pe}from"node:stream/promises";import Ae from"sharp";function T(u){return function(...s){const v=typeof s[s.length-1]=="function"?s.pop():null,F=u.apply(this,s);if(v)F.then(a=>v(null,a)).catch(a=>v(a));else return F}}d(T,"wrapAsync");const Ee=$e("android-tv-remote");function Ce(){const u=new Se;function s(a,C,K="android-tv-remote",f=null){u.emit("log",{level:a,message:C,source:K,timestamp:new Date().toISOString(),...f&&{data:f}})}d(s,"emitLog");function v(a,C="android-tv-remote",K=null){const f=a.message||"";if(f.includes("libspng")||f.includes("pngload_buffer")||f.includes("read error")){s("debug",`PNG processing error (likely post-disconnect): ${f}`,C);return}const I={error:a,source:C,message:K||a.message,timestamp:new Date().toISOString()};if(u.listenerCount("error")>0){u.emit("error",I);return}Ee("unhandled error from %s: %s",C,I.message),s("error",I.message,C,{error:a})}d(v,"emitError");function F(a){return v(a,"handleDisconnectError"),a.message&&(a.message.includes("device unauthorized")||a.message.includes("failed to authenticate")||a.message.includes("Authentication failed"))&&(v(a,"handleDisconnectError","Device unauthorized - authentication required"),s("error","Your device is unauthorized or failed to authenticate. Please check your TV and accept the authorization dialog to allow this system to connect via ADB.","handleDisconnectError"),s("info","If you do not see a prompt, try disconnecting and reconnecting the device, or reboot your TV.","handleDisconnectError"),s("info","If the problem persists, remove the device from the list of authorized ADB devices in Developer Options and try again.","handleDisconnectError"),s("info","Tip: In Developer Options on your TV, try toggling 'ADB Debugging' off and then back on. This often resolves authentication issues.","handleDisconnectError")),a.message&&(a.message.includes("ECONNREFUSED")||a.message.includes("actively refused")||a.message.includes("No connection could be made"))&&(v(a,"handleDisconnectError","Connection refused - ADB not enabled"),s("error","The device refused the connection. To enable ADB, follow these steps on your Android TV or Fire TV:","handleDisconnectError"),s("info","1. Open Settings > Device Preferences > About (or My Fire TV > About)","handleDisconnectError"),s("info","2. Scroll to 'Build' and press OK 7 times to enable Developer Options","handleDisconnectError"),s("info","3. Go back to Settings > Device Preferences > Developer Options","handleDisconnectError"),s("info","4. Enable 'Developer Options' if needed, then enable 'ADB Debugging' and 'Apps from Unknown Sources'","handleDisconnectError"),s("info","5. Ensure your TV and computer are on the same network","handleDisconnectError"),s("info","6. Connect again with remote.connect()","handleDisconnectError"),s("info","7. Accept the authorization prompt on your TV","handleDisconnectError"),s("info","If you do not see 'Developer Options', repeat step 2 until it appears.","handleDisconnectError")),a}return d(F,"handleDisconnectError"),{emitter:u,emitLog:s,emitError:v,handleDisconnectError:F}}d(Ce,"createEventChannel");import i from"../data/keycodes.json"with{type:"json"};import G from"../data/keyboard-keys.json"with{type:"json"};function Oe(u,s){return/^[a-z]$/.test(s)?s.toUpperCase():{1:"!",2:"@",3:"#",4:"$",5:"%",6:"^",7:"&",8:"*",9:"(",0:")","-":"_","=":"+","[":"{","]":"}","\\":"|",";":":","'":'"',",":"<",".":">","/":"?","`":"~"}[s]||s}d(Oe,"getShiftedCharacter");import Re from"../data/remote-keys.json"with{type:"json"};async function J(u){if(!u||typeof u!="object"||!u.ip)throw new Error("Missing required 'ip' property in RemoteConfig.");const s=u.ip,v=u.port||5555,F=u.inputDevice||"/dev/input/event0",a=s+":"+v,C=typeof u.connectTimeout=="number"?u.connectTimeout:1e4,K=await De({config:{timeout:C}});let f=null;const I=d(()=>{if(!f)throw new Error("Device not connected");return f},"requireLeaf"),O={shell:d((e,t)=>I().shell(e,t),"shell"),reboot:d(()=>I().reboot(),"reboot"),async screencap(){const e=await I().shell("screencap -p",{encoding:"latin1",timeout:C*3});return ke.from([Buffer.from(e,"latin1")])},async waitBootComplete(e=6e4){const t=Date.now()+e;for(;;){try{if((await I().shell("getprop sys.boot_completed",{timeout:Math.max(t-Date.now(),1)})).trim()==="1")return!0}catch(r){if(r.message.includes("unauthorized"))throw r}const o=t-Date.now();if(o<=0)throw new Error("Boot completion timeout after "+e+"ms");await new Promise(r=>setTimeout(r,Math.min(1e3,o)))}}},{emitter:y,emitLog:n,emitError:D,handleDisconnectError:Q}=Ce();let g=!1,W=new Set;function M(e,t="android-tv-remote",o=null){const r=e.message||"";if(!g&&(r.includes("libspng")||r.includes("pngload_buffer")||r.includes("read error"))){n("debug",`PNG processing error (post-disconnect): ${r}`,t);return}D(e,t,o)}d(M,"localEmitError");const V=u.autoConnect!==!1,ie=u.autoDisconnect===!0,se=typeof u.disconnectTimeout=="number"?u.disconnectTimeout:10;let x=null;const P=u.quiet!==!1,ae=u.maintainConnection!==!1,ce=typeof u.heartbeatInterval=="number"?u.heartbeatInterval:2e4,ue=7e3;let L,q;const X=new Promise((e,t)=>{if(L=e,q=t,!V){L(void 0);return}(async()=>{try{if(await Z(),g)L(void 0);else{const o=new Error("Failed to connect to device on initialization.");D(o,"initPromise","Auto-connect failed during initialization"),q(o)}}catch(o){D(o instanceof Error?o:new Error(String(o)),"initPromise","Exception during initialization"),q(o)}})()}),ee=Promise.race([X,new Promise((e,t)=>{setTimeout(()=>{t(new Error("ADB initPromise timed out"))},ue)})]);ee.catch(()=>{});function H(){ie&&(x&&clearTimeout(x),x=setTimeout(()=>{g&&te()},se*1e3))}d(H,"resetDisconnectTimer");function de(){f.on("connected",()=>{g=!0}),f.on("disconnected",({intentional:e})=>{g=!1,e||n("warn",`Connection to ${a} dropped`,"connectionCheck")}),f.on("reconnecting",({attempt:e,delay:t})=>{n("warn",`Reconnecting to ${a} (attempt ${e} in ${t}ms)`,"connectionCheck")}),f.on("reconnected",()=>{P||n("info",`Reconnected to ${a}`,"connectionCheck")}),f.on("gave-up",({reason:e,error:t})=>{D(t instanceof Error?t:new Error(`Gave up reconnecting to ${a} (${e})`),"connectionCheck",`Gave up reconnecting (${e})`)})}d(de,"watchLeaf");function B(){return!V||g?Promise.resolve():Z()}d(B,"ensureConnected");function Z(){if(g)return P||n("info",`Already connected to ${a}`,"connect"),Promise.resolve();const e=ae?{autoReconnect:!0,heartbeat:{interval:ce}}:{};return K.device.connect(s,v,e).then(t=>{t!==f&&(f=t,de()),g=!0,P||n("info",`Connected to ${a}`,"connect")}).catch(t=>Q(t))}d(Z,"connect");const le=T(Z);async function te(){if(x&&(clearTimeout(x),x=null),W.size>0){P||n("info",`\u{1F504} [DISCONNECT] Waiting for ${W.size} background operations to complete...`,"disconnect");const e=performance.now();try{await Promise.allSettled([...W]);const t=performance.now();P||n("info",`\u2705 [DISCONNECT] All background operations completed in ${(t-e).toFixed(2)}ms`,"disconnect")}catch(t){const o=performance.now();n("warn",`\u26A0\uFE0F [DISCONNECT] Some background operations failed after ${(o-e).toFixed(2)}ms: ${t.message}`,"disconnect")}}else P||n("info","\u2705 [DISCONNECT] No background operations to wait for","disconnect");try{return K.device.disconnect(s,v),g=!1,P||n("info",`Disconnected from ${a}`,"disconnect"),!0}catch(e){return e.message&&e.message.includes("disconnected")?(P||n("warn","Device already disconnected before explicit disconnect call","disconnect"),g=!1,!0):Q(e)}}d(te,"disconnect");const me=T(te);function h(e){return B().then(()=>(H(),O.shell("input keyevent "+e)))}d(h,"inputKeycode");const pe=T(h);function fe(e){const t="sendevent "+F+" 1 "+e+" 1 && sleep 1 && sendevent "+F+" 1 "+e+" 0";return B().then(()=>(H(),O.shell(t)))}d(fe,"inputKeycodeLongPress");const $=T(fe);function j(e){const t=e.replace(/ /g,"%s");return B().then(()=>(H(),O.shell('input text "'+t+'"')))}d(j,"inputText");const ge=T(j);async function he(e=!1){return e&&(g=!!f&&f.isConnected()),g?"connected":"disconnected"}d(he,"getConnectionStatus");function we(){return!!g}d(we,"isConnected");function ye(){return!this||!this.keyboard||!this.keyboard.key?[]:Object.keys(this.keyboard.key).filter(e=>typeof this.keyboard.key[e]=="function")}d(ye,"getKeyboardKeys");function be(){return!this||!this.press?[]:Object.keys(this.press).filter(e=>e!=="long"&&typeof this.press[e]=="function")}d(be,"getPressCommands");let N=null;const U={initPromise:ee,on(e,t){return y.on(e,t),U},off(e,t){return y.off(e,t),U},once(e,t){return y.once(e,t),U},emit(e,...t){return y.emit(e,...t)},getConnectionStatus:he,getKeyboardKeys(){return ye.call(U)},getPressCommands(){return be.call(U)},get isConnected(){return we()},get lastScreencapData(){return N},async setSettings(e="set"){try{n("info",`=== ${e==="set"?"Configuring":"Retrieving"} Android TV settings ===`,"setSettings"),await B();const t=[{ns:"system",key:"screen_off_timeout",value:2147483647},{ns:"secure",key:"sleep_timeout",value:0},{ns:"global",key:"stay_on_while_plugged_in",value:3}];for(const o of t){const r=e==="set"?`settings put ${o.ns} ${o.key} ${o.value}`:`settings get ${o.ns} ${o.key}`,c=await O.shell(r);P||(e==="set"?n("info",`Set ${o.ns} ${o.key} to ${o.value}`,"setSettings"):n("info",`${o.ns} ${o.key}: ${c.toString().trim()}`,"setSettings"))}if(e==="set"){n("info","Setting additional display and power settings","setSettings");const o=["settings put system screen_brightness_mode 0","settings put system screen_brightness 255","svc power stayon true"];for(const r of o)P||n("info",`Running: ${r}`,"setSettings"),await O.shell(r)}n("info",`\u2705 Android TV settings ${e==="set"?"configured":"retrieved"} successfully`,"setSettings")}catch(t){throw M(t,"setSettings",`Failed to ${e==="set"?"configure":"retrieve"} Android TV settings`),t}},async ensureAwake(){try{n("info","=== Starting ensureAwake sequence ===","ensureAwake"),await B();const e=d(m=>{const A=m.match(/^\s*mIsPowered=([a-zA-Z0-9]+)/m),k=m.match(/^\s*mWakefulness=([a-zA-Z0-9]+)/m),b=m.match(/^\s*mDisplayReady=([a-zA-Z0-9]+)/m);return{mIsPowered:A?A[1]:"unknown",mWakefulness:k?k[1]:"unknown",mDisplayReady:b?b[1]:"unknown"}},"parsePowerState"),t=d(async()=>{const m=await O.shell("dumpsys power");return e(m)},"getCurrentPowerState"),o=d((m,A="")=>{const k=A?`${A} `:"";n("info",`${k}Power State:`,"ensureAwake"),n("info",` mIsPowered: ${m.mIsPowered}`,"ensureAwake"),n("info",` mWakefulness: ${m.mWakefulness}`,"ensureAwake"),n("info",` mDisplayReady: ${m.mDisplayReady}`,"ensureAwake")},"emitPowerState"),r=await t();o(r,"Initial");const c=[];if(r.mIsPowered!=="true"?(n("info",`Device not powered (${r.mIsPowered}), will send POWER keycode`,"ensureAwake"),c.push({keycode:i.power,reason:"power on device"})):n("info","\u2705 Device already powered","ensureAwake"),r.mWakefulness!=="Awake"?(n("info",`Device not awake (${r.mWakefulness}), will send WAKEUP keycode`,"ensureAwake"),c.push({keycode:i.wakeUp,reason:"wake up device"})):n("info","\u2705 Device already awake","ensureAwake"),r.mDisplayReady!=="true"?(n("info",`Display not ready (${r.mDisplayReady}), will send POWER keycode`,"ensureAwake"),c.push({keycode:i.power,reason:"ensure display ready"})):n("info","\u2705 Display already ready","ensureAwake"),c.length>0){n("info",`Sending ${c.length} keycode(s)...`,"ensureAwake");for(const m of c)n("info",`Sending keycode ${m.keycode} to ${m.reason}`,"ensureAwake"),await h(m.keycode),await new Promise(A=>setTimeout(A,500));n("info","Waiting for commands to take effect...","ensureAwake"),await new Promise(m=>setTimeout(m,3e3))}const l=await t();o(l,"Final");const w=[];if(l.mIsPowered!=="true"&&w.push(`Device still not powered: ${l.mIsPowered}`),l.mWakefulness!=="Awake"&&w.push(`Device still not awake: ${l.mWakefulness}`),l.mDisplayReady!=="true"&&w.push(`Display still not ready: ${l.mDisplayReady}`),w.length===0)return n("info","\u{1F389} ensureAwake completed successfully - device is fully ready","ensureAwake"),!0;for(const m of w)n("warn",m,"ensureAwake");return D(new Error(`ensureAwake failed with ${w.length} persistent issue(s): ${w.join(", ")}`),"ensureAwake","Device may not be fully responsive"),!1}catch(e){throw D(e,"ensureAwake","Failed to ensure device is awake"),e}},connect:le,disconnect:me,inputKeycode:pe,async reboot(){try{n("info","=== Starting device reboot ===","reboot"),await B(),n("info","Sending reboot command to device","reboot");let e;try{e=await O.reboot(),n("info","\u2705 Reboot command completed normally","reboot")}catch(t){if(t.message&&t.message.includes("timeout"))n("info","\u2705 Reboot command sent (connection timeout is expected during reboot)","reboot"),e=!0;else throw t}return n("warn","Device will reboot shortly and connection will be lost","reboot"),setTimeout(()=>{n("info","Device should be rebooting now - connection will be terminated","reboot"),g=!1},1e3),n("info","=== Device reboot initiated ===","reboot"),e}catch(e){throw D(e,"reboot","Failed to reboot device"),e.message&&e.message.includes("unauthorized")?n("error","Device unauthorized - ensure ADB debugging is enabled and device is authorized","reboot"):e.message&&e.message.includes("device not found")?n("error","Device not found - check IP address and ADB connection","reboot"):e.message&&e.message.includes("permission")?n("error","Permission denied - reboot may require root access on some devices","reboot"):e.message&&e.message.includes("timeout")&&n("warn","Reboot command timed out - this may be normal behavior during reboot","reboot"),e}},async screencap(e={}){const t=performance.now(),{width:o,height:r,filepath:c}=e;try{n("info","=== Taking device screenshot ===","screencap"),y.emit("screencap-start",{timestamp:new Date().toISOString(),options:{width:o,height:r,filepath:c}}),await B(),n("info","Capturing screenshot using native screencap utility","screencap");const l=await O.screencap(),w=performance.now();n("info",`\u2705 Screenshot captured successfully (${(w-t).toFixed(2)}ms)`,"screencap"),y.emit("screencap-captured",{timestamp:new Date().toISOString(),captureTime:w-t});const m=o||r;if(c&&!m){const b=(async()=>{try{const p=performance.now();n("info",`\u{1F4BE} [BACKGROUND] Starting direct save to: ${c}`,"screencap");const R=performance.now(),E=re(c);N=l,n("info","\u{1F504} [BACKGROUND] Piping stream to file...","screencap"),l.pipe(E),n("info","\u23F3 [BACKGROUND] Waiting for write stream to finish...","screencap"),await new Promise((ne,Y)=>{E.on("finish",()=>{n("info",`\u2705 [BACKGROUND] Write stream finished for ${c}`,"screencap"),ne()}),E.on("error",oe=>{n("error",`\u274C [BACKGROUND] Write stream error for ${c}: ${oe.message}`,"screencap"),Y(oe)})});const S=performance.now()-R,z=performance.now()-p,_=performance.now()-t;n("info",`\u2705 Screenshot saved directly to ${c}`,"screencap"),n("info",`\u26A1 Direct pipe timing: ${S.toFixed(2)}ms (no Sharp processing!)`,"screencap"),y.emit("screencap-saved",{timestamp:new Date().toISOString(),filepath:c,timing:{adbStream:w-t,directPipe:S,fileOperation:z,total:_}}),y.emit("screencap-complete",{timestamp:new Date().toISOString(),filepath:c,processed:!1,timing:{adbStream:w-t,directPipe:S,fileOperation:z,total:_}})}catch(p){n("error",`\u{1F4A5} [BACKGROUND] Direct pipe error: ${p.message}`,"screencap"),M(p,"screencap",`Failed to save screenshot directly to ${c}: ${p.message}`)}finally{n("info",`\u{1F9F9} [BACKGROUND] Cleaning up background operation for ${c}`,"screencap"),W.delete(b)}})();W.add(b),n("info","Direct PNG pipe started in background","screencap");return}if(!m&&!c)return N=l,n("info","Raw PNG stream ready (no processing needed)","screencap"),y.emit("screencap-ready",{timestamp:new Date().toISOString(),processed:!1,totalTime:w-t}),y.emit("screencap-complete",{timestamp:new Date().toISOString(),totalTime:w-t,processed:!1}),l;n("info","Processing screenshot image...","screencap"),y.emit("screencap-processing",{timestamp:new Date().toISOString(),width:o,height:r,filepath:c});const A=performance.now();let k=Ae();if(o||r){const b={fit:"inside",withoutEnlargement:!0};o&&(b.width=o),r&&(b.height=r),k=k.resize(b),n("info",`Resizing to ${o||"auto"}x${r||"auto"}`,"screencap")}if(k=k.png({compressionLevel:1,progressive:!1}),c){const b=(async()=>{try{const p=performance.now(),R=[],E=new Te({transform(_,ne,Y){R.push(_),Y(null,_)}});await Pe(l,k,E,re(c)),N=Buffer.concat(R);const S=performance.now()-p,z=performance.now()-t;n("info",`\u2705 Screenshot saved to ${c}`,"screencap"),n("info",`\u23F1\uFE0F File save timing: ${S.toFixed(2)}ms, Total: ${z.toFixed(2)}ms`,"screencap"),y.emit("screencap-saved",{timestamp:new Date().toISOString(),filepath:c,timing:{fileOperation:S,total:z}}),y.emit("screencap-complete",{timestamp:new Date().toISOString(),filepath:c,processed:!0,width:o,height:r,timing:{fileOperation:S,total:z}})}catch(p){n("error",`\u{1F4A5} [BACKGROUND SHARP] File save error: ${p.message}`,"screencap"),n("error",`\u{1F4A5} [BACKGROUND SHARP] Error stack: ${p.stack}`,"screencap"),!g&&p.message&&(p.message.includes("libspng")||p.message.includes("pngload_buffer")||p.message.includes("read error"))?n("debug",`PNG processing error after disconnection (suppressed): ${c}`,"screencap"):M(p,"screencap",`Failed to save screenshot to ${c}: ${p.message}`)}finally{n("info",`\u{1F9F9} [BACKGROUND SHARP] Cleaning up background operation for ${c}`,"screencap"),W.delete(b)}})();W.add(b),n("info","Screenshot processing started in background","screencap");return}else{const b=l.pipe(k),p=performance.now(),R=w-t,E=p-A,S=p-t;n("debug",`\u{1F50D} Timing variables: captureTime=${w}, startTime=${t}, processEndTime=${p}, processStartTime=${A}`,"screencap"),n("info","PNG stream processed and ready","screencap");try{n("info",`\u23F1\uFE0F Timing breakdown: Capture=${R.toFixed(2)}ms, Sharp=${E.toFixed(2)}ms, Total=${S.toFixed(2)}ms`,"screencap")}catch(z){n("error",`\u26A0\uFE0F Timing log error in stream processing: ${z.message}. Variables: streamCaptureTime=${R}, sharpProcessTime=${E}, totalTime=${S}`,"screencap")}return y.emit("screencap-ready",{timestamp:new Date().toISOString(),processed:!0,width:o,height:r,timing:{capture:R,sharpProcess:E,total:S}}),y.emit("screencap-complete",{timestamp:new Date().toISOString(),processed:!0,width:o,height:r,timing:{capture:R,sharpProcess:E,total:S}}),N=b,b}}catch(l){throw M(l,"screencap","Failed to capture screenshot"),l.message&&l.message.includes("unauthorized")?n("error","Device unauthorized - ensure ADB debugging is enabled and device is authorized","screencap"):l.message&&l.message.includes("device not found")?n("error","Device not found - check IP address and ADB connection","screencap"):l.message&&l.message.includes("screencap")?n("warn","Screencap utility may not be available - automatic fallback to framebuffer attempted","screencap"):l.message&&l.message.includes("ENOENT")&&n("error",`File path error: ${l.message}`,"screencap"),l}},async thumbnail(e={}){const t={width:240,...e};return n("info",`\u{1F4F8} Taking thumbnail screenshot (${t.width}x${t.height||"auto"})`,"thumbnail"),await this.screencap(t)},async waitBootComplete(e=6e4){try{n("info","=== Waiting for device boot completion ===","waitBootComplete"),await B(),n("info",`Monitoring boot status (timeout: ${e}ms)`,"waitBootComplete");const t=await O.waitBootComplete(e);return n("info","\u2705 Device boot completed successfully","waitBootComplete"),n("info","Device is now ready for operations","waitBootComplete"),t}catch(t){throw D(t,"waitBootComplete","Failed while waiting for boot completion"),t.message&&t.message.includes("unauthorized")?n("error","Device unauthorized - ensure ADB debugging is enabled and device is authorized","waitBootComplete"):t.message&&t.message.includes("timeout")&&n("error",`Boot completion timeout after ${e}ms - device may still be starting`,"waitBootComplete"),t}},press:(()=>{const e={},t={};return Re.forEach(o=>{e[o]=T(function(){if(o==="ok"||o==="select")return h(i.dpadCenter||i.ok);if(o==="up")return h(i.dpadUp);if(o==="down")return h(i.dpadDown);if(o==="left")return h(i.dpadLeft);if(o==="right")return h(i.dpadRight);if(o==="play")return h(i.mediaPlay||i.playPause);if(o==="pause")return h(i.mediaPause||i.playPause);if(o==="volumeMute"||o==="mute")return h(i.volumeMute||i.mute);if(o==="input")return h(i.tvInput);if(o.startsWith("number")){const r=o.replace("number","");return h(i[r])}return h(i[o])}),t[o]=T(function(){if(o==="ok"||o==="select")return $(i.dpadCenter||i.ok);if(o==="up")return $(i.dpadUp);if(o==="down")return $(i.dpadDown);if(o==="left")return $(i.dpadLeft);if(o==="right")return $(i.dpadRight);if(o==="play")return $(i.mediaPlay||i.playPause);if(o==="pause")return $(i.mediaPause||i.playPause);if(o==="volumeMute"||o==="mute")return $(i.volumeMute||i.mute);if(o==="input")return $(i.tvInput);if(o.startsWith("number")){const r=o.replace("number","");return $(i[r])}return $(i[o])})}),e.long=t,e})(),keyboard:{text:ge,key:Object.assign(T(function(e,t){if(t=t||{},!G[e]){const r=new Error("Unknown keyboard key: "+e);return D(r,"keyboard.key",`Unknown keyboard key: ${e}`),Promise.reject(r)}if(!t.forceKeycode)return j(G[e]);if(i[e])return h(i[e]);const o=new Error("No keycode available for key: "+e);return D(o,"keyboard.key",`No keycode available for key: ${e}`),Promise.reject(o)}),{...(()=>{const e={};return Object.keys(G).forEach(t=>{e[t]=T(function(o){if(o=o||{},!o.forceKeycode)return j(G[t]);if(i[t])return h(i[t]);const r=new Error("No keycode available for key: "+t);return D(r,"keyboard.key",`No keycode available for key: ${t}`),Promise.reject(r)}),i[t]&&(e[t].keycode=T(function(){return h(i[t])}))}),e})(),shift:(()=>{const e={};return Object.keys(G).forEach(t=>{const o=G[t],r=Oe(t,o);r!==o&&(e[t]=T(function(){return j(r)}))}),e})()})}};if(V)try{await X}catch(e){D(e,"createRemote","Auto-connect failed during initialization")}return U}d(J,"createRemote");async function Ie(u){return await J(u)}d(Ie,"createAndroidTVRemote"),J.create=Ie;export{Ie as createAndroidTVRemote,J as default};
2
+ //# sourceMappingURL=android-tv-remote.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cldmv/node-android-tv-remote",
3
- "version": "2.2.1",
3
+ "version": "3.0.0",
4
4
  "description": "A Node.js library for controlling Android TV devices via ADB keycodes and text input.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -17,16 +17,16 @@
17
17
  "./package.json": "./package.json"
18
18
  },
19
19
  "scripts": {
20
- "postinstall": "node scripts/postinstall.mjs",
21
20
  "setup-device": "node scripts/setup-device.mjs",
22
- "build": "tsup",
21
+ "build": "node scripts/build.mjs",
23
22
  "build:ci": "npm run lint && npm run format:check && npm run build",
24
23
  "prepack": "npm run build",
25
- "test": "node tests/run-vitest.mjs && npm run test:cjs",
24
+ "test": "node tests/run-vitest.mjs && npm run test:cjs && npm run test:dist",
26
25
  "test:cjs": "npm run build && node --conditions=node-android-tv-remote-dev --test tests/cjs/entry.test.cjs",
26
+ "test:dist": "npm run build && node tests/run-vitest.mjs --mode=dist",
27
27
  "test:watch": "vitest --config .configs/vitest.config.mjs",
28
28
  "coverage": "node tests/run-vitest.mjs --coverage-quiet && npm run test:cjs",
29
- "ci:coverage": "npm run coverage",
29
+ "ci:coverage": "npm run coverage && npm run test:dist",
30
30
  "lint": "eslint --config .configs/eslint.config.mjs .",
31
31
  "lint:fix": "eslint --config .configs/eslint.config.mjs . --fix",
32
32
  "format": "prettier --config .prettierrc --write .",
@@ -64,18 +64,17 @@
64
64
  "files": [
65
65
  "dist/",
66
66
  "!dist/**/*.map",
67
- "types/",
68
- "scripts/postinstall.mjs"
67
+ "types/"
69
68
  ],
70
69
  "dependencies": {
71
- "@devicefarmer/adbkit": "^4.0.1",
70
+ "@cldmv/droidsock": "^2.2.1",
72
71
  "sharp": "^0.35.5"
73
72
  },
74
73
  "publishConfig": {
75
74
  "access": "public"
76
75
  },
77
76
  "engines": {
78
- "node": ">=22.12.0"
77
+ "node": ">=22.15.0"
79
78
  },
80
79
  "devEngines": {
81
80
  "runtime": {
@@ -89,18 +88,18 @@
89
88
  "minimatch": "^11.0.3"
90
89
  },
91
90
  "devDependencies": {
92
- "@cldmv/configs": "^1.3.0",
93
- "@cldmv/fix-headers": "^2.2.4",
94
- "@cldmv/vitest-runner": "^1.5.6",
91
+ "@cldmv/configs": "^1.5.0",
92
+ "@cldmv/fix-headers": "^2.6.1",
93
+ "@cldmv/vitest-runner": "^1.11.4",
95
94
  "@eslint/css": "^2.0.1",
96
95
  "@eslint/js": "^10.0.1",
97
96
  "@eslint/json": "^2.1.1",
98
- "@eslint/markdown": "^8.0.3",
97
+ "@eslint/markdown": "^9.0.0",
99
98
  "@vitest/coverage-v8": "^5.0.5",
99
+ "esbuild": "^0.28.2",
100
100
  "eslint": "^10.14.0",
101
101
  "globals": "^17.14.0",
102
102
  "prettier": "^3.9.10",
103
- "tsup": "^9.0.0",
104
103
  "typescript": "^6.0.3",
105
104
  "vitest": "^5.0.5"
106
105
  }
@@ -1,76 +0,0 @@
1
- /**
2
- *
3
- * @Project: @cldmv/node-android-tv-remote
4
- * @Filename: /scripts/postinstall.mjs
5
- * @Date: 2025-10-15T10:19:05-07:00 (1760548745)
6
- * @Author: Nate Corcoran <CLDMV>
7
- * @Email: <Shinrai@users.noreply.github.com>
8
- * -----
9
- * @Last modified by: Nate Corcoran <CLDMV> (Shinrai@users.noreply.github.com)
10
- * @Last modified time: 2026-10-02T12:16:14-07:00 (1790968574)
11
- * -----
12
- * @Copyright: Copyright (c) 2013-2026 Catalyzed Motivation Inc. All rights reserved.
13
- *
14
- */
15
-
16
- /**
17
- * Postinstall script to check for adb and print install instructions if missing.
18
- */
19
- import { execSync } from "child_process";
20
- import os from "os";
21
- import { realpathSync } from "node:fs";
22
- import { fileURLToPath } from "node:url";
23
-
24
- function hasAdb() {
25
- try {
26
- execSync("adb version", { stdio: "ignore" });
27
- return true;
28
- } catch (_) {
29
- return false;
30
- }
31
- }
32
-
33
- /**
34
- * Print whether adb is available, with install instructions when it isn't.
35
- * @returns {void}
36
- */
37
- export function main() {
38
- if (hasAdb()) {
39
- console.log("ADB is installed and available in your PATH.");
40
- return;
41
- }
42
-
43
- console.log("\nADB is not installed or not in your PATH.");
44
- console.log("Follow these instructions to install ADB:");
45
-
46
- const platform = os.platform();
47
- if (platform === "win32") {
48
- console.log("\nWindows:");
49
- console.log("1. Download the SDK Platform Tools for Windows: https://developer.android.com/studio/releases/platform-tools");
50
- console.log("2. Extract the ZIP file.");
51
- console.log("3. Add the extracted folder to your system PATH.");
52
- console.log('4. Test by running "adb version" in Command Prompt.');
53
- } else if (platform === "darwin") {
54
- console.log("\nmacOS:");
55
- console.log("1. Download the SDK Platform Tools for Mac: https://developer.android.com/studio/releases/platform-tools");
56
- console.log("2. Extract the ZIP file.");
57
- console.log("3. Move the extracted folder to /usr/local/bin or add it to your PATH.");
58
- console.log('4. Test by running "adb version" in Terminal.');
59
- } else if (platform === "linux") {
60
- console.log("\nLinux:");
61
- console.log("1. Download the SDK Platform Tools for Linux: https://developer.android.com/studio/releases/platform-tools");
62
- console.log("2. Extract the ZIP file.");
63
- console.log("3. Move the extracted folder to /usr/local/bin or add it to your PATH.");
64
- console.log("4. Or install via your package manager:");
65
- console.log(" - Ubuntu/Debian: sudo apt-get install android-tools-adb");
66
- console.log(" - Fedora/Red Hat: sudo dnf install android-tools");
67
- console.log(" - CentOS/yum: sudo yum install android-tools");
68
- console.log('5. Test by running "adb version" in your shell.');
69
- }
70
- console.log("\nYou must accept the ADB authorization prompt on your Android TV device the first time you connect.");
71
- }
72
-
73
- // Run only when executed directly (npm postinstall), not when imported.
74
- if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
75
- main();
76
- }