@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
@@ -1,4 +1,5 @@
1
1
  import { escapeNixDoubleQuoted, nixStringLiteral } from "../nix/serialize.js";
2
+ import { windowsBin } from "./wsl-interop.js";
2
3
  const expr = (value) => ({ __winixNixExpr: true, expr: value });
3
4
  const pkg = Object.assign((name) => expr(`pkgs.${name}`), {
4
5
  stable: (name) => expr(`pkgs.stable.${name}`),
@@ -55,6 +56,7 @@ export const nix = {
55
56
  isDarwin: expr("pkgs.stdenv.isDarwin"),
56
57
  isLinux: expr("pkgs.stdenv.isLinux"),
57
58
  binaryRelease,
59
+ wsl: { windowsBin },
58
60
  lib: {
59
61
  mkDefault: (value) => nixLibCall("mkDefault", value),
60
62
  mkForce: (value) => nixLibCall("mkForce", value),
@@ -14,12 +14,25 @@ export interface DarwinPlatformOpts {
14
14
  homebrew?: boolean;
15
15
  hostname?: string | false;
16
16
  }
17
+ export interface WslPlatformOpts extends NixosPlatformOpts {
18
+ /**
19
+ * Nix input name providing NixOS-WSL, as it appears in `inputs.<name>`.
20
+ * Defaults to "nixos-wsl" (the kebab-case name of a `nixosWsl` input).
21
+ */
22
+ input?: string;
23
+ }
17
24
  export interface WindowsPlatformOpts {
18
25
  /** Hostname override; falls back to the host name from eval context. */
19
26
  hostname?: string | false;
20
27
  }
21
28
  export interface PlatformsHelper {
22
29
  nixos: PlatformFactory<[opts?: NixosPlatformOpts]>;
30
+ /**
31
+ * NixOS running under WSL: imports the NixOS-WSL module and enables it.
32
+ * The host is still a NixOS host, so `platforms.nixos.isActive` is also
33
+ * true; `platforms.wsl.isActive` is true only for WSL hosts.
34
+ */
35
+ wsl: PlatformFactory<[opts?: WslPlatformOpts]>;
23
36
  darwin: PlatformFactory<[opts?: DarwinPlatformOpts]>;
24
37
  windows: PlatformFactory<[opts?: WindowsPlatformOpts]>;
25
38
  }
@@ -1,28 +1,44 @@
1
1
  import { platform, getOptionalEvalContext } from "../sdk/index.js";
2
+ function nixosPlatform(opts) {
3
+ const ctx = getOptionalEvalContext();
4
+ const hostname = opts.hostname === false ? undefined : opts.hostname ?? ctx?.hostname;
5
+ const useHomeManager = opts.homeManager ?? true;
6
+ return {
7
+ nixos: {
8
+ ...(useHomeManager && { imports: ["inputs.home-manager.nixosModules.home-manager"] }),
9
+ nixpkgs: {
10
+ hostPlatform: opts.system ?? "x86_64-linux",
11
+ config: { allowUnfree: opts.allowUnfree ?? true },
12
+ },
13
+ nix: { settings: { experimentalFeatures: ["nix-command", "flakes"] } },
14
+ ...(hostname && { networking: { hostName: hostname } }),
15
+ ...(opts.stateVersion && { system: { stateVersion: opts.stateVersion } }),
16
+ ...(useHomeManager && {
17
+ homeManager: {
18
+ useGlobalPkgs: true,
19
+ useUserPackages: true,
20
+ },
21
+ }),
22
+ },
23
+ };
24
+ }
2
25
  export const platforms = {
3
- nixos: platform("nixos", (opts = {}) => {
4
- const ctx = getOptionalEvalContext();
5
- const hostname = opts.hostname === false ? undefined : opts.hostname ?? ctx?.hostname;
6
- const useHomeManager = opts.homeManager ?? true;
26
+ nixos: platform("nixos", (opts = {}) => nixosPlatform(opts)),
27
+ wsl: platform("nixos", (opts = {}) => {
28
+ const { input = "nixos-wsl", ...nixosOpts } = opts;
29
+ if (typeof input !== "string" || !/^[A-Za-z_][A-Za-z0-9_'-]*$/.test(input)) {
30
+ throw new Error("platforms.wsl input must be a Nix input name, e.g. \"nixos-wsl\"");
31
+ }
32
+ const base = nixosPlatform(nixosOpts);
33
+ const imports = base.nixos?.imports ?? [];
7
34
  return {
8
35
  nixos: {
9
- ...(useHomeManager && { imports: ["inputs.home-manager.nixosModules.home-manager"] }),
10
- nixpkgs: {
11
- hostPlatform: opts.system ?? "x86_64-linux",
12
- config: { allowUnfree: opts.allowUnfree ?? true },
13
- },
14
- nix: { settings: { experimentalFeatures: ["nix-command", "flakes"] } },
15
- ...(hostname && { networking: { hostName: hostname } }),
16
- ...(opts.stateVersion && { system: { stateVersion: opts.stateVersion } }),
17
- ...(useHomeManager && {
18
- homeManager: {
19
- useGlobalPkgs: true,
20
- useUserPackages: true,
21
- },
22
- }),
36
+ ...base.nixos,
37
+ imports: [...imports, `inputs.${input}.nixosModules.wsl`],
38
+ wsl: { enable: true },
23
39
  },
24
40
  };
25
- }),
41
+ }, { variant: "wsl" }),
26
42
  darwin: platform("darwin", (opts = {}) => {
27
43
  const ctx = getOptionalEvalContext();
28
44
  const hostname = opts.hostname === false ? undefined : opts.hostname ?? ctx?.hostname;
@@ -0,0 +1,3 @@
1
+ import type { WinNpmRegistryPolicy } from "../types/windows.js";
2
+ export declare function npmRegistryUri(value: string): string;
3
+ export declare function npmRegistryEntries(policy: WinNpmRegistryPolicy): Record<string, string>;
@@ -0,0 +1,52 @@
1
+ export function npmRegistryUri(value) {
2
+ let url;
3
+ try {
4
+ url = new URL(value);
5
+ }
6
+ catch {
7
+ throw new Error("npm registry URI must be an HTTPS URL");
8
+ }
9
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash ||
10
+ /[\0\r\n]/.test(value)) {
11
+ throw new Error("npm registry URI must be HTTPS without credentials, query or fragment");
12
+ }
13
+ return url.href.replace(/\/+$/, "") + "/";
14
+ }
15
+ export function npmRegistryEntries(policy) {
16
+ if (!policy || typeof policy !== "object" || Array.isArray(policy) ||
17
+ !policy.registries || typeof policy.registries !== "object" || Array.isArray(policy.registries) ||
18
+ typeof policy.default !== "string") {
19
+ throw new Error("npm registry policy requires registries and a default registry name");
20
+ }
21
+ for (const key of Object.keys(policy)) {
22
+ if (!["registries", "default", "scopes"].includes(key))
23
+ throw new Error(`Unknown npm registry policy option: ${key}`);
24
+ }
25
+ const registries = new Map();
26
+ for (const [name, entry] of Object.entries(policy.registries)) {
27
+ if (!/^[a-z0-9][a-z0-9._-]*$/i.test(name) || registries.has(name.toLowerCase())) {
28
+ throw new Error(`Invalid or duplicate npm registry name: ${name}`);
29
+ }
30
+ if (!entry || typeof entry.uri !== "string")
31
+ throw new Error(`npm registry "${name}" requires a URI`);
32
+ registries.set(name.toLowerCase(), npmRegistryUri(entry.uri));
33
+ }
34
+ const resolve = (name) => {
35
+ const uri = typeof name === "string" ? registries.get(name.toLowerCase()) : undefined;
36
+ if (!uri)
37
+ throw new Error(`npm registry "${String(name)}" is not declared`);
38
+ return uri;
39
+ };
40
+ const entries = { registry: resolve(policy.default) };
41
+ if (policy.scopes !== undefined) {
42
+ if (!policy.scopes || typeof policy.scopes !== "object" || Array.isArray(policy.scopes)) {
43
+ throw new Error("npm registry scopes must be an object");
44
+ }
45
+ for (const [scope, registry] of Object.entries(policy.scopes)) {
46
+ if (!/^@[a-z0-9][a-z0-9._-]*$/.test(scope))
47
+ throw new Error(`Invalid npm scope: ${scope}`);
48
+ entries[`${scope}:registry`] = resolve(registry);
49
+ }
50
+ }
51
+ return entries;
52
+ }
@@ -1,5 +1,7 @@
1
- import type { Fragment, ResourceHandle } from "../core/types.js";
1
+ import type { Fragment, HostDef, ResourceHandle } from "../core/types.js";
2
+ import type { AccountUserRef } from "./account.js";
2
3
  import type { WinDscProperties, WinDscResource, WinPackageSource, WinSettings, WinFilePath, WinKnownFolder, WinKnownFolderName, WinStartupCommand, WinWslConfig, WinWslDistro, WinWslSetup, WinPowerShellRepositoryPolicy, WinFontSource, WinWallpaper, WinPersonalization } from "../types/index.js";
4
+ import type { WinNpmRegistryPolicy } from "../types/windows.js";
3
5
  /**
4
6
  * Accepted call shapes for `windows.package(...)`.
5
7
  *
@@ -66,8 +68,32 @@ export interface WinOptionalFeatureOpts {
66
68
  enabled?: boolean;
67
69
  dependsOn?: ResourceHandle | ResourceHandle[];
68
70
  }
69
- export interface WinWslDistroSpec extends Omit<WinWslDistro, "name" | "default"> {
71
+ /**
72
+ * Authoring form of a distro's first-run `setup`. Accepts host/account values
73
+ * instead of matching strings, and `repository: "self"` to clone the
74
+ * checkout that holds winix.config.ts.
75
+ */
76
+ export interface WinWslSetupSpec extends Omit<WinWslSetup, "repository" | "configDirectory" | "host" | "user"> {
77
+ /**
78
+ * HTTPS Git URL, or "self": use the tracked remote of the checkout holding
79
+ * winix.config.ts (SSH remotes are converted to HTTPS). With "self", `ref`
80
+ * defaults to the current upstream branch (or commit when detached) and
81
+ * `configDirectory` to the config's path within the repository.
82
+ */
83
+ repository: string;
84
+ /** Required unless `repository` is "self". */
85
+ configDirectory?: string;
86
+ /** Linux host to activate: its name, or the value returned by `host(...)`. */
87
+ host: string | HostDef;
88
+ /** Linux account: its name, or the factory returned by `account.user(...)`. */
89
+ user?: string | AccountUserRef;
90
+ }
91
+ export interface WinWslDistroSpec extends Omit<WinWslDistro, "name" | "default" | "host" | "setup" | "setupRefFromCheckout"> {
70
92
  default?: boolean;
93
+ /** Expected Linux hostname for adoption (a name or `host(...)` value); defaults to setup.host. */
94
+ host?: string | HostDef;
95
+ /** First-run setup for Winix-created distros; never run for adopted distros. */
96
+ setup?: WinWslSetupSpec;
71
97
  dependsOn?: ResourceHandle | ResourceHandle[];
72
98
  }
73
99
  export interface WinWslOpts extends Pick<WinFileOpts, "backup" | "force" | "dependsOn"> {
@@ -116,6 +142,9 @@ export interface WinFileNamespace {
116
142
  remove(target: WinFilePath, opts?: WinFileOpts): ResourceHandle;
117
143
  }
118
144
  export interface WindowsHelper {
145
+ npm: {
146
+ registries(policy: WinNpmRegistryPolicy): Fragment;
147
+ };
119
148
  fonts(spec: {
120
149
  sources: WinFontSource[];
121
150
  dependsOn?: ResourceHandle | ResourceHandle[];
@@ -224,4 +253,12 @@ export interface WindowsHelper {
224
253
  file: WinFileNamespace;
225
254
  }
226
255
  export declare const windows: WindowsHelper;
256
+ /**
257
+ * Resolve the authoring form of a WSL setup into its normalized, concrete
258
+ * shape. `repository: "self"` reads the config checkout (local Git only).
259
+ */
260
+ export declare function resolveWslSetupSpec(spec: WinWslSetupSpec): {
261
+ setup: WinWslSetup;
262
+ refFromCheckout: boolean;
263
+ };
227
264
  export declare function normalizeWslSetup(setup: WinWslSetup): WinWslSetup;
@@ -3,12 +3,15 @@
3
3
  // MVP vertical slice: packages plus raw commands. Mirrors the shape and
4
4
  // naming of the `nixos.*` / `darwin.*` namespaces. Additional helpers
5
5
  // (env, path, file, dsc, wsl, programs) land in follow-up milestones.
6
+ import { getOptionalEvalContext } from "../sdk/index.js";
7
+ import { inferWslSetupRepository } from "./wsl-repository.js";
6
8
  import { resolve, win32, posix } from "node:path";
7
9
  import { fileURLToPath } from "node:url";
8
10
  import { powerShellLiteral as psSingleQuoted } from "./utils.js";
9
11
  import { validatePowerShellRepositoryPolicy } from "./windows-repositories.js";
10
12
  import { validateFontSources, validateWallpaper, personalizationValues } from "./windows-personalization.js";
11
13
  import { personalizationProperties } from "../backends/windows/personalization.js";
14
+ import { npmRegistryEntries } from "./windows-npm.js";
12
15
  const KNOWN_FOLDERS = {
13
16
  documents: "MyDocuments",
14
17
  desktop: "Desktop",
@@ -1000,18 +1003,20 @@ export const windows = {
1000
1003
  (spec.default !== undefined && typeof spec.default !== "boolean")) {
1001
1004
  throw new Error("windows.wsl.distro requires source 'nixos-wsl', an absolute/environment/known-folder installLocation, and an optional boolean default");
1002
1005
  }
1003
- if (spec.host !== undefined && (typeof spec.host !== "string" ||
1004
- !/^[a-z0-9][a-z0-9._-]*$/i.test(spec.host))) {
1006
+ const expectedHost = spec.host === undefined ? undefined : hostName(spec.host, "windows.wsl.distro host");
1007
+ if (expectedHost !== undefined && !/^[a-z0-9][a-z0-9._-]*$/i.test(expectedHost)) {
1005
1008
  throw new Error("windows.wsl.distro host must be a valid expected Linux hostname");
1006
1009
  }
1010
+ const setup = spec.setup === undefined ? undefined : resolveWslSetupSpec(spec.setup);
1007
1011
  return dscHandle(withDscMetadata(withDscToken({
1008
1012
  resourceType: POWERSHELL_SCRIPT_RESOURCE,
1009
1013
  name: `WSL distro ${name}`,
1010
1014
  dependsOn: resolveDependsOn(spec.dependsOn),
1011
1015
  }), { kind: "wsl-distro", distro: {
1012
1016
  name, source: spec.source, installLocation: spec.installLocation, default: spec.default ?? false,
1013
- ...(spec.host === undefined ? {} : { host: spec.host }),
1014
- ...(spec.setup === undefined ? {} : { setup: normalizeWslSetup(spec.setup) }),
1017
+ ...(expectedHost === undefined ? {} : { host: expectedHost }),
1018
+ ...(setup === undefined ? {} : { setup: setup.setup }),
1019
+ ...(setup?.refFromCheckout ? { setupRefFromCheckout: true } : {}),
1015
1020
  } }));
1016
1021
  },
1017
1022
  }),
@@ -1054,6 +1059,12 @@ export const windows = {
1054
1059
  return dscHandle(resource);
1055
1060
  },
1056
1061
  },
1062
+ npm: {
1063
+ registries: (policy) => {
1064
+ npmRegistryEntries(policy);
1065
+ return { windows: { npm: { registries: policy } } };
1066
+ },
1067
+ },
1057
1068
  package: (arg) => {
1058
1069
  const pkg = normalizePackage(arg);
1059
1070
  const fragment = { windows: { packages: { [pkg.id]: pkg } } };
@@ -1104,6 +1115,53 @@ export const windows = {
1104
1115
  remove: (target, opts) => dscHandle(normalizeFileRemove(target, opts)),
1105
1116
  },
1106
1117
  };
1118
+ function hostName(value, label) {
1119
+ if (typeof value === "string")
1120
+ return value;
1121
+ if (value && typeof value === "object" && typeof value.name === "string" && value.platform)
1122
+ return value.name;
1123
+ throw new Error(`${label} must be a host name or a host(...) value`);
1124
+ }
1125
+ /**
1126
+ * Resolve the authoring form of a WSL setup into its normalized, concrete
1127
+ * shape. `repository: "self"` reads the config checkout (local Git only).
1128
+ */
1129
+ export function resolveWslSetupSpec(spec) {
1130
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) {
1131
+ throw new Error("windows.wsl.distro setup must be an object");
1132
+ }
1133
+ const host = hostName(spec.host, "WSL setup host");
1134
+ let user;
1135
+ if (spec.user === undefined || typeof spec.user === "string")
1136
+ user = spec.user;
1137
+ else if ((typeof spec.user === "object" || typeof spec.user === "function") &&
1138
+ spec.user.kind === "account.user" && typeof spec.user.name === "string")
1139
+ user = spec.user.name;
1140
+ else
1141
+ throw new Error("WSL setup user must be a Linux account name or an account.user(...) value");
1142
+ let { repository, ref, configDirectory } = spec;
1143
+ let refFromCheckout = false;
1144
+ if (repository === "self") {
1145
+ const configDir = getOptionalEvalContext()?.configDir;
1146
+ if (!configDir) {
1147
+ throw new Error('WSL setup repository "self" needs the config directory; evaluate the workspace through the Winix CLI');
1148
+ }
1149
+ const inferred = inferWslSetupRepository(configDir);
1150
+ repository = inferred.repository;
1151
+ refFromCheckout = ref === undefined;
1152
+ ref ??= inferred.ref;
1153
+ configDirectory ??= inferred.configDirectory;
1154
+ }
1155
+ if (configDirectory === undefined) {
1156
+ throw new Error('WSL setup configDirectory is required unless repository is "self"');
1157
+ }
1158
+ return {
1159
+ setup: normalizeWslSetup({
1160
+ ...spec, repository, ref, configDirectory, host, ...(user === undefined ? {} : { user }),
1161
+ }),
1162
+ refFromCheckout,
1163
+ };
1164
+ }
1107
1165
  export function normalizeWslSetup(setup) {
1108
1166
  if (!setup || typeof setup !== "object" || Array.isArray(setup)) {
1109
1167
  throw new Error("windows.wsl.distro setup must be an object");
@@ -0,0 +1,13 @@
1
+ import type { NixExpr } from "../core/types.js";
2
+ /**
3
+ * Default Git Credential Manager locations shipped with Git for Windows.
4
+ */
5
+ export declare const GIT_CREDENTIAL_MANAGER_PATHS: readonly ["%ProgramFiles%\\Git\\ucrt64\\bin\\git-credential-manager.exe", "%ProgramFiles%\\Git\\mingw64\\bin\\git-credential-manager.exe"];
6
+ /**
7
+ * Build a package containing `bin/<name>`, a shell shim that resolves the
8
+ * first existing Windows path among `targets` and execs it with all arguments.
9
+ * Targets are Windows paths, absolute (`C:\...`) or starting with an
10
+ * environment variable (`%LOCALAPPDATA%\...`), expanded through `cmd.exe`
11
+ * interop at run time and converted with `wslpath`.
12
+ */
13
+ export declare function windowsBin(name: string, targets: string | readonly string[]): NixExpr;
@@ -0,0 +1,72 @@
1
+ // WSL → Windows interop helpers: shims that locate Windows executables at
2
+ // runtime, so Linux configs never hard-code the Windows user or drive layout.
3
+ import { nixStringLiteral } from "../nix/serialize.js";
4
+ /**
5
+ * Default Git Credential Manager locations shipped with Git for Windows.
6
+ */
7
+ export const GIT_CREDENTIAL_MANAGER_PATHS = [
8
+ "%ProgramFiles%\\Git\\ucrt64\\bin\\git-credential-manager.exe",
9
+ "%ProgramFiles%\\Git\\mingw64\\bin\\git-credential-manager.exe",
10
+ ];
11
+ /**
12
+ * Build a package containing `bin/<name>`, a shell shim that resolves the
13
+ * first existing Windows path among `targets` and execs it with all arguments.
14
+ * Targets are Windows paths, absolute (`C:\...`) or starting with an
15
+ * environment variable (`%LOCALAPPDATA%\...`), expanded through `cmd.exe`
16
+ * interop at run time and converted with `wslpath`.
17
+ */
18
+ export function windowsBin(name, targets) {
19
+ if (typeof name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(name)) {
20
+ throw new Error("nix.wsl.windowsBin requires an executable name containing only letters, numbers, '.', '_', '+' or '-'");
21
+ }
22
+ const list = (typeof targets === "string" ? [targets] : [...(targets ?? [])]).map(normalizeWindowsTarget);
23
+ if (list.length === 0)
24
+ throw new Error(`nix.wsl.windowsBin("${name}") requires at least one Windows path`);
25
+ const quoted = list.map((target) => `'${target}'`).join(" ");
26
+ const script = [
27
+ "wslpath=/bin/wslpath",
28
+ `[ -x "$wslpath" ] || wslpath=$(command -v wslpath) || { echo '${name}: wslpath not found; this shim only works inside WSL' >&2; exit 127; }`,
29
+ `cmd=$("$wslpath" -u 'C:\\Windows\\System32\\cmd.exe' 2>/dev/null)`,
30
+ "resolve() {",
31
+ ' local win=$1',
32
+ ' case "$win" in',
33
+ " *%*)",
34
+ ' [ -n "$cmd" ] && [ -x "$cmd" ] || return 1',
35
+ // cmd.exe cannot run from a WSL (UNC) working directory.
36
+ ' win=$(cd "${cmd%/*}" && "$cmd" /d /c "echo $win" 2>/dev/null) || return 1',
37
+ " win=${win%$'\\r'}",
38
+ " case \"$win\" in *%*) return 1 ;; esac",
39
+ " ;;",
40
+ " esac",
41
+ ' "$wslpath" -u "$win" 2>/dev/null',
42
+ "}",
43
+ `for candidate in ${quoted}; do`,
44
+ ' if target=$(resolve "$candidate") && [ -n "$target" ] && [ -f "$target" ]; then',
45
+ ' exec "$target" "$@"',
46
+ " fi",
47
+ "done",
48
+ `echo '${name}: Windows executable not found at: ${list.join(", ")}' >&2`,
49
+ "exit 127",
50
+ ].join("\n");
51
+ return {
52
+ __winixNixExpr: true,
53
+ expr: `(pkgs.writeShellScriptBin ${nixStringLiteral(name)} ''\n${escapeIndentedString(script)}\n'')`,
54
+ };
55
+ }
56
+ function normalizeWindowsTarget(target) {
57
+ if (typeof target !== "string")
58
+ throw new Error("nix.wsl.windowsBin paths must be strings");
59
+ const path = target.replace(/\//g, "\\");
60
+ if (!/^(?:[A-Za-z]:\\|%[A-Za-z_][A-Za-z0-9_()]*%\\)/.test(path)) {
61
+ throw new Error(`nix.wsl.windowsBin path "${target}" must be absolute (C:\\...) or start with an environment variable (%LOCALAPPDATA%\\...)`);
62
+ }
63
+ // Paths are embedded in single-quoted shell words and echoed through cmd.exe.
64
+ if (/['"&|<>^\r\n\0`]/.test(path)) {
65
+ throw new Error(`nix.wsl.windowsBin path "${target}" contains unsupported characters`);
66
+ }
67
+ return path;
68
+ }
69
+ /** Escape text for a Nix indented string (`'' ... ''`). */
70
+ function escapeIndentedString(text) {
71
+ return text.replace(/''/g, "'''").replace(/\$\{/g, "''${");
72
+ }
@@ -0,0 +1,12 @@
1
+ export interface InferredWslRepository {
2
+ /** HTTPS clone URL of the tracked remote. */
3
+ repository: string;
4
+ /** Upstream branch name, or the commit when HEAD is detached. */
5
+ ref: string;
6
+ /** Config directory relative to the repository root, POSIX separators. */
7
+ configDirectory: string;
8
+ }
9
+ export type GitRunner = (args: string[], cwd: string) => string;
10
+ export declare function inferWslSetupRepository(configDir: string, git?: GitRunner): InferredWslRepository;
11
+ /** Convert common Git remote forms (HTTPS with userinfo, scp-like SSH, ssh://) to an HTTPS clone URL. */
12
+ export declare function httpsCloneUrl(url: string, context?: string): string;
@@ -0,0 +1,93 @@
1
+ // Infers a WSL setup repository from the Git checkout that holds winix.config.ts
2
+ // (`setup: { repository: "self" }`). Only local, read-only Git queries run here;
3
+ // the commit pin is still resolved against the remote into winix-windows.lock.
4
+ import { execFileSync } from "node:child_process";
5
+ import { realpathSync } from "node:fs";
6
+ import { relative, sep } from "node:path";
7
+ const runGit = (args, cwd) => execFileSync("git", args, {
8
+ cwd, encoding: "utf8", timeout: 15000, stdio: ["ignore", "pipe", "pipe"],
9
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
10
+ }).trim();
11
+ function tryGit(git, args, cwd) {
12
+ try {
13
+ return git(args, cwd) || undefined;
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ export function inferWslSetupRepository(configDir, git = runGit) {
20
+ const context = `setup.repository "self" (config directory ${configDir})`;
21
+ let toplevel;
22
+ try {
23
+ toplevel = git(["rev-parse", "--show-toplevel"], configDir);
24
+ }
25
+ catch (error) {
26
+ throw new Error(`${context}: not inside a Git checkout`, { cause: error });
27
+ }
28
+ const branch = tryGit(git, ["symbolic-ref", "--quiet", "--short", "HEAD"], configDir);
29
+ let remote = "origin";
30
+ let ref;
31
+ if (branch) {
32
+ const upstreamRemote = tryGit(git, ["config", "--get", `branch.${branch}.remote`], configDir);
33
+ const upstreamMerge = tryGit(git, ["config", "--get", `branch.${branch}.merge`], configDir);
34
+ if (upstreamRemote && upstreamRemote !== "." && upstreamMerge?.startsWith("refs/heads/")) {
35
+ remote = upstreamRemote;
36
+ ref = upstreamMerge.slice("refs/heads/".length);
37
+ }
38
+ else {
39
+ ref = branch;
40
+ }
41
+ }
42
+ else {
43
+ ref = git(["rev-parse", "HEAD"], configDir);
44
+ }
45
+ const url = tryGit(git, ["remote", "get-url", remote], configDir);
46
+ if (!url)
47
+ throw new Error(`${context}: the checkout has no "${remote}" remote to clone from`);
48
+ return {
49
+ repository: httpsCloneUrl(url, context),
50
+ ref,
51
+ configDirectory: configDirectoryWithin(toplevel, configDir, context),
52
+ };
53
+ }
54
+ /** Convert common Git remote forms (HTTPS with userinfo, scp-like SSH, ssh://) to an HTTPS clone URL. */
55
+ export function httpsCloneUrl(url, context = "setup.repository") {
56
+ const trimmed = url.trim();
57
+ const azureSsh = /^(?:ssh:\/\/)?[^@/]+@ssh\.dev\.azure\.com(?::22)?[:/]v3\/([^/]+)\/([^/]+)\/([^/]+?)\/?$/.exec(trimmed);
58
+ if (azureSsh) {
59
+ const [, org, project, repo] = azureSsh;
60
+ return `https://dev.azure.com/${org}/${project}/_git/${repo}`;
61
+ }
62
+ const scp = /^[^@/\s]+@([^:/\s]+):(?!\/)(.+)$/.exec(trimmed);
63
+ if (scp)
64
+ return `https://${scp[1]}/${scp[2]}`;
65
+ let parsed;
66
+ try {
67
+ parsed = new URL(trimmed);
68
+ }
69
+ catch {
70
+ throw new Error(`${context}: remote URL "${trimmed}" is not an HTTPS or SSH Git URL`);
71
+ }
72
+ if (parsed.protocol === "ssh:")
73
+ return `https://${parsed.hostname}${parsed.pathname}`;
74
+ if (parsed.protocol !== "https:") {
75
+ throw new Error(`${context}: remote URL "${trimmed}" must use HTTPS or SSH; set setup.repository explicitly`);
76
+ }
77
+ parsed.username = "";
78
+ parsed.password = "";
79
+ return parsed.href;
80
+ }
81
+ function configDirectoryWithin(toplevel, configDir, context) {
82
+ const real = (path) => { try {
83
+ return realpathSync(path);
84
+ }
85
+ catch {
86
+ return path;
87
+ } };
88
+ const inside = relative(real(toplevel), real(configDir));
89
+ if (inside.startsWith("..") || /^[a-z]:/i.test(inside) || inside.startsWith(sep)) {
90
+ throw new Error(`${context}: config directory is outside the repository root ${toplevel}`);
91
+ }
92
+ return inside === "" ? "." : inside.split(sep).join("/");
93
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export type { Fragment, ResourceHandle, FragmentFactory, PlatformFactory, ProfileFactory, LazyFragment, PlatformLazyFragment, FragmentEntry, FragmentResult, NixExpr, RawModuleRef, ImportRef, InputDef, InputWithOptions, WorkspaceDef, HostDef, EvalContext } from "./core/types.js";
2
- export type { Attrs, BootOptions, DarwinNetworking, DarwinOptions, DarwinSecurity, DarwinDefaults, DarwinSystem, EnvironmentOptions, FirewallOptions, FontsOptions, FzfOptions, GitInclude, GitOptions, HomeActivation, HomebrewOptions, HomeConfig, HomeFile, HomeOptions, I18nOptions, LaunchdAgentOptions, LaunchdOptions, NeovimOptions, NetworkingOptions, NixConfig, NixGcOptions, NixHomebrewOptions, NixOptions, NixpkgsOptions, NixosSecurityOptions, NixosSystemOptions, NixPrimitive, NixSettings, NixValue, NixosOptions, OciContainerOptions, PackageRef, Script, ServicesOptions, StarshipOptions, SystemdOptions, SystemdService, SystemdTimer, TimeOptions, TmuxOptions, UserOptions, UsersOptions, VirtualisationOptions, WslOptions, XdgFile, XdgOptions, ZoxideOptions, ZshOptions, WindowsOptions, WinPackage, WinPackageSource, WinRawCommand, WinSettings, WinFontSource, WinWallpaper, WinPersonalization, WinColorMode, WinStartFolder, WinTaskbarAlignment, WinTaskbarGroupingMode, WinTaskbarMultiMonMode, WinKnownFolder, WinKnownFolderName, WinFilePath, WinPowerShellModule, WinPowerShellRepositoryPolicy, WinStartupCommand, WinStartupWindowStyle, } from "./types/index.js";
1
+ export type { Fragment, ResourceHandle, FragmentFactory, PlatformFactory, ProfileFactory, LazyFragment, PlatformLazyFragment, FragmentEntry, FragmentResult, NixExpr, RawModuleRef, ImportRef, InputDef, InputWithOptions, WorkspaceDef, HostDef, EvalContext, EvaluateOptions } from "./core/types.js";
2
+ export type { Attrs, BootOptions, DarwinNetworking, DarwinOptions, DarwinSecurity, DarwinDefaults, DarwinSystem, EnvironmentOptions, FirewallOptions, FontsOptions, FzfOptions, GitInclude, GitOptions, HomeActivation, HomebrewOptions, HomeConfig, HomeFile, HomeOptions, I18nOptions, LaunchdAgentOptions, LaunchdOptions, NeovimOptions, NetworkingOptions, NixConfig, NixGcOptions, NixHomebrewOptions, NixOptions, NixpkgsOptions, NixosSecurityOptions, NixosSystemOptions, NixPrimitive, NixSettings, NixValue, NixosOptions, OciContainerOptions, PackageRef, Script, ServicesOptions, StarshipOptions, SystemdOptions, SystemdService, SystemdTimer, TimeOptions, TmuxOptions, UserOptions, UsersOptions, VirtualisationOptions, WslOptions, XdgFile, XdgOptions, ZoxideOptions, ZshOptions, WindowsOptions, WinPackage, WinPackageSource, WinRawCommand, WinSettings, WinFontSource, WinWallpaper, WinPersonalization, WinColorMode, WinStartFolder, WinTaskbarAlignment, WinTaskbarGroupingMode, WinTaskbarMultiMonMode, WinKnownFolder, WinKnownFolderName, WinFilePath, WinPowerShellModule, WinPowerShellRepositoryPolicy, WinNpmRegistryPolicy, WinStartupCommand, WinStartupWindowStyle, } from "./types/index.js";
3
3
  export { platform, feature, profile, host, workspace, input, defineInputs, rawModule, withContext } from "./sdk/index.js";
4
4
  export type { WinixContext } from "./sdk/context.js";
5
5
  export { evaluate } from "./evaluator/index.js";
@@ -9,6 +9,6 @@ export type { NixOutput } from "./backends/nix/index.js";
9
9
  export { generateWindows, isWindowsHost } from "./backends/windows/index.js";
10
10
  export type { WindowsOutput, WindowsHostOutput } from "./backends/windows/index.js";
11
11
  export { account, darwin, home, nix, nixos, overlay, platforms, windows } from "./helpers/index.js";
12
- export type { WinPowerShellModuleOpts, WinStartupCommandSpec, WinStartupNamespace, WinOptionalFeatureOpts, WinWslDistroSpec, WinWslOpts, WinWslNamespace } from "./helpers/index.js";
12
+ export type { WinPowerShellModuleOpts, WinStartupCommandSpec, WinStartupNamespace, WinOptionalFeatureOpts, WinWslDistroSpec, WinWslSetupSpec, WinWslOpts, WinWslNamespace } from "./helpers/index.js";
13
13
  export type { WinWslConfig, WinWslDistro, WinWslSetup } from "./types/index.js";
14
- export type { AccountGroupFactory, AccountGroupMember, AccountGroupOpts, AccountNamespace, AccountOpts, AccountUserFactory, AccountUserRef, ActivationOpts, BinaryReleaseArch, BinaryReleaseCompletions, BinaryReleaseFormat, BinaryReleaseMeta, BinaryReleaseOpts, BinaryReleasePlatform, DarwinHelper, DarwinPlatformOpts, DarwinProgramOptions, DarwinServiceOptions, HomeHelper, HomeProgramOptions, HomeServiceOptions, LaunchdHelper, NixNamespace, NixosHelper, NixosPlatformOpts, NixosProgramOptions, NixosServiceOptions, OverlayHelper, PkgHelper, PlatformsHelper, ScriptHelper, SysctlSettings, SystemdHelper, VirtualisationHelper, WindowsHelper, WindowsPlatformOpts, WinEnvNamespace, WinEnvOpts, WinEnvScope, WinFileEncoding, WinFileNamespace, WinFileOpts, WinPackageArg, WinPackageSpec, WinPathNamespace, WinRawCommandArg, WinRawCommandSpec, WinSettingOpts } from "./helpers/index.js";
14
+ export type { AccountGroupFactory, AccountGroupMember, AccountGroupOpts, AccountNamespace, AccountOpts, AccountUserFactory, AccountUserRef, ActivationOpts, BinaryReleaseArch, BinaryReleaseCompletions, BinaryReleaseFormat, BinaryReleaseMeta, BinaryReleaseOpts, BinaryReleasePlatform, DarwinHelper, DarwinPlatformOpts, DarwinProgramOptions, DarwinServiceOptions, HomeHelper, HomeProgramOptions, HomeServiceOptions, LaunchdHelper, NixNamespace, NixosHelper, NixosPlatformOpts, NixosProgramOptions, NixosServiceOptions, OverlayHelper, PkgHelper, PlatformsHelper, ScriptHelper, SysctlSettings, SystemdHelper, VirtualisationHelper, WindowsHelper, WindowsPlatformOpts, WslPlatformOpts, WinEnvNamespace, WinEnvOpts, WinEnvScope, WinFileEncoding, WinFileNamespace, WinFileOpts, WinPackageArg, WinPackageSpec, WinPathNamespace, WinRawCommandArg, WinRawCommandSpec, WinSettingOpts } from "./helpers/index.js";
@@ -5,7 +5,9 @@ export declare function restoreEvalContext(ctx: EvalContext | null): void;
5
5
  export declare function clearEvalContext(): void;
6
6
  export declare function getEvalContext(): EvalContext;
7
7
  export declare function getOptionalEvalContext(): EvalContext | null;
8
- export declare function platform<T extends unknown[]>(id: string, factory: (...args: T) => Fragment): PlatformFactory<T>;
8
+ export declare function platform<T extends unknown[]>(id: string, factory: (...args: T) => Fragment, options?: {
9
+ variant?: string;
10
+ }): PlatformFactory<T>;
9
11
  export declare function feature<T extends unknown[]>(id: string, factory: (ctx: WinixContext, ...args: T) => AuthoringResult): FragmentFactory<T>;
10
12
  export declare function profile(id: string, entries: readonly FragmentEntry[]): ProfileFactory<[]>;
11
13
  export declare function host(name: string, platform: PlatformLazyFragment, fragments: readonly FragmentEntry[]): HostDef;
@@ -22,6 +24,8 @@ export declare const rawModule: RawModuleHelper;
22
24
  export declare function escape(expr: string): NixExpr;
23
25
  export declare function withContext<R>(ctx: {
24
26
  platform: string;
27
+ variant?: string;
25
28
  hostname?: string;
26
29
  features?: string[];
30
+ configDir?: string;
27
31
  }, fn: () => R): R;
package/dist/sdk/index.js CHANGED
@@ -30,12 +30,14 @@ export function getOptionalEvalContext() {
30
30
  return G.__winixEvalContext ?? null;
31
31
  }
32
32
  // --- platform() ---
33
- export function platform(id, factory) {
33
+ export function platform(id, factory, options = {}) {
34
+ const { variant } = options;
34
35
  const fn = ((...args) => {
35
36
  return {
36
37
  __lazy: true,
37
38
  __id: id,
38
39
  __platform: true,
40
+ ...(variant === undefined ? {} : { __variant: variant }),
39
41
  __resolve: () => {
40
42
  const result = factory(...args);
41
43
  return { ...result, __id: id, __platform: true };
@@ -43,7 +45,10 @@ export function platform(id, factory) {
43
45
  };
44
46
  });
45
47
  Object.defineProperty(fn, "isActive", {
46
- get: () => getCtx().platform === id,
48
+ get: () => {
49
+ const ctx = getCtx();
50
+ return ctx.platform === id && (variant === undefined || ctx.variant === variant);
51
+ },
47
52
  configurable: true,
48
53
  enumerable: false,
49
54
  });
@@ -258,8 +263,10 @@ export function withContext(ctx, fn) {
258
263
  const prev = G.__winixEvalContext ?? null;
259
264
  G.__winixEvalContext = {
260
265
  platform: ctx.platform,
266
+ ...(ctx.variant === undefined ? {} : { variant: ctx.variant }),
261
267
  hostname: ctx.hostname ?? "test",
262
268
  activeIds: new Set(ctx.features ?? []),
269
+ ...(ctx.configDir === undefined ? {} : { configDir: ctx.configDir }),
263
270
  };
264
271
  try {
265
272
  return fn();