@adrifer/winix 0.3.0-preview.2 → 0.3.0-preview.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.
@@ -1,7 +1,6 @@
1
- import { execFileSync } from "node:child_process";
2
1
  import { filePathExpression, filePathPrelude } from "../../helpers/windows.js";
3
2
  import { powerShellLiteral as ps } from "../../helpers/utils.js";
4
- import { wslRepositoryKey, wslSetupPrelude } from "./wsl-setup.js";
3
+ import { wslRepositoryKey, wslSetupPrelude, wslScriptInvocation } from "./wsl-setup.js";
5
4
  export function validWslImage(value) {
6
5
  if (!value || typeof value !== "object")
7
6
  return false;
@@ -14,32 +13,34 @@ export function validWslImage(value) {
14
13
  const asset = entry.architecture === "x64" ? "nixos.wsl" : "nixos.aarch64.wsl";
15
14
  return entry.url === `https://github.com/nix-community/NixOS-WSL/releases/download/${entry.version}/${asset}`;
16
15
  }
17
- export const resolveNixosWslImage = (architecture) => {
16
+ export const resolveNixosWslImage = async (architecture) => {
18
17
  const assetName = architecture === "x64" ? "nixos.wsl" : "nixos.aarch64.wsl";
19
- const script = `
20
18
  const response = await fetch("https://api.github.com/repos/nix-community/NixOS-WSL/releases/latest", {
21
- headers: { Accept: "application/vnd.github+json", "User-Agent": "Winix" },
22
- signal: AbortSignal.timeout(30000),
19
+ headers: { Accept: "application/vnd.github+json", "User-Agent": "Winix" },
20
+ signal: AbortSignal.timeout(30000),
23
21
  });
24
- if (!response.ok) throw new Error("NixOS-WSL release lookup failed: HTTP " + response.status);
22
+ if (!response.ok)
23
+ throw new Error(`NixOS-WSL release lookup failed: HTTP ${response.status}`);
25
24
  const release = await response.json();
26
- if (release.draft || release.prerelease) throw new Error("Expected a stable NixOS-WSL release");
27
- const asset = release.assets?.find(asset => asset.name === ${JSON.stringify(assetName)});
28
- if (!asset || !/^sha256:[a-f0-9]{64}$/.test(asset.digest)) throw new Error("Release asset lacks a SHA256 digest");
29
- console.log(JSON.stringify({
30
- source: "nixos-wsl", architecture: ${JSON.stringify(architecture)},
31
- version: release.tag_name, url: asset.browser_download_url, sha256: asset.digest.slice(7),
32
- }));
33
- `;
34
- const image = JSON.parse(execFileSync(process.execPath, ["--input-type=module", "--eval", script], {
35
- encoding: "utf8", timeout: 45000, stdio: ["pipe", "pipe", "pipe"],
36
- }));
37
- if (!image || typeof image !== "object" || !validWslImage({ ...image, resolvedAt: "" })) {
25
+ if (!release || typeof release !== "object" || !("draft" in release) || release.draft !== false ||
26
+ !("prerelease" in release) || release.prerelease !== false) {
27
+ throw new Error("Expected a stable NixOS-WSL release");
28
+ }
29
+ const asset = "assets" in release && Array.isArray(release.assets)
30
+ ? release.assets.find((entry) => !!entry && typeof entry === "object" && "name" in entry && entry.name === assetName)
31
+ : undefined;
32
+ if (!asset || typeof asset.digest !== "string" || !/^sha256:[a-f0-9]{64}$/.test(asset.digest)) {
33
+ throw new Error("Release asset lacks a SHA256 digest");
34
+ }
35
+ const image = {
36
+ source: "nixos-wsl", architecture,
37
+ version: "tag_name" in release ? release.tag_name : undefined,
38
+ url: asset.browser_download_url, sha256: asset.digest.slice(7), resolvedAt: "",
39
+ };
40
+ if (!validWslImage(image)) {
38
41
  throw new Error("Invalid official NixOS-WSL release image");
39
42
  }
40
- const validated = image;
41
- if (validated.architecture !== architecture)
42
- throw new Error("NixOS-WSL image architecture mismatch");
43
+ const { resolvedAt: _, ...validated } = image;
43
44
  return validated;
44
45
  };
45
46
  export function optionalFeatureProperties(names, enabled) {
@@ -82,6 +83,16 @@ export function optionalFeatureProperties(names, enabled) {
82
83
  ].join("\n"),
83
84
  };
84
85
  }
86
+ export function wslIdentityProbe(host) {
87
+ return [
88
+ "set -euo pipefail",
89
+ 'export PATH="/run/current-system/sw/bin:/run/wrappers/bin${PATH:+:$PATH}"',
90
+ "grep -Eq '^ID=\"?nixos\"?$' /etc/os-release || { echo 'Existing WSL distro must run NixOS' >&2; exit 2; }",
91
+ 'actual=$(cat /proc/sys/kernel/hostname)',
92
+ `expected='${host.replaceAll("'", "'\\''")}'`,
93
+ '[[ "$actual" == "$expected" ]] || { printf \'Existing NixOS WSL hostname mismatch: expected %s, found %s\\n\' "$expected" "$actual" >&2; exit 2; }',
94
+ ].join("\n");
95
+ }
85
96
  export function wslDistroProperties(distro, pins, repositories = {}) {
86
97
  const images = [];
87
98
  for (const architecture of ["x64", "arm64"]) {
@@ -96,6 +107,7 @@ export function wslDistroProperties(distro, pins, repositories = {}) {
96
107
  ...filePathPrelude(),
97
108
  "if ([Security.Principal.WindowsIdentity]::GetCurrent().IsSystem) { throw 'WSL provisioning must run as the intended Windows user, not SYSTEM' }",
98
109
  `$name = ${ps(distro.name)}`,
110
+ `$expectedHostname = ${ps(distro.host ?? distro.setup?.host ?? "")}`,
99
111
  `$location = ${filePathExpression(distro.installLocation)}`,
100
112
  "if (-not [IO.Path]::IsPathFullyQualified($location)) { throw 'WSL installLocation must resolve to an absolute path' }",
101
113
  "$location = [IO.Path]::GetFullPath($location)",
@@ -103,12 +115,16 @@ export function wslDistroProperties(distro, pins, repositories = {}) {
103
115
  " throw 'WSL installLocation must be an absolute local-drive directory, not a drive root or UNC path'",
104
116
  "}",
105
117
  "$marker = Join-Path $location '.winix-wsl.json'",
118
+ "$localAppData = [Environment]::GetFolderPath('LocalApplicationData')",
119
+ "if (-not $localAppData -or -not [IO.Path]::IsPathFullyQualified($localAppData)) { throw 'Cannot determine WSL tracking location' }",
120
+ "$trackingDirectory = Join-Path $localAppData 'Winix\\wsl-registrations'",
121
+ `$tracking = Join-Path $trackingDirectory ${ps(`registration-${distro.name.toLowerCase()}.json`)}`,
106
122
  "$lxss = 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Lxss'",
107
123
  ` $makeDefault = ${distro.default ? "$true" : "$false"}`,
108
124
  ` $images = @{ ${images.join("; ")} }`,
109
125
  "function Normalize-WinixWslPath([string]$Path) {",
110
126
  " if ($Path.StartsWith('\\\\?\\')) { $Path = $Path.Substring(4) }",
111
- " [IO.Path]::GetFullPath($Path).TrimEnd('\\')",
127
+ " [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetFullPath($Path))",
112
128
  "}",
113
129
  "function Get-WinixWslRegistration {",
114
130
  " if (-not (Test-Path -LiteralPath $lxss)) { return $null }",
@@ -118,17 +134,65 @@ export function wslDistroProperties(distro, pins, repositories = {}) {
118
134
  " if ($matches.Count -eq 1) { return $matches[0] }",
119
135
  " return $null",
120
136
  "}",
121
- "function Assert-WinixWslRegistration($Registration, [bool]$RequireMarker = $true) {",
122
- " if ((Normalize-WinixWslPath $Registration.BasePath) -ine (Normalize-WinixWslPath $location) -or $Registration.Version -ne 2) {",
137
+ "function Assert-WinixWslLocation($Registration) {",
138
+ " if ((Normalize-WinixWslPath $Registration.BasePath) -ine (Normalize-WinixWslPath $location) -or $Registration.Version -ne 2 -or -not $Registration.PSChildName) {",
123
139
  " throw \"Conflicting WSL registration for $name; refusing to move, replace, or convert an existing distro\"",
124
140
  " }",
125
- " if ($RequireMarker) {",
126
- " if (-not (Test-Path -LiteralPath $marker -PathType Leaf)) { throw \"Existing WSL distro $name is not recorded by Winix; refusing automatic adoption\" }",
127
- " $record = [IO.File]::ReadAllText($marker) | ConvertFrom-Json",
128
- " if ($record.version -ne 1 -or $record.source -ne 'nixos-wsl' -or $record.name -ine $name -or $record.registration -ine $Registration.PSChildName) {",
141
+ "}",
142
+ "function Get-WinixWslTracking {",
143
+ " if (-not (Test-Path -LiteralPath $tracking)) { return $null }",
144
+ " $record = [IO.File]::ReadAllText($tracking) | ConvertFrom-Json",
145
+ " if ($record.version -ne 1 -or $record.source -ne 'nixos-wsl' -or $record.name -ine $name -or",
146
+ " $record.adopted -isnot [bool] -or $record.registration -isnot [string] -or -not $record.registration -or",
147
+ " $record.location -isnot [string] -or -not [IO.Path]::IsPathFullyQualified($record.location) -or",
148
+ " ($record.adopted -and ($record.host -isnot [string] -or -not $record.host))) {",
149
+ " throw \"Invalid WSL tracking record: $tracking; inspect it before manual recovery\"",
150
+ " }",
151
+ " return $record",
152
+ "}",
153
+ "function Assert-WinixWslIdentity {",
154
+ " if (-not $expectedHostname) { throw \"Cannot adopt existing WSL distro $name without an expected Linux hostname; declare host or setup.host\" }",
155
+ " if (-not (Invoke-WinixWslIdentity $true)) { throw 'WSL identity validation did not complete' }",
156
+ "}",
157
+ "function Get-WinixWslKind($Registration, $Record) {",
158
+ " if ($Registration.Version -ne 2 -or -not $Registration.PSChildName) { throw \"Expected a WSL 2 registration for $name; refusing conversion or replacement\" }",
159
+ " if ($null -ne $Record) {",
160
+ " if ($Record.registration -ine $Registration.PSChildName -or",
161
+ " (Normalize-WinixWslPath $Record.location) -ine (Normalize-WinixWslPath $Registration.BasePath)) {",
162
+ " throw \"Tracked WSL registration changed for $name; refusing replacement\"",
163
+ " }",
164
+ " if ($Record.adopted) {",
165
+ " if ($Record.host -cne $expectedHostname) { throw \"Adopted WSL hostname declaration changed for $name; refusing relink\" }",
166
+ " Assert-WinixWslIdentity",
167
+ " return 'adopted'",
168
+ " }",
169
+ " }",
170
+ " $existingMarker = Join-Path $Registration.BasePath '.winix-wsl.json'",
171
+ " if (Test-Path -LiteralPath $existingMarker) {",
172
+ " Assert-WinixWslLocation $Registration",
173
+ " $legacy = [IO.File]::ReadAllText($existingMarker) | ConvertFrom-Json",
174
+ " if ($legacy.version -ne 1 -or $legacy.source -ne 'nixos-wsl' -or $legacy.name -ine $name -or $legacy.registration -ine $Registration.PSChildName) {",
129
175
  " throw \"WSL ownership marker does not match registration for $name\"",
130
176
  " }",
177
+ " return 'created'",
178
+ " }",
179
+ " if ($null -ne $Record) { throw \"Winix-created WSL distro $name has lost its ownership marker; refusing adoption\" }",
180
+ " if (Test-Path -LiteralPath $marker) { throw \"Conflicting WSL registration for $name; the configured location already has a Winix marker\" }",
181
+ " Assert-WinixWslIdentity",
182
+ " return 'adopted'",
183
+ "}",
184
+ "function Register-WinixWsl($Registration, [bool]$Adopted) {",
185
+ " $current = Get-WinixWslRegistration",
186
+ " if ($null -eq $current -or $current.PSChildName -ine $Registration.PSChildName -or",
187
+ " (Normalize-WinixWslPath $current.BasePath) -ine (Normalize-WinixWslPath $Registration.BasePath) -or $current.Version -ne 2) {",
188
+ " throw 'WSL registration changed during validation; refusing to record it'",
131
189
  " }",
190
+ " [IO.Directory]::CreateDirectory($trackingDirectory) | Out-Null",
191
+ " $record = @{ version = 1; source = 'nixos-wsl'; name = $name; registration = $Registration.PSChildName;",
192
+ " location = Normalize-WinixWslPath $Registration.BasePath; adopted = $Adopted; host = $expectedHostname }",
193
+ " $stream = [IO.File]::Open($tracking, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None)",
194
+ " $writer = [IO.StreamWriter]::new($stream, [Text.UTF8Encoding]::new($false))",
195
+ " try { $writer.Write(($record | ConvertTo-Json -Compress)) } finally { $writer.Dispose() }",
132
196
  "}",
133
197
  "function Test-WinixWslDefault($Registration) {",
134
198
  " if (-not $makeDefault) { return $true }",
@@ -139,6 +203,8 @@ export function wslDistroProperties(distro, pins, repositories = {}) {
139
203
  " if ($LASTEXITCODE -ne 0) { throw \"WSL command failed ($LASTEXITCODE): $($Arguments -join ' ') $($output -join ' ')\" }",
140
204
  "}",
141
205
  ];
206
+ const identity = wslIdentityProbe(distro.host ?? distro.setup?.host ?? "");
207
+ prelude.push(...wslScriptInvocation("Invoke-WinixWslIdentity", identity, identity, "WSL identity validation"));
142
208
  if (distro.setup) {
143
209
  const pin = repositories[wslRepositoryKey(distro.setup)];
144
210
  if (!pin)
@@ -146,19 +212,32 @@ export function wslDistroProperties(distro, pins, repositories = {}) {
146
212
  prelude.push(...wslSetupPrelude(distro.setup, pin));
147
213
  }
148
214
  return {
149
- getScript: [...prelude, "Get-WinixWslRegistration | Select-Object DistributionName,BasePath,Version"].join("\n"),
215
+ getScript: [
216
+ ...prelude,
217
+ "$registration = Get-WinixWslRegistration",
218
+ "$record = Get-WinixWslTracking",
219
+ "if ($null -eq $registration -and $null -ne $record) { throw 'Tracked WSL registration is missing; inspect tracking before creating a replacement' }",
220
+ "if ($null -ne $registration) { [void](Get-WinixWslKind $registration $record) }",
221
+ "$registration | Select-Object DistributionName,BasePath,Version",
222
+ ].join("\n"),
150
223
  testScript: [
151
224
  ...prelude,
152
225
  "$registration = Get-WinixWslRegistration",
226
+ "$record = Get-WinixWslTracking",
227
+ "if ($null -eq $registration -and $null -ne $record) { throw 'Tracked WSL registration is missing; inspect tracking before creating a replacement' }",
153
228
  "if ($null -eq $registration) { return $false }",
154
- "Assert-WinixWslRegistration $registration",
229
+ "$kind = Get-WinixWslKind $registration $record",
230
+ "if ($null -eq $record) { return $false }",
231
+ "if ($kind -eq 'adopted') { return $true }",
155
232
  ...(distro.setup ? ["if (-not (Invoke-WinixWslSetup $true)) { return $false }"] : []),
156
233
  "Test-WinixWslDefault $registration",
157
234
  ].join("\n"),
158
235
  setScript: [
159
236
  ...prelude,
160
237
  "$registration = Get-WinixWslRegistration",
161
- "if ($null -ne $registration) { Assert-WinixWslRegistration $registration } else {",
238
+ "$record = Get-WinixWslTracking",
239
+ "if ($null -eq $registration -and $null -ne $record) { throw 'Tracked WSL registration is missing; inspect tracking before creating a replacement' }",
240
+ "if ($null -ne $registration) { $kind = Get-WinixWslKind $registration $record } else {",
162
241
  " if ((Test-Path -LiteralPath 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing\\RebootPending') -or",
163
242
  " (Test-Path -LiteralPath 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired')) {",
164
243
  " throw 'WINIX_REBOOT_REQUIRED: Restart Windows yourself, then rerun winix switch before registering WSL.'",
@@ -179,13 +258,16 @@ export function wslDistroProperties(distro, pins, repositories = {}) {
179
258
  " Invoke-WinixWsl @('--import', $name, $location, $archive, '--version', '2')",
180
259
  " $registration = Get-WinixWslRegistration",
181
260
  " if ($null -eq $registration) { throw 'WSL import returned success without registering the requested distro' }",
182
- " Assert-WinixWslRegistration $registration $false",
183
- " $record = @{ version = 1; source = 'nixos-wsl'; name = $name; registration = $registration.PSChildName; imageVersion = $image.Version; sha256 = $image.Sha256 }",
261
+ " Assert-WinixWslLocation $registration",
262
+ " $markerRecord = @{ version = 1; source = 'nixos-wsl'; name = $name; registration = $registration.PSChildName; imageVersion = $image.Version; sha256 = $image.Sha256 }",
184
263
  " $stream = [IO.File]::Open($marker, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None)",
185
264
  " $writer = [IO.StreamWriter]::new($stream, [Text.UTF8Encoding]::new($false))",
186
- " try { $writer.Write(($record | ConvertTo-Json -Compress)) } finally { $writer.Dispose() }",
265
+ " try { $writer.Write(($markerRecord | ConvertTo-Json -Compress)) } finally { $writer.Dispose() }",
187
266
  " } finally { Remove-Item -LiteralPath $temporary -Recurse -Force }",
267
+ " $kind = 'created'",
188
268
  "}",
269
+ "if ($null -eq $record) { Register-WinixWsl $registration ($kind -eq 'adopted') }",
270
+ "if ($kind -eq 'adopted') { Write-Host 'Existing NixOS WSL distro linked; Linux activation remains manual.'; return }",
189
271
  ...(distro.setup ? ["[void](Invoke-WinixWslSetup $false)"] : []),
190
272
  "if (-not (Test-WinixWslDefault $registration)) { Invoke-WinixWsl @('--set-default', $name) }",
191
273
  "if (-not (Test-WinixWslDefault $registration)) { throw 'WSL default distribution verification failed' }",
@@ -29,7 +29,7 @@ export async function applyWorkspace(cwd, opts) {
29
29
  for (const host of windowsHosts)
30
30
  validateWindowsWslResources(host.windows);
31
31
  const windowsLock = windowsHosts.length > 0
32
- ? prepareWindowsLock(configDir, windowsHosts, opts.dry || opts.windowsLockDry === true, opts.resolveWindowsPackageVersion ?? resolveWingetVersion, opts.resolveWindowsModuleVersion ?? resolvePowerShellModuleVersion, opts.resolveWindowsWslImage ?? resolveNixosWslImage, opts.resolveWindowsWslRepository ?? resolveWslRepository)
32
+ ? await prepareWindowsLock(configDir, windowsHosts, opts.dry || opts.windowsLockDry === true, opts.resolveWindowsPackageVersion ?? resolveWingetVersion, opts.resolveWindowsModuleVersion ?? resolvePowerShellModuleVersion, opts.resolveWindowsWslImage ?? resolveNixosWslImage, opts.resolveWindowsWslRepository ?? resolveWslRepository)
33
33
  : undefined;
34
34
  const nixOutput = nixHosts.length > 0 ? generateNix(workspace, nixHosts) : undefined;
35
35
  const windowsOutput = windowsHosts.length > 0
@@ -85,14 +85,14 @@ export async function applyWorkspace(cwd, opts) {
85
85
  export async function apply(cwd, opts) {
86
86
  await applyWorkspace(cwd, opts);
87
87
  }
88
- function prepareWindowsLock(configDir, windowsHosts, dry, resolveVersion, resolveModuleVersion, resolveWslImage, resolveRepository) {
88
+ async function prepareWindowsLock(configDir, windowsHosts, dry, resolveVersion, resolveModuleVersion, resolveWslImage, resolveRepository) {
89
89
  const now = new Date();
90
90
  const lock = readWindowsLock(configDir) ?? emptyWindowsLock(now);
91
91
  const reconciled = reconcileInlinePins(lock, windowsHosts, now);
92
92
  const resolved = resolveMissingWindowsLockEntries(reconciled, windowsHosts, resolveVersion, now);
93
93
  const modules = resolveWindowsModuleLockEntries(resolved.lock, collectWindowsModules(windowsHosts).values(), resolveModuleVersion, now, true);
94
94
  const images = hasWindowsWslDistros(windowsHosts)
95
- ? resolveWindowsWslImages(modules.lock, resolveWslImage, now, true)
95
+ ? await resolveWindowsWslImages(modules.lock, resolveWslImage, now, true)
96
96
  : { lock: modules.lock, changed: false };
97
97
  const repositories = resolveWindowsWslRepositories(images.lock, windowsHosts, resolveRepository, now, true);
98
98
  const changed = windowsLockChanged(lock, repositories.lock);
@@ -1,4 +1,5 @@
1
1
  import { runCommand } from "../run.js";
2
+ export { nodeTypeArguments } from "../node.js";
2
3
  export declare function pinnedWinixVersion(spec: unknown): string;
3
4
  export declare function checkoutWinixVersion(directory: string): Promise<string>;
4
5
  export declare function localWinixCommand(directory: string, expected: string, runtimeVersion: string, executable: string): Promise<{
@@ -6,7 +7,6 @@ export declare function localWinixCommand(directory: string, expected: string, r
6
7
  args: string[];
7
8
  }>;
8
9
  export declare function runCheckout(directory: string, args: string[], run?: typeof runCommand): Promise<void>;
9
- export declare function nodeTypeArguments(version: string): string[];
10
10
  export declare function bootstrapCheckout(directory: string, opts: {
11
11
  host: string;
12
12
  yes: boolean;
@@ -7,6 +7,8 @@ import { execFileSync } from "node:child_process";
7
7
  import { standaloneRuntime } from "../../runtime.js";
8
8
  import { resolveWinixVersionRange } from "./init.js";
9
9
  import { runCommand } from "../run.js";
10
+ import { nodeTypeArguments } from "../node.js";
11
+ export { nodeTypeArguments } from "../node.js";
10
12
  export function pinnedWinixVersion(spec) {
11
13
  if (typeof spec !== "string")
12
14
  throw new Error("package.json must declare an exact @adrifer/winix dependency");
@@ -77,13 +79,6 @@ export async function runCheckout(directory, args, run = runCommand) {
77
79
  }
78
80
  await run(command.command, [...command.args, ...args], { cwd: directory });
79
81
  }
80
- export function nodeTypeArguments(version) {
81
- const parsed = /^v?(\d+)\.(\d+)\.\d+$/.exec(version);
82
- if (!parsed || Number(parsed[1]) < 22 || Number(parsed[1]) === 22 && Number(parsed[2]) < 13) {
83
- throw new Error(`Local SDK requires stable Node >=22.13, found ${version}. Install it explicitly or remove the optional node_modules SDK to retain standalone mode.`);
84
- }
85
- return Number(parsed[1]) >= 26 ? [] : ["--experimental-transform-types"];
86
- }
87
82
  async function confirm(message, yes) {
88
83
  if (yes)
89
84
  return;
@@ -1,8 +1,7 @@
1
1
  import { hostname } from "node:os";
2
2
  import { join } from "node:path";
3
- import { realpath } from "node:fs/promises";
4
3
  import { createHash } from "node:crypto";
5
- import { managedWindowsResources, nativeWindowsStateAdapter, reconcileWindows, resourceKey, windowsStatePath, withWindowsStateLock, } from "../windows-state.js";
4
+ import { managedWindowsResources, nativeWindowsStateAdapter, reconcileWindows, resourceKey, windowsStatePath, windowsStateOwner, withWindowsStateLock, } from "../windows-state.js";
6
5
  import { evaluate } from "../../evaluator/index.js";
7
6
  import { loadWorkspace } from "../loader.js";
8
7
  import { runCommand } from "../run.js";
@@ -49,7 +48,7 @@ export async function switchCommand(cwd, opts) {
49
48
  }
50
49
  await reconcileWindows({
51
50
  statePath,
52
- owner: JSON.stringify([(await realpath(configDir)).toLowerCase(), hostName]),
51
+ owner: await windowsStateOwner(configDir, hostName),
53
52
  desired, definitions,
54
53
  dry: opts.dry,
55
54
  yes: opts.yes,
@@ -105,7 +105,7 @@ async function updateWindowsLock(cwd, opts) {
105
105
  lock = resolvedModules.lock;
106
106
  changed = changed || resolvedModules.changed;
107
107
  if (wslImages && (opts.inputs.length === 0 || opts.inputs.includes("nixos-wsl"))) {
108
- const images = resolveWindowsWslImages(lock, opts.resolveWindowsWslImage ?? resolveNixosWslImage, now);
108
+ const images = await resolveWindowsWslImages(lock, opts.resolveWindowsWslImage ?? resolveNixosWslImage, now);
109
109
  lock = images.lock;
110
110
  changed = changed || images.changed;
111
111
  console.log(` ${images.changed ? "resolved" : "up to date"} NixOS-WSL images (existing distros will not be reinstalled)`);
@@ -1,2 +1,2 @@
1
- #!/usr/bin/env -S node --experimental-transform-types --no-warnings
1
+ #!/usr/bin/env node
2
2
  export {};
package/dist/cli/index.js CHANGED
@@ -1,6 +1,7 @@
1
- #!/usr/bin/env -S node --experimental-transform-types --no-warnings
1
+ #!/usr/bin/env node
2
2
  // Winix CLI entry point
3
3
  import { parseArgs } from "node:util";
4
+ import { dirname } from "node:path";
4
5
  import { apply } from "./commands/apply.js";
5
6
  import { check } from "./commands/check.js";
6
7
  import { init, resolveWinixVersionRange } from "./commands/init.js";
@@ -10,7 +11,8 @@ import { switchCommand } from "./commands/switch.js";
10
11
  import { update } from "./commands/update.js";
11
12
  import { renderSkill } from "../skill.js";
12
13
  import { bootstrapCheckout, runCheckout } from "./commands/bootstrap.js";
13
- import { forgetWindowsResource, windowsStatePath } from "./windows-state.js";
14
+ import { forgetWindowsResource, windowsStatePath, listWindowsOwners, migrateWindowsOwner, windowsStateOwner, } from "./windows-state.js";
15
+ import { findConfig } from "./loader.js";
14
16
  if (process.argv[2] === "run") {
15
17
  try {
16
18
  await runCheckout(process.cwd(), process.argv.slice(3));
@@ -66,12 +68,14 @@ Commands:
66
68
  update Update generated flake.lock and copy it to project root
67
69
  inspect Print host composition and fragment graph
68
70
  state forget Release Windows removal ownership without deleting a resource
71
+ state owners List Windows applied-state owners and their migration IDs
72
+ state migrate-owner <id> Transfer an old owner's requirements to this checkout/--host
69
73
 
70
74
  Options:
71
75
  --host <name> Target a specific host
72
76
  --prepare-only Stop bootstrap after validation/preview; no activation
73
- --dry Preview generation (apply) or activation and managed cleanup (switch)
74
- -y, --yes Confirm managed Windows removals without prompting (switch)
77
+ --dry Preview generation, activation/cleanup, or owner migration
78
+ -y, --yes Confirm bootstrap, managed removals, or explicit owner migration
75
79
  --diff Show diff against current output (apply)
76
80
  --windows Resolve Windows package/module/WSL image lockfile (update)
77
81
  --strict Treat conflicts as errors (check)
@@ -100,8 +104,9 @@ if (values["prepare-only"] && command !== "bootstrap") {
100
104
  console.error("--prepare-only is only supported by winix bootstrap.");
101
105
  process.exit(2);
102
106
  }
103
- if (values.yes && command !== "switch" && command !== "bootstrap") {
104
- console.error("--yes is only supported by winix switch or bootstrap.");
107
+ if (values.yes && command !== "switch" && command !== "bootstrap" &&
108
+ !(command === "state" && positionals[1] === "migrate-owner")) {
109
+ console.error("--yes is only supported by winix switch, bootstrap or state migrate-owner.");
105
110
  process.exit(2);
106
111
  }
107
112
  switch (command) {
@@ -199,6 +204,23 @@ switch (command) {
199
204
  try {
200
205
  if (process.platform !== "win32")
201
206
  throw new Error("Windows applied state is only available on native Windows.");
207
+ if (positionals[1] === "owners" && positionals.length === 2) {
208
+ const owners = await listWindowsOwners(windowsStatePath());
209
+ for (const entry of owners)
210
+ console.log(`${entry.id} ${entry.owner} (${entry.resources} resource(s))`);
211
+ if (!owners.length)
212
+ console.log("No recorded Windows owners.");
213
+ break;
214
+ }
215
+ if (positionals[1] === "migrate-owner" && positionals.length === 3) {
216
+ if (!values.host)
217
+ throw new Error("Owner migration requires --host <new-declared-host>");
218
+ const config = findConfig(cwd);
219
+ if (!config)
220
+ throw new Error("Run owner migration from the new Winix config checkout.");
221
+ await migrateWindowsOwner(windowsStatePath(), positionals[2], await windowsStateOwner(dirname(config), values.host), { dry: values.dry, yes: values.yes });
222
+ break;
223
+ }
202
224
  let resource;
203
225
  if (positionals[1] === "forget" && positionals[2] === "startup" && positionals.length === 4) {
204
226
  resource = { kind: "startup", name: positionals[3] };
@@ -208,7 +230,7 @@ switch (command) {
208
230
  resource = { kind: "package", source: positionals[3], id: positionals[4] };
209
231
  }
210
232
  else {
211
- throw new Error("Usage: winix state forget startup <name> [--dry] OR winix state forget package <winget|msstore> <id> [--dry]");
233
+ throw new Error("Usage: winix state owners | state migrate-owner <id> --host <name> [--dry|--yes] | state forget startup <name> [--dry] | state forget package <winget|msstore> <id> [--dry]");
212
234
  }
213
235
  await forgetWindowsResource(windowsStatePath(), resource, values.dry);
214
236
  }
@@ -9,3 +9,4 @@ export interface LoadResult {
9
9
  * Searches for winix.config.ts in cwd and parent dirs.
10
10
  */
11
11
  export declare function loadWorkspace(cwd: string): Promise<LoadResult>;
12
+ export declare function findConfig(dir: string): string | null;
@@ -22,7 +22,7 @@ export async function loadWorkspace(cwd) {
22
22
  `Run \`winix init\` to create one.`);
23
23
  }
24
24
  const configDir = dirname(configPath);
25
- // Import the config file (requires Node --experimental-strip-types or pre-compiled)
25
+ // The npm launcher or embedded runtime supplies TypeScript support.
26
26
  const fileUrl = pathToFileURL(configPath).href;
27
27
  const mod = await import(__rewriteRelativeImportExtension(fileUrl));
28
28
  const workspace = mod.default;
@@ -31,7 +31,7 @@ export async function loadWorkspace(cwd) {
31
31
  }
32
32
  return { workspace, configDir, configPath };
33
33
  }
34
- function findConfig(dir) {
34
+ export function findConfig(dir) {
35
35
  let current = resolve(dir);
36
36
  for (let i = 0; i < 10; i++) {
37
37
  for (const name of CONFIG_NAMES) {
@@ -0,0 +1 @@
1
+ export declare function nodeTypeArguments(version: string): string[];
@@ -0,0 +1,8 @@
1
+ export function nodeTypeArguments(version) {
2
+ const parsed = /^v?(\d+)\.(\d+)\.\d+$/.exec(version);
3
+ if (!parsed || ![22, 24, 26].includes(Number(parsed[1])) ||
4
+ Number(parsed[1]) === 22 && Number(parsed[2]) < 13) {
5
+ throw new Error(`Winix npm requires stable Node 22.13+, 24.x or 26.x; found ${version}. Node 24 supports transformation; Node 26 supports erasable TypeScript only.`);
6
+ }
7
+ return Number(parsed[1]) >= 26 ? [] : ["--experimental-transform-types"];
8
+ }
@@ -41,6 +41,17 @@ export interface ReconcileOptions {
41
41
  lockHeld?: boolean;
42
42
  }
43
43
  export declare function resourceKey(resource: ManagedResource): string;
44
+ export declare function windowsStateOwner(configDir: string, host: string): Promise<string>;
45
+ export declare function windowsOwnerId(owner: string): string;
46
+ export declare function listWindowsOwners(path: string): Promise<{
47
+ id: string;
48
+ owner: string;
49
+ resources: number;
50
+ }[]>;
51
+ export declare function migrateWindowsOwner(path: string, oldId: string, target: string, opts: {
52
+ dry: boolean;
53
+ yes?: boolean;
54
+ }, report?: (message: string) => void): Promise<void>;
44
55
  export declare function managedWindowsResources(host: EvaluatedHost): ManagedResource[];
45
56
  export declare function parseAppliedState(text: string): AppliedState;
46
57
  export declare function withWindowsStateLock<T>(path: string, dry: boolean, action: () => Promise<T>): Promise<T>;
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { execFileSync } from "node:child_process";
3
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import { mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
4
4
  import { hostname } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
  import { createInterface } from "node:readline/promises";
@@ -11,6 +11,51 @@ export function resourceKey(resource) {
11
11
  ? ["startup", resource.name.toLowerCase()]
12
12
  : ["package", resource.source.toLowerCase(), resource.id.toLowerCase()]);
13
13
  }
14
+ export async function windowsStateOwner(configDir, host) {
15
+ if (!host)
16
+ throw new Error("A host name is required");
17
+ return JSON.stringify([(await realpath(configDir)).toLowerCase(), host]);
18
+ }
19
+ export function windowsOwnerId(owner) {
20
+ return createHash("sha256").update(owner).digest("hex");
21
+ }
22
+ export async function listWindowsOwners(path) {
23
+ const state = await loadState(path);
24
+ const counts = new Map();
25
+ for (const entry of Object.values(state.entries)) {
26
+ for (const owner of new Set(entry.owners))
27
+ counts.set(owner, (counts.get(owner) ?? 0) + 1);
28
+ }
29
+ return [...counts].sort(([left], [right]) => left.localeCompare(right))
30
+ .map(([owner, resources]) => ({ id: windowsOwnerId(owner), owner, resources }));
31
+ }
32
+ export async function migrateWindowsOwner(path, oldId, target, opts, report = console.log) {
33
+ if (!/^[a-f0-9]{64}$/i.test(oldId) || !target)
34
+ throw new Error("Use an owner ID from winix state owners and a target owner");
35
+ if (!opts.dry && !opts.yes) {
36
+ throw new Error("Owner migration changes applied-state requirements. Preview with --dry, then confirm with --yes. No resources will be deleted.");
37
+ }
38
+ await withWindowsStateLock(path, opts.dry, async () => {
39
+ const state = await loadState(path);
40
+ const owners = new Set(Object.values(state.entries).flatMap((entry) => entry.owners));
41
+ const matches = [...owners].filter((owner) => windowsOwnerId(owner) === oldId.toLowerCase());
42
+ if (matches.length !== 1)
43
+ throw new Error("Recorded owner not found or ambiguous; run winix state owners");
44
+ const previous = matches[0];
45
+ if (previous === target)
46
+ throw new Error("The recorded owner already matches this checkout and host");
47
+ report(`${opts.dry ? "Would migrate" : "Migrating"} owner ${previous} -> ${target}`);
48
+ for (const [key, entry] of Object.entries(state.entries)) {
49
+ if (!entry.owners.includes(previous))
50
+ continue;
51
+ report(` ${key}`);
52
+ entry.owners = [...new Set(entry.owners.map((owner) => owner === previous ? target : owner))];
53
+ }
54
+ if (!opts.dry)
55
+ await saveState(path, state);
56
+ report("No installed resources changed. Ownership, snapshots and shared requirements are preserved; the next switch still checks drift and confirms removals.");
57
+ });
58
+ }
14
59
  export function managedWindowsResources(host) {
15
60
  const windows = host.windows;
16
61
  const resources = Object.values(windows.packages ?? {}).map((pkg) => ({ kind: "package", id: pkg.id, source: pkg.source }));
@@ -165,7 +210,8 @@ export async function reconcileWindows(opts) {
165
210
  if (typeof opts.definitions[key] !== "string")
166
211
  throw new Error(`Missing resource definition: ${key}`);
167
212
  if (entry?.owners.some((owner) => owner !== opts.owner) && entry.definition !== opts.definitions[key]) {
168
- throw new Error(`Conflicting declaration for resource required by another workspace/host: ${key}`);
213
+ throw new Error(`Conflicting declaration for resource required by another workspace/host: ${key}. ` +
214
+ "Run winix state owners; after a checkout move or host rename, explicitly preview state migrate-owner <id> --host <name> --dry.");
169
215
  }
170
216
  if (entry?.owned && current !== null && !sameSnapshot(current, entry.snapshot)) {
171
217
  throw new Error(`Managed resource changed outside Winix: ${key}. Restore it or explicitly resolve ownership before activation.`);
@@ -3,6 +3,8 @@ export interface ResolvedPowerShellModule extends WinPowerShellModule {
3
3
  repository: string;
4
4
  repositoryUri?: string;
5
5
  }
6
+ export declare const powerShellModuleVersion: RegExp;
7
+ export declare function windowsSettingsModule(win: WindowsOptions): ResolvedPowerShellModule;
6
8
  export declare const powerShellRepositoryName: RegExp;
7
9
  export declare function powerShellRepositoryUri(value: string): string;
8
10
  export declare function validatePowerShellRepositoryPolicy(policy: WinPowerShellRepositoryPolicy): void;
@@ -1,3 +1,7 @@
1
+ export const powerShellModuleVersion = /^\d+\.\d+\.\d+(?:\.\d+)?(?:-[a-z0-9]+(?:[.-][a-z0-9]+)*)?$/i;
2
+ export function windowsSettingsModule(win) {
3
+ return resolvePowerShellModule(win, { name: "Microsoft.Windows.Settings", prerelease: true });
4
+ }
1
5
  export const powerShellRepositoryName = /^[a-z0-9][a-z0-9._-]*$/i;
2
6
  export function powerShellRepositoryUri(value) {
3
7
  let url;
@@ -50,6 +50,8 @@ export interface WinSettingOpts {
50
50
  export interface WinPowerShellModuleOpts {
51
51
  /** Registered repository; inherits the host policy, otherwise PSGallery. */
52
52
  repository?: string;
53
+ /** Include prereleases during lock resolution. Defaults to stable releases only. */
54
+ prerelease?: boolean;
53
55
  dependsOn?: ResourceHandle | ResourceHandle[];
54
56
  }
55
57
  export interface WinStartupCommandSpec extends WinStartupCommand {
@@ -72,7 +74,9 @@ export interface WinWslOpts extends Pick<WinFileOpts, "backup" | "force" | "depe
72
74
  config?: WinWslConfig;
73
75
  }
74
76
  export interface WinWslNamespace {
77
+ /** Declare the locked Microsoft.WSL package, required features, and optional .wslconfig. */
75
78
  (opts?: WinWslOpts): ResourceHandle;
79
+ /** Create an absent distro or adopt a matching WSL 2/NixOS/Linux hostname registration. */
76
80
  distro(name: string, spec: WinWslDistroSpec): ResourceHandle;
77
81
  }
78
82
  export declare function filePathExpression(value: WinFilePath): string;