dsh-wsl-workspace 0.7.2 → 0.7.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/README.md +74 -0
- package/README.zh.md +16 -0
- package/TESTING.md +66 -15
- package/lib/client.js +4 -4
- package/lib/client.js.map +1 -1
- package/lib/fs.js +2 -2
- package/lib/index.js +127 -20
- package/lib/index.js.map +1 -1
- package/lib/{links-BQxdJOMy.js → links-DQ8GgpMj.js} +19 -19
- package/lib/links-DQ8GgpMj.js.map +1 -0
- package/lib/shell.js +2 -2
- package/lib/{wsl-CECXiGZH.js → wsl-BTA7XT8X.js} +72 -12
- package/lib/wsl-BTA7XT8X.js.map +1 -0
- package/lib/{wsl-credentials-BJXc9tfi.js → wsl-credentials-gFHTqaiN.js} +2 -2
- package/lib/{wsl-credentials-BJXc9tfi.js.map → wsl-credentials-gFHTqaiN.js.map} +1 -1
- package/lib/wsl-relay.js +1 -1
- package/lib/wsl-search.js +2 -2
- package/package.json +10 -4
- package/src/client/locales.ts +4 -4
- package/src/index.ts +222 -25
- package/src/shared/links.ts +20 -11
- package/src/shared/wsl.ts +99 -15
- package/lib/links-BQxdJOMy.js.map +0 -1
- package/lib/wsl-CECXiGZH.js.map +0 -1
package/src/index.ts
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Host half of dsh-wsl-workspace. Three responsibilities:
|
|
3
3
|
*
|
|
4
|
-
* 1.
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
4
|
+
* 1. Publish a `wsl-<mode>` variant for every healthy roster preset, so the
|
|
5
|
+
* WSL execution world — `shell-wsl` + `fs-wsl` behind one entry-local
|
|
6
|
+
* realm, with `tool-bash`/`tool-fs` consumers — composes with ANY mode
|
|
7
|
+
* instead of being a mode itself. The channel follows the release:
|
|
8
|
+
* `0.1.7-alpha.1+` stopped scanning any user preset root and builds its roster
|
|
9
|
+
* from declarative `@deepseek-ai/dsh-agent-preset` rows, so there a variant
|
|
10
|
+
* is a *declaration registered through `ctx.agentPresets`* — and only that
|
|
11
|
+
* path rewrites the absolute provider specifiers below into `file:` URLs,
|
|
12
|
+
* because a registered preset's entry tree does not translate them the way
|
|
13
|
+
* the boot-time Include does; earlier releases still get a variant directory
|
|
14
|
+
* under `<dshHome>/.agent-presets/`, whose legacy standalone `wsl` directory
|
|
15
|
+
* and stale variants are removed on boot.
|
|
13
16
|
*
|
|
14
17
|
* 2. Serve the browser dialog's data route (`/wsl-workspace/api`):
|
|
15
18
|
* distribution discovery, one-level directory listing, path checks, and
|
|
@@ -26,8 +29,8 @@
|
|
|
26
29
|
import { Context } from '@deepseek-ai/cordis'
|
|
27
30
|
import z from '@deepseek-ai/schemastery'
|
|
28
31
|
import { cpSync, existsSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
29
|
-
import { fileURLToPath } from 'node:url'
|
|
30
|
-
import { dirname, join } from 'node:path'
|
|
32
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
33
|
+
import { dirname, isAbsolute, join } from 'node:path'
|
|
31
34
|
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
32
35
|
import { homedir } from 'node:os'
|
|
33
36
|
import { joinUnc, mntToWindowsPath, normalizeLinuxPath, isAbsoluteLinuxPath, isValidWslUsername, parseWslUnc } from './shared/paths.ts'
|
|
@@ -47,10 +50,18 @@ export const DEFAULT_ROUTE = '/wsl-workspace/api'
|
|
|
47
50
|
* preset.yml text verbatim, so the plugin writes one bilingual string so
|
|
48
51
|
* both locales can identify each variant. Custom presets keep their own
|
|
49
52
|
* name.
|
|
53
|
+
*
|
|
54
|
+
* This table is consulted before anything the release publishes, so every id
|
|
55
|
+
* the mode has ever carried needs an entry. `code` was the id up to
|
|
56
|
+
* `0.1.0-rc.8` and `ptc` is the id from `0.1.1` on; without the `ptc` entry the
|
|
57
|
+
* lookup returned undefined and the variant fell through to the release's own
|
|
58
|
+
* display name — which `0.1.7` does not publish at all, leaving the mode named
|
|
59
|
+
* `WSL · ptc` with the generic description `WSL execution world for ptc: …`.
|
|
50
60
|
*/
|
|
51
61
|
const MODE_DISPLAY_LABELS: Readonly<Record<string, { en: string; zh: string }>> = {
|
|
52
62
|
standard: { en: 'Standard mode', zh: '标准模式' },
|
|
53
63
|
code: { en: 'Code mode', zh: 'PTC 模式' },
|
|
64
|
+
ptc: { en: 'PTC mode', zh: 'PTC 模式' },
|
|
54
65
|
minimal: { en: 'Minimal mode', zh: '极简模式' },
|
|
55
66
|
cordis: { en: 'Creator mode', zh: '创造模式' },
|
|
56
67
|
}
|
|
@@ -352,10 +363,149 @@ async function dispatch(method: string, params: Record<string, unknown>): Promis
|
|
|
352
363
|
}
|
|
353
364
|
}
|
|
354
365
|
|
|
355
|
-
/**
|
|
366
|
+
/** One roster entry as the `ctx.agentPresets` face reports it. */
|
|
367
|
+
interface AgentPresetRosterEntry {
|
|
368
|
+
id: string
|
|
369
|
+
name?: string
|
|
370
|
+
description?: string
|
|
371
|
+
/** Roster position; `list()` sorts by it. */
|
|
372
|
+
order?: number
|
|
373
|
+
broken?: string
|
|
374
|
+
/** Legacy (≤ 0.1.6-alpha.2) only: the source preset's directory. */
|
|
375
|
+
path?: string
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** One preset's declared composition, as the declaration channel reports it. */
|
|
379
|
+
interface AgentPresetDocument {
|
|
380
|
+
agentPreset: string
|
|
381
|
+
/** The declared child plugin list as entry-list YAML, `!!js` expressions included. */
|
|
382
|
+
content: string
|
|
383
|
+
name?: string
|
|
384
|
+
description?: string
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** A declaration this plugin publishes; mirrors the Host's `PresetDefinition`. */
|
|
388
|
+
interface PresetDeclaration {
|
|
389
|
+
id: string
|
|
390
|
+
name?: string
|
|
391
|
+
description?: string
|
|
392
|
+
order?: number
|
|
393
|
+
plugins: readonly unknown[]
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* The `ctx.agentPresets` roster face this plugin consumes (optional service).
|
|
398
|
+
*
|
|
399
|
+
* Two generations sit behind this one shape, so both are probed by capability
|
|
400
|
+
* rather than by version:
|
|
401
|
+
*
|
|
402
|
+
* - `0.1.0-rc.7 … 0.1.6-alpha.2`: `list()` reports each preset's directory in
|
|
403
|
+
* `path`, and `read(id)` returns the composition text. A variant is a
|
|
404
|
+
* *directory* under the roster's scanned user root (`$DSH_HOME/.agent-presets/`).
|
|
405
|
+
* - `0.1.7-alpha.1+`: `read()` is renamed `readDocument()` and returns a document
|
|
406
|
+
* instead of a bare string, `AgentPreset.path` is gone, and **nothing scans
|
|
407
|
+
* the user root any more** — the roster is built from declarative
|
|
408
|
+
* `@deepseek-ai/dsh-agent-preset` rows carried by bundle patches. A variant
|
|
409
|
+
* is therefore a declaration row published through `register()`.
|
|
410
|
+
*/
|
|
356
411
|
interface AgentPresetsService {
|
|
357
|
-
list(): Promise<
|
|
358
|
-
|
|
412
|
+
list(): Promise<AgentPresetRosterEntry[]>
|
|
413
|
+
/** Legacy (≤ 0.1.6-alpha.2): the source composition text. */
|
|
414
|
+
read?(id: string): Promise<string>
|
|
415
|
+
/** 0.1.7-alpha.1+: the declared composition beside its published metadata. */
|
|
416
|
+
readDocument?(id: string): Promise<AgentPresetDocument>
|
|
417
|
+
/** 0.1.7-alpha.1+: publish a declaration; the returned disposer retires it. */
|
|
418
|
+
register?(definition: PresetDeclaration): Promise<() => Promise<void>>
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Read one preset's declared composition across both roster generations.
|
|
423
|
+
* @param agentPresets - the roster face.
|
|
424
|
+
* @param preset - the roster entry to read.
|
|
425
|
+
* @returns the composition text, plus the display name when the face publishes it.
|
|
426
|
+
*/
|
|
427
|
+
async function readPresetComposition(
|
|
428
|
+
agentPresets: AgentPresetsService,
|
|
429
|
+
preset: AgentPresetRosterEntry,
|
|
430
|
+
): Promise<{ content: string; name?: string }> {
|
|
431
|
+
if (typeof agentPresets.readDocument === 'function') {
|
|
432
|
+
const document = await agentPresets.readDocument(preset.id)
|
|
433
|
+
return document.name === undefined
|
|
434
|
+
? { content: document.content }
|
|
435
|
+
: { content: document.content, name: document.name }
|
|
436
|
+
}
|
|
437
|
+
if (typeof agentPresets.read === 'function') return { content: await agentPresets.read(preset.id) }
|
|
438
|
+
throw new Error(
|
|
439
|
+
`agentPresets: this DSH release exposes neither readDocument() nor read() (preset "${preset.id}")`,
|
|
440
|
+
)
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Parse one transformed composition back into declaration rows.
|
|
445
|
+
*
|
|
446
|
+
* The composition is the entry-list YAML dialect, whose `!!js` scalars are
|
|
447
|
+
* expression nodes the Loader evaluates when it activates the row.
|
|
448
|
+
* `@deepseek-ai/cordis-plugin-include` exports `entryListSchema` precisely so
|
|
449
|
+
* config tooling can round-trip that dialect, and it is the same schema the
|
|
450
|
+
* harness parses preset patches with. Parsing the text back is what lets the
|
|
451
|
+
* (text-level) WSL transform keep working unchanged now that a variant is a
|
|
452
|
+
* declaration row instead of a directory of YAML.
|
|
453
|
+
*
|
|
454
|
+
* Both modules are resolved at call time rather than at module load: they are
|
|
455
|
+
* Host-provided (`dsh` depends on `cordis-plugin-include`, which depends on
|
|
456
|
+
* `js-yaml`), and a release that ever drops them must fail this one variant
|
|
457
|
+
* rather than refuse to load the whole plugin.
|
|
458
|
+
* @param content - the variant composition text.
|
|
459
|
+
* @returns the declaration's plugin rows.
|
|
460
|
+
*/
|
|
461
|
+
async function parseVariantComposition(content: string): Promise<unknown[]> {
|
|
462
|
+
const includeSpecifier = '@deepseek-ai/cordis-plugin-include'
|
|
463
|
+
const yamlSpecifier = 'js-yaml'
|
|
464
|
+
const [include, yamlModule] = await Promise.all([
|
|
465
|
+
import(includeSpecifier) as Promise<{ entryListSchema: unknown }>,
|
|
466
|
+
import(yamlSpecifier) as Promise<{
|
|
467
|
+
load?(source: string, options: { schema: unknown }): unknown
|
|
468
|
+
default?: { load(source: string, options: { schema: unknown }): unknown }
|
|
469
|
+
}>,
|
|
470
|
+
])
|
|
471
|
+
const load = yamlModule.load ?? yamlModule.default?.load
|
|
472
|
+
if (typeof load !== 'function') throw new Error('js-yaml: no load() export')
|
|
473
|
+
const rows = load(content, { schema: include.entryListSchema })
|
|
474
|
+
if (!Array.isArray(rows)) throw new Error('the transformed composition did not parse as an entry list')
|
|
475
|
+
return toImportableSpecifiers(rows)
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Rewrite every absolute local module specifier as a `file:` URL.
|
|
480
|
+
*
|
|
481
|
+
* The generated world names THIS package's built providers (`shell.js`,
|
|
482
|
+
* `fs.js`, …) by absolute path. That is what the directory mechanism needed:
|
|
483
|
+
* those rows sat in an Include-backed tree, and the boot-time Include
|
|
484
|
+
* translates an absolute path into a `file:` URL before importing it. A preset
|
|
485
|
+
* mounted from a *declaration* is loaded by the registry's own entry tree,
|
|
486
|
+
* which has no such translation — handing it `C:/…/lib/shell.js` leaves those
|
|
487
|
+
* rows without a fiber, the audit reports them "never started", and the whole
|
|
488
|
+
* variant is refused. Rewriting the specifier is therefore part of adapting to
|
|
489
|
+
* the declaration mechanism, not a change to what the variant mounts.
|
|
490
|
+
*
|
|
491
|
+
* Only `name` is touched: config values (the relay path handed to the PTY
|
|
492
|
+
* backend, the interpreter path in `shellPath`) must stay native filesystem
|
|
493
|
+
* paths. Group rows carry their children in a `config` array, so those are
|
|
494
|
+
* walked too.
|
|
495
|
+
* @param rows - the parsed declaration rows.
|
|
496
|
+
* @returns the same rows with their module specifiers made importable.
|
|
497
|
+
*/
|
|
498
|
+
function toImportableSpecifiers(rows: unknown[]): unknown[] {
|
|
499
|
+
const rewrite = (row: unknown): unknown => {
|
|
500
|
+
if (row === null || typeof row !== 'object') return row
|
|
501
|
+
const entry = row as { name?: unknown; config?: unknown }
|
|
502
|
+
if (typeof entry.name === 'string' && isAbsolute(entry.name)) {
|
|
503
|
+
entry.name = pathToFileURL(entry.name).href
|
|
504
|
+
}
|
|
505
|
+
if (Array.isArray(entry.config)) entry.config = entry.config.map(rewrite)
|
|
506
|
+
return row
|
|
507
|
+
}
|
|
508
|
+
return rows.map(rewrite)
|
|
359
509
|
}
|
|
360
510
|
|
|
361
511
|
/**
|
|
@@ -469,6 +619,7 @@ async function materializeVariants(
|
|
|
469
619
|
dshHome: string,
|
|
470
620
|
paths: { shell: string; fs: string; relay: string; node: string; sandbox: string; search: string; jobs: string },
|
|
471
621
|
persistentShell: boolean,
|
|
622
|
+
track: (dispose: unknown) => void,
|
|
472
623
|
): Promise<void> {
|
|
473
624
|
const presets = await agentPresets.list()
|
|
474
625
|
const userRoot = join(dshHome, '.agent-presets')
|
|
@@ -477,12 +628,33 @@ async function materializeVariants(
|
|
|
477
628
|
if (preset.broken !== undefined) continue
|
|
478
629
|
if (isWslVariantId(preset.id)) continue
|
|
479
630
|
const variantId = variantIdFor(preset.id)
|
|
480
|
-
const
|
|
481
|
-
const transformed = transformPresetForWsl(
|
|
631
|
+
const composition = await readPresetComposition(agentPresets, preset)
|
|
632
|
+
const transformed = transformPresetForWsl(composition.content, paths.shell, paths.fs, persistentShell ? {
|
|
482
633
|
relayPath: paths.relay,
|
|
483
634
|
nodePath: paths.node,
|
|
484
635
|
sandboxPath: paths.sandbox,
|
|
485
636
|
} : undefined, paths.search, paths.jobs)
|
|
637
|
+
// 0.1.7-alpha.1+ publishes a variant as a declaration row (the composition is
|
|
638
|
+
// already the exact entry-list dialect the declaration wants, so the only
|
|
639
|
+
// conversion is YAML back to rows); earlier releases still discover one as
|
|
640
|
+
// a directory under the roster's scanned user root.
|
|
641
|
+
if (typeof agentPresets.register === 'function') {
|
|
642
|
+
const plugins = await parseVariantComposition(transformed)
|
|
643
|
+
// A shipped mode keeps its bilingual label; a custom preset keeps the
|
|
644
|
+
// display name it published, falling back to its id.
|
|
645
|
+
const declaration: PresetDeclaration = {
|
|
646
|
+
id: variantId,
|
|
647
|
+
name: variantName(preset.id, composition.name ?? preset.name ?? preset.id),
|
|
648
|
+
description: variantDescription(preset.id),
|
|
649
|
+
...(preset.order === undefined ? {} : { order: preset.order }),
|
|
650
|
+
plugins,
|
|
651
|
+
}
|
|
652
|
+
track(await agentPresets.register(declaration))
|
|
653
|
+
continue
|
|
654
|
+
}
|
|
655
|
+
if (preset.path === undefined) {
|
|
656
|
+
throw new Error(`agentPresets: roster entry "${preset.id}" carries no path on this release`)
|
|
657
|
+
}
|
|
486
658
|
const dir = join(userRoot, variantId)
|
|
487
659
|
const staging = `${dir}.staging`
|
|
488
660
|
rmSync(staging, { recursive: true, force: true })
|
|
@@ -524,15 +696,20 @@ async function materializeVariants(
|
|
|
524
696
|
publishVariant(staging, dir)
|
|
525
697
|
generated.add(variantId)
|
|
526
698
|
}
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
699
|
+
// Clean up the retired directory mechanism. `generated` holds the
|
|
700
|
+
// directories the directory path wrote on THIS boot; from 0.1.7-alpha.1 on it is
|
|
701
|
+
// always empty, because a variant is a declaration row and the roster no
|
|
702
|
+
// longer scans this root at all — so every `wsl*` entry left here (the legacy
|
|
703
|
+
// standalone `wsl` mode included) is inert leftover, and a `wsl-<mode>/`
|
|
704
|
+
// beside a registered `wsl-<mode>` declaration would only mislead. An absent
|
|
705
|
+
// root (a fresh install that never used the old mechanism) is not a failure.
|
|
706
|
+
if (existsSync(userRoot)) {
|
|
707
|
+
for (const entry of readdirSync(userRoot, { withFileTypes: true })) {
|
|
708
|
+
if (!entry.isDirectory()) continue
|
|
709
|
+
if (!/^wsl(-[a-z0-9-]+)?$/.test(entry.name)) continue
|
|
710
|
+
if (generated.has(entry.name)) continue
|
|
531
711
|
rmSync(join(userRoot, entry.name), { recursive: true, force: true })
|
|
532
|
-
continue
|
|
533
712
|
}
|
|
534
|
-
if (!/^wsl-[a-z0-9-]+$/.test(entry.name)) continue
|
|
535
|
-
if (!generated.has(entry.name)) rmSync(join(userRoot, entry.name), { recursive: true, force: true })
|
|
536
713
|
}
|
|
537
714
|
}
|
|
538
715
|
|
|
@@ -576,6 +753,21 @@ export function apply(ctx: Context, config: Config): void {
|
|
|
576
753
|
const agentPresets = ctx.get('agentPresets') as unknown as AgentPresetsService | undefined
|
|
577
754
|
if (agentPresets !== undefined) {
|
|
578
755
|
ctx.effect(() => {
|
|
756
|
+
// On 0.1.7-alpha.1+ the variants are declaration rows in Host state rather
|
|
757
|
+
// than files, so the effect owns their disposers: a plugin unload or hot
|
|
758
|
+
// reload retires them instead of leaving orphans the next apply could not
|
|
759
|
+
// replace (`Duplicate agent preset: wsl-<mode>`).
|
|
760
|
+
let stopped = false
|
|
761
|
+
const disposers: (() => Promise<void>)[] = []
|
|
762
|
+
const track = (dispose: unknown): void => {
|
|
763
|
+
if (typeof dispose !== 'function') return
|
|
764
|
+
const retire = dispose as () => Promise<void>
|
|
765
|
+
if (stopped) {
|
|
766
|
+
void Promise.resolve(retire()).catch(() => {})
|
|
767
|
+
return
|
|
768
|
+
}
|
|
769
|
+
disposers.push(retire)
|
|
770
|
+
}
|
|
579
771
|
void (async () => {
|
|
580
772
|
const persistentShell = await supportsPersistentShell(ctx)
|
|
581
773
|
await materializeVariants(agentPresets, dshHome, {
|
|
@@ -586,14 +778,19 @@ export function apply(ctx: Context, config: Config): void {
|
|
|
586
778
|
sandbox: sandboxPath,
|
|
587
779
|
search: searchPath,
|
|
588
780
|
jobs: jobsPath,
|
|
589
|
-
}, persistentShell)
|
|
781
|
+
}, persistentShell, track)
|
|
590
782
|
})().catch((error) => {
|
|
591
783
|
// Variant generation is best-effort over a live roster: a missing or
|
|
592
784
|
// unreadable source preset must not take the whole plugin down, but
|
|
593
785
|
// the failure is surfaced loudly rather than hidden.
|
|
594
786
|
console.error(`dsh-wsl-workspace: WSL preset-variant generation failed: ${messageOf(error)}`)
|
|
595
787
|
})
|
|
596
|
-
return () => {
|
|
788
|
+
return () => {
|
|
789
|
+
stopped = true
|
|
790
|
+
for (const retire of disposers.splice(0, disposers.length)) {
|
|
791
|
+
void Promise.resolve(retire()).catch(() => {})
|
|
792
|
+
}
|
|
793
|
+
}
|
|
597
794
|
}, 'dsh-wsl-workspace: WSL preset variants')
|
|
598
795
|
}
|
|
599
796
|
|
package/src/shared/links.ts
CHANGED
|
@@ -18,12 +18,9 @@
|
|
|
18
18
|
* @module dsh-wsl-workspace/shared/links
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
|
-
import {
|
|
22
|
-
import { promisify } from 'node:util'
|
|
21
|
+
import { execFileResult, textOf, wslExecutableCandidates } from './wsl.ts'
|
|
23
22
|
import { isAbsoluteLinuxPath, joinUnc, parseWslUnc } from './paths.ts'
|
|
24
23
|
|
|
25
|
-
const execFileAsync = promisify(execFile)
|
|
26
|
-
|
|
27
24
|
/** How many `readlink` calls may be in flight at once. */
|
|
28
25
|
export const LINK_RESOLVE_CONCURRENCY = 4
|
|
29
26
|
/** How long the distribution may take to answer one `readlink` call. */
|
|
@@ -75,13 +72,25 @@ export async function resolveLinuxSymlink(
|
|
|
75
72
|
// the path itself would come back mangled by that trim.
|
|
76
73
|
if (unc === null || /[\r\n]/.test(unc.linuxPath)) return undefined
|
|
77
74
|
try {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
)
|
|
83
|
-
const
|
|
84
|
-
|
|
75
|
+
// `execFileResult` is the callback form on purpose: a host that replaces
|
|
76
|
+
// `child_process.execFile` with a plain wrapper (DSH Desktop's
|
|
77
|
+
// `windowsHide` injection) strips the metadata `promisify` needs, and the
|
|
78
|
+
// promisified call would hand back stdout instead of `{ stdout, stderr }`
|
|
79
|
+
// — making this silently return `undefined` for every link (issue #35).
|
|
80
|
+
for (const candidate of wslExecutableCandidates(wslPath)) {
|
|
81
|
+
try {
|
|
82
|
+
const output = await execFileResult(
|
|
83
|
+
candidate,
|
|
84
|
+
['-d', unc.distro, '--', 'readlink', '-f', unc.linuxPath],
|
|
85
|
+
{ encoding: 'utf8', timeout: LINK_RESOLVE_TIMEOUT_MS, windowsHide: true },
|
|
86
|
+
)
|
|
87
|
+
const target = textOf(output.stdout).trim()
|
|
88
|
+
return isAbsoluteLinuxPath(target) ? joinUnc(unc.distro, target) : undefined
|
|
89
|
+
} catch {
|
|
90
|
+
// try the next spelling of wsl.exe
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return undefined
|
|
85
94
|
} catch {
|
|
86
95
|
// Missing intermediate components, an unreadable link, a stopped
|
|
87
96
|
// distribution or a missing `readlink` all land here.
|
package/src/shared/wsl.ts
CHANGED
|
@@ -7,9 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
import { execFile, execFileSync } from 'node:child_process'
|
|
10
|
-
import {
|
|
11
|
-
|
|
12
|
-
const execFileAsync = promisify(execFile)
|
|
10
|
+
import type { ExecFileOptions } from 'node:child_process'
|
|
13
11
|
|
|
14
12
|
/** Executable timeout for the short discovery calls. */
|
|
15
13
|
const DISCOVERY_TIMEOUT_MS = 10_000
|
|
@@ -21,13 +19,86 @@ function messageOf(value: unknown): string {
|
|
|
21
19
|
return value instanceof Error ? value.message : String(value)
|
|
22
20
|
}
|
|
23
21
|
|
|
22
|
+
/** One `execFile` outcome: the two streams, as `encoding` asked for them. */
|
|
23
|
+
export interface ExecFileResult {
|
|
24
|
+
stdout: Buffer | string
|
|
25
|
+
stderr: Buffer | string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Run `execFile` through its callback API and resolve `{ stdout, stderr }`.
|
|
30
|
+
*
|
|
31
|
+
* `util.promisify(execFile)` only resolves that object because `execFile`
|
|
32
|
+
* carries `util.promisify.custom`. A host that replaces
|
|
33
|
+
* `child_process.execFile` with a plain wrapper loses that metadata, and
|
|
34
|
+
* `promisify` then falls back to "resolve the first callback value" — which is
|
|
35
|
+
* stdout itself, so `result.stdout` is `undefined` (issue #35: DSH Desktop
|
|
36
|
+
* injects `windowsHide: true` that way, and `listDistros()` died with
|
|
37
|
+
* `Cannot read properties of undefined (reading 'includes')`).
|
|
38
|
+
*
|
|
39
|
+
* The callback form is what every such wrapper preserves, so this does not
|
|
40
|
+
* depend on how the host patched the module.
|
|
41
|
+
* @param file - the executable.
|
|
42
|
+
* @param args - its arguments.
|
|
43
|
+
* @param options - `execFile` options, including the requested encoding.
|
|
44
|
+
* @returns both streams; the caller narrows them by the encoding it asked for.
|
|
45
|
+
*/
|
|
46
|
+
export function execFileResult(
|
|
47
|
+
file: string,
|
|
48
|
+
args: readonly string[],
|
|
49
|
+
options: ExecFileOptions,
|
|
50
|
+
): Promise<ExecFileResult> {
|
|
51
|
+
// `settle`/`fail` rather than `resolve`/`reject`, matching
|
|
52
|
+
// `src/host/wsl-search.ts`; `scripts/verify-lib.mjs` reads a bare
|
|
53
|
+
// `resolve(` call as an unbound `node:path` export.
|
|
54
|
+
return new Promise<ExecFileResult>((settle, fail) => {
|
|
55
|
+
execFile(file, [...args], options, (error, stdout, stderr) => {
|
|
56
|
+
if (error !== null && error !== undefined) {
|
|
57
|
+
fail(error)
|
|
58
|
+
return
|
|
59
|
+
}
|
|
60
|
+
settle({ stdout, stderr })
|
|
61
|
+
})
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Read a captured stream as text, whichever way the encoding arrived. */
|
|
66
|
+
export function textOf(stream: Buffer | string): string {
|
|
67
|
+
return typeof stream === 'string' ? stream : stream.toString('utf8')
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The `wsl.exe` spellings to try, in order.
|
|
72
|
+
*
|
|
73
|
+
* The bare name relies on `PATH`. A host whose `PATH` omits `System32` can run
|
|
74
|
+
* every other part of this plugin — `listDir`/`check` go through the
|
|
75
|
+
* `\\wsl.localhost\…` share and never spawn anything — while `listDistros`
|
|
76
|
+
* reports that WSL is missing, which is what issue #36 describes. The
|
|
77
|
+
* absolute fallback removes that failure mode.
|
|
78
|
+
* @param wslPath - the configured executable.
|
|
79
|
+
* @returns the candidates, without duplicates.
|
|
80
|
+
*/
|
|
81
|
+
export function wslExecutableCandidates(wslPath: string): string[] {
|
|
82
|
+
if (wslPath !== 'wsl.exe') return [wslPath]
|
|
83
|
+
const root = process.env.SystemRoot ?? process.env.windir
|
|
84
|
+
if (root === undefined || root === '') return [wslPath]
|
|
85
|
+
const absolute = `${root.replace(/[\\/]+$/, '')}\\System32\\wsl.exe`
|
|
86
|
+
return [wslPath, absolute]
|
|
87
|
+
}
|
|
88
|
+
|
|
24
89
|
/**
|
|
25
90
|
* Decode `wsl.exe -l -q` output. Newer builds emit UTF-8; most emit UTF-16LE
|
|
26
|
-
* with NUL bytes interleaved — the NUL probe picks the right one.
|
|
91
|
+
* with NUL bytes interleaved — the NUL probe picks the right one. A host that
|
|
92
|
+
* handed back something other than the captured stream is reported as such
|
|
93
|
+
* instead of throwing `Cannot read properties of undefined`.
|
|
27
94
|
* @param buffer - the raw captured output.
|
|
28
95
|
* @returns the decoded text.
|
|
29
96
|
*/
|
|
30
|
-
export function decodeWslOutput(buffer: Buffer): string {
|
|
97
|
+
export function decodeWslOutput(buffer: Buffer | string): string {
|
|
98
|
+
if (typeof buffer === 'string') return buffer
|
|
99
|
+
if (!(buffer instanceof Uint8Array)) {
|
|
100
|
+
throw new Error(`wsl-workspace: expected captured output, got ${typeof buffer}`)
|
|
101
|
+
}
|
|
31
102
|
return buffer.includes(0) ? buffer.toString('utf16le') : buffer.toString('utf8')
|
|
32
103
|
}
|
|
33
104
|
|
|
@@ -37,12 +108,25 @@ export function decodeWslOutput(buffer: Buffer): string {
|
|
|
37
108
|
* @returns distribution names, blank lines dropped.
|
|
38
109
|
*/
|
|
39
110
|
export async function listDistros(wslPath = 'wsl.exe'): Promise<string[]> {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
111
|
+
const candidates = wslExecutableCandidates(wslPath)
|
|
112
|
+
let stdout: Buffer | string | undefined
|
|
113
|
+
let lastError: unknown
|
|
114
|
+
for (const candidate of candidates) {
|
|
115
|
+
try {
|
|
116
|
+
const result = await execFileResult(candidate, ['-l', '-q'], {
|
|
117
|
+
encoding: 'buffer',
|
|
118
|
+
timeout: DISCOVERY_TIMEOUT_MS,
|
|
119
|
+
})
|
|
120
|
+
stdout = result.stdout
|
|
121
|
+
break
|
|
122
|
+
} catch (error) {
|
|
123
|
+
lastError = error
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (stdout === undefined) {
|
|
127
|
+
throw new Error(
|
|
128
|
+
`wsl-workspace: cannot list WSL distributions (tried ${candidates.join(' and ')}: ${messageOf(lastError)}); is WSL installed?`,
|
|
129
|
+
)
|
|
46
130
|
}
|
|
47
131
|
return decodeWslOutput(stdout)
|
|
48
132
|
.split(/\r?\n/)
|
|
@@ -58,15 +142,15 @@ export async function listDistros(wslPath = 'wsl.exe'): Promise<string[]> {
|
|
|
58
142
|
*/
|
|
59
143
|
export async function defaultDistro(): Promise<string | undefined> {
|
|
60
144
|
try {
|
|
61
|
-
const value = await
|
|
145
|
+
const value = await execFileResult('reg.exe', ['query', LXSS_KEY, '/v', 'DefaultDistribution'], {
|
|
62
146
|
timeout: DISCOVERY_TIMEOUT_MS,
|
|
63
147
|
})
|
|
64
|
-
const guid = /DefaultDistribution\s+REG_SZ\s+(\{[0-9a-fA-F-]+\})/i.exec(value.stdout)?.[1]
|
|
148
|
+
const guid = /DefaultDistribution\s+REG_SZ\s+(\{[0-9a-fA-F-]+\})/i.exec(textOf(value.stdout))?.[1]
|
|
65
149
|
if (guid === undefined) return undefined
|
|
66
|
-
const name = await
|
|
150
|
+
const name = await execFileResult('reg.exe', ['query', `${LXSS_KEY}\\${guid}`, '/v', 'DistributionName'], {
|
|
67
151
|
timeout: DISCOVERY_TIMEOUT_MS,
|
|
68
152
|
})
|
|
69
|
-
const distro = /DistributionName\s+REG_SZ\s+(.+)/i.exec(name.stdout)?.[1]?.trim()
|
|
153
|
+
const distro = /DistributionName\s+REG_SZ\s+(.+)/i.exec(textOf(name.stdout))?.[1]?.trim()
|
|
70
154
|
return distro === undefined || distro === '' ? undefined : distro
|
|
71
155
|
} catch {
|
|
72
156
|
return undefined
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"links-BQxdJOMy.js","names":["resolved: (string | undefined)[]"],"sources":["../src/shared/links.ts"],"sourcesContent":["/**\n * Linux symlink resolution through the owning distribution.\n *\n * The `\\\\wsl.localhost\\<distro>\\…` 9P share lists a Linux symlink entry but\n * cannot resolve its target: `readdir` reports it, and every Windows-side\n * `stat` on it fails (`ENOENT`/`EISDIR`). The distribution resolves the same\n * path trivially, so both halves of this plugin — the skill walk and the\n * filesystem backend — ask it with one short `wsl.exe … readlink -f` call per\n * link.\n *\n * Each link gets its own call on purpose: `wsl.exe` drops the arguments that\n * follow a command (`sh -c 'echo ARGC:$#' sh a b c` answers 0) and its\n * command-line parser truncates an argument containing a double quote, while a\n * bare multi-argument `readlink -f a b c` stops at the first path it cannot\n * resolve and still exits non-zero. A process argument carries any path\n * without quoting, which is what keeps this correct.\n *\n * @module dsh-wsl-workspace/shared/links\n */\n\nimport { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport { isAbsoluteLinuxPath, joinUnc, parseWslUnc } from './paths.ts'\n\nconst execFileAsync = promisify(execFile)\n\n/** How many `readlink` calls may be in flight at once. */\nexport const LINK_RESOLVE_CONCURRENCY = 4\n/** How long the distribution may take to answer one `readlink` call. */\nexport const LINK_RESOLVE_TIMEOUT_MS = 10_000\n\n/**\n * Resolve Linux symlinks through the distribution that owns them.\n *\n * Never throws: a link the distribution cannot resolve (a missing component, a\n * stopped distribution, a `readlink` that fails) stays unresolved, and callers\n * keep whatever behaviour they had before this fallback existed.\n *\n * @param uncPaths - the links to resolve, in UNC spelling.\n * @param wslPath - the `wsl.exe` executable (absolute or PATH name).\n * @returns one entry per input, in order: the resolved real path as a UNC\n * path, or `undefined` when the link or the distribution could not answer.\n */\nexport async function resolveLinuxSymlinks(\n uncPaths: readonly string[],\n wslPath = 'wsl.exe',\n): Promise<(string | undefined)[]> {\n const resolved: (string | undefined)[] = uncPaths.map(() => undefined)\n let next = 0\n const workers = Array.from(\n { length: Math.min(LINK_RESOLVE_CONCURRENCY, uncPaths.length) },\n async () => {\n for (let index = next; index < uncPaths.length; index = next) {\n next += 1\n resolved[index] = await resolveLinuxSymlink(uncPaths[index] ?? '', wslPath)\n }\n },\n )\n await Promise.all(workers)\n return resolved\n}\n\n/**\n * Resolve one Linux symlink the share cannot follow.\n * @param uncPath - the link, in UNC spelling.\n * @param wslPath - the `wsl.exe` executable (absolute or PATH name).\n * @returns the real path as a UNC path, or `undefined` when it does not resolve.\n */\nexport async function resolveLinuxSymlink(\n uncPath: string,\n wslPath = 'wsl.exe',\n): Promise<string | undefined> {\n const unc = parseWslUnc(uncPath)\n // `readlink` answers one line, which the caller trims: a line break inside\n // the path itself would come back mangled by that trim.\n if (unc === null || /[\\r\\n]/.test(unc.linuxPath)) return undefined\n try {\n const output = await execFileAsync(\n wslPath,\n ['-d', unc.distro, '--', 'readlink', '-f', unc.linuxPath],\n { encoding: 'utf8', timeout: LINK_RESOLVE_TIMEOUT_MS, windowsHide: true },\n )\n const target = String(output.stdout).trim()\n return isAbsoluteLinuxPath(target) ? joinUnc(unc.distro, target) : undefined\n } catch {\n // Missing intermediate components, an unreadable link, a stopped\n // distribution or a missing `readlink` all land here.\n return undefined\n }\n}\n"],"mappings":";;;;;AAwBA,MAAM,gBAAgB,UAAU;;AAGhC,MAAa,2BAA2B;;AAExC,MAAa,0BAA0B;;;;;;;;;;;;;AAcvC,eAAsB,qBACpB,UACA,UAAU,WACuB;CACjC,MAAMA,WAAmC,SAAS,UAAU;CAC5D,IAAI,OAAO;CACX,MAAM,UAAU,MAAM,KACpB,EAAE,QAAQ,KAAK,IAAI,0BAA0B,SAAS,WACtD,YAAY;AACV,OAAK,IAAI,QAAQ,MAAM,QAAQ,SAAS,QAAQ,QAAQ,MAAM;AAC5D,WAAQ;AACR,YAAS,SAAS,MAAM,oBAAoB,SAAS,UAAU,IAAI;;;AAIzE,OAAM,QAAQ,IAAI;AAClB,QAAO;;;;;;;;AAST,eAAsB,oBACpB,SACA,UAAU,WACmB;CAC7B,MAAM,MAAM,YAAY;AAGxB,KAAI,QAAQ,QAAQ,SAAS,KAAK,IAAI,WAAY,QAAO;AACzD,KAAI;EACF,MAAM,SAAS,MAAM,cACnB,SACA;GAAC;GAAM,IAAI;GAAQ;GAAM;GAAY;GAAM,IAAI;KAC/C;GAAE,UAAU;GAAQ,SAAS;GAAyB,aAAa;;EAErE,MAAM,SAAS,OAAO,OAAO,QAAQ;AACrC,SAAO,oBAAoB,UAAU,QAAQ,IAAI,QAAQ,UAAU;SAC7D;AAGN,SAAO"}
|
package/lib/wsl-CECXiGZH.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"wsl-CECXiGZH.js","names":["stdout: Buffer","syncDefault: string | undefined"],"sources":["../src/shared/paths.ts","../src/shared/wsl.ts"],"sourcesContent":["/**\n * WSL path helpers shared by the client and host halves. Pure and\n * dependency-free so both planes can import them without a runtime edge.\n */\n\n/** WSL2 default loopback bridge host: `\\\\wsl.localhost\\<distro>\\...`. */\nconst WSL_LOCALHOST_HOST = 'wsl.localhost'\n/** Legacy WSL interop host: `\\\\wsl$\\<distro>\\...`. */\nconst WSL_LEGACY_HOST = 'wsl$'\n\n/** The two UNC hosts WSL exposes a distribution's filesystem under. */\nconst UNC_HOSTS = [WSL_LOCALHOST_HOST, WSL_LEGACY_HOST]\n\n/** One WSL workspace coordinate parsed out of a UNC path. */\nexport interface WslUncTarget {\n /** Distro name (e.g. `Ubuntu`) as `wsl -l -q` reports it. */\n readonly distro: string\n /** Normalized absolute Linux path (leading `/`; no trailing slash except root). */\n readonly linuxPath: string\n}\n\n/**\n * Parse a WSL UNC path into its distro and Linux path. Accepts the WSL2\n * `\\\\wsl.localhost\\<distro>\\<linux>` form, the legacy `\\\\wsl$\\<distro>\\<linux>`\n * interop form, and forward-slash spellings of either.\n * @param raw - candidate absolute path.\n * @returns the parsed target, or null when the path is not a WSL UNC.\n */\nexport function parseWslUnc(raw: string): WslUncTarget | null {\n const normalized = raw.replace(/\\\\/g, '/').replace(/\\/\\/+/g, '//')\n if (!normalized.startsWith('//')) return null\n const segments = normalized.slice(2).split('/')\n const host = (segments[0] ?? '').toLowerCase()\n if (!UNC_HOSTS.includes(host)) return null\n const distro = segments[1] ?? ''\n if (distro === '') return null\n const rest = segments.slice(2).filter(segment => segment.length > 0)\n return { distro, linuxPath: `/${rest.join('/')}` }\n}\n\n/**\n * Whether a path resolves into a WSL distro through either UNC form.\n * @param raw - candidate absolute path.\n * @returns whether the path parses as a WSL UNC.\n */\nexport function isWslUnc(raw: string): boolean {\n return parseWslUnc(raw) !== null\n}\n\n/**\n * Translate a WSL UNC path to the absolute Linux path a process inside the\n * distribution can open. Throws on non-WSL input: callers rely on this\n * conversion to hand paths to the Linux world, so a silent pass-through\n * would hand a Windows path to bash.\n * @param uncPath - a path {@link parseWslUnc} accepts.\n * @returns the absolute Linux path.\n */\nexport function uncToLinux(uncPath: string): string {\n const parts = parseWslUnc(uncPath)\n if (parts === null) {\n throw new Error(`wsl-workspace: \"${uncPath}\" is not a WSL UNC path`)\n }\n return parts.linuxPath\n}\n\n/**\n * Normalize a Linux absolute path for the Host: collapse repeated slashes and\n * strip a trailing slash (root becomes `/`).\n * @param path - absolute Linux path.\n * @returns the normalized path.\n */\nexport function normalizeLinuxPath(path: string): string {\n const collapsed = path.replace(/\\/+/g, '/')\n return collapsed === '/' ? '/' : collapsed.replace(/\\/$/, '')\n}\n\n/**\n * Whether a path is an absolute, non-empty Linux path.\n * @param path - candidate.\n * @returns whether it starts with `/` and contains no NUL.\n */\nexport function isAbsoluteLinuxPath(path: string): boolean {\n return path.startsWith('/') && !path.includes('\\0')\n}\n\n/**\n * Join a distro and a Linux absolute path into the WSL2 UNC form used as the\n * workspace identity (`\\\\wsl.localhost\\<distro>\\<linux>`, backslash segments).\n * @param distro - distro name.\n * @param linuxPath - absolute Linux path (leading `/`).\n * @returns the UNC path.\n */\nexport function joinUnc(distro: string, linuxPath: string): string {\n if (!isAbsoluteLinuxPath(linuxPath)) {\n throw new Error(`wsl-workspace: cannot map a non-absolute Linux path \"${linuxPath}\" to UNC`)\n }\n // Defense in depth: a distribution name with separators or dot-dirs would\n // escape the `\\\\wsl.localhost\\` share structure (the host route validates\n // wire-supplied names too; every other caller passes through here).\n if (distro === '' || distro === '.' || distro === '..' || /[\\\\/]/.test(distro)) {\n throw new Error(`wsl-workspace: invalid distribution name \"${distro}\"`)\n }\n const normalized = linuxPath.replace(/\\/+/g, '/').replace(/\\/$/, '')\n const withoutLeading = normalized.startsWith('/') ? normalized.slice(1) : normalized\n const windowsSegments = withoutLeading.replace(/\\//g, '\\\\')\n const suffix = windowsSegments === '' ? '' : `\\\\${windowsSegments}`\n return `\\\\\\\\wsl.localhost\\\\${distro}${suffix}`\n}\n\n/**\n * Translate a Windows drive path to the drvfs mount path WSL distributions\n * conventionally expose it at (`C:\\foo` → `/mnt/c/foo`). Only single-letter\n * drives under `/mnt` are mapped; custom mount points are out of scope.\n * @param path - the candidate Windows path.\n * @returns the `/mnt/<drive>/…` path, or `null` for non-drive paths.\n */\nexport function windowsToMntPath(path: string): string | null {\n const match = /^([A-Za-z]):[\\\\/](.*)$/.exec(path)\n if (match === null) return null\n const rest = (match[2] ?? '').replace(/\\\\/g, '/').replace(/\\/+/g, '/').replace(/\\/$/, '')\n return `/mnt/${(match[1] ?? '').toLowerCase()}${rest === '' ? '' : `/${rest}`}`\n}\n\n/**\n * Translate a `/mnt/<drive>/…` path back to its Windows drive path.\n * @param linuxPath - the candidate Linux path.\n * @returns the `X:\\…` drive path, or `null` when the path is not a drvfs mount.\n */\nexport function mntToWindowsPath(linuxPath: string): string | null {\n const match = /^\\/mnt\\/([a-zA-Z])(?:\\/(.*))?$/.exec(linuxPath)\n if (match === null) return null\n const rest = (match[2] ?? '').replace(/\\//g, '\\\\')\n return `${(match[1] ?? '').toUpperCase()}:\\\\${rest}`\n}\n\n/**\n * Canonical Windows drive path for store keys and cross-realm identity:\n * separators unified to `\\`, trailing separator stripped, and the WHOLE path\n * lowercased — Windows paths compare case-insensitively, and the workspace\n * registry may realpath a different casing than the caller spelled (8.3 or\n * on-disk casing), so the store key must collide across casings.\n * @param path - candidate Windows drive path.\n * @returns the canonical form, or `null` when not drive-shaped.\n */\nexport function canonicalWindowsPath(path: string): string | null {\n const match = /^([A-Za-z]):[\\\\/](.*)$/.exec(path)\n if (match === null) return null\n const rest = (match[2] ?? '').replace(/[\\\\/]+/g, '\\\\').replace(/\\\\$/, '').toLowerCase()\n return `${(match[1] ?? '').toLowerCase()}:\\\\${rest}`\n}\n\n/**\n * True when a value is a Windows-shaped path (drive or UNC), which is how\n * the shell executor decides the WSLENV `/p` translation flag: only Windows\n * path values need translation when they cross into the Linux process.\n * @param value - the environment value to classify.\n * @returns whether the value looks like a Windows path.\n */\nexport function isWindowsPathShaped(value: string): boolean {\n return /^[A-Za-z]:[\\\\/]/.test(value) || value.startsWith('\\\\\\\\')\n}\n\n/** Linux username shape for `wsl.exe -u`: starts with a letter or underscore, then letters/digits/`_`/`.`/`-` (max 64). */\nconst WSL_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/\n\n/**\n * Whether a value is a safe Linux username for `wsl.exe -u`. The check is\n * strict on purpose: a value starting with `-` could be parsed as a wsl.exe\n * option instead of a username.\n * @param value - candidate username.\n * @returns whether it matches the Linux username shape.\n */\nexport function isValidWslUsername(value: string): boolean {\n return WSL_USERNAME_PATTERN.test(value)\n}\n","/**\n * WSL discovery helpers (host side): enumerate installed distributions\n * through `wsl.exe -l -q` and read the default distribution from the Lxss\n * registry key. `wsl.exe` output is UTF-16LE on most builds, so decoding\n * sniffs for NUL bytes before choosing an encoding.\n * @module dsh-wsl-workspace/shared/wsl\n */\n\nimport { execFile, execFileSync } from 'node:child_process'\nimport { promisify } from 'node:util'\n\nconst execFileAsync = promisify(execFile)\n\n/** Executable timeout for the short discovery calls. */\nconst DISCOVERY_TIMEOUT_MS = 10_000\n\nconst LXSS_KEY = 'HKCU\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Lxss'\n\n/** Human text for an unknown rejection. */\nfunction messageOf(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/**\n * Decode `wsl.exe -l -q` output. Newer builds emit UTF-8; most emit UTF-16LE\n * with NUL bytes interleaved — the NUL probe picks the right one.\n * @param buffer - the raw captured output.\n * @returns the decoded text.\n */\nexport function decodeWslOutput(buffer: Buffer): string {\n return buffer.includes(0) ? buffer.toString('utf16le') : buffer.toString('utf8')\n}\n\n/**\n * List installed WSL distributions in `wsl.exe` order.\n * @param wslPath - the `wsl.exe` executable (absolute or PATH name).\n * @returns distribution names, blank lines dropped.\n */\nexport async function listDistros(wslPath = 'wsl.exe'): Promise<string[]> {\n let stdout: Buffer\n try {\n const result = await execFileAsync(wslPath, ['-l', '-q'], { encoding: 'buffer', timeout: DISCOVERY_TIMEOUT_MS })\n stdout = result.stdout as Buffer\n } catch (error) {\n throw new Error(`wsl-workspace: cannot list WSL distributions (${messageOf(error)}); is WSL installed?`)\n }\n return decodeWslOutput(stdout)\n .split(/\\r?\\n/)\n .map(line => line.trim())\n .filter(line => line.length > 0)\n}\n\n/**\n * Read the user's default distribution from the Lxss registry. Non-fatal:\n * returns `undefined` when the value is absent or unreadable (the caller\n * falls back to list order).\n * @returns the default distribution name, or `undefined`.\n */\nexport async function defaultDistro(): Promise<string | undefined> {\n try {\n const value = await execFileAsync('reg.exe', ['query', LXSS_KEY, '/v', 'DefaultDistribution'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const guid = /DefaultDistribution\\s+REG_SZ\\s+(\\{[0-9a-fA-F-]+\\})/i.exec(value.stdout)?.[1]\n if (guid === undefined) return undefined\n const name = await execFileAsync('reg.exe', ['query', `${LXSS_KEY}\\\\${guid}`, '/v', 'DistributionName'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const distro = /DistributionName\\s+REG_SZ\\s+(.+)/i.exec(name.stdout)?.[1]?.trim()\n return distro === undefined || distro === '' ? undefined : distro\n } catch {\n return undefined\n }\n}\n\n/** Module-level cache for {@link defaultDistroSync} (one registry read per process). */\nlet syncDefaultResolved = false\nlet syncDefault: string | undefined\n\n/**\n * Synchronous variant of {@link defaultDistro} for executors that must\n * resolve a distribution inside a synchronous plan step. Cached after the\n * first read; non-fatal (returns `undefined` when the registry is\n * unreadable, letting the caller fail loud with its own message).\n * @returns the default distribution name, or `undefined`.\n */\nexport function defaultDistroSync(): string | undefined {\n if (syncDefaultResolved) return syncDefault\n syncDefaultResolved = true\n try {\n const value = execFileSync('reg.exe', ['query', LXSS_KEY, '/v', 'DefaultDistribution'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const guid = /DefaultDistribution\\s+REG_SZ\\s+(\\{[0-9a-fA-F-]+\\})/i.exec(String(value))?.[1]\n if (guid === undefined) return undefined\n const name = execFileSync('reg.exe', ['query', `${LXSS_KEY}\\\\${guid}`, '/v', 'DistributionName'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const distro = /DistributionName\\s+REG_SZ\\s+(.+)/i.exec(String(name))?.[1]?.trim()\n syncDefault = distro === undefined || distro === '' ? undefined : distro\n } catch {\n syncDefault = undefined\n }\n return syncDefault\n}\n"],"mappings":";;;;;;;;;AAMA,MAAM,qBAAqB;;AAE3B,MAAM,kBAAkB;;AAGxB,MAAM,YAAY,CAAC,oBAAoB;;;;;;;;AAiBvC,SAAgB,YAAY,KAAkC;CAC5D,MAAM,aAAa,IAAI,QAAQ,OAAO,KAAK,QAAQ,UAAU;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