From 44eac1be6c6dd028bede212ea2d310ebbf33cda9 Mon Sep 17 00:00:00 2001 From: "Joe Skeen, Jr." Date: Mon, 23 Nov 2026 18:44:55 -0700 Subject: [PATCH 1/2] Add @generatePwshEnv PowerShell code generator Generates a .ps1 file that compiles the C# output from @generateCsharpEnv with Add-Type and returns the typed object from Get-Env. The C# class decrypts and validates the env blob, so the PowerShell side only wraps it. --- .bumpy/pwsh-codegen.md | 5 + .../content/docs/guides/code-generation.mdx | 1 + .../docs/integrations/other-languages.mdx | 3 +- .../content/docs/integrations/powershell.mdx | 64 ++++++ .../docs/reference/cli/cache-and-codegen.mdx | 2 +- .../docs/reference/root-decorators.mdx | 12 ++ packages/varlock-website/src/sidebar.ts | 1 + packages/varlock/src/env-graph/index.ts | 1 + .../lib/type-generation/code-generators.ts | 8 + .../lib/type-generation/emitters/pwsh.ts | 184 ++++++++++++++++++ .../env-graph/lib/type-generation/index.ts | 1 + .../test/type-generation/pwsh.test.ts | 92 +++++++++ 12 files changed, 372 insertions(+), 2 deletions(-) create mode 100644 .bumpy/pwsh-codegen.md create mode 100644 packages/varlock-website/src/content/docs/integrations/powershell.mdx create mode 100644 packages/varlock/src/env-graph/lib/type-generation/emitters/pwsh.ts create mode 100644 packages/varlock/src/env-graph/test/type-generation/pwsh.test.ts diff --git a/.bumpy/pwsh-codegen.md b/.bumpy/pwsh-codegen.md new file mode 100644 index 000000000..97db21157 --- /dev/null +++ b/.bumpy/pwsh-codegen.md @@ -0,0 +1,5 @@ +--- +varlock: minor +--- + +Added @generatePwshEnv to generate a typed PowerShell module that loads the injected env blob. diff --git a/packages/varlock-website/src/content/docs/guides/code-generation.mdx b/packages/varlock-website/src/content/docs/guides/code-generation.mdx index ee1fe6ba1..8bfd8ad91 100644 --- a/packages/varlock-website/src/content/docs/guides/code-generation.mdx +++ b/packages/varlock-website/src/content/docs/guides/code-generation.mdx @@ -60,6 +60,7 @@ Varlock ships generators for several languages. Each emits a **self-contained, i | PHP | `@generatePhpEnv` | `Env::load()` | [PHP](/integrations/php/) | | Java | `@generateJavaEnv` | `Env.load()` | [Java](/integrations/java/) | | C# | `@generateCsharpEnv` | `Env.Load()` | [C#](/integrations/csharp/) | +| PowerShell | `@generatePwshEnv` | `Get-Env` | [PowerShell](/integrations/powershell/) | For a language without a generated module, see [Other languages](/integrations/other-languages/). diff --git a/packages/varlock-website/src/content/docs/integrations/other-languages.mdx b/packages/varlock-website/src/content/docs/integrations/other-languages.mdx index a3a2ad5bc..cb40a219c 100644 --- a/packages/varlock-website/src/content/docs/integrations/other-languages.mdx +++ b/packages/varlock-website/src/content/docs/integrations/other-languages.mdx @@ -27,8 +27,9 @@ It exposes only these primitives (no global singleton or imposed caching), so it | PHP | `@generatePhpEnv` | [PHP](/integrations/php/) | | Java | `@generateJavaEnv` | [Java](/integrations/java/) | | C# | `@generateCsharpEnv` | [C#](/integrations/csharp/) | +| PowerShell | `@generatePwshEnv` | [PowerShell](/integrations/powershell/) | -Files are generated automatically on [`varlock load`](/reference/cli/load-and-run/#load) and [`varlock run`](/reference/cli/load-and-run/#run), or explicitly via [`varlock codegen`](/reference/cli/cache-and-codegen/#codegen). The loaders read `__VARLOCK_ENV`, so run your program under [`varlock run`](/reference/cli/load-and-run/#run), which always injects a **plaintext** blob. The generated loaders don't decrypt, so they don't support [`@encryptInjectedEnv`](/reference/root-decorators/#encryptinjectedenv) (a JS/SSR build-output feature); if a loader is handed an encrypted blob it fails with a clear message rather than a raw parse error. +Files are generated automatically on [`varlock load`](/reference/cli/load-and-run/#load) and [`varlock run`](/reference/cli/load-and-run/#run), or explicitly via [`varlock codegen`](/reference/cli/cache-and-codegen/#codegen). The loaders read `__VARLOCK_ENV`, so run your program under [`varlock run`](/reference/cli/load-and-run/#run), which always injects a **plaintext** blob. The generated loaders for Python, Rust, Go, PHP, and Java don't decrypt, so they don't support [`@encryptInjectedEnv`](/reference/root-decorators/#encryptinjectedenv) (a JS/SSR build-output feature); if one of those loaders is handed an encrypted blob it fails with a clear message rather than a raw parse error. The C# and PowerShell loaders decrypt the blob with `_VARLOCK_ENV_KEY`, so they work with encrypted blobs. Note that `varlock run --inject vars` strips the `__VARLOCK_ENV` blob from the child process, so the generated loaders can't work under it. Use the default injection mode (or `--inject blob`) when your program loads a generated module. diff --git a/packages/varlock-website/src/content/docs/integrations/powershell.mdx b/packages/varlock-website/src/content/docs/integrations/powershell.mdx new file mode 100644 index 000000000..c47fd5ba2 --- /dev/null +++ b/packages/varlock-website/src/content/docs/integrations/powershell.mdx @@ -0,0 +1,64 @@ +--- +title: PowerShell +description: Use varlock with PowerShell via a generated, typed loader function +--- + +To use varlock with PowerShell, [install the standalone binary](/getting-started/installation/#as-a-standalone-binary) and run your script under [`varlock run`](/reference/cli/load-and-run/#run). It loads and validates your env, then injects it into the process. + +Add [`@generatePwshEnv`](/reference/root-decorators/#generatepwshenv) to your schema to generate a self-contained `.ps1` file: a loader function that parses the injected [`__VARLOCK_ENV`](/reference/reserved-variables/#__varlock_env) blob and returns a typed object, plus a function that lists the sensitive keys. The object is an instance of a small C# class that the file compiles with `Add-Type`. + +```env-spec title=".env.schema" +# @generatePwshEnv(path=./Env.ps1) +``` + +The file is regenerated automatically on [`varlock load`](/reference/cli/load-and-run/#load) and [`varlock run`](/reference/cli/load-and-run/#run), or explicitly with [`varlock codegen`](/reference/cli/cache-and-codegen/#codegen). Requires **PowerShell 7.2+** (the loader uses `System.Security.Cryptography.AesGcm` and the C# compiler that ships with PowerShell 7). Optional `functionName=` sets the loader function name (default: `Get-Env`). It must be a Verb-Noun name, such as `Get-AppEnv`. Property names are PascalCase (`DB_HOST` becomes `DbHost`). + +## Reading values + +Dot-source the generated file, then call the loader function. The file uses `$PSScriptRoot` in your script to find it, so the path works from any directory: + +```powershell title="run.ps1" +. "$PSScriptRoot/Env.ps1" + +$e = Get-Env +Write-Output "$($e.DbHost):$($e.DbPort)" +``` + +```bash +varlock run -- pwsh ./run.ps1 +``` + +Each property holds the value with the type the schema declares: integers, decimals, and booleans are converted, and optional values that are unset come back as `$null`. Objects, arrays, and records come back as `JsonElement`, so read them with its methods (for example `(Get-Env).Cfg.GetProperty('a').GetInt64()`). The object is a snapshot taken when you call `Get-Env`, so call it again to read values after the environment changes. The first load in a session compiles the class, which takes a moment (about half a second in testing). Later loads of the same schema reuse it. To read a single value, select its property: + +```powershell +$dbHost = (Get-Env).DbHost +Get-Env | Select-Object DbPort +``` + +`Get-Env` takes no parameters. Read a value from the object's property, or pipe the object to `Select-Object`. + +The loader throws a clear error if `__VARLOCK_ENV` is missing (for example, if you forgot `varlock run`) or if a required key is absent. + +:::note[Editor completion] +In the VS Code editor, completion for the generated functions (for example `Get-Env` and its properties) may not appear in a script until the file is dot-sourced in the integrated terminal. The editor doesn't pick up functions from a dot-source that uses `$PSScriptRoot`, which keeps the path portable. Once the file is loaded in the terminal, completion works. This was observed with PowerShell extension 2025.4.0. +::: + +## Sensitive keys + +The generated file also defines `SensitiveKeys`, which returns the names of the sensitive items. Use it to build your own redaction or leak-scanning: + +```powershell +Get-EnvSensitiveKeys +``` + +:::note +Every key is also injected as a plain environment variable, so you can read any of them with `$env:NAME` (raw strings) if you don't need the typed loader. Keys whose names aren't valid identifiers (they contain `.` or `-`) can't be properties, so read those from the env var directly. See [Other languages](/integrations/other-languages/) for the shared details on the injected blob, raw env vars, and encryption. +::: + +## Help + +`Get-Help Get-Env` lists each property with its type and schema description. `-Examples` shows usage examples, and `-Full` adds the output type and the notes. + +## Encrypted blobs + +If [`@encryptInjectedEnv`](/reference/root-decorators/#encryptinjectedenv) is set, use `varlock run --inject blob` so the encrypted blob reaches your script. The loader decrypts it with the key in `_VARLOCK_ENV_KEY`, which `varlock run` provides in that mode. diff --git a/packages/varlock-website/src/content/docs/reference/cli/cache-and-codegen.mdx b/packages/varlock-website/src/content/docs/reference/cli/cache-and-codegen.mdx index d042d4833..35a53094b 100644 --- a/packages/varlock-website/src/content/docs/reference/cli/cache-and-codegen.mdx +++ b/packages/varlock-website/src/content/docs/reference/cli/cache-and-codegen.mdx @@ -57,7 +57,7 @@ See the [Caching guide](/guides/caching/) for cache mode strategy and troublesho Runs the [code-generation decorators](/reference/root-decorators/#code-generation) in your schema: typed env accessors like `@generateTsTypes` (type declarations) and `@generatePythonEnv` (a loadable module), plus any generators contributed by plugins. Uses only your schema definitions, so output is deterministic regardless of which environment is active. (One exception: `@generateTsTypes` fetches custom `@icon` values over the network; set [`icons=false`](/reference/root-decorators/#generatetstypes) if the output must not depend on network access.) Keys (and decorators) that come only from value files like `.env` or `.env.local` are ignored. Only items declared in your `.env.schema` (or imported into it) are included. When run directly, the command reports any keys found only in a plain `.env` so you can move them into your schema if they belong there. -Add a per-language decorator for each output file you want: `@generateTsTypes`, `@generatePythonEnv`, `@generateRustEnv`, `@generateGoEnv`, `@generatePhpEnv`, `@generateJavaEnv`, or `@generateCsharpEnv`. Each generates its own file. Each decorator can also take a `filter=` arg to scope its output to a subset of items, using the same selectors as the [`--filter` CLI flag](/reference/cli-commands/#filtering-items); see the [code generation reference](/reference/root-decorators/#code-generation). +Add a per-language decorator for each output file you want: `@generateTsTypes`, `@generatePythonEnv`, `@generateRustEnv`, `@generateGoEnv`, `@generatePhpEnv`, `@generateJavaEnv`, `@generateCsharpEnv`, or `@generatePwshEnv`. Each generates its own file. Each decorator can also take a `filter=` arg to scope its output to a subset of items, using the same selectors as the [`--filter` CLI flag](/reference/cli-commands/#filtering-items); see the [code generation reference](/reference/root-decorators/#code-generation). This command is particularly useful when you have set `auto=false` on a generator decorator to disable automatic generation during `varlock load` or `varlock run`. diff --git a/packages/varlock-website/src/content/docs/reference/root-decorators.mdx b/packages/varlock-website/src/content/docs/reference/root-decorators.mdx index 43916db42..fde99b8bb 100644 --- a/packages/varlock-website/src/content/docs/reference/root-decorators.mdx +++ b/packages/varlock-website/src/content/docs/reference/root-decorators.mdx @@ -826,6 +826,18 @@ A self-contained C# class: a typed `Env` with a static `Load()` and a `Sensitive Optional `namespace=` and `class=` (default: no namespace, class `Env`). +
+### `@generatePwshEnv()` + +A self-contained PowerShell file: a loader function (default `Get-Env`) that returns a typed object (an instance of a C# class compiled with `Add-Type`), plus a `SensitiveKeys` function. Requires PowerShell 7.2+. See [PowerShell usage](/integrations/powershell/). + +```env-spec +# @generatePwshEnv(path=./Env.ps1) +``` + +Optional `functionName=` (default: `Get-Env`). Must be a Verb-Noun name, such as `Get-AppEnv`. +
+
### `@generateTypes()` (deprecated) diff --git a/packages/varlock-website/src/sidebar.ts b/packages/varlock-website/src/sidebar.ts index 05ea3a578..2b4ec6bd8 100644 --- a/packages/varlock-website/src/sidebar.ts +++ b/packages/varlock-website/src/sidebar.ts @@ -178,6 +178,7 @@ export const sidebar: StarlightUserConfig['sidebar'] = [ { label: 'PHP', slug: 'integrations/php' }, { label: 'Java', slug: 'integrations/java' }, { label: 'C#', slug: 'integrations/csharp' }, + { label: 'PowerShell', slug: 'integrations/powershell' }, { label: 'Other languages', slug: 'integrations/other-languages' }, ], }, diff --git a/packages/varlock/src/env-graph/index.ts b/packages/varlock/src/env-graph/index.ts index 637f1f3c7..47a8b01d9 100644 --- a/packages/varlock/src/env-graph/index.ts +++ b/packages/varlock/src/env-graph/index.ts @@ -22,6 +22,7 @@ export { generateGoEnvSrc, generateJavaEnvSrc, generatePhpEnvSrc, + generatePwshEnvSrc, generatePythonEnvSrc, generateRustEnvSrc, generateTsTypesSrc, diff --git a/packages/varlock/src/env-graph/lib/type-generation/code-generators.ts b/packages/varlock/src/env-graph/lib/type-generation/code-generators.ts index 1478a61ec..df4925036 100644 --- a/packages/varlock/src/env-graph/lib/type-generation/code-generators.ts +++ b/packages/varlock/src/env-graph/lib/type-generation/code-generators.ts @@ -6,6 +6,7 @@ import { generateCsharpEnvSrc } from './emitters/csharp'; import { generateGoEnvSrc, resolveGoPackageName } from './emitters/go'; import { generateJavaEnvSrc } from './emitters/java'; import { generatePhpEnvSrc } from './emitters/php'; +import { generatePwshEnvSrc } from './emitters/pwsh'; import { generatePythonEnvSrc } from './emitters/python'; import { generateRustEnvSrc } from './emitters/rust'; import { generateTsTypesSrc } from './emitters/ts'; @@ -151,6 +152,13 @@ export const builtInCodeGenerators: Array = [ className: ctx.options.class, }), }, + { + decoratorName: 'generatePwshEnv', + knownOptions: ['functionName'], + generate: (ctx) => generatePwshEnvSrc(ctx.fields, { + functionName: ctx.options.functionName, + }), + }, { // deprecated ts-only alias — kept for back-compat with existing schemas that still use it. // no knownOptions: it historically ignored unknown args, so stay lenient diff --git a/packages/varlock/src/env-graph/lib/type-generation/emitters/pwsh.ts b/packages/varlock/src/env-graph/lib/type-generation/emitters/pwsh.ts new file mode 100644 index 000000000..1fab0d457 --- /dev/null +++ b/packages/varlock/src/env-graph/lib/type-generation/emitters/pwsh.ts @@ -0,0 +1,184 @@ +import { createHash } from 'node:crypto'; + +import { getAutogeneratedBanner } from '../banners'; +import { + getFieldDocLines, + getSensitiveKeys, + type ResolvedFieldType, +} from '../shared'; +import { generateCsharpEnvSrc, snakeToPascalCase } from './csharp'; + +/** `Verb-Noun` function name, e.g. `Get-AppEnv` */ +const PWSH_FUNCTION_NAME = /^[A-Za-z][A-Za-z0-9]*-[A-Za-z][A-Za-z0-9]*$/; + +const PWSH_DOCS_URL = 'https://varlock.dev/integrations/powershell/'; + +/** Single-quoted PowerShell literal. Doubles the quote characters PowerShell accepts as quotes. */ +function pwshStringLiteral(text: string): string { + return `'${text.replace(/['\u2018\u2019\u201A\u201B]/g, (ch) => ch + ch)}'`; +} + +/** + * The PowerShell name for a generated C# property type. Read from the generated source, so the help + * can't disagree with the class. `string?` and `object?` are shown without the `?`, as the reference + * types they are. + */ +function psTypeName(csharpType: string): string { + const nullable = csharpType.endsWith('?'); + const base = nullable ? csharpType.slice(0, -1) : csharpType; + if (base === 'string' || base === 'object') return base; + const names: Record = { + long: 'long', double: 'double', bool: 'bool', JsonElement: 'JsonElement', + }; + const name = names[base] ?? base; + return nullable ? `${name}?` : name; +} + +/** Each property's C# type, keyed by property name, read from the `{ get; init; }` declarations. */ +function csharpPropertyTypes(csharpSrc: string): Map { + const types = new Map(); + for (const match of csharpSrc.matchAll(/^\s*public (?:required )?(\S+) ([A-Za-z_][A-Za-z0-9_]*) \{ get; init; \}\s*$/gm)) { + types.set(match[2], match[1]); + } + return types; +} + + +/** + * Comment-based help for the generated function, with a section per help tier: + * SYNOPSIS and DESCRIPTION (default), EXAMPLE (-Examples), and INPUTS, OUTPUTS, NOTES, and LINK (-Full). + * `#>` in generated text is neutralized so it can't end the comment block early. + */ +function helpLines( + functionName: string, + typeFullName: string, + properties: Array<{ field: ResolvedFieldType, prop: string, type: string }>, +): Array { + const safeLine = (line: string) => line.replace(/#>/g, '# >'); + const nameWidth = Math.max(0, ...properties.map(({ prop }) => prop.length)); + const typeWidth = Math.max(0, ...properties.map(({ type }) => type.length)); + const propertyLines = properties.map(({ field, prop, type }) => { + const docs = getFieldDocLines(field).join(' '); + const sensitive = field.isSensitive ? ' (sensitive)' : ''; + return safeLine(` ${prop.padEnd(nameWidth)} ${type.padEnd(typeWidth)} ${docs}${sensitive}`.trimEnd()); + }); + const [first, second] = properties; + + const examples: Array = [ + '.EXAMPLE', + `${functionName}`, + '', + 'Returns the whole object, with one property per schema item.', + '', + ]; + if (first) { + examples.push( + '.EXAMPLE', + `(${functionName}).${first.prop}`, + '', + 'Reads a single value. The result has the type shown under Properties.', + '', + ); + } + if (first && second) { + examples.push( + '.EXAMPLE', + `${functionName} | Select-Object ${first.prop}, ${second.prop}`, + '', + 'Selects several values from the object.', + '', + ); + } + examples.push( + '.EXAMPLE', + `try { ${functionName} } catch { Write-Error $_.Exception.Message }`, + '', + 'Handles a missing __VARLOCK_ENV or a missing required key without stopping the script.', + '', + ); + + return [ + '<#', + '.SYNOPSIS', + 'Load the varlock __VARLOCK_ENV blob into a typed object.', + '', + '.DESCRIPTION', + 'Reads the __VARLOCK_ENV environment variable set by `varlock run`, decrypts it if it is a varlock:v1 blob using _VARLOCK_ENV_KEY, and returns the typed object for this project.', + '', + 'The object is a snapshot of the values at load time. Each property holds the value with the type shown below, and an optional item that is unset is $null. Composite values are JsonElement. Read a value from its property, or pipe the object to Select-Object. Call the command again to read values after the environment changes.', + '', + 'If __VARLOCK_ENV is missing (the script wasn\'t started with varlock run), or a required key is absent, the command throws.', + '', + ...(properties.length ? ['Properties:', ...propertyLines, ''] : []), + ...examples, + '.INPUTS', + 'None. This command takes no pipeline input.', + '', + '.OUTPUTS', + typeFullName, + 'An object with one property for each schema item (see Properties).', + '', + '.NOTES', + 'Requires PowerShell 7.2+. The typed class is compiled with Add-Type the first time the file is loaded in a session.', + 'This file is generated by varlock. Regenerate it with varlock codegen instead of editing it by hand.', + '', + '.LINK', + PWSH_DOCS_URL, + '#>', + ].map((line, i, all) => (i === 0 || i === all.length - 1 ? line : safeLine(line))); +} + +export function generatePwshEnvSrc( + fields: Array, + opts?: { functionName?: unknown }, +): string { + const functionName = opts?.functionName === undefined ? 'Get-Env' : String(opts.functionName); + if (!PWSH_FUNCTION_NAME.test(functionName)) { + throw new Error(`@generatePwshEnv - \`function\` must be a Verb-Noun PowerShell function name (got ${JSON.stringify(opts?.functionName)})`); + } + + // the namespace hashes the generated C#, so a changed schema compiles to a new type + const probe = generateCsharpEnvSrc(fields, { namespace: 'Varlock.Pwsh', className: 'Env' }); + const typeId = createHash('sha256').update(probe).digest('hex').slice(0, 12); + const namespace = `Varlock.Pwsh_${typeId}`; + const fullName = `${namespace}.Env`; + const csharpSrc = generateCsharpEnvSrc(fields, { namespace, className: 'Env' }); + + // the properties are the ones the C# class declares, so the help matches the object + const csharpTypes = csharpPropertyTypes(csharpSrc); + const properties = fields + .map((field) => ({ field, prop: snakeToPascalCase(field.key) })) + .filter(({ prop }) => csharpTypes.has(prop)) + .map(({ field, prop }) => ({ field, prop, type: psTypeName(csharpTypes.get(prop) ?? 'object') })); + const sensitiveList = getSensitiveKeys(fields).map(pwshStringLiteral).join(', '); + + const src = [ + getAutogeneratedBanner('#'), + '# Requires PowerShell 7.2+ (the C# source uses System.Text.Json and AesGcm, compiled with Add-Type).', + '', + `if (-not (${pwshStringLiteral(fullName)} -as [type])) {`, + // `#nullable enable` is needed for the `string?` members, and the define selects the + // AesGcm constructor that takes a tag size (the other one is obsolete on .NET 8) + ' Add-Type -CompilerOptions \'/define:NET8_0_OR_GREATER\' -TypeDefinition @\'', + '#nullable enable', + ...csharpSrc.split('\n'), + '\'@', + '}', + '', + `function ${functionName}SensitiveKeys {`, + ` @(${sensitiveList})`, + '}', + '', + ...helpLines(functionName, fullName, properties), + `function ${functionName} {`, + ' [CmdletBinding()]', + ` [OutputType(${pwshStringLiteral(fullName)})]`, + ' param()', + '', + ` [${fullName}]::Load()`, + '}', + '', + ]; + + return src.join('\n'); +} diff --git a/packages/varlock/src/env-graph/lib/type-generation/index.ts b/packages/varlock/src/env-graph/lib/type-generation/index.ts index b0b034830..baa2bcb60 100644 --- a/packages/varlock/src/env-graph/lib/type-generation/index.ts +++ b/packages/varlock/src/env-graph/lib/type-generation/index.ts @@ -5,6 +5,7 @@ export { generateGoEnvSrc } from './emitters/go'; export { generatePhpEnvSrc } from './emitters/php'; export { generateJavaEnvSrc } from './emitters/java'; export { generateCsharpEnvSrc } from './emitters/csharp'; +export { generatePwshEnvSrc } from './emitters/pwsh'; export { resolveFieldType, resolveFieldTypes, diff --git a/packages/varlock/src/env-graph/test/type-generation/pwsh.test.ts b/packages/varlock/src/env-graph/test/type-generation/pwsh.test.ts new file mode 100644 index 000000000..6ab742fa7 --- /dev/null +++ b/packages/varlock/src/env-graph/test/type-generation/pwsh.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, test } from 'vitest'; +import outdent from 'outdent'; + +import { builtInCodeGenerators, generatePwshEnvSrc } from '../../index'; +import { loadFixtureFields } from './helpers'; + +const typeId = (src: string) => /Varlock\.Pwsh_([0-9a-f]{12})\.Env/.exec(src)?.[1]; + +describe('generatePwshEnvSrc', () => { + test('wraps the generated C# class in Add-Type and adds a parameterless Get-Env', async () => { + const { fields } = await loadFixtureFields(outdent` + # @defaultSensitive=false + # --- + DB_HOST=localhost # @required @public + DB_PORT=5432 # @optional @public + API_KEY=secret # @required @sensitive + `); + const src = generatePwshEnvSrc(fields); + + expect(src).toMatch(/if \(-not \('Varlock\.Pwsh_[0-9a-f]{12}\.Env' -as \[type\]\)\) \{/); + expect(src).toContain('Add-Type -CompilerOptions \'/define:NET8_0_OR_GREATER\' -TypeDefinition @\''); + expect(src).toContain('#nullable enable'); + expect(src).toMatch(/namespace Varlock\.Pwsh_[0-9a-f]{12};/); + expect(src).toContain('function Get-EnvSensitiveKeys {'); + expect(src).toContain('@(\'API_KEY\')'); + expect(src).not.toContain('::SensitiveKeys'); + expect(src).toContain('function Get-Env {'); + expect(src).toContain('[CmdletBinding()]'); + expect(src).toMatch(/\[OutputType\('Varlock\.Pwsh_[0-9a-f]{12}\.Env'\)\]/); + expect(src).toContain(' param()'); + expect(src).toContain('::Load()'); + expect(src).not.toContain('[switch]'); + expect(src).not.toContain('ParameterSetName'); + }); + + test('functionName= sets the function name', async () => { + const { fields } = await loadFixtureFields(outdent` + # @defaultSensitive=false + # --- + DB_HOST=localhost # @required @public + `); + const src = generatePwshEnvSrc(fields, { functionName: 'Get-AppEnv' }); + expect(src).toContain('function Get-AppEnv {'); + expect(src).toContain('function Get-AppEnvSensitiveKeys {'); + expect(src).not.toContain('Get-Env {'); + }); + + test('the namespace only depends on the generated C#, so a changed schema gets a new type', async () => { + const { fields: a } = await loadFixtureFields(outdent` + # --- + DB_HOST=localhost # @required @public + `); + const { fields: b } = await loadFixtureFields(outdent` + # --- + DB_HOST=localhost # @required @public + DB_PORT=5432 # @optional @public + `); + expect(typeId(generatePwshEnvSrc(a))).toBeDefined(); + expect(typeId(generatePwshEnvSrc(a))).not.toBe(typeId(generatePwshEnvSrc(b))); + expect(typeId(generatePwshEnvSrc(a, { functionName: 'Get-Other' }))).toBe(typeId(generatePwshEnvSrc(a))); + }); + + test('rejects a function name that is not Verb-Noun', async () => { + const { fields } = await loadFixtureFields(); + expect(() => generatePwshEnvSrc(fields, { functionName: 'GetEnv' })).toThrow(/function/); + expect(() => generatePwshEnvSrc(fields, { functionName: 'Get-App Env' })).toThrow(/function/); + expect(() => generatePwshEnvSrc(fields, { functionName: 'Get-$(calc)' })).toThrow(/function/); + }); + + test('help lists each property with its type and description', async () => { + const { fields } = await loadFixtureFields(outdent` + # @defaultSensitive=false + # --- + DB_HOST=localhost # @required @public @sensitive + # @type=port + DB_PORT=5432 # @optional @public + `); + const src = generatePwshEnvSrc(fields); + expect(src).toContain('Properties:'); + expect(src).toMatch(/DbHost\s+string\s+\(sensitive\)/); + expect(src).toMatch(/DbPort\s+long\?/); + expect(src).toContain('.OUTPUTS'); + expect(src).toContain('(Get-Env).DbHost'); + expect(src).not.toContain('# >'); + }); + + test('is registered as the generatePwshEnv decorator', () => { + const def = builtInCodeGenerators.find((d) => d.decoratorName === 'generatePwshEnv'); + expect(def).toBeDefined(); + expect(def?.knownOptions).toEqual(['functionName']); + }); +}); From d208e6f2c8edd9610a1c024a45b5d7da85fa2a68 Mon Sep 17 00:00:00 2001 From: "Joe Skeen, Jr." Date: Mon, 23 Nov 2026 19:01:54 -0700 Subject: [PATCH 2/2] Require PowerShell 7.4 for generated pwsh modules The generated C# uses the AesGcm tag-size constructor, which only exists on .NET 8. PowerShell 7.2 and 7.3 run on .NET 6 and 7, and their compilers do not support the C# 11 required members that the shared C# output uses. The generated module now checks the PowerShell version first and throws a clear error on older versions. --- .../src/content/docs/integrations/powershell.mdx | 2 +- .../src/content/docs/reference/root-decorators.mdx | 2 +- .../env-graph/lib/type-generation/emitters/pwsh.ts | 8 ++++++-- .../src/env-graph/test/type-generation/pwsh.test.ts | 12 ++++++++++++ 4 files changed, 20 insertions(+), 4 deletions(-) diff --git a/packages/varlock-website/src/content/docs/integrations/powershell.mdx b/packages/varlock-website/src/content/docs/integrations/powershell.mdx index c47fd5ba2..6597f09b6 100644 --- a/packages/varlock-website/src/content/docs/integrations/powershell.mdx +++ b/packages/varlock-website/src/content/docs/integrations/powershell.mdx @@ -11,7 +11,7 @@ Add [`@generatePwshEnv`](/reference/root-decorators/#generatepwshenv) to your sc # @generatePwshEnv(path=./Env.ps1) ``` -The file is regenerated automatically on [`varlock load`](/reference/cli/load-and-run/#load) and [`varlock run`](/reference/cli/load-and-run/#run), or explicitly with [`varlock codegen`](/reference/cli/cache-and-codegen/#codegen). Requires **PowerShell 7.2+** (the loader uses `System.Security.Cryptography.AesGcm` and the C# compiler that ships with PowerShell 7). Optional `functionName=` sets the loader function name (default: `Get-Env`). It must be a Verb-Noun name, such as `Get-AppEnv`. Property names are PascalCase (`DB_HOST` becomes `DbHost`). +The file is regenerated automatically on [`varlock load`](/reference/cli/load-and-run/#load) and [`varlock run`](/reference/cli/load-and-run/#run), or explicitly with [`varlock codegen`](/reference/cli/cache-and-codegen/#codegen). Requires **PowerShell 7.4+** (.NET 8; the loader uses `System.Security.Cryptography.AesGcm` and the C# compiler that ships with PowerShell 7.4). Optional `functionName=` sets the loader function name (default: `Get-Env`). It must be a Verb-Noun name, such as `Get-AppEnv`. Property names are PascalCase (`DB_HOST` becomes `DbHost`). ## Reading values diff --git a/packages/varlock-website/src/content/docs/reference/root-decorators.mdx b/packages/varlock-website/src/content/docs/reference/root-decorators.mdx index fde99b8bb..7d2d2a2bd 100644 --- a/packages/varlock-website/src/content/docs/reference/root-decorators.mdx +++ b/packages/varlock-website/src/content/docs/reference/root-decorators.mdx @@ -829,7 +829,7 @@ Optional `namespace=` and `class=` (default: no namespace, class `Env`).
### `@generatePwshEnv()` -A self-contained PowerShell file: a loader function (default `Get-Env`) that returns a typed object (an instance of a C# class compiled with `Add-Type`), plus a `SensitiveKeys` function. Requires PowerShell 7.2+. See [PowerShell usage](/integrations/powershell/). +A self-contained PowerShell file: a loader function (default `Get-Env`) that returns a typed object (an instance of a C# class compiled with `Add-Type`), plus a `SensitiveKeys` function. Requires PowerShell 7.4+. See [PowerShell usage](/integrations/powershell/). ```env-spec # @generatePwshEnv(path=./Env.ps1) diff --git a/packages/varlock/src/env-graph/lib/type-generation/emitters/pwsh.ts b/packages/varlock/src/env-graph/lib/type-generation/emitters/pwsh.ts index 1fab0d457..2a5d6bcac 100644 --- a/packages/varlock/src/env-graph/lib/type-generation/emitters/pwsh.ts +++ b/packages/varlock/src/env-graph/lib/type-generation/emitters/pwsh.ts @@ -119,7 +119,7 @@ function helpLines( 'An object with one property for each schema item (see Properties).', '', '.NOTES', - 'Requires PowerShell 7.2+. The typed class is compiled with Add-Type the first time the file is loaded in a session.', + 'Requires PowerShell 7.4+ (.NET 8). The typed class is compiled with Add-Type the first time the file is loaded in a session.', 'This file is generated by varlock. Regenerate it with varlock codegen instead of editing it by hand.', '', '.LINK', @@ -154,7 +154,11 @@ export function generatePwshEnvSrc( const src = [ getAutogeneratedBanner('#'), - '# Requires PowerShell 7.2+ (the C# source uses System.Text.Json and AesGcm, compiled with Add-Type).', + '# Requires PowerShell 7.4+ (.NET 8). The C# source uses System.Text.Json and AesGcm, compiled with Add-Type.', + '', + 'if ($PSVersionTable.PSVersion -lt [version]\'7.4\') {', + ' throw \'varlock: this generated module requires PowerShell 7.4 or later\'', + '}', '', `if (-not (${pwshStringLiteral(fullName)} -as [type])) {`, // `#nullable enable` is needed for the `string?` members, and the define selects the diff --git a/packages/varlock/src/env-graph/test/type-generation/pwsh.test.ts b/packages/varlock/src/env-graph/test/type-generation/pwsh.test.ts index 6ab742fa7..b41e0e2e6 100644 --- a/packages/varlock/src/env-graph/test/type-generation/pwsh.test.ts +++ b/packages/varlock/src/env-graph/test/type-generation/pwsh.test.ts @@ -84,6 +84,18 @@ describe('generatePwshEnvSrc', () => { expect(src).not.toContain('# >'); }); + test('requires PowerShell 7.4 and fails clearly on older versions', async () => { + const { fields } = await loadFixtureFields(outdent` + # --- + DB_HOST=localhost # @required @public + `); + const src = generatePwshEnvSrc(fields); + expect(src).toContain('# Requires PowerShell 7.4+'); + expect(src).toContain('if ($PSVersionTable.PSVersion -lt [version]\'7.4\') {'); + expect(src).toContain('requires PowerShell 7.4 or later'); + expect(src).not.toContain('7.2'); + }); + test('is registered as the generatePwshEnv decorator', () => { const def = builtInCodeGenerators.find((d) => d.decoratorName === 'generatePwshEnv'); expect(def).toBeDefined();