Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .bumpy/pwsh-codegen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
varlock: minor
---

Added @generatePwshEnv to generate a typed PowerShell module that loads the injected env blob.
Original file line number Diff line number Diff line change
Expand Up @@ -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/).

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
@@ -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.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

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 `<functionName>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.
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
</div>

<div>
### `@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 `<functionName>SensitiveKeys` function. Requires PowerShell 7.4+. 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`.
</div>

<div>
### `@generateTypes()` (deprecated)

Expand Down
1 change: 1 addition & 0 deletions packages/varlock-website/src/sidebar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
],
},
Expand Down
1 change: 1 addition & 0 deletions packages/varlock/src/env-graph/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export {
generateGoEnvSrc,
generateJavaEnvSrc,
generatePhpEnvSrc,
generatePwshEnvSrc,
generatePythonEnvSrc,
generateRustEnvSrc,
generateTsTypesSrc,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -151,6 +152,13 @@ export const builtInCodeGenerators: Array<CodeGeneratorDef> = [
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
Expand Down
188 changes: 188 additions & 0 deletions packages/varlock/src/env-graph/lib/type-generation/emitters/pwsh.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
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<string, string> = {
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<string, string> {
const types = new Map<string, string>();
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<string> {
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<string> = [
'.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.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',
PWSH_DOCS_URL,
'#>',
].map((line, i, all) => (i === 0 || i === all.length - 1 ? line : safeLine(line)));
}

export function generatePwshEnvSrc(
fields: Array<ResolvedFieldType>,
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.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
// AesGcm constructor that takes a tag size (the other one is obsolete on .NET 8)
' Add-Type -CompilerOptions \'/define:NET8_0_OR_GREATER\' -TypeDefinition @\'',
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
'#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');
}
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading