@adrifer/winix 0.3.0-preview.6 → 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 (53) hide show
  1. package/README.md +137 -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 +18 -11
  6. package/dist/backends/windows/lockfile.d.ts +3 -3
  7. package/dist/backends/windows/lockfile.js +4 -3
  8. package/dist/backends/windows/npm.d.ts +2 -0
  9. package/dist/backends/windows/npm.js +60 -0
  10. package/dist/backends/windows/powershell.d.ts +4 -2
  11. package/dist/backends/windows/powershell.js +152 -21
  12. package/dist/backends/windows/wsl-setup-runtime.d.ts +17 -1
  13. package/dist/backends/windows/wsl-setup-runtime.js +75 -11
  14. package/dist/backends/windows/wsl-setup.d.ts +7 -1
  15. package/dist/backends/windows/wsl-setup.js +29 -8
  16. package/dist/backends/windows/wsl.js +1 -1
  17. package/dist/cli/analysis.d.ts +11 -2
  18. package/dist/cli/analysis.js +35 -7
  19. package/dist/cli/commands/apply.d.ts +6 -1
  20. package/dist/cli/commands/apply.js +12 -6
  21. package/dist/cli/commands/check.js +11 -5
  22. package/dist/cli/commands/inspect.js +2 -2
  23. package/dist/cli/commands/switch.d.ts +7 -0
  24. package/dist/cli/commands/switch.js +58 -11
  25. package/dist/cli/commands/update.js +4 -4
  26. package/dist/cli/windows-package-versions.d.ts +2 -1
  27. package/dist/cli/windows-package-versions.js +12 -5
  28. package/dist/cli/windows-state.js +45 -17
  29. package/dist/core/types.d.ts +18 -0
  30. package/dist/evaluator/index.d.ts +5 -3
  31. package/dist/evaluator/index.js +30 -16
  32. package/dist/helpers/account.js +1 -7
  33. package/dist/helpers/home.d.ts +18 -0
  34. package/dist/helpers/home.js +39 -0
  35. package/dist/helpers/index.d.ts +2 -2
  36. package/dist/helpers/nix.d.ts +14 -0
  37. package/dist/helpers/nix.js +2 -0
  38. package/dist/helpers/platforms.d.ts +13 -0
  39. package/dist/helpers/platforms.js +35 -19
  40. package/dist/helpers/windows-npm.d.ts +3 -0
  41. package/dist/helpers/windows-npm.js +52 -0
  42. package/dist/helpers/windows.d.ts +39 -2
  43. package/dist/helpers/windows.js +62 -4
  44. package/dist/helpers/wsl-interop.d.ts +13 -0
  45. package/dist/helpers/wsl-interop.js +72 -0
  46. package/dist/helpers/wsl-repository.d.ts +12 -0
  47. package/dist/helpers/wsl-repository.js +93 -0
  48. package/dist/index.d.ts +4 -4
  49. package/dist/sdk/index.d.ts +5 -1
  50. package/dist/sdk/index.js +9 -2
  51. package/dist/skill.js +34 -2
  52. package/dist/types/windows.d.ts +17 -0
  53. 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
@@ -960,6 +1045,41 @@ as `.lnk.bak` and refuses backup collisions, while `force: true` opts into
960
1045
  replacement without a backup. A new shortcut is staged and verified before
961
1046
  replacing the old one. Keep names unique per host.
962
1047
 
1048
+ ### Windows npm registries
1049
+
1050
+ Configure npm's current-user default and scoped registries independently from
1051
+ PowerShell repositories:
1052
+
1053
+ ```ts
1054
+ windows.npm.registries({
1055
+ registries: {
1056
+ npmjs: { uri: "https://registry.npmjs.org/" },
1057
+ work: { uri: "https://packages.example.com/npm/" },
1058
+ },
1059
+ default: "work",
1060
+ scopes: { "@my-company": "work", "@adrifer": "npmjs" },
1061
+ });
1062
+ ```
1063
+
1064
+ The host's merged policy emits one idempotent DSC resource managing only
1065
+ `registry` and the declared `@scope:registry` entries in the current user's
1066
+ `.npmrc` (or absolute `NPM_CONFIG_USERCONFIG` when set during activation).
1067
+ Existing authentication, comments and unrelated scopes/options are preserved.
1068
+ Managed keys are explicitly replaced; symlinked userconfigs and concurrent
1069
+ edits fail rather than overwriting their targets. Removing declarations leaves
1070
+ their previous settings in place; cleanup is not tracked.
1071
+
1072
+ Registries require HTTPS URLs without embedded credentials, queries or
1073
+ fragments. Authentication stays external (for example `npm login` or existing
1074
+ environment-token references); Winix never logs or declares tokens. npm itself
1075
+ need not be installed to generate or apply this file resource.
1076
+
1077
+ Unlike PowerShell module policy, this does not enforce an `allowed` list:
1078
+ project `.npmrc`, environment variables and npm command-line options can
1079
+ override user settings, and package locks may contain independent download
1080
+ URLs. It does not redirect Winix bootstrap/SDK downloads, WSL setup npm, or
1081
+ install packages. `check`/`apply --dry` do not modify the userconfig.
1082
+
963
1083
  ### Windows personalization and fonts
964
1084
 
965
1085
  These helpers manage the current Windows user without requiring elevation:
@@ -1094,6 +1214,11 @@ Normal missing-pin resolution remains unchanged. These defaults apply to
1094
1214
  `winix switch`, not direct generated-script/DSC activation or plain `apply`.
1095
1215
 
1096
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.
1097
1222
  External shortcut edits, package downgrades, and exact-pin drift block
1098
1223
  reconciliation rather than silently deleting or overwriting managed resources.
1099
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;
@@ -37,16 +37,14 @@ import { windowsSourcePath } from "./paths.js";
37
37
  import { optionalFeatureProperties, wslDistroProperties } from "./wsl.js";
38
38
  import { fontsProperties } from "./fonts.js";
39
39
  import { wallpaperProperties } from "./personalization.js";
40
+ import { npmRegistryProperties } from "./npm.js";
41
+ import { npmRegistryEntries } from "../../helpers/windows-npm.js";
40
42
  export { isWindowsHost } from "./host.js";
41
43
  const DSC_SCHEMA = "https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/2023/08/config/document.json";
42
44
  const WINGET_PACKAGE_TYPE = "Microsoft.WinGet/Package";
43
45
  const RUN_COMMAND_ON_SET_TYPE = "Microsoft.DSC.Transitional/RunCommandOnSet";
44
46
  const WINDOWS_SETTINGS_MODULE_COMMAND_NAME = "Ensure Microsoft Windows Settings module";
45
- /**
46
- * Generate Windows bundles for every Windows host in the evaluated workspace.
47
- * Non-Windows hosts are skipped.
48
- */
49
- export function generateWindows(evaluatedHosts, lock = emptyWindowsLock(), configDir) {
47
+ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock(), configDir, options = {}) {
50
48
  const hosts = {};
51
49
  const warnings = [];
52
50
  const windowsHosts = evaluatedHosts.filter(isWindowsHost);
@@ -54,7 +52,7 @@ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock(), confi
54
52
  for (const host of windowsHosts) {
55
53
  const win = host.windows;
56
54
  hosts[host.name] = {
57
- "configuration.winget": generateConfiguration(host.name, win, resolvedLock, configDir),
55
+ "configuration.winget": generateConfiguration(host.name, win, resolvedLock, configDir, options.presenceOnlyPackages),
58
56
  "apply.ps1": generateApplyScript(),
59
57
  };
60
58
  }
@@ -63,7 +61,7 @@ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock(), confi
63
61
  /**
64
62
  * Render the WinGet Configuration YAML document (DSC v3) for one host.
65
63
  */
66
- function generateConfiguration(hostName, win, lock, configDir) {
64
+ function generateConfiguration(hostName, win, lock, configDir, presenceOnlyPackages = new Set()) {
67
65
  validateWindowsWslResources(win);
68
66
  validateWindowsPowerShellPolicy(win);
69
67
  const packages = sortedPackages(win.packages ?? {});
@@ -85,7 +83,12 @@ function generateConfiguration(hostName, win, lock, configDir) {
85
83
  const developerModeRefs = (win.dsc ?? [])
86
84
  .filter((resource) => resource.winix?.kind === "setting" && resource.properties?.DeveloperMode === true)
87
85
  .map((resource) => ({ kind: "dsc", token: resource.token }));
88
- const resources = (win.dsc ?? []).map((resource) => {
86
+ const npmResource = win.npm?.registries ? [{
87
+ resourceType: "Microsoft.DSC.Transitional/PowerShellScript",
88
+ name: "npm registries",
89
+ properties: npmRegistryProperties(npmRegistryEntries(win.npm.registries)),
90
+ }] : [];
91
+ const resources = [...(win.dsc ?? []), ...npmResource].map((resource) => {
89
92
  const metadata = resource.winix;
90
93
  if (metadata?.kind === "fonts") {
91
94
  return cloneDscResource(resource, fontsProperties(metadata.sources, lock, configDir));
@@ -155,7 +158,9 @@ function generateConfiguration(hostName, win, lock, configDir) {
155
158
  lines.push("resources:");
156
159
  for (const pkg of packages) {
157
160
  const plan = naming.packages.get(pkg);
158
- 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));
159
164
  }
160
165
  for (const command of commands) {
161
166
  const plan = naming.commands.get(command);
@@ -531,8 +536,10 @@ function renderPackageResource(pkg, version, plan, naming) {
531
536
  out.push(` id: ${yamlScalar(pkg.id)}`);
532
537
  out.push(` source: ${yamlScalar(pkg.source)}`);
533
538
  out.push(` acceptAgreements: true`);
534
- // Quote versions so values like "1.0" are not parsed as numbers.
535
- 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)}`);
536
543
  // Only request elevation when explicitly asked. Per-user packages install
537
544
  // fine without it, and forcing elevation makes `winget configure` fail with
538
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();
@@ -0,0 +1,2 @@
1
+ import type { WinDscProperties } from "../../types/windows.js";
2
+ export declare function npmRegistryProperties(entries: Record<string, string>): WinDscProperties;
@@ -0,0 +1,60 @@
1
+ import { powerShellLiteral } from "../../helpers/utils.js";
2
+ export function npmRegistryProperties(entries) {
3
+ const prelude = `
4
+ $ErrorActionPreference = 'Stop'
5
+ $entries = ConvertFrom-Json -AsHashtable ${powerShellLiteral(JSON.stringify(entries))}
6
+ $path = if ($env:NPM_CONFIG_USERCONFIG) {
7
+ [Environment]::ExpandEnvironmentVariables($env:NPM_CONFIG_USERCONFIG)
8
+ } else { Join-Path ([Environment]::GetFolderPath('UserProfile')) '.npmrc' }
9
+ if (-not [IO.Path]::IsPathFullyQualified($path)) { throw 'npm userconfig must be an absolute path' }
10
+ if (Test-Path -LiteralPath $path) {
11
+ if ((Get-Item -LiteralPath $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) {
12
+ throw 'npm userconfig is a symlink; configure its source file explicitly instead'
13
+ }
14
+ }
15
+ function Read-WinixNpmConfig {
16
+ if (-not (Test-Path -LiteralPath $path)) { return '' }
17
+ return [IO.File]::ReadAllText($path, [Text.UTF8Encoding]::new($false, $true))
18
+ }
19
+ function Get-WinixNpmKey([string]$line) {
20
+ if ($line -match '^\\s*([^#;=\\s]+)\\s*=') { return $Matches[1] }
21
+ return ''
22
+ }
23
+ function Test-WinixNpmConfig([string]$text) {
24
+ foreach ($key in $entries.Keys) {
25
+ $matching = @($text -split '\\r?\\n' | Where-Object { (Get-WinixNpmKey $_) -ceq $key })
26
+ if ($matching.Count -ne 1) { return $false }
27
+ if (($matching[0] -split '=', 2)[1].Trim() -cne $entries[$key]) { return $false }
28
+ }
29
+ return $true
30
+ }`;
31
+ return {
32
+ getScript: `${prelude}\n@{ InDesiredState = (Test-WinixNpmConfig (Read-WinixNpmConfig)) }`,
33
+ testScript: `${prelude}\nTest-WinixNpmConfig (Read-WinixNpmConfig)`,
34
+ setScript: `${prelude}
35
+ $original = Read-WinixNpmConfig
36
+ if (Test-WinixNpmConfig $original) { return }
37
+ $newline = if ($original.Contains("\`r\`n")) { "\`r\`n" } else { "\`n" }
38
+ $lines = [Collections.Generic.List[string]]::new()
39
+ foreach ($line in ($original -split '\\r?\\n')) {
40
+ if (-not $entries.ContainsKey((Get-WinixNpmKey $line))) { $lines.Add($line) }
41
+ }
42
+ if ($lines.Count -gt 0 -and $lines[$lines.Count - 1] -eq '') { $lines.RemoveAt($lines.Count - 1) }
43
+ foreach ($key in ($entries.Keys | Sort-Object)) { $lines.Add("$key=$($entries[$key])") }
44
+ $next = ($lines -join $newline) + $newline
45
+ $parent = [IO.Path]::GetDirectoryName($path)
46
+ [IO.Directory]::CreateDirectory($parent) | Out-Null
47
+ $temporary = Join-Path $parent ('.winix-npm-' + [guid]::NewGuid().ToString() + '.tmp')
48
+ try {
49
+ [IO.File]::WriteAllText($temporary, $next, [Text.UTF8Encoding]::new($false))
50
+ if ((Read-WinixNpmConfig) -cne $original) { throw 'npm userconfig changed during activation; rerun' }
51
+ if (Test-Path -LiteralPath $path) {
52
+ if ((Get-Item -LiteralPath $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'npm userconfig became a link' }
53
+ [IO.File]::Replace($temporary, $path, [NullString]::Value)
54
+ } else { [IO.File]::Move($temporary, $path, $false) }
55
+ } finally {
56
+ if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -Force }
57
+ }
58
+ if (-not (Test-WinixNpmConfig (Read-WinixNpmConfig))) { throw 'npm registry configuration verification failed' }`,
59
+ };
60
+ }
@@ -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;