@adrifer/winix 0.2.0-preview.3 → 0.2.0-preview.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -25,6 +25,7 @@
25
25
  //
26
26
  // `winget configure -f configuration.winget` runs this directly; the dscv3
27
27
  // processor is selected by the metadata block.
28
+ import { yamlEntry, yamlScalar } from "./yaml.js";
28
29
  import { emptyWindowsLock, reconcileInlinePins, } from "./lockfile.js";
29
30
  import { isWindowsHost } from "./host.js";
30
31
  export { isWindowsHost } from "./host.js";
@@ -55,6 +56,7 @@ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock()) {
55
56
  function generateConfiguration(hostName, win, lock) {
56
57
  const packages = sortedPackages(win.packages ?? {});
57
58
  const commands = win.commands ?? [];
59
+ const dscResources = win.dsc ?? [];
58
60
  const lines = [];
59
61
  lines.push(`# yaml-language-server: $schema=${DSC_SCHEMA}`);
60
62
  lines.push(`# Generated by Winix for host "${hostName}". Do not edit.`);
@@ -62,14 +64,14 @@ function generateConfiguration(hostName, win, lock) {
62
64
  lines.push("metadata:");
63
65
  lines.push(" winget:");
64
66
  lines.push(" processor: dscv3");
65
- if (packages.length === 0 && commands.length === 0) {
67
+ if (packages.length === 0 && commands.length === 0 && dscResources.length === 0) {
66
68
  lines.push("resources: []");
67
69
  return lines.join("\n") + "\n";
68
70
  }
69
71
  // Two-pass: first assign every resource a schema-valid, unique name and build
70
72
  // the ref → (type, name) map; then render, resolving each resource's
71
73
  // `dependsOn` against that map.
72
- const naming = assignResourceNames(hostName, packages, commands);
74
+ const naming = assignResourceNames(hostName, packages, commands, dscResources);
73
75
  lines.push("resources:");
74
76
  for (const pkg of packages) {
75
77
  const plan = naming.packages.get(pkg);
@@ -79,6 +81,10 @@ function generateConfiguration(hostName, win, lock) {
79
81
  const plan = naming.commands.get(command);
80
82
  lines.push(...renderRawCommandResource(command, plan, naming));
81
83
  }
84
+ for (const resource of dscResources) {
85
+ const plan = naming.dsc.get(resource);
86
+ lines.push(...renderDscResource(resource, plan, naming));
87
+ }
82
88
  return lines.join("\n") + "\n";
83
89
  }
84
90
  /**
@@ -104,13 +110,15 @@ function sanitizeName(raw) {
104
110
  * - On a name collision, a ` N` suffix is appended to keep names unique, since
105
111
  * DSC requires instance names to be unique within a document.
106
112
  */
107
- function assignResourceNames(hostName, packages, commands) {
113
+ function assignResourceNames(hostName, packages, commands, dscResources) {
108
114
  const used = new Set();
109
115
  const plan = {
110
116
  packages: new Map(),
111
117
  commands: new Map(),
118
+ dsc: new Map(),
112
119
  byPackageId: new Map(),
113
120
  byCommandToken: new Map(),
121
+ byDscToken: new Map(),
114
122
  hostName,
115
123
  };
116
124
  const unique = (base) => {
@@ -142,6 +150,19 @@ function assignResourceNames(hostName, packages, commands) {
142
150
  plan.byCommandToken.set(command.token, rp);
143
151
  }
144
152
  }
153
+ let dscCounter = 0;
154
+ for (const resource of dscResources) {
155
+ dscCounter += 1;
156
+ const base = resource.name
157
+ ? sanitizeName(resource.name)
158
+ : `dsc ${dscCounter}`;
159
+ const name = unique(base);
160
+ const rp = { type: resource.resourceType, name };
161
+ plan.dsc.set(resource, rp);
162
+ if (resource.token) {
163
+ plan.byDscToken.set(resource.token, rp);
164
+ }
165
+ }
145
166
  return plan;
146
167
  }
147
168
  /**
@@ -155,11 +176,21 @@ function resolveDependsOnRefs(refs, naming) {
155
176
  return [];
156
177
  const ids = [];
157
178
  for (const ref of refs) {
158
- const target = ref.kind === "package"
159
- ? naming.byPackageId.get(ref.id)
160
- : naming.byCommandToken.get(ref.token);
179
+ let target;
180
+ let what;
181
+ if (ref.kind === "package") {
182
+ target = naming.byPackageId.get(ref.id);
183
+ what = `package "${ref.id}"`;
184
+ }
185
+ else if (ref.kind === "command") {
186
+ target = naming.byCommandToken.get(ref.token);
187
+ what = "a raw command";
188
+ }
189
+ else {
190
+ target = naming.byDscToken.get(ref.token);
191
+ what = "a DSC resource";
192
+ }
161
193
  if (!target) {
162
- const what = ref.kind === "package" ? `package "${ref.id}"` : "a raw command";
163
194
  throw new Error(`windows dependsOn references ${what} that is not declared in host ` +
164
195
  `"${naming.hostName}". Resources can only depend on other resources ` +
165
196
  `within the same host.`);
@@ -228,9 +259,36 @@ function renderRawCommandResource(command, plan, naming) {
228
259
  return out;
229
260
  }
230
261
  /**
231
- * The thin apply entry point. Idempotency, elevation, ordering, and error
232
- * reporting all live inside `winget configure` / the DSC v3 processor.
262
+ * Render one generic DSC resource (from `windows.dsc(...)` and typed helpers)
263
+ * as a DSC v3 resource block. The `properties` object is serialized verbatim
264
+ * via the YAML helper, so arbitrary nested DSC resource shapes round-trip
265
+ * exactly.
233
266
  */
267
+ function renderDscResource(resource, plan, naming) {
268
+ const out = [];
269
+ out.push(` - name: ${yamlScalar(plan.name)}`);
270
+ out.push(` type: ${yamlScalar(resource.resourceType)}`);
271
+ const deps = resolveDependsOnRefs(resource.dependsOn, naming);
272
+ if (deps.length > 0) {
273
+ out.push(` dependsOn: ${yamlStringArray(deps)}`);
274
+ }
275
+ const properties = resource.properties ?? {};
276
+ if (Object.keys(properties).length === 0) {
277
+ out.push(` properties: {}`);
278
+ }
279
+ else {
280
+ // Serialize properties at depth 0, then re-indent under `properties:` (2
281
+ // levels deep within the resource block: 4 spaces).
282
+ out.push(` properties:`);
283
+ for (const [key, value] of Object.entries(properties)) {
284
+ const lines = yamlEntry(key, value, 0);
285
+ for (const line of lines) {
286
+ out.push(` ${line}`);
287
+ }
288
+ }
289
+ }
290
+ return out;
291
+ }
234
292
  function generateApplyScript() {
235
293
  return [
236
294
  "# Generated by Winix. Do not edit.",
@@ -267,16 +325,17 @@ function lockedVersionForPackage(pkg, lock) {
267
325
  return entry.version;
268
326
  }
269
327
  /**
270
- * Render a YAML scalar. Package ids and sources are simple tokens; quote
271
- * defensively only if the value contains YAML-significant characters.
328
+ * Render a quoted YAML string for `dependsOn` array items, which are always
329
+ * quoted because they contain `[`, `]`, `'`, and `(` (the `resourceId(...)`
330
+ * expression). Reuses the shared scalar quoting via a forced-quote path.
272
331
  */
273
- function yamlScalar(value) {
274
- if (/^[A-Za-z0-9._+\-]+$/.test(value))
275
- return value;
276
- return yamlQuoted(value);
277
- }
278
332
  function yamlQuoted(value) {
279
- return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
333
+ // The shared yamlScalar would quote these anyway (they contain `[`), but be
334
+ // explicit: dependsOn ids are always emitted quoted.
335
+ const escaped = value
336
+ .replace(/\\/g, "\\\\")
337
+ .replace(/"/g, '\\"');
338
+ return `"${escaped}"`;
280
339
  }
281
340
  function yamlStringArray(values) {
282
341
  return `[${values.map((value) => yamlQuoted(value)).join(", ")}]`;
@@ -0,0 +1,27 @@
1
+ /** A JSON-like value the serializer accepts. */
2
+ export type YamlValue = string | number | boolean | null | YamlValue[] | {
3
+ [key: string]: YamlValue;
4
+ };
5
+ /**
6
+ * Serialize a value as block-style YAML lines at the given indent depth.
7
+ * Returns an array of lines WITHOUT a trailing newline; the caller joins them.
8
+ *
9
+ * The `keyContext` form (rendering a value that sits to the right of a `key:`)
10
+ * is handled by the caller via {@link yamlEntry}; this function renders a value
11
+ * standing on its own (e.g. an array item or the document root).
12
+ */
13
+ export declare function yamlLines(value: YamlValue, depth?: number): string[];
14
+ /**
15
+ * Render a single `key: value` entry, choosing inline vs. block layout based on
16
+ * the value's shape:
17
+ * - scalars render inline: `key: value`
18
+ * - empty collections render inline: `key: []` / `key: {}`
19
+ * - non-empty arrays/objects render on following indented lines
20
+ */
21
+ export declare function yamlEntry(key: string, value: YamlValue, depth: number): string[];
22
+ /**
23
+ * Render a scalar (string | number | boolean | null). Strings are quoted unless
24
+ * they are safe plain tokens, so values like `Present`, `winget`, or `Git.Git`
25
+ * stay unquoted while paths, spaces, and YAML-significant characters are quoted.
26
+ */
27
+ export declare function yamlScalar(value: string | number | boolean | null): string;
@@ -0,0 +1,178 @@
1
+ // Minimal YAML value serializer for the Windows DSC emitter.
2
+ //
3
+ // Winix emits Nix by hand and has zero runtime dependencies; the Windows
4
+ // backend keeps that property by serializing the small, well-typed subset of
5
+ // YAML that DSC v3 configuration documents need, rather than pulling in a YAML
6
+ // library.
7
+ //
8
+ // SCOPE: this serializes arbitrary *JSON-like* values (string, number, boolean,
9
+ // null, arrays, plain objects) into block-style YAML. It is used for the
10
+ // `properties` of generic and typed DSC resources. It is deliberately NOT a
11
+ // general YAML emitter: it does not handle anchors, tags, or non-JSON values.
12
+ //
13
+ // DETERMINISM: object keys are emitted in insertion order. Callers that need a
14
+ // stable document order across runs must build their objects deterministically
15
+ // (the helpers do: they construct property objects in a fixed field order).
16
+ const INDENT = " ";
17
+ /**
18
+ * Serialize a value as block-style YAML lines at the given indent depth.
19
+ * Returns an array of lines WITHOUT a trailing newline; the caller joins them.
20
+ *
21
+ * The `keyContext` form (rendering a value that sits to the right of a `key:`)
22
+ * is handled by the caller via {@link yamlEntry}; this function renders a value
23
+ * standing on its own (e.g. an array item or the document root).
24
+ */
25
+ export function yamlLines(value, depth = 0) {
26
+ const pad = INDENT.repeat(depth);
27
+ if (Array.isArray(value)) {
28
+ if (value.length === 0)
29
+ return [`${pad}[]`];
30
+ const out = [];
31
+ for (const item of value) {
32
+ out.push(...yamlArrayItem(item, depth));
33
+ }
34
+ return out;
35
+ }
36
+ if (isPlainObject(value)) {
37
+ const keys = Object.keys(value);
38
+ if (keys.length === 0)
39
+ return [`${pad}{}`];
40
+ const out = [];
41
+ for (const key of keys) {
42
+ out.push(...yamlEntry(key, value[key], depth));
43
+ }
44
+ return out;
45
+ }
46
+ return [`${pad}${yamlScalar(value)}`];
47
+ }
48
+ /**
49
+ * Render a single `key: value` entry, choosing inline vs. block layout based on
50
+ * the value's shape:
51
+ * - scalars render inline: `key: value`
52
+ * - empty collections render inline: `key: []` / `key: {}`
53
+ * - non-empty arrays/objects render on following indented lines
54
+ */
55
+ export function yamlEntry(key, value, depth) {
56
+ const pad = INDENT.repeat(depth);
57
+ const k = yamlKey(key);
58
+ if (Array.isArray(value)) {
59
+ if (value.length === 0)
60
+ return [`${pad}${k}: []`];
61
+ // Array items sit at the SAME indent as the key (block sequence style),
62
+ // matching how the existing emitter and Microsoft's own DSC docs lay out
63
+ // `resources:` and `dependsOn:`.
64
+ const out = [`${pad}${k}:`];
65
+ for (const item of value) {
66
+ out.push(...yamlArrayItem(item, depth));
67
+ }
68
+ return out;
69
+ }
70
+ if (isPlainObject(value)) {
71
+ const keys = Object.keys(value);
72
+ if (keys.length === 0)
73
+ return [`${pad}${k}: {}`];
74
+ const out = [`${pad}${k}:`];
75
+ for (const childKey of keys) {
76
+ out.push(...yamlEntry(childKey, value[childKey], depth + 1));
77
+ }
78
+ return out;
79
+ }
80
+ return [`${pad}${k}: ${yamlScalar(value)}`];
81
+ }
82
+ /**
83
+ * Render one array item as a `- ...` block sequence entry. Scalars render
84
+ * inline after the dash; objects render with their first key on the dash line
85
+ * and the rest indented under it (canonical block-sequence-of-mappings style).
86
+ */
87
+ function yamlArrayItem(value, depth) {
88
+ const pad = INDENT.repeat(depth);
89
+ if (isPlainObject(value)) {
90
+ const keys = Object.keys(value);
91
+ if (keys.length === 0)
92
+ return [`${pad}- {}`];
93
+ const out = [];
94
+ keys.forEach((key, index) => {
95
+ const entryLines = yamlEntry(key, value[key], depth + 1);
96
+ if (index === 0) {
97
+ // Hoist the first entry onto the dash line: "- key: value" or "- key:".
98
+ out.push(`${pad}- ${entryLines[0].slice((depth + 1) * INDENT.length)}`);
99
+ out.push(...entryLines.slice(1));
100
+ }
101
+ else {
102
+ out.push(...entryLines);
103
+ }
104
+ });
105
+ return out;
106
+ }
107
+ if (Array.isArray(value)) {
108
+ // Nested bare arrays are not expected in DSC documents; render defensively
109
+ // as an indented block under the dash.
110
+ if (value.length === 0)
111
+ return [`${pad}- []`];
112
+ const out = [`${pad}-`];
113
+ for (const item of value) {
114
+ out.push(...yamlArrayItem(item, depth + 1));
115
+ }
116
+ return out;
117
+ }
118
+ return [`${pad}- ${yamlScalar(value)}`];
119
+ }
120
+ /** Render an object key, quoting it only when it is not a safe plain token. */
121
+ function yamlKey(key) {
122
+ return isPlainToken(key) ? key : yamlQuoted(key);
123
+ }
124
+ /**
125
+ * Render a scalar (string | number | boolean | null). Strings are quoted unless
126
+ * they are safe plain tokens, so values like `Present`, `winget`, or `Git.Git`
127
+ * stay unquoted while paths, spaces, and YAML-significant characters are quoted.
128
+ */
129
+ export function yamlScalar(value) {
130
+ if (value === null)
131
+ return "null";
132
+ if (typeof value === "boolean")
133
+ return value ? "true" : "false";
134
+ if (typeof value === "number") {
135
+ if (!Number.isFinite(value)) {
136
+ throw new Error(`Cannot serialize non-finite number to YAML: ${value}`);
137
+ }
138
+ return String(value);
139
+ }
140
+ return isPlainToken(value) ? value : yamlQuoted(value);
141
+ }
142
+ /**
143
+ * A "plain token" is a string safe to emit unquoted in YAML in both key and
144
+ * value position. Conservative on purpose: letters, digits, and the few
145
+ * punctuation marks common in package ids / DSC type names (`.`, `_`, `+`,
146
+ * `-`, `/`). Anything else (spaces, `:`, backslashes, quotes, leading
147
+ * indicators) gets quoted.
148
+ *
149
+ * Strings that look like other YAML types (numbers, booleans, null) are NOT
150
+ * plain tokens, so `"true"`, `"123"`, and `"null"` round-trip as strings.
151
+ */
152
+ function isPlainToken(value) {
153
+ if (value.length === 0)
154
+ return false;
155
+ if (!/^[A-Za-z0-9._+/-]+$/.test(value))
156
+ return false;
157
+ // Disambiguate from non-string YAML scalars.
158
+ if (/^[+-]?(\d+\.?\d*|\.\d+)$/.test(value))
159
+ return false; // numeric-looking
160
+ if (/^(true|false|null|yes|no|on|off|~)$/i.test(value))
161
+ return false; // keyword-looking
162
+ return true;
163
+ }
164
+ function yamlQuoted(value) {
165
+ // Double-quoted YAML scalar with the escapes that matter for our inputs.
166
+ const escaped = value
167
+ .replace(/\\/g, "\\\\")
168
+ .replace(/"/g, '\\"')
169
+ .replace(/\n/g, "\\n")
170
+ .replace(/\t/g, "\\t")
171
+ .replace(/\r/g, "\\r");
172
+ return `"${escaped}"`;
173
+ }
174
+ function isPlainObject(value) {
175
+ return (typeof value === "object" &&
176
+ value !== null &&
177
+ !Array.isArray(value));
178
+ }
@@ -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
@@ -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, WinPackageArg, WinPackageSpec, WinPathNamespace, WinRawCommandArg, WinRawCommandSpec, } from "./windows.js";
@@ -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 } 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,32 @@ 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
+ /** Scope for Windows environment and PATH writes. */
47
+ export type WinEnvScope = "user" | "machine";
48
+ /** Options shared by `windows.env.*` and `windows.path.*` methods. */
49
+ export interface WinEnvOpts {
50
+ scope?: WinEnvScope;
51
+ dependsOn?: ResourceHandle | ResourceHandle[];
52
+ }
53
+ export interface WinEnvNamespace {
54
+ set(name: string, value: string, opts?: WinEnvOpts): ResourceHandle;
55
+ remove(name: string, opts?: WinEnvOpts): ResourceHandle;
56
+ }
57
+ export interface WinPathNamespace {
58
+ add(value: string, opts?: WinEnvOpts): ResourceHandle;
59
+ remove(value: string, opts?: WinEnvOpts): ResourceHandle;
60
+ }
36
61
  export interface WindowsHelper {
37
62
  /**
38
63
  * Declare a winget/msstore package.
@@ -59,5 +84,39 @@ export interface WindowsHelper {
59
84
  * ```
60
85
  */
61
86
  raw(arg: WinRawCommandArg): ResourceHandle;
87
+ /**
88
+ * Declare an arbitrary DSC v3 resource (escape hatch). The `type` is a fully
89
+ * qualified DSC resource type and `properties` is serialized verbatim to the
90
+ * generated configuration. Use this for resources Winix has no typed helper
91
+ * for.
92
+ *
93
+ * ```ts
94
+ * windows.dsc({
95
+ * type: "Microsoft.Windows/Service",
96
+ * properties: { name: "spooler", startType: "automatic" },
97
+ * });
98
+ * ```
99
+ */
100
+ dsc(arg: WinDscSpec): ResourceHandle;
101
+ /**
102
+ * Manage a user/machine environment variable declaratively via the native
103
+ * `Microsoft.Windows/Registry` DSC resource.
104
+ *
105
+ * ```ts
106
+ * windows.env.set("EDITOR", "nvim");
107
+ * windows.env.remove("OLD_VAR");
108
+ * ```
109
+ */
110
+ env: WinEnvNamespace;
111
+ /**
112
+ * Ensure a directory is on the PATH, appending/removing surgically via an
113
+ * idempotent `Microsoft.DSC.Transitional/WindowsPowerShellScript` resource.
114
+ *
115
+ * ```ts
116
+ * windows.path.add("%USERPROFILE%\\.local\\bin");
117
+ * windows.path.remove("%USERPROFILE%\\.old-bin");
118
+ * ```
119
+ */
120
+ path: WinPathNamespace;
62
121
  }
63
122
  export declare const windows: WindowsHelper;
@@ -20,7 +20,7 @@ function resolveDependsOn(dependsOn) {
20
20
  const ref = handle?.__winixHandle;
21
21
  if (!ref) {
22
22
  throw new Error("windows.*(dependsOn) expects resource handles returned by " +
23
- "windows.package(...) or windows.raw(...). Got a value without a " +
23
+ "resource-producing windows.* helpers. Got a value without a " +
24
24
  "resource identity.");
25
25
  }
26
26
  refs.push(ref);
@@ -109,6 +109,181 @@ function withToken(command) {
109
109
  });
110
110
  return command;
111
111
  }
112
+ /** Stamp a non-enumerable identity token onto a generic DSC resource. */
113
+ function withDscToken(resource) {
114
+ Object.defineProperty(resource, "token", {
115
+ value: Symbol("winix.dsc"),
116
+ enumerable: false,
117
+ configurable: true,
118
+ });
119
+ return resource;
120
+ }
121
+ const REGISTRY_RESOURCE = "Microsoft.Windows/Registry";
122
+ const WINDOWS_POWERSHELL_SCRIPT_RESOURCE = "Microsoft.DSC.Transitional/WindowsPowerShellScript";
123
+ const USER_ENV_KEY_PATH = "HKCU\\Environment";
124
+ const MACHINE_ENV_KEY_PATH = "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
125
+ const USER_ENV_REGISTRY_PATH = "HKCU:\\Environment";
126
+ const MACHINE_ENV_REGISTRY_PATH = "HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
127
+ function normalizeDsc(arg) {
128
+ if (!arg || typeof arg !== "object") {
129
+ throw new Error("windows.dsc(...) requires a spec object");
130
+ }
131
+ if (!arg.type || typeof arg.type !== "string") {
132
+ throw new Error("windows.dsc({ type }) requires a non-empty resource type");
133
+ }
134
+ const resource = { resourceType: arg.type };
135
+ if (arg.name !== undefined) {
136
+ if (typeof arg.name !== "string" || arg.name.length === 0) {
137
+ throw new Error("windows.dsc({ name }) must be a non-empty string");
138
+ }
139
+ resource.name = arg.name;
140
+ }
141
+ if (arg.properties !== undefined) {
142
+ if (arg.properties === null || typeof arg.properties !== "object" || Array.isArray(arg.properties)) {
143
+ throw new Error("windows.dsc({ properties }) must be a plain object");
144
+ }
145
+ resource.properties = arg.properties;
146
+ }
147
+ const deps = resolveDependsOn(arg.dependsOn);
148
+ if (deps)
149
+ resource.dependsOn = deps;
150
+ return withDscToken(resource);
151
+ }
152
+ function normalizeEnvOpts(opts, helper) {
153
+ if (opts === undefined)
154
+ return undefined;
155
+ if (opts === null || typeof opts !== "object" || Array.isArray(opts)) {
156
+ throw new Error(`${helper} options must be an object when provided`);
157
+ }
158
+ if (opts.scope !== undefined &&
159
+ opts.scope !== "user" &&
160
+ opts.scope !== "machine") {
161
+ throw new Error(`${helper} scope "${opts.scope}" is invalid; expected "user" or "machine"`);
162
+ }
163
+ return opts;
164
+ }
165
+ function envScope(opts) {
166
+ return opts?.scope ?? "user";
167
+ }
168
+ function envKeyPath(scope) {
169
+ return scope === "machine" ? MACHINE_ENV_KEY_PATH : USER_ENV_KEY_PATH;
170
+ }
171
+ function envRegistryPath(scope) {
172
+ return scope === "machine" ? MACHINE_ENV_REGISTRY_PATH : USER_ENV_REGISTRY_PATH;
173
+ }
174
+ function envTarget(scope) {
175
+ return scope === "machine" ? "Machine" : "User";
176
+ }
177
+ function registryDsc(opts) {
178
+ const properties = {
179
+ keyPath: opts.keyPath,
180
+ valueName: opts.valueName,
181
+ _exist: opts.exists,
182
+ };
183
+ if (opts.exists) {
184
+ properties.valueData = { String: opts.value ?? "" };
185
+ }
186
+ const resource = {
187
+ resourceType: REGISTRY_RESOURCE,
188
+ name: opts.name,
189
+ properties,
190
+ };
191
+ if (opts.dependsOn)
192
+ resource.dependsOn = opts.dependsOn;
193
+ return withDscToken(resource);
194
+ }
195
+ function normalizeEnv(name, ensure, value, opts) {
196
+ const normalizedOpts = normalizeEnvOpts(opts, "windows.env.*");
197
+ if (!name || typeof name !== "string") {
198
+ throw new Error("windows.env.*(name) requires a non-empty variable name");
199
+ }
200
+ if (ensure === "Present" && (value === undefined || typeof value !== "string")) {
201
+ throw new Error(`windows.env.set("${name}", value) requires a string value`);
202
+ }
203
+ const scope = envScope(normalizedOpts);
204
+ return registryDsc({
205
+ name: ensure === "Present" ? `Set ${name}` : `Remove ${name}`,
206
+ keyPath: envKeyPath(scope),
207
+ valueName: name,
208
+ value,
209
+ exists: ensure === "Present",
210
+ dependsOn: resolveDependsOn(normalizedOpts?.dependsOn),
211
+ });
212
+ }
213
+ function normalizePath(value, ensure, opts) {
214
+ const normalizedOpts = normalizeEnvOpts(opts, "windows.path.*");
215
+ if (!value || typeof value !== "string") {
216
+ throw new Error("windows.path.*(value) requires a non-empty directory");
217
+ }
218
+ const scope = envScope(normalizedOpts);
219
+ const resource = {
220
+ resourceType: WINDOWS_POWERSHELL_SCRIPT_RESOURCE,
221
+ name: `${ensure === "Present" ? "Add" : "Remove"} ${value} ${ensure === "Present" ? "to" : "from"} PATH`,
222
+ properties: buildPathScriptProperties({
223
+ dir: value,
224
+ scope,
225
+ action: ensure === "Present" ? "add" : "remove",
226
+ }),
227
+ };
228
+ const deps = resolveDependsOn(normalizedOpts?.dependsOn);
229
+ if (deps)
230
+ resource.dependsOn = deps;
231
+ return withDscToken(resource);
232
+ }
233
+ function buildPathScriptProperties(opts) {
234
+ const registryPath = envRegistryPath(opts.scope);
235
+ const target = envTarget(opts.scope);
236
+ const quotedDir = psSingleQuoted(opts.dir);
237
+ const quotedRegistryPath = psSingleQuoted(registryPath);
238
+ const quotedTarget = psSingleQuoted(target);
239
+ const presentCheck = opts.action === "add"
240
+ ? "$entries -contains $dir"
241
+ : "-not ($entries -contains $dir)";
242
+ return {
243
+ getScript: [
244
+ `$registryPath = ${quotedRegistryPath}`,
245
+ "Get-ItemPropertyValue -Path $registryPath -Name 'Path' -ErrorAction SilentlyContinue",
246
+ ].join("\n"),
247
+ testScript: [
248
+ `$dir = ${quotedDir}`,
249
+ `$registryPath = ${quotedRegistryPath}`,
250
+ "$current = Get-ItemPropertyValue -Path $registryPath -Name 'Path' -ErrorAction SilentlyContinue",
251
+ "$entries = if ([string]::IsNullOrEmpty($current)) { @() } else { $current -split ';' }",
252
+ presentCheck,
253
+ ].join("\n"),
254
+ setScript: [
255
+ `$dir = ${quotedDir}`,
256
+ `$registryPath = ${quotedRegistryPath}`,
257
+ `$target = ${quotedTarget}`,
258
+ "$key = Get-Item -Path $registryPath",
259
+ "$originalKind = $null",
260
+ "try { $originalKind = $key.GetValueKind('Path') } catch { $originalKind = $null }",
261
+ "$current = Get-ItemPropertyValue -Path $registryPath -Name 'Path' -ErrorAction SilentlyContinue",
262
+ "$entries = if ([string]::IsNullOrEmpty($current)) { @() } else { $current -split ';' }",
263
+ ...(opts.action === "add"
264
+ ? [
265
+ "if ($entries -notcontains $dir) {",
266
+ " $new = if ([string]::IsNullOrEmpty($current)) { $dir } else { \"$current;$dir\" }",
267
+ " [Environment]::SetEnvironmentVariable('Path', $new, $target)",
268
+ "}",
269
+ ]
270
+ : [
271
+ "if ($entries -contains $dir) {",
272
+ " $new = ($entries | Where-Object { $_ -ne $dir }) -join ';'",
273
+ " [Environment]::SetEnvironmentVariable('Path', $new, $target)",
274
+ "}",
275
+ ]),
276
+ "$afterKey = Get-Item -Path $registryPath",
277
+ "$afterValue = Get-ItemPropertyValue -Path $registryPath -Name 'Path' -ErrorAction SilentlyContinue",
278
+ "if ($originalKind -eq [Microsoft.Win32.RegistryValueKind]::ExpandString -and $afterKey.GetValueKind('Path') -ne [Microsoft.Win32.RegistryValueKind]::ExpandString) {",
279
+ " Set-ItemProperty -Path $registryPath -Name 'Path' -Value $afterValue -Type ExpandString",
280
+ "}",
281
+ ].join("\n"),
282
+ };
283
+ }
284
+ function psSingleQuoted(value) {
285
+ return `'${value.replace(/'/g, "''")}'`;
286
+ }
112
287
  /**
113
288
  * Attach a resource identity to a fragment, turning it into a handle that can
114
289
  * be passed to another resource's `dependsOn`. The `__winixHandle` marker is
@@ -122,6 +297,10 @@ function asHandle(fragment, ref) {
122
297
  });
123
298
  return fragment;
124
299
  }
300
+ function dscHandle(resource) {
301
+ const fragment = { windows: { dsc: [resource] } };
302
+ return asHandle(fragment, { kind: "dsc", token: resource.token });
303
+ }
125
304
  export const windows = {
126
305
  package: (arg) => {
127
306
  const pkg = normalizePackage(arg);
@@ -133,4 +312,17 @@ export const windows = {
133
312
  const fragment = { windows: { commands: [command] } };
134
313
  return asHandle(fragment, { kind: "command", token: command.token });
135
314
  },
315
+ dsc: (arg) => {
316
+ const resource = normalizeDsc(arg);
317
+ const fragment = { windows: { dsc: [resource] } };
318
+ return asHandle(fragment, { kind: "dsc", token: resource.token });
319
+ },
320
+ env: {
321
+ set: (name, value, opts) => dscHandle(normalizeEnv(name, "Present", value, opts)),
322
+ remove: (name, opts) => dscHandle(normalizeEnv(name, "Absent", undefined, opts)),
323
+ },
324
+ path: {
325
+ add: (value, opts) => dscHandle(normalizePath(value, "Present", opts)),
326
+ remove: (value, opts) => dscHandle(normalizePath(value, "Absent", opts)),
327
+ },
136
328
  };
package/dist/index.d.ts CHANGED
@@ -9,4 +9,4 @@ 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 { AccountGroupFactory, AccountGroupMember, AccountGroupOpts, AccountNamespace, AccountOpts, AccountUserFactory, AccountUserRef, ActivationOpts, BinaryReleaseArch, BinaryReleaseCompletions, 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, WinPackageArg, WinPackageSpec, WinRawCommandArg, WinRawCommandSpec } from "./helpers/index.js";
12
+ export type { AccountGroupFactory, AccountGroupMember, AccountGroupOpts, AccountNamespace, AccountOpts, AccountUserFactory, AccountUserRef, ActivationOpts, BinaryReleaseArch, BinaryReleaseCompletions, 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, WinPackageArg, WinPackageSpec, WinPathNamespace, WinRawCommandArg, WinRawCommandSpec } from "./helpers/index.js";
@@ -60,6 +60,52 @@ export interface WinRawCommand {
60
60
  */
61
61
  dependsOn?: ResourceRef[];
62
62
  }
63
+ /**
64
+ * A generic DSC v3 resource, produced by `windows.dsc(...)` and by the typed
65
+ * helpers built on top of it (env/path). This is the escape hatch's IR: it
66
+ * carries an arbitrary DSC resource `type` and a free-form `properties` object
67
+ * that the emitter serializes verbatim as YAML.
68
+ *
69
+ * Typed helpers (env/path) construct native DSC resources internally:
70
+ * `Microsoft.Windows/Registry` for env and
71
+ * `Microsoft.DSC.Transitional/WindowsPowerShellScript` for PATH.
72
+ */
73
+ export interface WinDscResource {
74
+ /**
75
+ * Fully qualified DSC resource type, e.g. `Microsoft.Windows/Registry` or
76
+ * `Microsoft.Windows/Service`.
77
+ */
78
+ resourceType: string;
79
+ /**
80
+ * Optional friendly name. When omitted, the emitter generates one
81
+ * (`dsc N` in declaration order), sanitized to the DSC name charset.
82
+ */
83
+ name?: string;
84
+ /**
85
+ * Free-form DSC resource properties, serialized verbatim to YAML. May be a
86
+ * deeply nested object (e.g. the adapter's `resources:` array). Restricted to
87
+ * JSON-like values (string/number/boolean/null/array/object).
88
+ */
89
+ properties?: WinDscProperties;
90
+ /**
91
+ * Unique identity token so a handle returned by `windows.dsc(...)`,
92
+ * `windows.env.*(...)`, or `windows.path.*(...)` can be referenced in another
93
+ * resource's `dependsOn`. Non-enumerable in spirit; carried internally only.
94
+ */
95
+ token?: symbol;
96
+ /**
97
+ * Resources this resource must be applied after, as resolved references.
98
+ * Emitted as DSC v3 `dependsOn`. References must belong to the same host.
99
+ */
100
+ dependsOn?: ResourceRef[];
101
+ }
102
+ /** JSON-like value accepted in generic DSC `properties`. */
103
+ export type WinDscPropertyValue = string | number | boolean | null | WinDscPropertyValue[] | {
104
+ [key: string]: WinDscPropertyValue;
105
+ };
106
+ export type WinDscProperties = {
107
+ [key: string]: WinDscPropertyValue;
108
+ };
63
109
  /**
64
110
  * The `windows` scope of a Fragment. Deep-merged across all fragments for a
65
111
  * host, then handed to the Windows emitter.
@@ -75,6 +121,12 @@ export interface WindowsOptions extends Record<string, unknown> {
75
121
  packages?: Record<string, WinPackage>;
76
122
  /** Raw commands to run on apply, in declaration order. */
77
123
  commands?: WinRawCommand[];
124
+ /**
125
+ * Generic DSC resources (from `windows.dsc(...)` and the env/path helpers),
126
+ * in declaration order. Ordered because they have no natural key and order
127
+ * can carry meaning; `dependsOn` expresses hard ordering.
128
+ */
129
+ dsc?: WinDscResource[];
78
130
  /** Hostname for the target, set by the platform baseline. */
79
131
  hostname?: string;
80
132
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adrifer/winix",
3
- "version": "0.2.0-preview.3",
3
+ "version": "0.2.0-preview.4",
4
4
  "description": "TypeScript-first system configuration for NixOS, nix-darwin, and Home Manager",
5
5
  "license": "MIT",
6
6
  "author": "Adrian Fernandez",