lycheedev 1.0.2 → 1.0.4

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/bin/lycheedev.js CHANGED
@@ -6,9 +6,16 @@ import path from 'node:path';
6
6
 
7
7
  import { runDoctor } from '../src/doctor.js';
8
8
  import { runInstall } from '../src/install.js';
9
- import { loadConfig } from '../src/config.js';
9
+ import { loadConfig, updateConfig } from '../src/config.js';
10
10
  import { runAutomation } from '../src/python.js';
11
- import { findSavedVariablesCandidates, scanClients } from '../src/wow.js';
11
+ import {
12
+ findInstances,
13
+ findSavedVariablesCandidates,
14
+ formatInstance,
15
+ matchPinned,
16
+ resolveInstance,
17
+ scanClients,
18
+ } from '../src/wow.js';
12
19
  import { addonFolderName, exists } from '../src/paths.js';
13
20
 
14
21
  const HELP = `lycheedev - Lychee Dev installer and World of Warcraft automation driver
@@ -19,7 +26,10 @@ commands
19
26
  install install python dependencies, the skill and the addon
20
27
  update refresh dependencies, skill and addon to this version
21
28
  doctor report what is installed and what is missing
22
- clients list detected clients and their addon directories
29
+ clients list every detected build and its addon state
30
+ instances list running game clients (build, pid, window)
31
+ use [index] pin one running client as the default target
32
+ use --clear drop the pin
23
33
  send <text> type one slash command into the running game
24
34
  capture poll the game window and decode the completion notice
25
35
  run --task <id> deliver, decode, reload once and read the result ticket
@@ -32,8 +42,11 @@ commands
32
42
  recover show reload intents that were never confirmed
33
43
 
34
44
  options
35
- --wow-root <path> folder that contains _retail_/_classic_/_classic_arena_
45
+ --wow-root <path> folder that contains _retail_/_classic_/_classic_titan_
36
46
  --client <id> retail | classic | titan (default: the only configured one)
47
+ --instance <index> which running client to target when several are open
48
+ --hwnd <handle> target one window directly, skipping instance lookup
49
+ --pid <pid> expected process id for the target window
37
50
  --python <bin> python interpreter to use
38
51
  --force redo work that is already present
39
52
  --reset-registry install the addon with an empty task registry
@@ -41,6 +54,12 @@ options
41
54
  -h, --help show this help
42
55
  -v, --version show the version
43
56
 
57
+ Every non-retail client runs as WowClassic.exe, so a running client is matched
58
+ by its install path, not its process name. With several clients open, run
59
+ "lycheedev instances" then "lycheedev use <index>" to pin one as the target;
60
+ the pin stores the build, so it survives a restart even though the pid and
61
+ window handle change. Pass --instance <index> to override it for one command.
62
+
44
63
  The automation subcommands are thin wrappers over the bundled python helper, so
45
64
  the same arguments it accepts are forwarded unchanged.`;
46
65
 
@@ -121,15 +140,160 @@ function runClients(flags) {
121
140
  }
122
141
  console.log(root);
123
142
  for (const client of scanClients(root)) {
124
- const supported = ['retail', 'classic', 'titan'].includes(client.id);
125
- const installed = exists(path.join(client.addonsDir, addonFolderName));
126
- console.log(` ${client.id.padEnd(11)} ${client.folder.padEnd(16)} `
127
- + `${installed ? 'addon installed' : 'addon missing'}`.padEnd(18)
128
- + `${supported ? '' : '(not supported by the addon)'}`);
143
+ const version = client.version ? `v${client.version}` : 'unknown version';
144
+ const state = !client.toc
145
+ ? 'not served by the addon'
146
+ : (client.installed ? 'addon installed' : 'addon missing');
147
+ console.log(` ${client.id.padEnd(12)} ${client.folder.padEnd(18)} ${version.padEnd(18)} ${state}`);
148
+ }
149
+ return 0;
150
+ }
151
+
152
+ /** `lycheedev instances`: which game clients are running right now. */
153
+ function runInstances(flags) {
154
+ const config = loadConfig();
155
+ const instances = findInstances({ pythonBin: flags.python || null });
156
+ if (instances.length === 0) {
157
+ console.log('no World of Warcraft instance is running');
158
+ return 0;
159
+ }
160
+ const pinned = matchPinned(instances, config.pinnedInstance);
161
+ console.log('running instances:');
162
+ instances.forEach((instance, index) => {
163
+ console.log(formatInstance(instance, index));
164
+ });
165
+ const supported = instances.filter((item) => item.supported);
166
+ console.log('');
167
+ if (pinned) {
168
+ const label = pinned.flavorLabel || pinned.flavorFolder;
169
+ console.log(`pinned: ${label} (pid ${pinned.pid}), pid ${pinned.pid} - commands target it`);
170
+ } else if (config.pinnedInstance) {
171
+ console.log('pinned client is not running; run `lycheedev use` to repin');
172
+ }
173
+ if (supported.length === 0) {
174
+ console.log('none of these builds are served by the addon');
175
+ } else if (!pinned && supported.length > 1) {
176
+ console.log('several clients are running: `lycheedev use <index>` pins one, '
177
+ + 'or pass --instance <index> per command');
178
+ } else if (!pinned) {
179
+ console.log('commands target this instance automatically');
129
180
  }
130
181
  return 0;
131
182
  }
132
183
 
184
+ /**
185
+ * Resolve the live game window a command should type into.
186
+ *
187
+ * Precedence: an explicit `--hwnd`/`--pid`, then `--instance <index>`, then the
188
+ * saved pin, then `--client`, and finally the only running instance when there
189
+ * is exactly one. `WowClassic.exe` looks identical for every classic build, so
190
+ * an ambiguous choice fails loudly instead of typing into the wrong game.
191
+ */
192
+ function resolveRuntime(flags) {
193
+ if (flags.hwnd || flags.pid) {
194
+ return { hwnd: flags.hwnd, pid: flags.pid };
195
+ }
196
+ const instances = findInstances({ pythonBin: flags.python || null });
197
+ const supported = instances.filter((item) => item.supported);
198
+
199
+ if (flags.instance !== undefined) {
200
+ const chosen = supported[Number(flags.instance)];
201
+ if (!chosen) {
202
+ console.error(`error: --instance ${flags.instance} is out of range (0..${supported.length - 1})`);
203
+ supported.forEach((item, index) => console.log(formatInstance(item, index)));
204
+ return { error: true };
205
+ }
206
+ return toTarget(chosen);
207
+ }
208
+
209
+ if (!flags.client) {
210
+ const config = loadConfig();
211
+ const pinned = matchPinned(instances, config.pinnedInstance);
212
+ if (pinned) {
213
+ return toTarget(pinned);
214
+ }
215
+ if (config.pinnedInstance) {
216
+ console.error('error: the pinned client is not running; run `lycheedev use` again '
217
+ + 'or pass --instance <index>');
218
+ }
219
+ }
220
+
221
+ const resolved = resolveInstance(instances, { clientId: flags.client || null, index: null });
222
+ if (resolved.error) {
223
+ console.error(`error: ${resolved.error}`);
224
+ if (resolved.candidates) {
225
+ resolved.candidates.forEach((item, index) => console.log(formatInstance(item, index)));
226
+ }
227
+ if (supported.length === 0 && instances.length > 0) {
228
+ instances.forEach((item, index) => console.log(formatInstance(item, index)));
229
+ }
230
+ return { error: true };
231
+ }
232
+ return toTarget(resolved.instance);
233
+ }
234
+
235
+ function toTarget(instance) {
236
+ return {
237
+ hwnd: instance.hwnd ? `0x${instance.hwnd.toString(16)}` : null,
238
+ pid: instance.pid ? String(instance.pid) : null,
239
+ instance,
240
+ };
241
+ }
242
+
243
+ /**
244
+ * `lycheedev use [index]`: keep one running client as the default target.
245
+ *
246
+ * Stores only the build and the instance ordinal, so the pin survives a
247
+ * restart even though the pid and window handle do not.
248
+ */
249
+ function runUse(flags, rest) {
250
+ const instances = findInstances({ pythonBin: flags.python || null });
251
+ const supported = instances.filter((item) => item.supported);
252
+
253
+ if (flags.clear) {
254
+ updateConfig({ pinnedInstance: null });
255
+ console.log('cleared the pinned client');
256
+ return 0;
257
+ }
258
+ if (supported.length === 0) {
259
+ console.error('error: no supported World of Warcraft instance is running');
260
+ if (instances.length > 0) {
261
+ instances.forEach((item, index) => console.log(formatInstance(item, index)));
262
+ }
263
+ return 1;
264
+ }
265
+
266
+ const requested = rest.length > 0 ? Number(rest[0]) : (flags.instance !== undefined ? Number(flags.instance) : null);
267
+ let chosen;
268
+ let ordinal;
269
+ if (requested !== null) {
270
+ chosen = supported[requested];
271
+ if (!chosen) {
272
+ console.error(`error: instance ${requested} is out of range (0..${supported.length - 1})`);
273
+ supported.forEach((item, index) => console.log(formatInstance(item, index)));
274
+ return 1;
275
+ }
276
+ ordinal = supported
277
+ .slice(0, requested)
278
+ .filter((item) => item.flavorId === chosen.flavorId)
279
+ .length;
280
+ } else {
281
+ if (supported.length > 1) {
282
+ console.error('error: several clients are running; pass an index, e.g. `lycheedev use 0`');
283
+ supported.forEach((item, index) => console.log(formatInstance(item, index)));
284
+ return 1;
285
+ }
286
+ [chosen] = supported;
287
+ ordinal = 0;
288
+ }
289
+
290
+ updateConfig({ pinnedInstance: { flavor: chosen.flavorId, ordinal } });
291
+ const label = chosen.flavorLabel || chosen.flavorFolder;
292
+ console.log(`pinned ${label}${ordinal > 0 ? ` instance ${ordinal}` : ''} (pid ${chosen.pid})`);
293
+ console.log('commands now target it; pass --instance <index> to override');
294
+ return 0;
295
+ }
296
+
133
297
  function main(argv) {
134
298
  const { flags, rest } = parse(argv);
135
299
  const command = rest.shift();
@@ -161,6 +325,10 @@ function main(argv) {
161
325
  return runDoctor({ flags });
162
326
  case 'clients':
163
327
  return runClients(flags);
328
+ case 'instances':
329
+ return runInstances(flags);
330
+ case 'use':
331
+ return runUse(flags, rest);
164
332
  case 'help':
165
333
  console.log(HELP);
166
334
  return 0;
@@ -178,6 +346,17 @@ function main(argv) {
178
346
  // AddOns folder that contains it.
179
347
  if (client.addonsDir) forwarded.push('--install-dir', path.join(client.addonsDir, addonFolderName));
180
348
 
349
+ // Commands that type into the game must target a live window, and the
350
+ // executable name cannot tell two instances apart, so resolve which running
351
+ // instance to use before forwarding.
352
+ const runtime = ['send', 'capture', 'run', 'bugs'].includes(command)
353
+ ? resolveRuntime(flags)
354
+ : null;
355
+ if (runtime && runtime.error) return 1;
356
+ const live = runtime && runtime.hwnd
357
+ ? { hwnd: runtime.hwnd, pid: runtime.pid }
358
+ : null;
359
+
181
360
  switch (command) {
182
361
  case 'send': {
183
362
  const text = rest.join(' ');
@@ -185,39 +364,47 @@ function main(argv) {
185
364
  console.error('error: send needs the command text, e.g. `lycheedev send "/dev auto status x"`');
186
365
  return 1;
187
366
  }
188
- return forward(['send', ...targetArgs(client), '--text', text, ...passthrough(flags)]);
367
+ if (!live) return 1;
368
+ return forward(['send', ...targetArgs(live), '--text', text, ...passthrough(flags)]);
189
369
  }
190
370
  case 'capture':
191
- return forward(['capture', ...targetArgs(client), ...passthrough(flags)]);
371
+ if (!live) return 1;
372
+ return forward(['capture', ...targetArgs(live), ...passthrough(flags)]);
192
373
  case 'run':
193
374
  if (!flags.task) {
194
375
  console.error('error: run needs --task <id>');
195
376
  return 1;
196
377
  }
378
+ if (!live) return 1;
197
379
  if (!client.svPath) {
198
380
  console.error('error: no SavedVariables path recorded for this client; re-run `lycheedev install`');
199
381
  return 1;
200
382
  }
201
- return forward(['run', ...targetArgs(client), '--task', flags.task, '--sv', client.svPath,
383
+ return forward(['run', ...targetArgs(live), '--task', flags.task, '--sv', client.svPath,
202
384
  ...passthrough(flags)]);
203
385
  case 'bugs':
204
386
  if (!flags.count) {
205
387
  console.error('error: bugs needs --count <1-100>');
206
388
  return 1;
207
389
  }
390
+ if (!live) return 1;
208
391
  if (!client.svPath) {
209
392
  console.error('error: no SavedVariables path recorded for this client; re-run `lycheedev install`');
210
393
  return 1;
211
394
  }
212
- return forward(['bugs', ...targetArgs(client), '--count', String(flags.count), '--sv', client.svPath,
395
+ return forward(['bugs', ...targetArgs(live), '--count', String(flags.count), '--sv', client.svPath,
213
396
  ...passthrough(flags)]);
214
- case 'ack':
397
+ case 'ack': {
215
398
  if (!flags.ticket || !flags.status) {
216
399
  console.error('error: ack needs --ticket <t> --status received|failed');
217
400
  return 1;
218
401
  }
219
- return forward(['ack', ...targetArgs(client), '--ticket', flags.ticket,
402
+ // An acknowledgement also has to reach a live window.
403
+ const ackTarget = resolveRuntime(flags);
404
+ if (ackTarget.error) return 1;
405
+ return forward(['ack', ...targetArgs(ackTarget), '--ticket', flags.ticket,
220
406
  '--status', flags.status, ...passthrough(flags)]);
407
+ }
221
408
  case 'task': {
222
409
  const sub = rest.shift();
223
410
  if (!sub) {
@@ -277,7 +464,7 @@ function main(argv) {
277
464
  // These are either handled by the wrapper itself or are global python
278
465
  // options that `forward()` places before the subcommand.
279
466
  const handled = ['wow-root', 'client', 'python', 'force', 'reset-registry', 'task', 'count',
280
- 'ticket', 'status', 'json', 'help', 'version', 'data-dir', 'installation'];
467
+ 'ticket', 'status', 'json', 'help', 'version', 'data-dir', 'installation', 'instance'];
281
468
  for (const [name, value] of Object.entries(all)) {
282
469
  if (handled.includes(name)) continue;
283
470
  if (value === true) out.push(`--${name}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lycheedev",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "lycheedev: install the World of Warcraft inspection addon, its in-game automation tooling, and drive it from the command line.",
5
5
  "keywords": [
6
6
  "wow",
package/src/addon.js CHANGED
@@ -25,12 +25,15 @@ export function payloadVersion() {
25
25
  }
26
26
  }
27
27
 
28
- /** Version of whatever is currently installed, if any. */
29
- export function installedVersion(addonsDir) {
28
+ /** Version of whatever is currently installed for one build's catalog. */
29
+ export function installedVersion(addonsDir, toc = null) {
30
30
  const target = addonTargetDir(addonsDir);
31
- for (const toc of [`${addonFolderName}_Mainline.toc`, `${addonFolderName}_Mists.toc`,
32
- `${addonFolderName}_Wrath.toc`]) {
33
- const file = path.join(target, toc);
31
+ const catalogs = toc
32
+ ? [toc]
33
+ : [`${addonFolderName}_Mainline.toc`, `${addonFolderName}_Mists.toc`,
34
+ `${addonFolderName}_Wrath.toc`];
35
+ for (const name of catalogs) {
36
+ const file = path.join(target, name);
34
37
  if (!exists(file)) continue;
35
38
  const match = fs.readFileSync(file, 'utf8').match(/^##\s*Version:\s*(.+)$/m);
36
39
  if (match) return match[1].trim();
@@ -55,11 +58,16 @@ export function countFiles(dir) {
55
58
  * cannot linger. `auto.lua` is local task data, so it is preserved when the
56
59
  * caller asks for it: the empty shipped registry must not wipe pending work.
57
60
  */
58
- export function installAddon(addonsDir, { preserveRegistry = true } = {}) {
61
+ export function installAddon(addonsDir, { preserveRegistry = true, toc = null } = {}) {
59
62
  const source = vendoredAddonRoot();
60
63
  if (!exists(source)) {
61
64
  return { ok: false, error: 'vendored addon payload is missing; reinstall the package' };
62
65
  }
66
+ // Refuse to write a build the addon has no catalog for: the game would load
67
+ // nothing and report only a silent "out of date" addon.
68
+ if (toc && !exists(path.join(source, toc))) {
69
+ return { ok: false, error: `the payload has no ${toc}` };
70
+ }
63
71
  const target = addonTargetDir(addonsDir);
64
72
 
65
73
  let savedRegistry = null;
package/src/config.js CHANGED
@@ -8,6 +8,10 @@ const EMPTY = {
8
8
  pythonBin: null,
9
9
  installedAt: null,
10
10
  packageVersion: null,
11
+ // Which running client commands should target. `flavor` pins a build,
12
+ // `ordinal` picks among several instances of that same build. Window
13
+ // handles and pids change every launch, so only these stable fields persist.
14
+ pinnedInstance: null,
11
15
  };
12
16
 
13
17
  export function loadConfig() {
package/src/doctor.js CHANGED
@@ -5,9 +5,9 @@ import path from 'node:path';
5
5
 
6
6
  import { installedVersion, payloadVersion } from './addon.js';
7
7
  import { loadConfig } from './config.js';
8
- import { addonFolderName, configPath, dataDir, exists, pythonDepsDir, skillTargetDir } from './paths.js';
8
+ import { configPath, dataDir, exists, pythonDepsDir, skillTargetDir } from './paths.js';
9
9
  import { automationScript, findPython, pythonEnv } from './python.js';
10
- import { findSavedVariablesCandidates, scanClients } from './wow.js';
10
+ import { findInstances, findSavedVariablesCandidates, scanClients } from './wow.js';
11
11
 
12
12
  const OK = 'ok ';
13
13
  const WARN = 'warn';
@@ -66,16 +66,22 @@ export function runDoctor({ flags }) {
66
66
  results.push(line(WARN, 'wow root', 'not configured; run `lycheedev install --wow-root <path>`'));
67
67
  } else {
68
68
  results.push(line(OK, 'wow root', roots[0]));
69
- for (const client of scanClients(roots[0])) {
70
- if (!['retail', 'classic', 'titan'].includes(client.id)) continue;
71
- const target = path.join(client.addonsDir, addonFolderName);
72
- if (!exists(target)) {
69
+ const clients = scanClients(roots[0]);
70
+ for (const client of clients) {
71
+ const version = client.version ? `v${client.version}` : 'unknown version';
72
+ if (!client.toc) {
73
+ // Present but intentionally not served: say so instead of hiding it.
74
+ results.push(line(OK, `build (${client.id})`, `${client.folder} ${version} - not served by the addon`));
75
+ continue;
76
+ }
77
+ const target = client.installedDir;
78
+ if (!client.installed) {
73
79
  results.push(line(WARN, `addon (${client.id})`, `not installed in ${client.addonsDir}`));
74
80
  continue;
75
81
  }
76
82
  const current = installedVersion(client.addonsDir);
77
83
  const shipped = payloadVersion();
78
- const detail = `${target} (installed ${current || '?'}, package ${shipped || '?'})`;
84
+ const detail = `${client.folder} ${version} (installed ${current || '?'}, package ${shipped || '?'})`;
79
85
  results.push(current && shipped && current !== shipped
80
86
  ? line(WARN, `addon (${client.id})`, `${detail} - run \`lycheedev update\``)
81
87
  : line(OK, `addon (${client.id})`, detail));
@@ -87,6 +93,25 @@ export function runDoctor({ flags }) {
87
93
  }
88
94
  }
89
95
 
96
+ // Which clients are running decides what `send`/`run` can target.
97
+ const instances = findInstances({ pythonBin: python ? python.bin : null });
98
+ const supportedRunning = instances.filter((item) => item.supported);
99
+ if (instances.length === 0) {
100
+ results.push(line(OK, 'running clients', 'none'));
101
+ } else {
102
+ for (const [index, instance] of instances.entries()) {
103
+ const label = instance.flavorLabel || instance.flavorFolder || 'unknown';
104
+ const detail = `${label} pid=${instance.pid}`
105
+ + `${instance.hwnd ? ` hwnd=0x${instance.hwnd.toString(16)}` : ''}`
106
+ + `${instance.supported ? '' : ' (not served by the addon)'}`;
107
+ results.push(line(instance.supported ? OK : WARN, `running [${index}]`, detail));
108
+ }
109
+ if (supportedRunning.length > 1) {
110
+ results.push(line(WARN, 'instance choice',
111
+ 'several clients are running; pass `--instance <index>` to target one'));
112
+ }
113
+ }
114
+
90
115
  console.log(`\nconfig: ${configPath()}`);
91
116
  console.log(`data : ${dataDir()}`);
92
117
  if (python) {
package/src/install.js CHANGED
@@ -4,7 +4,7 @@ import path from 'node:path';
4
4
 
5
5
  import { installAddon, installedVersion, payloadVersion } from './addon.js';
6
6
  import { loadConfig, setClient, updateConfig } from './config.js';
7
- import { addonFolderName, exists } from './paths.js';
7
+ import { exists } from './paths.js';
8
8
  import { depsInstalled, findPython, installDeps } from './python.js';
9
9
  import { installSkill } from './skill.js';
10
10
  import { detectWowRoots, findSavedVariablesCandidates, scanClients } from './wow.js';
@@ -82,8 +82,10 @@ export function runInstall({ flags }) {
82
82
  let defaultClient = config.defaultClient || null;
83
83
 
84
84
  for (const client of resolved.clients) {
85
- if (!['retail', 'classic', 'titan'].includes(client.id)) {
86
- console.log(`\n${client.label}: skipped (unsupported by the addon)`);
85
+ // A build without a catalog is reported, not silently dropped: the folder
86
+ // still exists and the user should know why nothing was installed there.
87
+ if (!client.toc) {
88
+ console.log(`\n${client.label} (${client.folder}): not served by the addon, skipped`);
87
89
  continue;
88
90
  }
89
91
  step(`${client.label}: installing addon into ${client.folder}`, () => {
@@ -92,12 +94,15 @@ export function runInstall({ flags }) {
92
94
  return { ok: false, skipped: true };
93
95
  }
94
96
  const before = installedVersion(client.addonsDir);
95
- const installed = installAddon(client.addonsDir, { preserveRegistry: !flags['reset-registry'] });
97
+ const installed = installAddon(client.addonsDir, {
98
+ preserveRegistry: !flags['reset-registry'],
99
+ toc: client.toc,
100
+ });
96
101
  if (!installed.ok) {
97
102
  console.log(` error: ${installed.error}`);
98
103
  return installed;
99
104
  }
100
- console.log(` ${addonFolderName} -> ${installed.target}`);
105
+ console.log(` ${client.toc} -> ${installed.target}`);
101
106
  console.log(` files: ${installed.files}, version: ${before ? `${before} -> ` : ''}${installed.version}`);
102
107
  if (installed.keptRegistry) console.log(' kept the existing task registry (local task data)');
103
108
  addonResults.push({ client: client.id, ...installed });
@@ -107,6 +112,7 @@ export function runInstall({ flags }) {
107
112
  const candidates = findSavedVariablesCandidates(resolved.root, client.folder);
108
113
  setClient(nextConfig, client.id, {
109
114
  flavorFolder: client.folder,
115
+ toc: client.toc,
110
116
  addonsDir: client.addonsDir,
111
117
  svPath: candidates[0] ? candidates[0].path : null,
112
118
  installedAt: new Date().toISOString(),
@@ -0,0 +1,120 @@
1
+ """List running World of Warcraft instances as JSON.
2
+
3
+ The executable name cannot identify a build: Blizzard ships every non-retail
4
+ client as ``WowClassic.exe``. The install path can, because each build lives in
5
+ a ``_flavor_`` directory. Visible top-level window handles are attached so the
6
+ caller can tell same-build instances apart.
7
+
8
+ Read-only: this opens no process, only enumerates windows and process metadata.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import ctypes
14
+ import json
15
+ import os
16
+ import sys
17
+ from ctypes import wintypes
18
+
19
+ user32 = ctypes.windll.user32
20
+ kernel32 = ctypes.windll.kernel32
21
+
22
+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
23
+ ERROR_INSUFFICIENT_BUFFER = 122
24
+
25
+ user32.EnumWindows.restype = wintypes.BOOL
26
+ user32.EnumWindows.argtypes = [ctypes.c_void_p, wintypes.LPARAM]
27
+ user32.IsWindowVisible.restype = wintypes.BOOL
28
+ user32.GetWindowTextLengthW.restype = ctypes.c_int
29
+ user32.GetWindowTextW.restype = ctypes.c_int
30
+ user32.GetWindowThreadProcessId.restype = wintypes.DWORD
31
+ user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
32
+
33
+ kernel32.OpenProcess.restype = wintypes.HANDLE
34
+ kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
35
+ kernel32.QueryFullProcessImageNameW.restype = wintypes.BOOL
36
+ kernel32.QueryFullProcessImageNameW.argtypes = [
37
+ wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)]
38
+ kernel32.CloseHandle.restype = wintypes.BOOL
39
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
40
+
41
+ EnumWindowsProc = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
42
+
43
+ FLAVOR_LABELS = {
44
+ "_retail_": ("retail", "Retail"),
45
+ "_classic_": ("classic", "Classic"),
46
+ "_classic_titan_": ("titan", "Classic Titan"),
47
+ "_classic_era_": ("classicEra", "Classic Era"),
48
+ "_anniversary_": ("anniversary", "Anniversary"),
49
+ "_beta_": ("beta", "Beta"),
50
+ }
51
+
52
+ SUPPORTED_EXE = {"wow.exe", "wowclassic.exe", "wowb.exe"}
53
+
54
+
55
+ def process_image(pid: int) -> str | None:
56
+ handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
57
+ if not handle:
58
+ return None
59
+ try:
60
+ size = wintypes.DWORD(32768)
61
+ buffer = ctypes.create_unicode_buffer(size.value)
62
+ if not kernel32.QueryFullProcessImageNameW(handle, 0, buffer, ctypes.byref(size)):
63
+ return None
64
+ return buffer.value or None
65
+ finally:
66
+ kernel32.CloseHandle(handle)
67
+
68
+
69
+ def visible_windows() -> dict[int, dict]:
70
+ found: dict[int, dict] = {}
71
+
72
+ def callback(hwnd, _lparam):
73
+ if not user32.IsWindowVisible(hwnd):
74
+ return True
75
+ pid = wintypes.DWORD(0)
76
+ user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
77
+ length = user32.GetWindowTextLengthW(hwnd)
78
+ if length <= 0:
79
+ return True
80
+ buffer = ctypes.create_unicode_buffer(length + 1)
81
+ user32.GetWindowTextW(hwnd, buffer, length + 1)
82
+ found.setdefault(pid.value, {"hwnd": int(hwnd), "title": buffer.value})
83
+ return True
84
+
85
+ user32.EnumWindows(EnumWindowsProc(callback), 0)
86
+ return found
87
+
88
+
89
+ def main() -> int:
90
+ windows = visible_windows()
91
+ instances = []
92
+
93
+ for pid in windows:
94
+ image = process_image(pid)
95
+ if not image:
96
+ continue
97
+ base = os.path.basename(image).lower()
98
+ if base not in SUPPORTED_EXE:
99
+ continue
100
+ parts = image.replace("/", os.sep).split(os.sep)
101
+ folder = next((part for part in parts if part.startswith("_") and part.endswith("_")), None)
102
+ flavor_id, label = FLAVOR_LABELS.get(folder, (None, None))
103
+ instances.append({
104
+ "pid": pid,
105
+ "exe": os.path.basename(image),
106
+ "exePath": image,
107
+ "flavorFolder": folder,
108
+ "flavorId": flavor_id,
109
+ "flavorLabel": label,
110
+ "hwnd": windows[pid]["hwnd"],
111
+ "title": windows[pid]["title"],
112
+ })
113
+
114
+ instances.sort(key=lambda item: (item.get("flavorId") or "", item["pid"]))
115
+ print(json.dumps(instances, ensure_ascii=False))
116
+ return 0
117
+
118
+
119
+ if __name__ == "__main__":
120
+ sys.exit(main())
package/src/python.js CHANGED
@@ -61,6 +61,10 @@ export function pythonEnv() {
61
61
  ...process.env,
62
62
  PYTHONPATH: existing ? `${deps}${path.delimiter}${existing}` : deps,
63
63
  PYTHONDONTWRITEBYTECODE: '1',
64
+ // Player names, window titles and zone names are not ASCII; without this
65
+ // the helper's stdout is encoded with the console code page and comes back
66
+ // as mojibake.
67
+ PYTHONIOENCODING: 'utf-8',
64
68
  };
65
69
  }
66
70
 
package/src/wow.js CHANGED
@@ -1,21 +1,71 @@
1
- /** Locate World of Warcraft installations and their client flavors. */
1
+ /** Locate World of Warcraft installations, their builds, and running instances. */
2
2
 
3
+ import { execFileSync } from 'node:child_process';
3
4
  import fs from 'node:fs';
4
5
  import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
5
7
 
6
8
  import { addonFolderName, exists, isDir } from './paths.js';
7
9
 
10
+ const here = path.dirname(fileURLToPath(import.meta.url));
11
+ const instancesScript = path.join(here, 'py', 'instances.py');
12
+
8
13
  /**
9
- * Flavor folders the addon supports. `id` is the stable key used by the CLI and
10
- * by the Python automation profile; `folder` is what Blizzard names it.
14
+ * Locate a Python 3 interpreter.
15
+ *
16
+ * This lives here instead of `python.js` on purpose: `python.js` only depends
17
+ * on `paths.js`, and importing it from here would create a cycle.
18
+ */
19
+ export function findPythonBin() {
20
+ if (process.env.LYCHEEDEV_PYTHON) return process.env.LYCHEEDEV_PYTHON;
21
+ const candidates = process.platform === 'win32'
22
+ ? ['python', 'python3', 'py']
23
+ : ['python3', 'python'];
24
+ for (const candidate of candidates) {
25
+ try {
26
+ const out = execFileSync(candidate, ['-c', 'import sys; print(sys.version_info[0])'], {
27
+ encoding: 'utf8', windowsHide: true, timeout: 15000,
28
+ });
29
+ if (out.trim().startsWith('3')) return candidate;
30
+ } catch {
31
+ // try the next candidate
32
+ }
33
+ }
34
+ return null;
35
+ }
36
+
37
+ /**
38
+ * Every flavor folder Blizzard ships. `id` is the stable key used by the CLI;
39
+ * `folder` is what Blizzard names the directory; `toc` is the addon catalog
40
+ * that serves it, or null when the addon does not support that build.
41
+ *
42
+ * The Titan folder is `_classic_titan_`, which holds client 3.80.2 — the build
43
+ * the addon's Wrath TOC targets (Interface 38002). The previous value
44
+ * `_classic_arena_` does not exist, so an installed Titan client was silently
45
+ * skipped by both `install` and `doctor`.
11
46
  */
12
47
  export const CLIENT_FLAVORS = [
13
- { id: 'retail', folder: '_retail_', label: 'Retail (Midnight)' },
14
- { id: 'classic', folder: '_classic_', label: 'Classic (Mists)' },
15
- { id: 'titan', folder: '_classic_arena', label: 'Classic Titan (Wrath)' },
16
- { id: 'classicEra', folder: '_classic_era_', label: 'Classic Era' },
48
+ { id: 'retail', folder: '_retail_', label: 'Retail', exe: 'Wow.exe', toc: 'Lychee Dev_Mainline.toc' },
49
+ { id: 'classic', folder: '_classic_', label: 'Classic', exe: 'WowClassic.exe', toc: 'Lychee Dev_Mists.toc' },
50
+ { id: 'titan', folder: '_classic_titan_', label: 'Classic Titan', exe: 'WowClassic.exe', toc: 'Lychee Dev_Wrath.toc' },
51
+ { id: 'classicEra', folder: '_classic_era_', label: 'Classic Era', exe: 'WowClassic.exe', toc: null },
52
+ { id: 'anniversary', folder: '_anniversary_', label: 'Anniversary', exe: 'WowClassic.exe', toc: null },
53
+ { id: 'beta', folder: '_beta_', label: 'Beta', exe: 'WowB.exe', toc: null },
17
54
  ];
18
55
 
56
+ /** Flavors with an addon catalog, i.e. the builds the addon can install into. */
57
+ export function supportedFlavors() {
58
+ return CLIENT_FLAVORS.filter((flavor) => flavor.toc);
59
+ }
60
+
61
+ export function flavorById(id) {
62
+ return CLIENT_FLAVORS.find((flavor) => flavor.id === id) || null;
63
+ }
64
+
65
+ export function flavorByFolder(folder) {
66
+ return CLIENT_FLAVORS.find((flavor) => flavor.folder === folder) || null;
67
+ }
68
+
19
69
  const KNOWN_ROOTS = {
20
70
  win32: [
21
71
  'C:\\Program Files (x86)\\World of Warcraft',
@@ -34,7 +84,7 @@ function looksLikeWowRoot(dir) {
34
84
  return CLIENT_FLAVORS.some((flavor) => isDir(path.join(dir, flavor.folder)));
35
85
  }
36
86
 
37
- /** Directories that contain at least one known flavor folder. */
87
+ /** Roots on this machine that contain at least one known flavor folder. */
38
88
  export function detectWowRoots() {
39
89
  const candidates = [];
40
90
  const seen = new Set();
@@ -52,24 +102,41 @@ export function detectWowRoots() {
52
102
  return candidates;
53
103
  }
54
104
 
105
+ /** Client version, read from the executable's own file metadata. */
106
+ function exeVersion(exePath) {
107
+ try {
108
+ const out = execFileSync('powershell', [
109
+ '-NoProfile', '-Command',
110
+ `(Get-Item -LiteralPath '${exePath.replace(/'/g, "''")}').VersionInfo.FileVersion`,
111
+ ], { encoding: 'utf8', windowsHide: true, timeout: 20000 });
112
+ const value = out.replace(/^\uFEFF/, '').trim();
113
+ return value || null;
114
+ } catch {
115
+ return null;
116
+ }
117
+ }
118
+
55
119
  /**
56
- * Describe the flavors present under a root. A given root may hold several
57
- * (retail + classic), and each gets its own AddOns directory.
120
+ * Describe every flavor present under a root, including builds the addon does
121
+ * not serve, so `doctor` can explain them instead of ignoring them silently.
58
122
  */
59
123
  export function scanClients(wowRoot) {
60
124
  const found = [];
61
125
  for (const flavor of CLIENT_FLAVORS) {
62
126
  const flavorDir = path.join(wowRoot, flavor.folder);
63
- const addonsDir = path.join(flavorDir, 'Interface', 'AddOns');
64
127
  if (!isDir(flavorDir)) continue;
128
+ const addonsDir = path.join(flavorDir, 'Interface', 'AddOns');
129
+ const exePath = path.join(flavorDir, flavor.exe);
130
+ const hasExe = exists(exePath);
65
131
  found.push({
66
132
  ...flavor,
67
133
  flavorDir,
68
134
  addonsDir,
69
135
  addonsDirExists: isDir(addonsDir),
70
- installed: exists(path.join(addonsDir, addonFolderName, `${addonFolderName}_Mainline.toc`))
71
- || exists(path.join(addonsDir, addonFolderName, `${addonFolderName}_Mists.toc`))
72
- || exists(path.join(addonsDir, addonFolderName, `${addonFolderName}_Wrath.toc`)),
136
+ exePath: hasExe ? exePath : null,
137
+ version: hasExe ? exeVersion(exePath) : null,
138
+ installedDir: path.join(addonsDir, addonFolderName),
139
+ installed: flavor.toc ? exists(path.join(addonsDir, addonFolderName, flavor.toc)) : false,
73
140
  });
74
141
  }
75
142
  return found;
@@ -95,16 +162,97 @@ export function findSavedVariablesCandidates(wowRoot, flavorFolder) {
95
162
  return results.sort((a, b) => b.mtime - a.mtime);
96
163
  }
97
164
 
98
- /** `Lychee Dev_Mainline.toc` style file for a flavor. */
99
- export function tocSuffixFor(flavorId) {
100
- switch (flavorId) {
101
- case 'retail':
102
- return 'Mainline';
103
- case 'classic':
104
- return 'Mists';
105
- case 'titan':
106
- return 'Wrath';
107
- default:
108
- return null;
165
+ /**
166
+ * Running game instances.
167
+ *
168
+ * Window handles need the Win32 enumeration API, which Node cannot call, so a
169
+ * small read-only helper does it: `src/py/instances.py` enumerates visible
170
+ * windows and reads process image paths without opening a process.
171
+ *
172
+ * Blizzard ships every non-retail client as `WowClassic.exe`, so the process
173
+ * name cannot identify a build; the executable path can, because each install
174
+ * lives under a `_flavor_` directory.
175
+ */
176
+ export function findInstances({ pythonBin = null } = {}) {
177
+ if (process.platform !== 'win32') return [];
178
+ const python = pythonBin || findPythonBin();
179
+ if (!python || !exists(instancesScript)) return [];
180
+
181
+ let rows = [];
182
+ try {
183
+ const out = execFileSync(python, ['-B', instancesScript], {
184
+ encoding: 'utf8',
185
+ windowsHide: true,
186
+ timeout: 30000,
187
+ env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
188
+ });
189
+ const parsed = JSON.parse(out.replace(/^\uFEFF/, '') || '[]');
190
+ rows = Array.isArray(parsed) ? parsed : [parsed];
191
+ } catch {
192
+ return [];
193
+ }
194
+
195
+ return rows
196
+ .map((row) => {
197
+ const flavor = flavorByFolder(row.flavorFolder);
198
+ return { ...row, supported: Boolean(flavor && flavor.toc) };
199
+ })
200
+ .sort((a, b) => (a.flavorId || '').localeCompare(b.flavorId || '') || a.pid - b.pid);
201
+ }
202
+
203
+ /**
204
+ * Choose which running instance a command targets.
205
+ *
206
+ * One instance needs no flag. Several instances of different builds are picked
207
+ * with `--client`. Several instances of the *same* build are genuinely
208
+ * ambiguous, so the caller must pass `--instance <index>` after seeing the
209
+ * table; guessing would type into the wrong game window.
210
+ */
211
+ export function resolveInstance(instances, { clientId = null, index = null } = {}) {
212
+ const supported = instances.filter((item) => item.supported);
213
+ if (supported.length === 0) {
214
+ return { error: 'no supported World of Warcraft instance is running' };
215
+ }
216
+ if (index !== null && index !== undefined) {
217
+ const chosen = supported[Number(index)];
218
+ if (!chosen) {
219
+ return { error: `--instance ${index} is out of range (0..${supported.length - 1})` };
220
+ }
221
+ return { instance: chosen };
222
+ }
223
+ const candidates = clientId ? supported.filter((item) => item.flavorId === clientId) : supported;
224
+ if (candidates.length === 0) {
225
+ return { error: `no running instance for client '${clientId}'` };
226
+ }
227
+ if (candidates.length === 1) {
228
+ return { instance: candidates[0] };
109
229
  }
230
+ return {
231
+ error: `${candidates.length} instances match; pass --instance <index>`,
232
+ candidates,
233
+ };
234
+ }
235
+
236
+ /**
237
+ * Find the instance a saved pin refers to.
238
+ *
239
+ * A pin stores the build plus which instance of that build, because window
240
+ * handles and pids change every launch. The number shown to the user counts
241
+ * among supported instances, so the same index works here.
242
+ */
243
+ export function matchPinned(instances, pin) {
244
+ if (!pin || !pin.flavor) return null;
245
+ const supported = instances.filter((item) => item.supported);
246
+ const ofFlavor = supported.filter((item) => item.flavorId === pin.flavor);
247
+ if (ofFlavor.length === 0) return null;
248
+ return ofFlavor[pin.ordinal || 0] || ofFlavor[0];
249
+ }
250
+
251
+ export function formatInstance(instance, index) {
252
+ const flavor = instance.flavorLabel || instance.flavorFolder || 'unknown';
253
+ const suffix = instance.supported ? '' : ' (the addon does not serve this build)';
254
+ const hwnd = instance.hwnd ? `0x${instance.hwnd.toString(16)}` : '-';
255
+ const title = instance.title ? ` "${instance.title}"` : '';
256
+ return ` [${index}] ${flavor.padEnd(14)} pid=${String(instance.pid).padEnd(8)} `
257
+ + `hwnd=${hwnd.padEnd(12)}${title}${suffix}`;
110
258
  }
@@ -6,7 +6,7 @@
6
6
  ## Notes-zhCN: 运行 Lua,检查对象与事件,追踪函数并查看错误。
7
7
  ## Notes-zhTW: 執行 Lua,檢查物件與事件,追蹤函式並檢視錯誤。
8
8
  ## Author: Follen
9
- ## Version: 1.0.2
9
+ ## Version: 1.0.4
10
10
  ## Dependencies: !BugGrabber
11
11
  ## SavedVariables: LycheeDevDB, DumperDB
12
12
  ## IconTexture: Interface\AddOns\Lychee Dev\Media\Logo.png
@@ -6,7 +6,7 @@
6
6
  ## Notes-zhCN: 运行 Lua,检查对象与事件,追踪函数并查看错误。
7
7
  ## Notes-zhTW: 執行 Lua,檢查物件與事件,追蹤函式並檢視錯誤。
8
8
  ## Author: Follen
9
- ## Version: 1.0.2
9
+ ## Version: 1.0.4
10
10
  ## Dependencies: !BugGrabber
11
11
  ## SavedVariables: LycheeDevDB, DumperDB
12
12
  ## IconTexture: Interface\AddOns\Lychee Dev\Media\Logo.png
@@ -6,7 +6,7 @@
6
6
  ## Notes-zhCN: 运行 Lua,检查对象与事件,追踪函数并查看错误。
7
7
  ## Notes-zhTW: 執行 Lua,檢查物件與事件,追蹤函式並檢視錯誤。
8
8
  ## Author: Follen
9
- ## Version: 1.0.2
9
+ ## Version: 1.0.4
10
10
  ## Dependencies: !BugGrabber
11
11
  ## SavedVariables: LycheeDevDB, DumperDB
12
12
  ## IconTexture: Interface\AddOns\Lychee Dev\Media\Logo.png
@@ -47,7 +47,7 @@ from automation.saved_variables import SavedVariablesError # noqa: E402
47
47
 
48
48
  NOTICE_MAX_BYTES = 512
49
49
  BUG_TASK_ID = "bug"
50
- CLIENT_FOLDERS = {"retail": "_retail_", "classic": "_classic_", "titan": "_classic_arena"}
50
+ CLIENT_FOLDERS = {"retail": "_retail_", "classic": "_classic_", "titan": "_classic_titan_"}
51
51
  DEFAULT_TIMEOUT = 120.0
52
52
  DEFAULT_INTERVAL = 0.1
53
53
  SV_READ_RETRIES = 3