@adrifer/winix 0.2.0-preview.0 → 0.2.0-preview.1

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.
@@ -0,0 +1,108 @@
1
+ // Winix authoring context: the object injected into feature/profile/host
2
+ // callbacks. It bundles the *body declaration* namespaces so configs can
3
+ // destructure them (`({ home, windows }) => ...`) instead of importing globals.
4
+ //
5
+ // Scope rule: the context holds only what you destructure *inside a callback
6
+ // body to declare the body of your unit*. That is the per-platform declaration
7
+ // namespaces plus `platforms` (for its query side, `platforms.darwin.isActive`).
8
+ //
9
+ // Deliberately NOT in the context (still imported as file-level globals):
10
+ // - `nix` : a pure NixExpr-building utility (the `lib` of Winix); never
11
+ // returns a Fragment, so it declares nothing on its own.
12
+ // - `account` : used top-level as a factory constructor
13
+ // (`const adri = account.user(...)`), never inside a body.
14
+ // - `overlay` : used as a direct value in profile arrays
15
+ // (`profile("linux", [overlay.stable(...)])`), not destructured.
16
+ //
17
+ // The namespaces themselves are the same singletons exported from the package;
18
+ // they already read the ambient EvalContext for their context-aware behavior
19
+ // (e.g. `platforms.darwin.isActive`). Injecting them is ergonomic sugar today
20
+ // and the seam where resource handles / effect registration hook in later.
21
+ import { darwin } from "../helpers/darwin.js";
22
+ import { home } from "../helpers/home.js";
23
+ import { nixos } from "../helpers/nixos.js";
24
+ import { platforms } from "../helpers/platforms.js";
25
+ import { windows } from "../helpers/windows.js";
26
+ import { collect, hasActiveCollector } from "./collector.js";
27
+ /**
28
+ * Heuristic: does a returned value look like a Fragment (a declaration to
29
+ * register), as opposed to a NixExpr, a boolean (`isActive`), a nested factory,
30
+ * a `HomeFile` builder result, etc.?
31
+ *
32
+ * A Fragment is a plain object carrying at least one known scope key
33
+ * (`nixos` / `homeManager` / `darwin` / `windows`). Requiring a scope key is
34
+ * what keeps non-fragment helper returns out of the effect collector: e.g.
35
+ * `home.symlink(...)` returns a `HomeFile` (`{ source, text, ... }`) with no
36
+ * scope key, so it is correctly left alone instead of being registered and
37
+ * polluting the merged fragment list.
38
+ */
39
+ const FRAGMENT_SCOPE_KEYS = ["nixos", "homeManager", "darwin", "windows"];
40
+ function looksLikeFragment(value) {
41
+ if (value === null || typeof value !== "object")
42
+ return false;
43
+ const v = value;
44
+ if (v.__winixNixExpr || v.__lazy || v.__winixRawModule || v.__platform)
45
+ return false;
46
+ // Must declare into at least one real scope to count as a collectible effect.
47
+ return FRAGMENT_SCOPE_KEYS.some((key) => v[key] !== undefined);
48
+ }
49
+ /**
50
+ * Wrap a namespace so that, while an effect collector is active, any Fragment a
51
+ * method returns is also registered as an effect. Non-fragment returns (booleans
52
+ * from `isActive`, NixExpr builders, nested factories) pass through untouched.
53
+ *
54
+ * Implemented with a single Proxy that handles both shapes uniformly:
55
+ * - `apply` trap: when the wrapped value is itself called (callable namespaces
56
+ * like `home(...)`, or factories), collect a Fragment result.
57
+ * - `get` trap: property access returns nested namespaces/functions wrapped too,
58
+ * so `platforms.darwin.isActive` (a getter on a PlatformFactory) and
59
+ * `platforms.darwin(...)` both keep working. Function properties are wrapped
60
+ * without losing their own properties (isActive/id), because we proxy the
61
+ * function instead of replacing it with a fresh arrow.
62
+ *
63
+ * Wrapping is transparent when no collector is active (returns values as-is).
64
+ */
65
+ function wrapForEffects(ns) {
66
+ return new Proxy(ns, {
67
+ apply(target, thisArg, args) {
68
+ const result = Reflect.apply(target, thisArg, args);
69
+ if (hasActiveCollector() && looksLikeFragment(result)) {
70
+ return collect(result);
71
+ }
72
+ return result;
73
+ },
74
+ get(target, prop, receiver) {
75
+ const value = Reflect.get(target, prop, receiver);
76
+ if (!hasActiveCollector())
77
+ return value;
78
+ if (typeof value === "function") {
79
+ // Wrap the function (preserving its own props like isActive/id) so that
80
+ // calling it collects, and reading e.g. `.isActive` still works.
81
+ return wrapForEffects(value);
82
+ }
83
+ if (value && typeof value === "object") {
84
+ // Nested namespace object (e.g. a sub-namespace); wrap lazily.
85
+ return wrapForEffects(value);
86
+ }
87
+ return value;
88
+ },
89
+ });
90
+ }
91
+ /**
92
+ * Build the context object passed to authoring callbacks.
93
+ *
94
+ * Returns references to the same namespace singletons the package exports, so
95
+ * `({ home }) => home.program(...)` and the global `home.program(...)` are
96
+ * interchangeable. Methods called through the context register their Fragment
97
+ * result as an effect when a collector is active (layer 2), while still
98
+ * returning it so the return forms keep working.
99
+ */
100
+ export function createWinixContext() {
101
+ return {
102
+ home: wrapForEffects(home),
103
+ nixos: wrapForEffects(nixos),
104
+ darwin: wrapForEffects(darwin),
105
+ windows: wrapForEffects(windows),
106
+ platforms: wrapForEffects(platforms),
107
+ };
108
+ }
@@ -1,3 +1,4 @@
1
+ import { type WinixContext } from "./context.js";
1
2
  import type { Fragment, FragmentFactory, PlatformFactory, ProfileFactory, PlatformLazyFragment, FragmentEntry, FragmentResult, InputDef, InputWithOptions, WorkspaceDef, HostDef, EvalContext, NixExpr } from "../core/types.js";
2
3
  export declare function setEvalContext(ctx: EvalContext): EvalContext | null;
3
4
  export declare function restoreEvalContext(ctx: EvalContext | null): void;
@@ -5,10 +6,11 @@ export declare function clearEvalContext(): void;
5
6
  export declare function getEvalContext(): EvalContext;
6
7
  export declare function getOptionalEvalContext(): EvalContext | null;
7
8
  export declare function platform<T extends unknown[]>(id: string, factory: (...args: T) => Fragment): PlatformFactory<T>;
8
- export declare function feature<T extends unknown[]>(id: string, factory: (...args: T) => FragmentResult): FragmentFactory<T>;
9
- export declare function profile<T extends unknown[]>(id: string, factory: (...args: T) => FragmentResult): ProfileFactory<T>;
9
+ export declare function feature<T extends unknown[]>(id: string, factory: (ctx: WinixContext, ...args: T) => FragmentResult): FragmentFactory<T>;
10
+ export declare function profile<T extends unknown[]>(id: string, factory: (ctx: WinixContext, ...args: T) => FragmentResult): ProfileFactory<T>;
10
11
  export declare function profile(id: string, entries: FragmentEntry | readonly FragmentEntry[]): ProfileFactory<[]>;
11
12
  export declare function host(name: string, platform: PlatformLazyFragment, fragments: readonly FragmentEntry[]): HostDef;
13
+ export declare function host(name: string, platform: PlatformLazyFragment, body: (ctx: WinixContext) => FragmentResult): HostDef;
12
14
  export declare function workspace(def: WorkspaceDef): WorkspaceDef;
13
15
  export declare function input(url: string, opts?: Omit<InputWithOptions, "url">): InputWithOptions;
14
16
  export declare function defineInputs<T extends Record<string, InputDef>>(inputs: T): T;
package/dist/sdk/index.js CHANGED
@@ -1,5 +1,7 @@
1
1
  // SDK: helpers exposed to user configs (platform, feature, host, workspace, etc.)
2
2
  import { posix as pathPosix } from "node:path";
3
+ import { createWinixContext } from "./context.js";
4
+ import { withCollector, wasCollected } from "./collector.js";
3
5
  // --- Evaluation context (implicit, set by evaluator) ---
4
6
  const G = globalThis;
5
7
  export function setEvalContext(ctx) {
@@ -55,7 +57,12 @@ export function feature(id, factory) {
55
57
  __lazy: true,
56
58
  __id: id,
57
59
  __resolve: () => {
58
- const result = factory(...args);
60
+ const ctx = createWinixContext();
61
+ let returned;
62
+ const effects = withCollector(() => {
63
+ returned = factory(ctx, ...args);
64
+ });
65
+ const result = mergeEffectsAndReturn(effects, returned);
59
66
  return annotateResult(result, id);
60
67
  },
61
68
  };
@@ -71,12 +78,31 @@ export function feature(id, factory) {
71
78
  export function profile(id, entriesOrFactory) {
72
79
  const factory = typeof entriesOrFactory === "function"
73
80
  ? entriesOrFactory
74
- : (() => entriesOrFactory);
81
+ : ((_ctx, ..._args) => entriesOrFactory);
75
82
  return feature(id, factory);
76
83
  }
77
- // --- host() ---
78
- export function host(name, platform, fragments) {
79
- return { name, platform, fragments };
84
+ export function host(name, platform, fragmentsOrBody) {
85
+ if (typeof fragmentsOrBody === "function") {
86
+ // Callback form: wrap the body in an anonymous feature-like lazy fragment so
87
+ // it resolves under the host's eval context (and, in later layers, its
88
+ // handle collector). The body declares via the injected context and/or
89
+ // returns fragments.
90
+ const body = fragmentsOrBody;
91
+ const lazy = {
92
+ __lazy: true,
93
+ __id: `${name}:inline`,
94
+ __resolve: () => {
95
+ const ctx = createWinixContext();
96
+ let returned;
97
+ const effects = withCollector(() => {
98
+ returned = body(ctx);
99
+ });
100
+ return mergeEffectsAndReturn(effects, returned);
101
+ },
102
+ };
103
+ return { name, platform, fragments: [lazy] };
104
+ }
105
+ return { name, platform, fragments: fragmentsOrBody };
80
106
  }
81
107
  // --- workspace() ---
82
108
  export function workspace(def) {
@@ -106,6 +132,51 @@ export function escape(expr) {
106
132
  expr,
107
133
  };
108
134
  }
135
+ /**
136
+ * Combine fragments declared by effect with whatever the body returned.
137
+ *
138
+ * - Effect-only body (no return / returns undefined): just the effects.
139
+ * - Return-only body (legacy, no effects collected): just the return value,
140
+ * so existing `() => home.program(...)` features behave exactly as before.
141
+ * - Mixed: effects first (declaration order), then any returned entries that
142
+ * were NOT already captured as effects (dedupe via wasCollected), so
143
+ * `return home.program(...)` does not double-count.
144
+ */
145
+ function mergeEffectsAndReturn(effects, returned) {
146
+ const hasReturn = returned !== undefined && returned !== null;
147
+ if (effects.length === 0) {
148
+ // Legacy path: nothing registered by effect, pass the return through as-is.
149
+ return hasReturn ? returned : [];
150
+ }
151
+ if (!hasReturn) {
152
+ return effects;
153
+ }
154
+ const extraFromReturn = filterUncollected(returned);
155
+ return [...effects, ...extraFromReturn];
156
+ }
157
+ /**
158
+ * Flatten a FragmentResult into entries that were not already collected by
159
+ * effect. Preserves lazy entries (they resolve later) and arrays.
160
+ */
161
+ function filterUncollected(result) {
162
+ const entries = Array.isArray(result) ? result : [result];
163
+ const out = [];
164
+ for (const entry of entries) {
165
+ if (Array.isArray(entry)) {
166
+ out.push(...filterUncollected(entry));
167
+ continue;
168
+ }
169
+ if (isLazy(entry)) {
170
+ // Lazy entries resolve on their own later; never collected here.
171
+ out.push(entry);
172
+ continue;
173
+ }
174
+ if (!wasCollected(entry)) {
175
+ out.push(entry);
176
+ }
177
+ }
178
+ return out;
179
+ }
109
180
  function annotateResult(result, id) {
110
181
  if (Array.isArray(result)) {
111
182
  return result.map((entry) => annotateEntry(entry, id));
@@ -1,3 +1,4 @@
1
+ import type { ResourceRef } from "../core/types.js";
1
2
  /**
2
3
  * A winget package source. MVP supports the two first-party catalogues.
3
4
  * Additional sources (chocolatey, scoop) can plug in later without changing
@@ -29,6 +30,35 @@ export interface WinPackage {
29
30
  * `winget configure` is run from a non-elevated shell.
30
31
  */
31
32
  elevated?: boolean;
33
+ /**
34
+ * Resources this package must be applied after, as resolved resource
35
+ * references (from handles passed to `dependsOn`). Emitted as DSC v3
36
+ * `dependsOn` entries. References must belong to the same host.
37
+ */
38
+ dependsOn?: ResourceRef[];
39
+ }
40
+ /**
41
+ * A raw Windows command to run through DSC v3's transitional command resource.
42
+ */
43
+ export interface WinRawCommand {
44
+ /** Optional stable resource name. When omitted, the emitter generates one. */
45
+ name?: string;
46
+ /** Executable to invoke, e.g. "powershell", "pwsh", or "cmd". */
47
+ executable: string;
48
+ /** Arguments passed to the executable, in order. */
49
+ arguments?: string[];
50
+ /**
51
+ * Unique identity token for this command, so a handle returned by
52
+ * `windows.raw(...)` can be referenced in another resource's `dependsOn`.
53
+ * Survives fragment merging (commands are concatenated by reference, never
54
+ * cloned). Non-enumerable in spirit; carried internally only.
55
+ */
56
+ token?: symbol;
57
+ /**
58
+ * Resources this command must run after, as resolved resource references.
59
+ * Emitted as DSC v3 `dependsOn`. References must belong to the same host.
60
+ */
61
+ dependsOn?: ResourceRef[];
32
62
  }
33
63
  /**
34
64
  * The `windows` scope of a Fragment. Deep-merged across all fragments for a
@@ -36,10 +66,15 @@ export interface WinPackage {
36
66
  *
37
67
  * `packages` is keyed by package id so that merging is idempotent and a later
38
68
  * fragment pinning a version overrides an earlier float for the same id.
69
+ *
70
+ * `commands` is an ordered list because raw commands can repeat and declaration
71
+ * order controls apply order.
39
72
  */
40
73
  export interface WindowsOptions extends Record<string, unknown> {
41
74
  /** Declared packages, keyed by package id. */
42
75
  packages?: Record<string, WinPackage>;
76
+ /** Raw commands to run on apply, in declaration order. */
77
+ commands?: WinRawCommand[];
43
78
  /** Hostname for the target, set by the platform baseline. */
44
79
  hostname?: string;
45
80
  }
@@ -1,6 +1,6 @@
1
1
  // Windows backend types: the IR carried by fragments under the `windows` key.
2
2
  //
3
- // These are intentionally minimal for the MVP vertical slice (packages only).
3
+ // These are intentionally minimal for the MVP vertical slice.
4
4
  // They will grow to cover env/path/file/raw/dsc/wsl/programs as the backend
5
5
  // matures. The shape here is the *internal* representation produced by the
6
6
  // `windows.*` helpers and consumed by the Windows emitter, not the public
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adrifer/winix",
3
- "version": "0.2.0-preview.0",
3
+ "version": "0.2.0-preview.1",
4
4
  "description": "TypeScript-first system configuration for NixOS, nix-darwin, and Home Manager",
5
5
  "license": "MIT",
6
6
  "author": "Adrian Fernandez",