@adrifer/winix 0.2.0-preview.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,14 @@
1
+ import { type NixOutput } from "../../backends/nix/index.js";
1
2
  interface CheckOptions {
2
3
  strict: boolean;
3
4
  escapeReport: boolean;
4
5
  }
5
6
  export declare function check(cwd: string, opts: CheckOptions): Promise<void>;
7
+ interface NixParseResult {
8
+ error?: NodeJS.ErrnoException;
9
+ status: number | null;
10
+ stderr: string;
11
+ }
12
+ type NixParser = (source: string) => NixParseResult;
13
+ export declare function validateGeneratedNixSyntax(output: NixOutput, parse?: NixParser): void;
6
14
  export {};
@@ -1,4 +1,5 @@
1
1
  // winix check — validate configuration
2
+ import { spawnSync } from "node:child_process";
2
3
  import { loadWorkspace } from "../loader.js";
3
4
  import { evaluate } from "../../evaluator/index.js";
4
5
  import { generateNix } from "../../backends/nix/index.js";
@@ -9,6 +10,7 @@ export async function check(cwd, opts) {
9
10
  const duplicateHosts = findDuplicateHosts(workspace);
10
11
  const evaluated = evaluate(workspace);
11
12
  const output = generateNix(workspace, evaluated);
13
+ validateGeneratedNixSyntax(output);
12
14
  const analyses = analyzeWorkspace(workspace);
13
15
  const conflicts = detectConflicts(analyses);
14
16
  console.log(`✓ Configuration valid`);
@@ -44,3 +46,26 @@ export async function check(cwd, opts) {
44
46
  process.exit(1);
45
47
  }
46
48
  }
49
+ export function validateGeneratedNixSyntax(output, parse = parseNixSource) {
50
+ const sources = [
51
+ ["flake.nix", output["flake.nix"]],
52
+ ...Object.entries(output.hosts).map(([name, source]) => [`hosts/${name}`, source]),
53
+ ];
54
+ for (const [name, source] of sources) {
55
+ const result = parse(source);
56
+ if (result.error?.code === "ENOENT")
57
+ return;
58
+ if (result.error)
59
+ throw result.error;
60
+ if (result.status !== 0) {
61
+ const detail = result.stderr.trim() || `nix-instantiate exited with status ${result.status}`;
62
+ throw new Error(`Generated Nix syntax is invalid in ${name}:\n${detail}`);
63
+ }
64
+ }
65
+ }
66
+ function parseNixSource(source) {
67
+ return spawnSync("nix-instantiate", ["--parse", "-"], {
68
+ input: source,
69
+ encoding: "utf8",
70
+ });
71
+ }
@@ -35,6 +35,9 @@ export interface NixExpr {
35
35
  * - `package`: identified by its natural, stable package id.
36
36
  * - `command`: has no natural id, so it carries a unique token; the emitter
37
37
  * assigns it a generated name (`command-N`) per host.
38
+ * - `dsc`: a generic DSC resource (from `windows.dsc(...)` and the typed
39
+ * helpers built on it, like env/path). Like commands it has no natural id,
40
+ * so it carries a unique token resolved to a generated name per host.
38
41
  */
39
42
  export type ResourceRef = {
40
43
  kind: "package";
@@ -42,6 +45,9 @@ export type ResourceRef = {
42
45
  } | {
43
46
  kind: "command";
44
47
  token: symbol;
48
+ } | {
49
+ kind: "dsc";
50
+ token: symbol;
45
51
  };
46
52
  /**
47
53
  * A resource handle: the value returned by resource-producing helpers like
@@ -1,5 +1,5 @@
1
1
  import type { ProgramOptions, ServiceOptions } from "./options.js";
2
- import type { Fragment } from "../core/types.js";
2
+ import type { Fragment, NixExpr } from "../core/types.js";
3
3
  import type { HomeFile, HomeOptions, PackageRef } from "../types/index.js";
4
4
  /**
5
5
  * Map of Home Manager program names to their option types.
@@ -19,9 +19,9 @@ export interface HomeHelper {
19
19
  imports(...imports: string[]): Fragment;
20
20
  program<const K extends string>(name: K, opts?: ProgramOptions<HomeProgramOptions, K>): Fragment;
21
21
  service<const K extends string>(name: K, opts?: ServiceOptions<HomeServiceOptions, K>): Fragment;
22
- env(vars: Record<string, string>): Fragment;
23
- path(paths: string[]): Fragment;
24
- path(...paths: string[]): Fragment;
22
+ env(vars: Record<string, string | NixExpr>): Fragment;
23
+ path(paths: (string | NixExpr)[]): Fragment;
24
+ path(...paths: (string | NixExpr)[]): Fragment;
25
25
  packages(packages: PackageRef[]): Fragment;
26
26
  packages(...packages: PackageRef[]): Fragment;
27
27
  files(files: Record<string, HomeFile>): Fragment;
@@ -1,4 +1,5 @@
1
1
  import { normalizeArgs } from "./utils.js";
2
+ import { escapeNixDoubleQuoted, nixStringLiteral } from "../nix/serialize.js";
2
3
  export const home = Object.assign((config) => ({ homeManager: config }), {
3
4
  program: (name, opts = {}) => ({
4
5
  homeManager: { programs: { [name]: { enable: true, ...opts } } },
@@ -37,7 +38,7 @@ export const home = Object.assign((config) => ({ homeManager: config }), {
37
38
  raw: (config) => ({ homeManager: { __raw: [config] } }),
38
39
  activation: (name, opts) => {
39
40
  const after = opts.after ?? ["writeBoundary"];
40
- const afterList = after.map((s) => JSON.stringify(s)).join(" ");
41
+ const afterList = after.map((s) => nixStringLiteral(s)).join(" ");
41
42
  return {
42
43
  homeManager: {
43
44
  home: {
@@ -54,10 +55,7 @@ export const home = Object.assign((config) => ({ homeManager: config }), {
54
55
  });
55
56
  function homePathToNixString(path) {
56
57
  if (path.startsWith("~/")) {
57
- return `"${escapeNixString(`\${config.home.homeDirectory}/${path.slice(2)}`)}"`;
58
+ return '"${config.home.homeDirectory}/' + escapeNixDoubleQuoted(path.slice(2)) + '"';
58
59
  }
59
- return JSON.stringify(path);
60
- }
61
- function escapeNixString(value) {
62
- return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
60
+ return nixStringLiteral(path);
63
61
  }
@@ -13,4 +13,4 @@ export type { NixosHelper, NixosProgramOptions, NixosServiceOptions, SysctlSetti
13
13
  export { darwin } from "./darwin.js";
14
14
  export type { DarwinHelper, DarwinProgramOptions, DarwinServiceOptions, LaunchdHelper } from "./darwin.js";
15
15
  export { windows } from "./windows.js";
16
- export type { WindowsHelper, WinPackageArg, WinPackageSpec, WinRawCommandArg, WinRawCommandSpec } from "./windows.js";
16
+ export type { WindowsHelper, WinDscSpec, WinEnvNamespace, WinEnvOpts, WinEnvScope, WinFileEncoding, WinFileNamespace, WinFileOpts, WinPackageArg, WinPackageSpec, WinPathNamespace, WinRawCommandArg, WinRawCommandSpec, WinSettingOpts, } from "./windows.js";
@@ -1,3 +1,4 @@
1
+ import { escapeNixDoubleQuoted, nixStringLiteral } from "../nix/serialize.js";
1
2
  const expr = (value) => ({ __winixNixExpr: true, expr: value });
2
3
  const pkg = Object.assign((name) => expr(`pkgs.${name}`), {
3
4
  stable: (name) => expr(`pkgs.stable.${name}`),
@@ -123,12 +124,16 @@ function binaryRelease(opts) {
123
124
  const sourcesAttrs = filtered
124
125
  .map(([arch, platform]) => {
125
126
  const parts = [
126
- `file = ${JSON.stringify(platform.file)};`,
127
- `hash = ${JSON.stringify(platform.hash)};`,
128
- `binary = ${JSON.stringify(platform.binary ?? opts.binary)};`,
127
+ `file = ${nixStringLiteral(platform.file)};`,
128
+ `hash = ${nixStringLiteral(platform.hash)};`,
129
+ `binary = ${nixStringLiteral(platform.binary ?? opts.binary)};`,
129
130
  ];
130
131
  if (usesPlatformPlaceholder) {
131
- parts.push(`platform = ${JSON.stringify(platform.platform)};`);
132
+ const platformName = platform.platform;
133
+ if (platformName === undefined) {
134
+ throw new Error(`nix.binaryRelease: "${arch}" must define \`platform\` because \`urlTemplate\` uses \`{platform}\``);
135
+ }
136
+ parts.push(`platform = ${nixStringLiteral(platformName)};`);
132
137
  }
133
138
  return ` ${arch} = { ${parts.join(" ")} };`;
134
139
  })
@@ -142,15 +147,15 @@ function binaryRelease(opts) {
142
147
  ? license.expr
143
148
  : `pkgs.lib.licenses.${license}`;
144
149
  const metaLines = [
145
- ` description = ${JSON.stringify(opts.meta.description)};`,
150
+ ` description = ${nixStringLiteral(opts.meta.description)};`,
146
151
  ];
147
152
  if (opts.meta.homepage !== undefined) {
148
- metaLines.push(` homepage = ${JSON.stringify(opts.meta.homepage)};`);
153
+ metaLines.push(` homepage = ${nixStringLiteral(opts.meta.homepage)};`);
149
154
  }
150
155
  if (licenseExpr !== undefined) {
151
156
  metaLines.push(` license = ${licenseExpr};`);
152
157
  }
153
- metaLines.push(` mainProgram = ${JSON.stringify(mainProgram)};`);
158
+ metaLines.push(` mainProgram = ${nixStringLiteral(mainProgram)};`);
154
159
  metaLines.push(` platforms = builtins.attrNames sources;`);
155
160
  const extraInstallBlock = opts.extraInstall
156
161
  ? `\n ${dedent(opts.extraInstall).split("\n").join("\n ")}`
@@ -181,13 +186,13 @@ function binaryRelease(opts) {
181
186
  ? `\n\n dontStrip = pkgs.stdenv.hostPlatform.isDarwin;`
182
187
  : "";
183
188
  const text = `(let
184
- version = ${JSON.stringify(opts.version)};
189
+ version = ${nixStringLiteral(opts.version)};
185
190
  sources = {
186
191
  ${sourcesAttrs}
187
192
  };
188
193
  source = sources.\${pkgs.stdenv.hostPlatform.system};
189
194
  in pkgs.stdenvNoCC.mkDerivation {
190
- pname = ${JSON.stringify(opts.name)};
195
+ pname = ${nixStringLiteral(opts.name)};
191
196
  inherit version;
192
197
 
193
198
  src = pkgs.fetchurl {
@@ -289,7 +294,7 @@ function dedent(value) {
289
294
  return lines.map((line) => (line.length >= min ? line.slice(min) : line)).join("\n");
290
295
  }
291
296
  function stringPartToNix(value) {
292
- return isNixExpr(value) ? value.expr : JSON.stringify(value);
297
+ return isNixExpr(value) ? value.expr : nixStringLiteral(value);
293
298
  }
294
299
  function conditionToNix(condition) {
295
300
  if (isNixExpr(condition))
@@ -302,7 +307,7 @@ function nixLiteral(value) {
302
307
  if (isNixExpr(value))
303
308
  return value.expr;
304
309
  if (typeof value === "string")
305
- return JSON.stringify(value);
310
+ return nixStringLiteral(value);
306
311
  if (typeof value === "number")
307
312
  return String(value);
308
313
  if (typeof value === "boolean")
@@ -324,7 +329,7 @@ function formatAttrs(attrs) {
324
329
  .join(" ");
325
330
  }
326
331
  function formatAttrKey(key) {
327
- return needsQuoting(key) ? JSON.stringify(key) : key;
332
+ return needsQuoting(key) ? nixStringLiteral(key) : key;
328
333
  }
329
334
  function needsQuoting(key) {
330
335
  if (NIX_KEYWORDS.has(key))
@@ -354,12 +359,6 @@ function joinRawTemplate(strings, values, formatValue) {
354
359
  function trimScript(body) {
355
360
  return body.replace(/^\n/, "").replace(/\n\s*$/, "");
356
361
  }
357
- function escapeNixDoubleQuoted(value) {
358
- return value
359
- .replace(/\\/g, "\\\\")
360
- .replace(/"/g, '\\"')
361
- .replace(/\$\{/g, "\\${");
362
- }
363
362
  function isNixExpr(value) {
364
363
  return (typeof value === "object" &&
365
364
  value !== null &&
@@ -1,5 +1,5 @@
1
1
  import type { ResourceHandle } from "../core/types.js";
2
- import type { WinPackageSource } from "../types/index.js";
2
+ import type { WinDscProperties, WinPackageSource, WinSettings } from "../types/index.js";
3
3
  /**
4
4
  * Accepted call shapes for `windows.package(...)`.
5
5
  *
@@ -13,8 +13,7 @@ export interface WinPackageSpec {
13
13
  elevated?: boolean;
14
14
  /**
15
15
  * Resources this package must be applied after. Accepts a single handle or
16
- * an array of handles, both returned by `windows.package(...)` /
17
- * `windows.raw(...)`.
16
+ * an array of handles returned by resource-producing `windows.*` helpers.
18
17
  */
19
18
  dependsOn?: ResourceHandle | ResourceHandle[];
20
19
  }
@@ -33,6 +32,52 @@ export interface WinRawCommandSpec {
33
32
  dependsOn?: ResourceHandle | ResourceHandle[];
34
33
  }
35
34
  export type WinRawCommandArg = string | WinRawCommandSpec;
35
+ /**
36
+ * Accepted object shape for `windows.dsc(...)`, the generic DSC v3 escape
37
+ * hatch. `type` is the fully qualified DSC resource type; `properties` is a
38
+ * free-form JSON-like object serialized verbatim to YAML.
39
+ */
40
+ export interface WinDscSpec {
41
+ type: string;
42
+ name?: string;
43
+ properties?: WinDscProperties;
44
+ dependsOn?: ResourceHandle | ResourceHandle[];
45
+ }
46
+ /** Options for `windows.setting(...)`. */
47
+ export interface WinSettingOpts {
48
+ dependsOn?: ResourceHandle | ResourceHandle[];
49
+ }
50
+ /** Scope for Windows environment and PATH writes. */
51
+ export type WinEnvScope = "user" | "machine";
52
+ /** Options shared by `windows.env.*` and `windows.path.*` methods. */
53
+ export interface WinEnvOpts {
54
+ scope?: WinEnvScope;
55
+ dependsOn?: ResourceHandle | ResourceHandle[];
56
+ }
57
+ export type WinFileEncoding = "utf8" | "utf8bom" | "ascii";
58
+ /** Options shared by `windows.file.*` methods. */
59
+ export interface WinFileOpts {
60
+ force?: boolean;
61
+ backup?: boolean;
62
+ recursive?: boolean;
63
+ elevate?: boolean;
64
+ encoding?: WinFileEncoding;
65
+ dependsOn?: ResourceHandle | ResourceHandle[];
66
+ }
67
+ export interface WinEnvNamespace {
68
+ set(name: string, value: string, opts?: WinEnvOpts): ResourceHandle;
69
+ remove(name: string, opts?: WinEnvOpts): ResourceHandle;
70
+ }
71
+ export interface WinPathNamespace {
72
+ add(value: string, opts?: WinEnvOpts): ResourceHandle;
73
+ remove(value: string, opts?: WinEnvOpts): ResourceHandle;
74
+ }
75
+ export interface WinFileNamespace {
76
+ text(target: string, content: string, opts?: WinFileOpts): ResourceHandle;
77
+ symlink(target: string, source: string, opts?: WinFileOpts): ResourceHandle;
78
+ copy(target: string, source: string, opts?: WinFileOpts): ResourceHandle;
79
+ remove(target: string, opts?: WinFileOpts): ResourceHandle;
80
+ }
36
81
  export interface WindowsHelper {
37
82
  /**
38
83
  * Declare a winget/msstore package.
@@ -59,5 +104,63 @@ export interface WindowsHelper {
59
104
  * ```
60
105
  */
61
106
  raw(arg: WinRawCommandArg): ResourceHandle;
107
+ /**
108
+ * Declare an arbitrary DSC v3 resource (escape hatch). The `type` is a fully
109
+ * qualified DSC resource type and `properties` is serialized verbatim to the
110
+ * generated configuration. Use this for resources Winix has no typed helper
111
+ * for.
112
+ *
113
+ * ```ts
114
+ * windows.dsc({
115
+ * type: "Microsoft.Windows/Service",
116
+ * properties: { name: "spooler", startType: "automatic" },
117
+ * });
118
+ * ```
119
+ */
120
+ dsc(arg: WinDscSpec): ResourceHandle;
121
+ /**
122
+ * Manage Windows OS settings through the native
123
+ * `Microsoft.Windows.Settings/WindowsSettings` DSC resource. The emitter
124
+ * automatically ensures the required `Microsoft.Windows.Settings` module is
125
+ * installed and wires settings resources to depend on it.
126
+ *
127
+ * ```ts
128
+ * windows.setting({ DeveloperMode: true });
129
+ * windows.setting({ SystemColorMode: "Dark", TaskbarAlignment: "Left" });
130
+ * ```
131
+ */
132
+ setting(settings: WinSettings, opts?: WinSettingOpts): ResourceHandle;
133
+ /**
134
+ * Manage a user/machine environment variable declaratively via the native
135
+ * `Microsoft.Windows/Registry` DSC resource.
136
+ *
137
+ * ```ts
138
+ * windows.env.set("EDITOR", "nvim");
139
+ * windows.env.remove("OLD_VAR");
140
+ * ```
141
+ */
142
+ env: WinEnvNamespace;
143
+ /**
144
+ * Ensure a directory is on the PATH, appending/removing surgically via an
145
+ * idempotent `Microsoft.DSC.Transitional/WindowsPowerShellScript` resource.
146
+ *
147
+ * ```ts
148
+ * windows.path.add("%USERPROFILE%\\.local\\bin");
149
+ * windows.path.remove("%USERPROFILE%\\.old-bin");
150
+ * ```
151
+ */
152
+ path: WinPathNamespace;
153
+ /**
154
+ * Manage files, copies, and dotfile symlinks declaratively via an idempotent
155
+ * `Microsoft.DSC.Transitional/WindowsPowerShellScript` resource.
156
+ *
157
+ * ```ts
158
+ * windows.file.text("%USERPROFILE%\\.gitconfig", "[user]\n");
159
+ * windows.file.symlink("%LOCALAPPDATA%\\nvim", "%USERPROFILE%\\dotfiles\\nvim");
160
+ * windows.file.copy("%APPDATA%\\tool\\config.json", ".\\config.json");
161
+ * windows.file.remove("%USERPROFILE%\\.oldrc");
162
+ * ```
163
+ */
164
+ file: WinFileNamespace;
62
165
  }
63
166
  export declare const windows: WindowsHelper;