@adrifer/winix 0.3.0-preview.8 → 0.3.0-preview.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +102 -12
  2. package/dist/backends/nix/index.d.ts +1 -0
  3. package/dist/backends/nix/index.js +18 -1
  4. package/dist/backends/windows/index.d.ts +9 -1
  5. package/dist/backends/windows/index.js +10 -10
  6. package/dist/backends/windows/lockfile.d.ts +3 -3
  7. package/dist/backends/windows/lockfile.js +4 -3
  8. package/dist/backends/windows/powershell.d.ts +4 -2
  9. package/dist/backends/windows/powershell.js +152 -21
  10. package/dist/backends/windows/wsl-setup-runtime.d.ts +17 -1
  11. package/dist/backends/windows/wsl-setup-runtime.js +75 -11
  12. package/dist/backends/windows/wsl-setup.d.ts +7 -1
  13. package/dist/backends/windows/wsl-setup.js +29 -8
  14. package/dist/backends/windows/wsl.js +1 -1
  15. package/dist/cli/analysis.d.ts +11 -2
  16. package/dist/cli/analysis.js +35 -7
  17. package/dist/cli/commands/apply.d.ts +6 -1
  18. package/dist/cli/commands/apply.js +12 -6
  19. package/dist/cli/commands/check.js +11 -5
  20. package/dist/cli/commands/inspect.js +2 -2
  21. package/dist/cli/commands/switch.d.ts +7 -0
  22. package/dist/cli/commands/switch.js +58 -11
  23. package/dist/cli/commands/update.js +4 -4
  24. package/dist/cli/windows-package-versions.d.ts +2 -1
  25. package/dist/cli/windows-package-versions.js +12 -5
  26. package/dist/cli/windows-state.js +45 -17
  27. package/dist/core/types.d.ts +18 -0
  28. package/dist/evaluator/index.d.ts +5 -3
  29. package/dist/evaluator/index.js +30 -16
  30. package/dist/helpers/account.js +1 -7
  31. package/dist/helpers/home.d.ts +18 -0
  32. package/dist/helpers/home.js +39 -0
  33. package/dist/helpers/index.d.ts +2 -2
  34. package/dist/helpers/nix.d.ts +14 -0
  35. package/dist/helpers/nix.js +2 -0
  36. package/dist/helpers/platforms.d.ts +13 -0
  37. package/dist/helpers/platforms.js +35 -19
  38. package/dist/helpers/windows.d.ts +35 -2
  39. package/dist/helpers/windows.js +55 -4
  40. package/dist/helpers/wsl-interop.d.ts +13 -0
  41. package/dist/helpers/wsl-interop.js +72 -0
  42. package/dist/helpers/wsl-repository.d.ts +12 -0
  43. package/dist/helpers/wsl-repository.js +93 -0
  44. package/dist/index.d.ts +3 -3
  45. package/dist/sdk/index.d.ts +5 -1
  46. package/dist/sdk/index.js +9 -2
  47. package/dist/skill.js +23 -2
  48. package/dist/types/windows.d.ts +6 -0
  49. package/package.json +1 -1
package/README.md CHANGED
@@ -418,9 +418,21 @@ const shell = feature("shell", ({ home, platforms }) =>
418
418
  );
419
419
  ```
420
420
 
421
+ `platforms.wsl({ stateVersion, ... })` is NixOS running under WSL. It takes the
422
+ same options as `platforms.nixos()`, imports the NixOS-WSL module and sets
423
+ `wsl.enable`, so a WSL host needs no module boilerplate. Declare the input
424
+ (`nixosWsl: input("github:nix-community/NixOS-WSL", { follows: { nixpkgs: "nixpkgs" } })`);
425
+ `winix check` warns when an imported module's input is missing. Pass
426
+ `input: "<name>"` if your NixOS-WSL input has another Nix name. A WSL host is
427
+ still NixOS, so `platforms.nixos.isActive` stays true there and
428
+ `platforms.wsl.isActive` tells WSL hosts apart.
429
+
421
430
  ### Account helpers
422
431
 
423
432
  `account.user()` wires together platform users and Home Manager users.
433
+ On NixOS-WSL, `wslDefault: true` sets `wsl.defaultUser` as a Nix default,
434
+ unless the host already declares a default user. It detects WSL from
435
+ `wsl.enable` or the NixOS-WSL module import, not a feature or profile name.
424
436
 
425
437
  ```ts
426
438
  const adrifer = account.user("adrifer", () => ({
@@ -430,7 +442,7 @@ const adrifer = account.user("adrifer", () => ({
430
442
  wslDefault: true,
431
443
  }));
432
444
 
433
- host("wsl", platforms.nixos({ stateVersion: "25.05" }), [
445
+ host("wsl", platforms.wsl({ stateVersion: "25.05" }), [
434
446
  adrifer(),
435
447
  ]);
436
448
  ```
@@ -448,7 +460,7 @@ nixos.users({ users: { root: { shell: nix.pkg("bash") } } })
448
460
  nixos.system({ stateVersion: "25.05" })
449
461
 
450
462
  home.program("zsh", { enableCompletion: true })
451
- home.configFiles({ nvim: home.symlink("~/dotfiles/nvim/.config/nvim") })
463
+ home.configFiles({ nvim: home.symlink("../nvim/.config/nvim") })
452
464
  home.activation("ensureNpmrc", { script: "mkdir -p \"$HOME/.config/npm\"" })
453
465
 
454
466
  darwin.defaults({ dock: { autohide: true } })
@@ -643,8 +655,8 @@ replace existing pins. Network access is still needed for installation.
643
655
 
644
656
  `windows.powershell.module(name, { repository?, prerelease?, dependsOn? })` defaults to
645
657
  the host repository policy, otherwise PSGallery, selects stable releases, and installs the exact locked version for
646
- the current user. PowerShell 7 with PSResourceGet must already be available for
647
- resolution. Installation is idempotent and runs directly in DSC's
658
+ the current user. Registered feeds are queried with PowerShell 7 and PSResourceGet.
659
+ Installation is idempotent and runs directly in DSC's
648
660
  `Microsoft.DSC.Transitional/PowerShellScript` resource; a declared `Microsoft.PowerShell` package is an
649
661
  automatic dependency. Other versions are not removed. Profiles still import
650
662
  modules themselves; an unversioned `Import-Module` can load a newer installed
@@ -684,13 +696,16 @@ PowerShell installers, not raw commands, generic DSC, npm, NuGet, or WSL.
684
696
  Personal hosts without this feature retain PSGallery.
685
697
  Conflicting policies in one host fail instead of silently widening its allowlist.
686
698
 
687
- Named feeds use HTTPS URLs without embedded credentials. Version resolution
688
- registers a missing feed for the current user; activation also ensures registration
689
- before module installation. A same-name registration with a different URI is an
690
- error, never overwritten. Registration persists, but global priorities and permanent
691
- trust are unchanged. Authenticate separately using the organization's supported
692
- PSResourceGet setup; do not put secrets in config or locks. `--dry` does not write
693
- the lock or activate resources, but resolving missing versions can register a feed.
699
+ Named feeds use HTTPS URLs without embedded credentials. Lock resolution reuses an
700
+ existing registration only when its name and URI match. Otherwise, it queries the
701
+ declared NuGet v3 feed's `PackageBaseAddress` anonymously, without following
702
+ redirects. Feeds that require authentication or do not expose this v3 endpoint
703
+ need a matching registration configured separately through PSResourceGet.
704
+ PSGallery uses its public v2 endpoint if no matching registration exists.
705
+ Lock resolution never creates or modifies registrations, including during `--dry`.
706
+ Activation ensures registration before module installation and rejects a same-name
707
+ registration with a different URI. Global priorities and permanent trust are
708
+ unchanged. Do not put secrets in config or locks.
694
709
  Pins distinguish module name, repository name, and configured URI across hosts;
695
710
  a new source resolves its own pin. Existing matching installed versions are reused,
696
711
  not reinstalled to attest their original source. Settings retains its existing
@@ -823,12 +838,82 @@ and dependency authentication must already be available inside Linux; credential
823
838
  are never provisioned by this helper.
824
839
 
825
840
  The Linux host must explicitly enable NixOS-WSL, import its input module, declare
826
- `system.stateVersion`, and match the distro architecture. `user` selects an
841
+ `system.stateVersion`, and match the distro architecture; `platforms.wsl({
842
+ stateVersion })` does all of that. `user` selects an
827
843
  already-declared normal account, not a second account definition. Omit it when
828
844
  Home Manager or the sole normal account identifies the user unambiguously.
845
+ `winix check` (and every apply) validates the whole setup plan offline, before
846
+ any distro exists: `setup.host` names one NixOS host, the NixOS-WSL module and
847
+ `system.stateVersion` are declared, the account is a normal user on that host and
848
+ the checkout stays inside its home. Errors name the Windows host and distro.
829
849
  Home Manager's username/home must agree with the selected account. `checkout`
830
850
  defaults to `<declared-home>/dotfiles` and must stay inside that home.
831
851
 
852
+ #### Pair a Windows host with its WSL host
853
+
854
+ Strings that must match across hosts drift. Hold the Linux host in a variable and
855
+ pass values instead; `repository: "self"` reuses the checkout you run Winix from:
856
+
857
+ ```ts
858
+ const alice = account.user("alice", () => ({ admin: true, shell: "zsh", stateVersion: "25.05", wslDefault: true }));
859
+
860
+ const wslWork = host("wsl-work", platforms.wsl({ stateVersion: "25.05" }), [alice(), devTools()]);
861
+
862
+ const desktop = host("DESKTOP", platforms.windows(), ({ windows }) => {
863
+ windows.wsl();
864
+ windows.wsl.distro("NixOS", {
865
+ source: "nixos-wsl",
866
+ installLocation: windows.knownFolder.localAppData("Winix\\WSL\\NixOS"),
867
+ default: true,
868
+ setup: { repository: "self", host: wslWork, user: alice },
869
+ });
870
+ });
871
+
872
+ export default workspace({ inputs, hosts: [desktop, wslWork] });
873
+ ```
874
+
875
+ - `host` accepts the value returned by `host(...)` (or its name), and `user`
876
+ the `account.user(...)` factory (or its name). A distro's adoption `host`
877
+ accepts a host value too.
878
+ - `repository: "self"` reads the Git checkout holding `winix.config.ts` (local
879
+ Git only): the current branch's tracked remote (else `origin`; SSH remotes
880
+ such as `git@github.com:me/dotfiles.git` become HTTPS), its upstream branch as
881
+ `ref` (the commit when detached) and the config's path as `configDirectory`.
882
+ The commit is still pinned in `wslRepositories`; push the branch first, since
883
+ the pin is resolved on the remote. An inferred `ref` is left out of the
884
+ completed-setup fingerprint, so switching branches on Windows never trips the
885
+ "settings changed" guard on finished distros. Any other change to a setup
886
+ declaration, including moving to `"self"` without the same explicit `ref`,
887
+ still changes the fingerprint, and completed distros then refuse activation.
888
+ Keep the existing `ref` and `checkout` explicit when migrating machines that
889
+ were already provisioned.
890
+ - After `winix switch` on Windows, Winix prints how to apply later Linux changes
891
+ in each distro, e.g. `wsl.exe -d NixOS --cd /home/alice/dotfiles/winix --
892
+ npm exec -- winix switch --host wsl-work`.
893
+
894
+ #### Reach Windows from WSL
895
+
896
+ Avoid hard-coding the Windows user or drive in Linux config. These helpers find
897
+ Windows programs through interop each time they run:
898
+
899
+ ```ts
900
+ feature("windows-interop", ({ home }) => {
901
+ // bin/code-insiders runs the Windows VS Code Insiders CLI.
902
+ home.packages(nix.wsl.windowsBin("code-insiders",
903
+ "%LOCALAPPDATA%\\Programs\\Microsoft VS Code Insiders\\bin\\code-insiders"));
904
+ // git uses Git for Windows' Credential Manager.
905
+ home.wsl.gitCredentialManager();
906
+ });
907
+ ```
908
+
909
+ `nix.wsl.windowsBin(name, paths)` builds a package whose `bin/<name>` runs the
910
+ first existing path from a list. Paths are absolute (`C:\...`) or start with an
911
+ environment variable (`%LOCALAPPDATA%\...`); variables are expanded with
912
+ `cmd.exe` and converted with `wslpath`, which costs about 50ms per run. The shim exits 127
913
+ with the paths it tried when none exist. `home.wsl.gitCredentialManager({ paths? })`
914
+ enables `programs.git` and points `credential.helper` at such a shim for Git for
915
+ Windows' ucrt64/mingw64 GCM.
916
+
832
917
  First apply locks the repository ref (default `HEAD`) to a commit in
833
918
  `wslRepositories`. `winix update --windows wsl-setup` refreshes these pins;
834
919
  an update without names includes them too. Dry generation never clones or executes
@@ -1129,6 +1214,11 @@ Normal missing-pin resolution remains unchanged. These defaults apply to
1129
1214
  `winix switch`, not direct generated-script/DSC activation or plain `apply`.
1130
1215
 
1131
1216
  Startup file hashes and installed package versions still protect removals.
1217
+ If the installed version is non-numeric or reported as `Unknown` (common for
1218
+ self-updating installers), switch warns and emits that floating package without
1219
+ a version, so activation ensures it is installed instead of reinstalling the
1220
+ locked version every run. The lock entry is kept. Exact pins still require a
1221
+ match, and automatic removal refuses non-comparable installed versions.
1132
1222
  External shortcut edits, package downgrades, and exact-pin drift block
1133
1223
  reconciliation rather than silently deleting or overwriting managed resources.
1134
1224
  Restore the recorded resource, or explicitly
@@ -16,3 +16,4 @@ export interface RawModuleCopy {
16
16
  * Generate Nix files from an evaluated workspace.
17
17
  */
18
18
  export declare function generateNix(workspace: WorkspaceDef, evaluatedHosts: EvaluatedHost[]): NixOutput;
19
+ export declare function hasHomeManagerImport(host: EvaluatedHost): boolean;
@@ -392,9 +392,26 @@ function validateWorkspaceInputs(workspace, hosts) {
392
392
  if (hosts.some(hasHomeManagerImport) && !hasInput(workspace, "home-manager")) {
393
393
  warnings.push("home-manager module import detected but workspace inputs do not include home-manager");
394
394
  }
395
+ const missing = new Map();
396
+ for (const host of hosts) {
397
+ for (const imp of [...getImports(host.nixos), ...getImports(host.darwin), ...getImports(host.homeManager)]) {
398
+ const name = typeof imp === "string" ? /^inputs\.([A-Za-z_][A-Za-z0-9_'-]*)\./.exec(imp.trim())?.[1] : undefined;
399
+ if (!name || name === "home-manager" || hasInput(workspace, name))
400
+ continue;
401
+ if (!missing.has(name))
402
+ missing.set(name, new Set());
403
+ missing.get(name).add(host.name);
404
+ }
405
+ }
406
+ for (const [name, hostNames] of missing) {
407
+ const hint = name === "nixos-wsl"
408
+ ? ` (e.g. nixosWsl: input("github:nix-community/NixOS-WSL", { follows: { nixpkgs: "nixpkgs" } }))`
409
+ : "";
410
+ warnings.push(`${[...hostNames].join(", ")}: module import uses inputs.${name}, but workspace inputs do not include ${name}${hint}`);
411
+ }
395
412
  return warnings;
396
413
  }
397
- function hasHomeManagerImport(host) {
414
+ export function hasHomeManagerImport(host) {
398
415
  return [
399
416
  ...getImports(host.nixos),
400
417
  ...getImports(host.darwin),
@@ -22,5 +22,13 @@ export interface WindowsOutput {
22
22
  * Generate Windows bundles for every Windows host in the evaluated workspace.
23
23
  * Non-Windows hosts are skipped.
24
24
  */
25
- export declare function generateWindows(evaluatedHosts: EvaluatedHost[], lock?: WindowsLock, configDir?: string): WindowsOutput;
25
+ export interface GenerateWindowsOptions {
26
+ /**
27
+ * Floating package ids whose installed version is not comparable (winget
28
+ * reports e.g. "Unknown"). They are emitted without `version`, so DSC only
29
+ * ensures presence instead of reinstalling the locked version on every run.
30
+ */
31
+ presenceOnlyPackages?: ReadonlySet<string>;
32
+ }
33
+ export declare function generateWindows(evaluatedHosts: EvaluatedHost[], lock?: WindowsLock, configDir?: string, options?: GenerateWindowsOptions): WindowsOutput;
26
34
  export declare function validateWindowsWslResources(win: WindowsOptions): void;
@@ -44,11 +44,7 @@ const DSC_SCHEMA = "https://raw.githubusercontent.com/PowerShell/DSC/main/schema
44
44
  const WINGET_PACKAGE_TYPE = "Microsoft.WinGet/Package";
45
45
  const RUN_COMMAND_ON_SET_TYPE = "Microsoft.DSC.Transitional/RunCommandOnSet";
46
46
  const WINDOWS_SETTINGS_MODULE_COMMAND_NAME = "Ensure Microsoft Windows Settings module";
47
- /**
48
- * Generate Windows bundles for every Windows host in the evaluated workspace.
49
- * Non-Windows hosts are skipped.
50
- */
51
- export function generateWindows(evaluatedHosts, lock = emptyWindowsLock(), configDir) {
47
+ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock(), configDir, options = {}) {
52
48
  const hosts = {};
53
49
  const warnings = [];
54
50
  const windowsHosts = evaluatedHosts.filter(isWindowsHost);
@@ -56,7 +52,7 @@ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock(), confi
56
52
  for (const host of windowsHosts) {
57
53
  const win = host.windows;
58
54
  hosts[host.name] = {
59
- "configuration.winget": generateConfiguration(host.name, win, resolvedLock, configDir),
55
+ "configuration.winget": generateConfiguration(host.name, win, resolvedLock, configDir, options.presenceOnlyPackages),
60
56
  "apply.ps1": generateApplyScript(),
61
57
  };
62
58
  }
@@ -65,7 +61,7 @@ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock(), confi
65
61
  /**
66
62
  * Render the WinGet Configuration YAML document (DSC v3) for one host.
67
63
  */
68
- function generateConfiguration(hostName, win, lock, configDir) {
64
+ function generateConfiguration(hostName, win, lock, configDir, presenceOnlyPackages = new Set()) {
69
65
  validateWindowsWslResources(win);
70
66
  validateWindowsPowerShellPolicy(win);
71
67
  const packages = sortedPackages(win.packages ?? {});
@@ -162,7 +158,9 @@ function generateConfiguration(hostName, win, lock, configDir) {
162
158
  lines.push("resources:");
163
159
  for (const pkg of packages) {
164
160
  const plan = naming.packages.get(pkg);
165
- lines.push(...renderPackageResource(pkg, lockedVersionForPackage(pkg, lock), plan, naming));
161
+ const version = lockedVersionForPackage(pkg, lock);
162
+ const presenceOnly = pkg.version === undefined && presenceOnlyPackages.has(pkg.id);
163
+ lines.push(...renderPackageResource(pkg, presenceOnly ? undefined : version, plan, naming));
166
164
  }
167
165
  for (const command of commands) {
168
166
  const plan = naming.commands.get(command);
@@ -538,8 +536,10 @@ function renderPackageResource(pkg, version, plan, naming) {
538
536
  out.push(` id: ${yamlScalar(pkg.id)}`);
539
537
  out.push(` source: ${yamlScalar(pkg.source)}`);
540
538
  out.push(` acceptAgreements: true`);
541
- // Quote versions so values like "1.0" are not parsed as numbers.
542
- out.push(` version: ${yamlQuoted(version)}`);
539
+ // Quote versions so values like "1.0" are not parsed as numbers. Presence-only
540
+ // packages (non-comparable installed version) omit it deliberately.
541
+ if (version !== undefined)
542
+ out.push(` version: ${yamlQuoted(version)}`);
543
543
  // Only request elevation when explicitly asked. Per-user packages install
544
544
  // fine without it, and forcing elevation makes `winget configure` fail with
545
545
  // an internal error when run from a non-elevated shell.
@@ -35,7 +35,7 @@ export interface WindowsLockModule {
35
35
  version: string;
36
36
  resolvedAt: string;
37
37
  }
38
- export type WindowsModuleVersionResolver = (name: string, repository: string, repositoryUri?: string, prerelease?: boolean) => string;
38
+ export type WindowsModuleVersionResolver = (name: string, repository: string, repositoryUri?: string, prerelease?: boolean) => string | Promise<string>;
39
39
  export declare function windowsModuleKey(module: ResolvedPowerShellModule): string;
40
40
  export declare function windowsModulePin(lock: WindowsLock, module: ResolvedPowerShellModule): WindowsLockModule | undefined;
41
41
  export type WindowsPackageVersionResolver = (id: string, source: WinPackageSource) => string;
@@ -69,8 +69,8 @@ export declare function resolveWindowsWslRepositories(lock: WindowsLock, hosts:
69
69
  lock: WindowsLock;
70
70
  changed: boolean;
71
71
  };
72
- export declare function resolveWindowsModuleLockEntries(lock: WindowsLock, modules: Iterable<ResolvedPowerShellModule>, resolveVersion: WindowsModuleVersionResolver, now?: Date, missingOnly?: boolean): {
72
+ export declare function resolveWindowsModuleLockEntries(lock: WindowsLock, modules: Iterable<ResolvedPowerShellModule>, resolveVersion: WindowsModuleVersionResolver, now?: Date, missingOnly?: boolean): Promise<{
73
73
  lock: WindowsLock;
74
74
  resolutions: Omit<WindowsLockResolution, "source">[];
75
75
  changed: boolean;
76
- };
76
+ }>;
@@ -260,7 +260,7 @@ export function resolveWindowsWslRepositories(lock, hosts, resolve, now = new Da
260
260
  }
261
261
  return { lock: changed ? { ...lock, generatedAt: now.toISOString(), wslRepositories: repositories } : lock, changed };
262
262
  }
263
- export function resolveWindowsModuleLockEntries(lock, modules, resolveVersion, now = new Date(), missingOnly = false) {
263
+ export async function resolveWindowsModuleLockEntries(lock, modules, resolveVersion, now = new Date(), missingOnly = false) {
264
264
  const next = { ...lock, modules: { ...lock.modules } };
265
265
  const resolutions = [];
266
266
  let changed = false;
@@ -270,9 +270,10 @@ export function resolveWindowsModuleLockEntries(lock, modules, resolveVersion, n
270
270
  if (missingOnly && previous) {
271
271
  continue;
272
272
  }
273
- const version = resolveVersion(module.name, module.repository, module.repositoryUri, !!module.prerelease);
273
+ const version = await resolveVersion(module.name, module.repository, module.repositoryUri, !!module.prerelease);
274
274
  if (!powerShellModuleVersion.test(version) || (!module.prerelease && version.includes("-"))) {
275
- throw new Error(`PowerShell module "${module.name}" resolver did not return an allowed version: ${version}`);
275
+ const source = module.repositoryUri ? ` (${module.repositoryUri})` : "";
276
+ throw new Error(`PowerShell module "${module.name}" resolver for "${module.repository}"${source} did not return an allowed version: ${version}`);
276
277
  }
277
278
  const unchanged = previous?.version === version &&
278
279
  previous.repository.toLowerCase() === module.repository.toLowerCase();
@@ -6,6 +6,8 @@ export declare function powerShellRepositoryScripts(name: string, uri: string):
6
6
  set: string;
7
7
  };
8
8
  export type PowerShellGalleryRunner = (script: string) => string;
9
- /** Find-PSResource returns the newest stable release unless -Prerelease is requested. */
10
- export declare function resolvePowerShellModuleVersion(name: string, repository: string, repositoryUriOrRunner?: string | PowerShellGalleryRunner, prereleaseOrRunner?: boolean | PowerShellGalleryRunner, runner?: PowerShellGalleryRunner): string;
9
+ export declare function resolvePowerShellModuleVersion(name: string, repository: string, repositoryUri?: string, prerelease?: boolean, { run, fetch: fetchFeed }?: {
10
+ run?: PowerShellGalleryRunner;
11
+ fetch?: typeof fetch;
12
+ }): Promise<string>;
11
13
  export declare function powerShellModuleProperties(module: WinPowerShellModule, pin: WindowsLockModule): WinDscProperties;
@@ -1,6 +1,6 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { powerShellLiteral } from "../../helpers/utils.js";
3
- import { powerShellModuleVersion } from "../../helpers/windows-repositories.js";
3
+ import { powerShellModuleVersion, powerShellRepositoryName, powerShellRepositoryUri, } from "../../helpers/windows-repositories.js";
4
4
  export function powerShellRepositoryScripts(name, uri) {
5
5
  const prelude = [
6
6
  "$ErrorActionPreference = 'Stop'",
@@ -18,37 +18,168 @@ export function powerShellRepositoryScripts(name, uri) {
18
18
  ].join("\n"),
19
19
  };
20
20
  }
21
- /** Find-PSResource returns the newest stable release unless -Prerelease is requested. */
22
- export function resolvePowerShellModuleVersion(name, repository, repositoryUriOrRunner, prereleaseOrRunner = false, runner) {
23
- const repositoryUri = typeof repositoryUriOrRunner === "string" ? repositoryUriOrRunner : undefined;
24
- const prerelease = prereleaseOrRunner === true;
25
- const run = (typeof repositoryUriOrRunner === "function" ? repositoryUriOrRunner :
26
- typeof prereleaseOrRunner === "function" ? prereleaseOrRunner : runner) ??
27
- ((script) => execFileSync("pwsh", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", encode(script)], { encoding: "utf8" }));
28
- const script = [
21
+ const galleryUri = "https://www.powershellgallery.com/api/v2";
22
+ export async function resolvePowerShellModuleVersion(name, repository, repositoryUri, prerelease = false, { run = runPowerShell, fetch: fetchFeed = fetch } = {}) {
23
+ const isGallery = !repositoryUri && repository.toLowerCase() === "psgallery";
24
+ try {
25
+ if (!powerShellRepositoryName.test(name) || !powerShellRepositoryName.test(repository)) {
26
+ throw new Error("Expected an exact module and repository name without paths or wildcards");
27
+ }
28
+ const uri = repositoryUri === undefined ? undefined : powerShellRepositoryUri(repositoryUri);
29
+ const find = registeredModuleScript(name, repository, uri ?? (isGallery ? galleryUri : undefined), prerelease);
30
+ let version;
31
+ try {
32
+ version = JSON.parse(run(find).trim());
33
+ }
34
+ catch (error) {
35
+ if (!uri || !(error instanceof Error && "code" in error && error.code === "ENOENT"))
36
+ throw error;
37
+ // An anonymous V3 policy feed can also be resolved without pwsh.
38
+ version = null;
39
+ }
40
+ if (version === null) {
41
+ if (uri)
42
+ version = await resolveNugetV3Version(name, uri, prerelease, fetchFeed);
43
+ else if (isGallery)
44
+ version = JSON.parse(run(galleryModuleScript(name, prerelease)).trim());
45
+ else
46
+ throw new Error("The repository must already be registered for the current user");
47
+ }
48
+ if (typeof version !== "string" || !powerShellModuleVersion.test(version) || (!prerelease && version.includes("-"))) {
49
+ throw new Error("Repository did not return an allowed module version");
50
+ }
51
+ return version;
52
+ }
53
+ catch (error) {
54
+ const source = repositoryUri === undefined ? (isGallery ? galleryUri : "registered URI") :
55
+ describeRepositoryUri(repositoryUri);
56
+ throw new Error(`Failed to resolve PowerShell module "${name}" from "${repository}" (${source}): ` +
57
+ (error instanceof Error ? error.message : String(error)), { cause: error });
58
+ }
59
+ }
60
+ function describeRepositoryUri(value) {
61
+ try {
62
+ return powerShellRepositoryUri(value);
63
+ }
64
+ catch {
65
+ return "invalid repository URI";
66
+ }
67
+ }
68
+ function registeredModuleScript(name, repository, uri, prerelease) {
69
+ return [
29
70
  "$ErrorActionPreference = 'Stop'",
30
- ...(repositoryUri ? [powerShellRepositoryScripts(repository, repositoryUri).set] : []),
71
+ // Both PSResourceGet cmdlets initialize a missing store. Keep the existing file open read-only
72
+ // and deny deletion on Windows until the lookup completes.
73
+ "$localAppData = [Environment]::GetFolderPath('LocalApplicationData')",
74
+ "if (-not $localAppData) { 'null'; return }",
75
+ "$store = Join-Path $localAppData 'PSResourceGet/PSResourceRepository.xml'",
76
+ "try { $storeHandle = [IO.File]::Open($store, 'Open', 'Read', 'Read') }",
77
+ "catch [IO.FileNotFoundException], [IO.DirectoryNotFoundException] { 'null'; return }",
78
+ "try {",
79
+ `$registeredRepository = @(Get-PSResourceRepository -ErrorAction Stop | Where-Object { $_.Name -ieq ${powerShellLiteral(repository)} })`,
80
+ `if ($registeredRepository.Count -ne 1${uri ? ` -or $registeredRepository[0].Uri.AbsoluteUri.TrimEnd('/') -cne ${powerShellLiteral(uri)}` : ""}) { 'null'; return }`,
31
81
  `$found = @(Find-PSResource -Name ${powerShellLiteral(name)} -Repository ${powerShellLiteral(repository)}${prerelease ? " -Prerelease" : ""} -ErrorAction Stop)`,
32
82
  `if ($found.Count -ne 1 -or $found[0].Name -ine ${powerShellLiteral(name)}${prerelease ? "" : " -or $found[0].Prerelease"}) { throw 'Expected one matching module release' }`,
33
83
  "$version = $found[0].Version.ToString()",
34
84
  "if ($found[0].Prerelease) { $version += '-' + $found[0].Prerelease }",
35
85
  "$version | ConvertTo-Json -Compress",
86
+ "} finally { $storeHandle.Dispose() }",
36
87
  ].join("\n");
37
- try {
38
- const version = JSON.parse(run(script).trim());
39
- if (typeof version !== "string" || !powerShellModuleVersion.test(version) || (!prerelease && version.includes("-"))) {
40
- throw new Error("Repository did not return an allowed module version");
88
+ }
89
+ function galleryModuleScript(name, prerelease) {
90
+ const url = new URL(`${galleryUri}/FindPackagesById()`);
91
+ url.searchParams.set("id", `'${name}'`);
92
+ url.searchParams.set("$filter", `Id eq '${name}' and ${prerelease ? "IsAbsoluteLatestVersion" : "IsLatestVersion"} eq true`);
93
+ return [
94
+ "$ErrorActionPreference = 'Stop'",
95
+ `[xml]$feed = (Invoke-WebRequest -Uri ${powerShellLiteral(url.href)} -MaximumRedirection 0 -TimeoutSec 30).Content`,
96
+ "$ns = [Xml.XmlNamespaceManager]::new($feed.NameTable)",
97
+ "$ns.AddNamespace('a', 'http://www.w3.org/2005/Atom')",
98
+ "$ns.AddNamespace('m', 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata')",
99
+ "$ns.AddNamespace('d', 'http://schemas.microsoft.com/ado/2007/08/dataservices')",
100
+ "$releases = @($feed.SelectNodes('/a:feed/a:entry/m:properties', $ns) |",
101
+ ` Where-Object { $_.SelectSingleNode('d:Id', $ns).InnerText -ieq ${powerShellLiteral(name)} })`,
102
+ "if ($releases.Count -ne 1) { throw 'Expected one matching module release from the PowerShell Gallery' }",
103
+ "$releases[0].SelectSingleNode('d:Version', $ns).InnerText | ConvertTo-Json -Compress",
104
+ ].join("\n");
105
+ }
106
+ async function resolveNugetV3Version(name, uri, prerelease, fetchFeed) {
107
+ async function getJson(url) {
108
+ let response;
109
+ try {
110
+ response = await fetchFeed(url, {
111
+ credentials: "omit", redirect: "manual", signal: AbortSignal.timeout(30000),
112
+ headers: { Accept: "application/json" },
113
+ });
41
114
  }
42
- return version;
115
+ catch (error) {
116
+ // undici reports only "fetch failed"; the cause names TLS, DNS, proxy or timeout failures.
117
+ const cause = error instanceof Error && error.cause instanceof Error ? error.cause : undefined;
118
+ const code = cause && "code" in cause && typeof cause.code === "string" ? `${cause.code}: ` : "";
119
+ const message = error instanceof Error ? error.message : String(error);
120
+ const detail = ` (${cause ? `${message}: ${code}${cause.message.split("\n")[0]}` : message})`;
121
+ throw new Error(`NuGet request to ${url} failed${detail}. Check network access to the feed.`, { cause: error });
122
+ }
123
+ if (!response.ok) {
124
+ await response.body?.cancel();
125
+ throw new Error(`NuGet request failed (HTTP ${response.status}) for ${url}`);
126
+ }
127
+ return response.json();
43
128
  }
44
- catch (error) {
45
- throw new Error(`Failed to resolve PowerShell module "${name}" from "${repository}". ` +
46
- `PowerShell 7 with PSResourceGet and the registered repository is required: ` +
47
- (error instanceof Error ? error.message : String(error)), { cause: error });
129
+ const index = await getJson(uri).catch((error) => {
130
+ if (!(error instanceof SyntaxError))
131
+ throw error;
132
+ throw new Error("Expected a JSON NuGet v3 service index; other feeds require an existing matching PSResourceGet registration", { cause: error });
133
+ });
134
+ const resources = index && typeof index === "object" && "resources" in index ? index.resources : undefined;
135
+ const resource = Array.isArray(resources) ? resources.find((value) => value && typeof value === "object" && "@type" in value && value["@type"] === "PackageBaseAddress/3.0.0") : undefined;
136
+ if (!resource || typeof resource !== "object" || !("@id" in resource) || typeof resource["@id"] !== "string") {
137
+ throw new Error("Expected a NuGet v3 service index with PackageBaseAddress/3.0.0; other feeds require an existing matching PSResourceGet registration");
138
+ }
139
+ const base = powerShellRepositoryUri(resource["@id"]);
140
+ const releases = await getJson(`${base}/${name.toLowerCase()}/index.json`);
141
+ const versions = releases && typeof releases === "object" && "versions" in releases ? releases.versions : undefined;
142
+ if (!Array.isArray(versions) || !versions.every((value) => typeof value === "string" && powerShellModuleVersion.test(value))) {
143
+ throw new Error("NuGet feed did not return valid module versions");
144
+ }
145
+ const latest = versions.filter((version) => prerelease || !version.includes("-")).sort(compareModuleVersions).at(-1);
146
+ if (!latest)
147
+ throw new Error(`NuGet feed has no ${prerelease ? "matching" : "stable"} module releases`);
148
+ return latest;
149
+ }
150
+ function compareModuleVersions(left, right) {
151
+ const [leftVersion, leftLabel] = left.toLowerCase().split(/-(.*)/);
152
+ const [rightVersion, rightLabel] = right.toLowerCase().split(/-(.*)/);
153
+ const a = leftVersion.split(".").map(BigInt);
154
+ const b = rightVersion.split(".").map(BigInt);
155
+ for (let i = 0; i < 4; i++) {
156
+ const x = a[i] ?? 0n;
157
+ const y = b[i] ?? 0n;
158
+ if (x !== y)
159
+ return x < y ? -1 : 1;
160
+ }
161
+ if (!leftLabel || !rightLabel)
162
+ return Number(!leftLabel) - Number(!rightLabel);
163
+ const leftParts = leftLabel.split(".");
164
+ const rightParts = rightLabel.split(".");
165
+ for (let i = 0; i < Math.min(leftParts.length, rightParts.length); i++) {
166
+ const x = leftParts[i];
167
+ const y = rightParts[i];
168
+ const xNumeric = /^\d+$/.test(x);
169
+ const yNumeric = /^\d+$/.test(y);
170
+ if (xNumeric && yNumeric) {
171
+ if (BigInt(x) !== BigInt(y))
172
+ return BigInt(x) < BigInt(y) ? -1 : 1;
173
+ }
174
+ else if (xNumeric !== yNumeric)
175
+ return xNumeric ? -1 : 1;
176
+ else if (x !== y)
177
+ return x < y ? -1 : 1;
48
178
  }
179
+ return leftParts.length - rightParts.length;
49
180
  }
50
- function encode(script) {
51
- return Buffer.from(script, "utf16le").toString("base64");
181
+ function runPowerShell(script) {
182
+ return execFileSync("pwsh", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { encoding: "utf8" });
52
183
  }
53
184
  export function powerShellModuleProperties(module, pin) {
54
185
  if (!powerShellModuleVersion.test(pin.version) || (!module.prerelease && pin.version.includes("-"))) {
@@ -1,3 +1,4 @@
1
+ import type { WorkspaceDef } from "../../core/types.js";
1
2
  import type { EvaluatedHost } from "../../evaluator/index.js";
2
3
  import type { WinWslSetup } from "../../types/index.js";
3
4
  interface Request {
@@ -5,7 +6,7 @@ interface Request {
5
6
  revision: string;
6
7
  fingerprint: string;
7
8
  }
8
- interface Plan {
9
+ export interface Plan {
9
10
  user: string;
10
11
  home: string;
11
12
  checkout: string;
@@ -19,6 +20,21 @@ interface CommandOptions {
19
20
  }
20
21
  export type SetupRunner = (command: string, args: string[], options?: CommandOptions) => string;
21
22
  export declare function checkoutWslRevision(git: (args: string[]) => string, ref: string, revision: string, existingHead?: string): void;
23
+ export interface WindowsWslSetupTarget {
24
+ windowsHost: string;
25
+ distro: string;
26
+ setup: WinWslSetup;
27
+ /** Linux account, home and checkout the first-run setup will use. */
28
+ plan: Plan;
29
+ }
30
+ /**
31
+ * Validate every Windows WSL distro setup against its Linux host offline and
32
+ * return the account/checkout plan each would use. Catches host/user typos,
33
+ * a missing NixOS-WSL module, ambiguous accounts and checkouts outside the
34
+ * account's home before any distro is created.
35
+ */
36
+ export declare function windowsWslSetupTargets(workspace: WorkspaceDef, evaluated: EvaluatedHost[], windowsHosts: EvaluatedHost[]): WindowsWslSetupTarget[];
37
+ export declare function validateWindowsWslSetupTargets(workspace: WorkspaceDef, evaluated: EvaluatedHost[], windowsHosts: EvaluatedHost[]): void;
22
38
  export declare function createWslAccountPlan(host: EvaluatedHost, setup: WinWslSetup, architecture: string): {
23
39
  plan: Plan;
24
40
  accountHost: EvaluatedHost;