@cnc-tools/storm 0.14.0 → 0.14.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.
@@ -1,3 +1,3 @@
1
1
  // Written by scripts/write-build-info.js when the package was built.
2
- export const sha = "9fd3c08b6555";
2
+ export const sha = "36a0a0305429";
3
3
  export const dirty = false;
@@ -1,9 +1,15 @@
1
1
  import type { Redactor } from "./redaction.ts";
2
2
  /**
3
- * An invocation's `vercel` arguments: `args`, then the hidden `--api` flag pointing the CLI at the proxy, `--token`
4
- * when a token is given, `--global-config`, and `--scope` when one is given. Throws a `TypeError` when `args` already
5
- * passes a flag the invoker adds, `--token` included when no token is given, or a scope flag along with `scope`: the
6
- * invoker never sends a flag twice, and owns how an invocation authenticates.
3
+ * `args` with `extra` inserted immediately before the first `"--"`, or appended at the end when `args` has no `"--"`,
4
+ * so flags the invoker adds are never turned into positional arguments after `"--"`.
5
+ */
6
+ export declare function insertBeforeDoubleDash(args: readonly string[], extra: readonly string[]): readonly string[];
7
+ /**
8
+ * An invocation's `vercel` arguments: `args`, with the hidden `--api` flag pointing the CLI at the proxy, `--token`
9
+ * when a token is given, `--global-config`, and `--scope` when one is given inserted immediately before the first
10
+ * `"--"` (or appended at the end when `args` has no `"--"`). Throws a `TypeError` when `args` already passes a flag
11
+ * the invoker adds, `--token` included when no token is given, or a scope flag along with `scope`: the invoker never
12
+ * sends a flag twice, and owns how an invocation authenticates.
7
13
  */
8
14
  export declare function vercelArguments(options: {
9
15
  readonly args: readonly string[];
@@ -6,10 +6,21 @@ const SCOPE_FLAGS = ["--scope", "-S", "--team"];
6
6
  /** Flags whose next argument is a token. */
7
7
  const TOKEN_FLAGS = new Set(["--token", "-t"]);
8
8
  /**
9
- * An invocation's `vercel` arguments: `args`, then the hidden `--api` flag pointing the CLI at the proxy, `--token`
10
- * when a token is given, `--global-config`, and `--scope` when one is given. Throws a `TypeError` when `args` already
11
- * passes a flag the invoker adds, `--token` included when no token is given, or a scope flag along with `scope`: the
12
- * invoker never sends a flag twice, and owns how an invocation authenticates.
9
+ * `args` with `extra` inserted immediately before the first `"--"`, or appended at the end when `args` has no `"--"`,
10
+ * so flags the invoker adds are never turned into positional arguments after `"--"`.
11
+ */
12
+ export function insertBeforeDoubleDash(args, extra) {
13
+ const separator = args.indexOf("--");
14
+ if (separator === -1)
15
+ return [...args, ...extra];
16
+ return [...args.slice(0, separator), ...extra, ...args.slice(separator)];
17
+ }
18
+ /**
19
+ * An invocation's `vercel` arguments: `args`, with the hidden `--api` flag pointing the CLI at the proxy, `--token`
20
+ * when a token is given, `--global-config`, and `--scope` when one is given inserted immediately before the first
21
+ * `"--"` (or appended at the end when `args` has no `"--"`). Throws a `TypeError` when `args` already passes a flag
22
+ * the invoker adds, `--token` included when no token is given, or a scope flag along with `scope`: the invoker never
23
+ * sends a flag twice, and owns how an invocation authenticates.
13
24
  */
14
25
  export function vercelArguments(options) {
15
26
  const given = flagsIn(options.args);
@@ -23,8 +34,7 @@ export function vercelArguments(options) {
23
34
  throw new TypeError(`vercel-cli: pass the scope either as the scope option or as ${scoped.join(", ")}, not both`);
24
35
  }
25
36
  }
26
- return [
27
- ...options.args,
37
+ const invokerFlags = [
28
38
  "--api",
29
39
  options.proxyUrl,
30
40
  ...(options.token === undefined ? [] : ["--token", options.token]),
@@ -32,6 +42,7 @@ export function vercelArguments(options) {
32
42
  options.globalConfigDir,
33
43
  ...(options.scope === undefined ? [] : ["--scope", options.scope]),
34
44
  ];
45
+ return insertBeforeDoubleDash(options.args, invokerFlags);
35
46
  }
36
47
  /** Whether `args` names the scope with `--scope`, `-S` or `--team`, alone or with `=`, before any `--`. */
37
48
  export function passesScopeFlag(args) {
@@ -13,7 +13,18 @@ export declare const TERMINAL_COLUMNS = 400;
13
13
  */
14
14
  export declare const RESERVED_VARIABLES: ReadonlySet<string>;
15
15
  /**
16
- * An invocation's whole environment: `PATH`, `SystemRoot` and `TEMP` from `host` when set, `HOME`, the fixed
16
+ * Throws a `TypeError` when `env` names any variable in `RESERVED_VARIABLES`, even when its value is `null`.
17
+ */
18
+ export declare function checkExtraEnvironment(env: Readonly<Record<string, string | null>>): void;
19
+ /**
20
+ * Merges a handle's default environment variables (`VercelCliOptions.env` and `withEnv`) with an overlay (`withEnv`
21
+ * or a call's `env`): a string value sets or replaces the key, and `null` deletes it from the merged map so the
22
+ * variable is not inherited (and `{ PATH: null }` falls back to `host.PATH`). Validates every key against
23
+ * `RESERVED_VARIABLES`, including keys whose value is `null`.
24
+ */
25
+ export declare function resolveExtraEnvironment(defaults: Readonly<Record<string, string>> | undefined, call: Readonly<Record<string, string | null>> | undefined): Readonly<Record<string, string>>;
26
+ /**
27
+ * An invocation's whole environment: `PATH`, `SystemRoot`, and `TEMP` from `host` when set, `HOME`, the fixed
17
28
  * variables (`NO_COLOR`, `NO_UPDATE_NOTIFIER`, `VERCEL_TELEMETRY_DISABLED`, `VERCEL_TEST_KEYRING_UNAVAILABLE`),
18
29
  * `FORCE_TTY=1`, no `CI`, and `CLI_WIDTH` and `COLUMNS` set to `columns` (default `TERMINAL_COLUMNS`) for an
19
30
  * invocation at a terminal, or else `CI=1` and no width, as a script or CI has, and the call's `extra`, whose `PATH`
@@ -38,7 +38,40 @@ export const RESERVED_VARIABLES = new Set([
38
38
  "VERCEL_TOKEN",
39
39
  ]);
40
40
  /**
41
- * An invocation's whole environment: `PATH`, `SystemRoot` and `TEMP` from `host` when set, `HOME`, the fixed
41
+ * Throws a `TypeError` when `env` names any variable in `RESERVED_VARIABLES`, even when its value is `null`.
42
+ */
43
+ export function checkExtraEnvironment(env) {
44
+ const reserved = Object.keys(env).filter((name) => RESERVED_VARIABLES.has(name));
45
+ if (reserved.length > 0) {
46
+ throw new TypeError(`vercel-cli: env may not set ${reserved.join(", ")}, which the invoker owns`);
47
+ }
48
+ }
49
+ /**
50
+ * Merges a handle's default environment variables (`VercelCliOptions.env` and `withEnv`) with an overlay (`withEnv`
51
+ * or a call's `env`): a string value sets or replaces the key, and `null` deletes it from the merged map so the
52
+ * variable is not inherited (and `{ PATH: null }` falls back to `host.PATH`). Validates every key against
53
+ * `RESERVED_VARIABLES`, including keys whose value is `null`.
54
+ */
55
+ export function resolveExtraEnvironment(defaults, call) {
56
+ if (defaults !== undefined)
57
+ checkExtraEnvironment(defaults);
58
+ if (call !== undefined)
59
+ checkExtraEnvironment(call);
60
+ const merged = defaults === undefined ? {} : { ...defaults };
61
+ if (call !== undefined) {
62
+ for (const [name, value] of Object.entries(call)) {
63
+ if (value === null) {
64
+ delete merged[name];
65
+ }
66
+ else {
67
+ merged[name] = value;
68
+ }
69
+ }
70
+ }
71
+ return merged;
72
+ }
73
+ /**
74
+ * An invocation's whole environment: `PATH`, `SystemRoot`, and `TEMP` from `host` when set, `HOME`, the fixed
42
75
  * variables (`NO_COLOR`, `NO_UPDATE_NOTIFIER`, `VERCEL_TELEMETRY_DISABLED`, `VERCEL_TEST_KEYRING_UNAVAILABLE`),
43
76
  * `FORCE_TTY=1`, no `CI`, and `CLI_WIDTH` and `COLUMNS` set to `columns` (default `TERMINAL_COLUMNS`) for an
44
77
  * invocation at a terminal, or else `CI=1` and no width, as a script or CI has, and the call's `extra`, whose `PATH`
@@ -50,10 +83,7 @@ export const RESERVED_VARIABLES = new Set([
50
83
  */
51
84
  export function invocationEnvironment(options) {
52
85
  const extra = options.extra ?? {};
53
- const reserved = Object.keys(extra).filter((name) => RESERVED_VARIABLES.has(name));
54
- if (reserved.length > 0) {
55
- throw new TypeError(`vercel-cli: env may not set ${reserved.join(", ")}, which the invoker owns`);
56
- }
86
+ checkExtraEnvironment(extra);
57
87
  const env = {};
58
88
  for (const name of PASSED_ON) {
59
89
  const value = options.host[name];
@@ -32,10 +32,16 @@ export interface VercelCliOptions {
32
32
  /** How long an invocation may run before it's killed, unless the call says otherwise; default 45s. */
33
33
  readonly timeoutMs?: number;
34
34
  /**
35
- * Where `PATH`, `SystemRoot` and `TEMP` come from; default `process.env`. Nothing else in it reaches `vercel`. A
36
- * call's `env.PATH` replaces its `PATH` for that invocation.
35
+ * Where `PATH`, `SystemRoot`, and `TEMP` come from; default `process.env`. Nothing else in it reaches `vercel`. A
36
+ * handle's or call's `env.PATH` replaces its `PATH` for that invocation.
37
37
  */
38
38
  readonly hostEnv?: Readonly<Record<string, string | undefined>>;
39
+ /**
40
+ * Default environment variables added to every invocation on the returned handle (and handles derived from it via
41
+ * `withEnv`). Validated eagerly against the invoker's reserved variables and shallow-copied. A derived handle's
42
+ * `withEnv` or a call's `env` overrides a key or unsets an inherited key with `null`.
43
+ */
44
+ readonly env?: Readonly<Record<string, string>>;
39
45
  /**
40
46
  * Hears each invocation once it has ended, or failed to start, tokens redacted, such as to print it with
41
47
  * `describeInvocation` as the test goes. What it throws is dropped. Without one, `vercelCli` prints each invocation
@@ -73,8 +79,8 @@ export interface VercelCallOptions {
73
79
  * - `"flag"`: `--token <secret>`, with the token `as` or the default identity names.
74
80
  * - `"saved"`: no `--token`. The invoker first saves that token as `token` in `<globalConfigDir>/auth.json`,
75
81
  * keeping the file's other keys, so `vercel` reads it as it reads a `vercel login`.
76
- * - `"none"`: no `--token`, and the invoker removes `token`, `refreshToken` and `expiresAt` from `auth.json`, keeping
77
- * its other keys: a logged-out `vercel`. It needs no default identity.
82
+ * - `"none"`: no `--token`, and the invoker removes `token`, `refreshToken`, and `expiresAt` from `auth.json`,
83
+ * keeping its other keys: a logged-out `vercel`. It needs no default identity.
78
84
  *
79
85
  * The invoker writes `auth.json` only when it differs from what the call needs in those keys. Under `"saved"` and
80
86
  * `"none"`, only the call's own `scope` sends `--scope`: `vercel` picks the team as after a login, the saved
@@ -92,14 +98,15 @@ export interface VercelCallOptions {
92
98
  /** Where it runs; default `<home>/work`. */
93
99
  readonly cwd?: string;
94
100
  /**
95
- * Variables added to its environment. `PATH` replaces the one from `hostEnv`; setting any other variable the
96
- * invoker sets (`HOME`, `SystemRoot`, `TEMP`, `FORCE_TTY`, `CI`, `CLI_WIDTH`, `COLUMNS`, `NO_COLOR`,
97
- * `NO_UPDATE_NOTIFIER`, `VERCEL_TELEMETRY_DISABLED`, `VERCEL_TEST_KEYRING_UNAVAILABLE`), or `VERCEL_TOKEN`, which
98
- * would undo `auth`, is a usage error. A bare `command.file`,
99
- * such as the default `vercel`, is looked up on this `PATH`, so a `PATH` without `vercel` needs an absolute
100
- * `command`.
101
+ * Variables added to its environment on top of any defaults this handle carries (`VercelCliOptions.env` and
102
+ * `withEnv`). A string value sets or replaces a variable, and `null` unsets an inherited default (`{ PATH: null }`
103
+ * falls back to `hostEnv.PATH`). `PATH` replaces the one from `hostEnv`; naming any other variable the invoker sets
104
+ * (`HOME`, `SystemRoot`, `TEMP`, `FORCE_TTY`, `CI`, `CLI_WIDTH`, `COLUMNS`, `NO_COLOR`, `NO_UPDATE_NOTIFIER`,
105
+ * `VERCEL_TELEMETRY_DISABLED`, `VERCEL_TEST_KEYRING_UNAVAILABLE`), or `VERCEL_TOKEN`, which would undo `auth`, is a
106
+ * usage error, even with `null`. A bare `command.file`, such as the default `vercel`, is looked up on this `PATH`,
107
+ * so a `PATH` without `vercel` needs an absolute `command`.
101
108
  */
102
- readonly env?: Readonly<Record<string, string>>;
109
+ readonly env?: Readonly<Record<string, string | null>>;
103
110
  /** How long it may run before it's killed; default the invoker's `timeoutMs`. */
104
111
  readonly timeoutMs?: number;
105
112
  }
@@ -177,12 +184,20 @@ export interface VercelCli {
177
184
  * Sets who `vercel` acts as by default: `token.secretString` for `--token` and `team.slug` for `--scope` (none for
178
185
  * `team: null`), and `auth`, how a call authenticates unless it says otherwise (default `"flag"`). Calling it again
179
186
  * replaces the default, `auth` included. The token reads `<token>` in everything the invoker returns or prints from
180
- * now on. A call's `as`, `scope` or `auth` overrides it; the default scope steps aside when a call's arguments name
181
- * `--scope`, `-S` or `--team`, and under `"saved"` and `"none"`.
187
+ * now on. A call's `as`, `scope`, or `auth` overrides it; the default scope steps aside when a call's arguments name
188
+ * `--scope`, `-S`, or `--team`, and under `"saved"` and `"none"`.
182
189
  */
183
190
  actAs(identity: VercelIdentity, options?: {
184
191
  readonly auth?: VercelAuth;
185
192
  }): void;
193
+ /**
194
+ * Returns a new `VercelCli` handle over the same underlying session (`home`, `globalConfigDir`, `workDir`,
195
+ * `invocations`, `close()`, `failureReport()`, and shared `actAs` identity) with `env` merged over this handle's
196
+ * default environment. String values set or replace a variable, and `null` unsets an inherited default (`{ PATH:
197
+ * null }` falls back to `hostEnv.PATH`). Validates every key eagerly against the invoker's reserved variables,
198
+ * including `null` entries, and leaves this handle unchanged.
199
+ */
200
+ withEnv(env: Readonly<Record<string, string | null>>): VercelCli;
186
201
  /**
187
202
  * Runs `vercel` with `args`, and resolves however it ends: its `stdout` and `stderr` with ANSI codes removed, as
188
203
  * `waitFor` removes them, and `rawStdout` and `rawStderr` as they arrived. At a terminal, stdin closes at once:
@@ -3,10 +3,10 @@
3
3
  // invocations share. `createVercelCli` takes its Context; `vercelCli` (`entry.ts`), the published entry, passes the
4
4
  // live one.
5
5
  import { join } from "node:path";
6
- import { displayCommand, passesFlag, passesScopeFlag, vercelArguments } from "./arguments.js";
6
+ import { displayCommand, insertBeforeDoubleDash, passesFlag, passesScopeFlag, vercelArguments } from "./arguments.js";
7
7
  import { authFileConflict, authFileSettled, settledAuthConfig, VERCEL_AUTH_MODES, } from "./auth-config.js";
8
8
  import { AUTH_CONFIG_FILE, readConfigText, serializeConfig } from "./config-files.js";
9
- import { invocationEnvironment } from "./environment.js";
9
+ import { checkExtraEnvironment, invocationEnvironment, resolveExtraEnvironment } from "./environment.js";
10
10
  import { VercelCliError } from "./errors.js";
11
11
  import { Invocation, STOP_SIGNALS, WAIT_FOR_TIMEOUT_MS, } from "./invocation.js";
12
12
  import { KEY_SEQUENCES } from "./keys.js";
@@ -19,6 +19,9 @@ const DEFAULT_COMMAND = { file: "vercel", args: [] };
19
19
  /** A `VercelCli` over `context`. It prepares `<home>/global-config` and `<home>/work` first. */
20
20
  export async function createVercelCli(options, context) {
21
21
  const defaultTimeoutMs = checkedTimeout(options.timeoutMs ?? VERCEL_TIMEOUT_MS, "timeoutMs");
22
+ if (options.env !== undefined)
23
+ checkExtraEnvironment(options.env);
24
+ const initialEnv = options.env === undefined ? {} : { ...options.env };
22
25
  const home = options.home;
23
26
  const globalConfigDir = join(home, "global-config");
24
27
  const workDir = join(home, "work");
@@ -52,7 +55,7 @@ export async function createVercelCli(options, context) {
52
55
  * and `close()` kills it even while it is starting. Then it settles `auth.json` for a saved login or a logged-out
53
56
  * invocation, after any settlement already under way, and starts the process.
54
57
  */
55
- const launch = async (args, call, how) => {
58
+ const launch = async (args, call, handleEnv, how) => {
56
59
  const { interactive, stdin } = how;
57
60
  const terminal = stdin.kind === "terminal";
58
61
  const authentication = resolveAuthentication(checkedAuth(call.auth ?? defaultAuth), call.as, identity?.token);
@@ -67,7 +70,13 @@ export async function createVercelCli(options, context) {
67
70
  globalConfigDir,
68
71
  scope,
69
72
  });
70
- const env = invocationEnvironment({ host: hostEnv, home, terminal, columns: how.columns, extra: call.env });
73
+ const env = invocationEnvironment({
74
+ host: hostEnv,
75
+ home,
76
+ terminal,
77
+ columns: how.columns,
78
+ extra: resolveExtraEnvironment(handleEnv, call.env),
79
+ });
71
80
  const cwd = call.cwd ?? workDir;
72
81
  const conflict = invocations.find((other) => other.running && authFileConflict(authentication, other.authentication));
73
82
  if (conflict !== undefined)
@@ -168,11 +177,11 @@ export async function createVercelCli(options, context) {
168
177
  * result once it has ended. Kills it when `block` throws. Every call but `json` runs through here; `run`'s block
169
178
  * does nothing.
170
179
  */
171
- const execute = async (args, call, interactive, block) => {
180
+ const execute = async (args, call, handleEnv, interactive, block) => {
172
181
  const stdin = invocationStdin(call);
173
182
  const columns = invocationColumns(call);
174
183
  const terminal = stdin.kind === "terminal";
175
- const invocation = await launch(args, call, { interactive, stdin, columns });
184
+ const invocation = await launch(args, call, handleEnv, { interactive, stdin, columns });
176
185
  try {
177
186
  await block(handle(invocation, terminal));
178
187
  }
@@ -185,69 +194,74 @@ export async function createVercelCli(options, context) {
185
194
  invocation.closeStdin();
186
195
  return invocation.result();
187
196
  };
188
- async function interact(args, callOrBlock, maybeBlock) {
189
- const [call, block] = typeof callOrBlock === "function" ? [{}, callOrBlock] : [callOrBlock, maybeBlock];
190
- if (typeof block !== "function") {
191
- throw new TypeError("vercel-cli: interact takes a block: interact(args, options?, async (invocation) => ...)");
192
- }
193
- return execute(args, call, true, block);
194
- }
195
- return {
196
- home,
197
- globalConfigDir,
198
- workDir,
199
- actAs({ token, team }, actAsOptions = {}) {
200
- if (token.secretString === "")
201
- throw new TypeError("vercel-cli: actAs names an empty token");
202
- if (team !== null && team.slug === "")
203
- throw new TypeError("vercel-cli: actAs names a team with an empty slug");
204
- const auth = checkedAuth(actAsOptions.auth ?? "flag");
205
- redactor.add(token.secretString);
206
- identity = { token: token.secretString, scope: team?.slug };
207
- defaultAuth = auth;
208
- },
209
- run: async (args, call = {}) => execute(args, call, false, () => undefined),
210
- interact,
211
- async json(args, schema, call = {}) {
212
- if (passesFlag(args, "--format")) {
213
- throw new TypeError("vercel-cli: json adds --format json itself; leave --format out of the arguments");
214
- }
215
- const invocation = await launch([...args, "--format", "json"], call, {
216
- interactive: false,
217
- stdin: { kind: "ignored" },
218
- });
219
- const result = await invocation.result();
220
- const failed = (why) => new VercelCliError(`vercel-cli: invocation ${invocation.number} ${why}\n${describeInvocation(invocation.snapshot())}`);
221
- if (result.exitCode !== 0 || result.timedOut || result.aborted)
222
- throw failed("didn't exit 0");
223
- let document;
224
- try {
225
- document = JSON.parse(result.stdout);
226
- }
227
- catch {
228
- throw failed("printed something other than JSON");
229
- }
230
- const parsed = schema.safeParse(document);
231
- if (!parsed.success) {
232
- const issue = parsed.error.issues[0];
233
- const where = issue === undefined || issue.path.length === 0 ? "" : ` at ${issue.path.map(String).join(".")}`;
234
- throw failed(`printed JSON its schema rejects${where}: ${redactor.redact(issue?.message ?? "invalid")}`);
197
+ const actAs = ({ token, team }, actAsOptions = {}) => {
198
+ if (token.secretString === "")
199
+ throw new TypeError("vercel-cli: actAs names an empty token");
200
+ if (team !== null && team.slug === "")
201
+ throw new TypeError("vercel-cli: actAs names a team with an empty slug");
202
+ const auth = checkedAuth(actAsOptions.auth ?? "flag");
203
+ redactor.add(token.secretString);
204
+ identity = { token: token.secretString, scope: team?.slug };
205
+ defaultAuth = auth;
206
+ };
207
+ const close = async () => {
208
+ const running = invocations.filter((invocation) => invocation.running);
209
+ for (const invocation of running)
210
+ invocation.kill("close");
211
+ await Promise.all(running.map((invocation) => invocation.ended()));
212
+ };
213
+ const failureReport = () => describeInvocations(invocations.map((invocation) => invocation.snapshot()));
214
+ const cliWithEnv = (handleEnv) => {
215
+ async function interact(args, callOrBlock, maybeBlock) {
216
+ const [call, block] = typeof callOrBlock === "function" ? [{}, callOrBlock] : [callOrBlock, maybeBlock];
217
+ if (typeof block !== "function") {
218
+ throw new TypeError("vercel-cli: interact takes a block: interact(args, options?, async (invocation) => ...)");
235
219
  }
236
- return parsed.data;
237
- },
238
- get invocations() {
239
- return invocations.map((invocation) => invocation.snapshot());
240
- },
241
- async close() {
242
- const running = invocations.filter((invocation) => invocation.running);
243
- for (const invocation of running)
244
- invocation.kill("close");
245
- await Promise.all(running.map((invocation) => invocation.ended()));
246
- },
247
- failureReport() {
248
- return describeInvocations(invocations.map((invocation) => invocation.snapshot()));
249
- },
220
+ return execute(args, call, handleEnv, true, block);
221
+ }
222
+ return {
223
+ home,
224
+ globalConfigDir,
225
+ workDir,
226
+ actAs,
227
+ withEnv: (extra) => cliWithEnv(resolveExtraEnvironment(handleEnv, extra)),
228
+ run: async (args, call = {}) => execute(args, call, handleEnv, false, () => undefined),
229
+ interact,
230
+ async json(args, schema, call = {}) {
231
+ if (passesFlag(args, "--format")) {
232
+ throw new TypeError("vercel-cli: json adds --format json itself; leave --format out of the arguments");
233
+ }
234
+ const invocation = await launch(insertBeforeDoubleDash(args, ["--format", "json"]), call, handleEnv, {
235
+ interactive: false,
236
+ stdin: { kind: "ignored" },
237
+ });
238
+ const result = await invocation.result();
239
+ const failed = (why) => new VercelCliError(`vercel-cli: invocation ${invocation.number} ${why}\n${describeInvocation(invocation.snapshot())}`);
240
+ if (result.exitCode !== 0 || result.timedOut || result.aborted)
241
+ throw failed("didn't exit 0");
242
+ let document;
243
+ try {
244
+ document = JSON.parse(result.stdout);
245
+ }
246
+ catch {
247
+ throw failed("printed something other than JSON");
248
+ }
249
+ const parsed = schema.safeParse(document);
250
+ if (!parsed.success) {
251
+ const issue = parsed.error.issues[0];
252
+ const where = issue === undefined || issue.path.length === 0 ? "" : ` at ${issue.path.map(String).join(".")}`;
253
+ throw failed(`printed JSON its schema rejects${where}: ${redactor.redact(issue?.message ?? "invalid")}`);
254
+ }
255
+ return parsed.data;
256
+ },
257
+ get invocations() {
258
+ return invocations.map((invocation) => invocation.snapshot());
259
+ },
260
+ close,
261
+ failureReport,
262
+ };
250
263
  };
264
+ return cliWithEnv(initialEnv);
251
265
  }
252
266
  /** A `TypeError` for starting `wanted` while `other`, still running, needs `auth.json` to hold something else. */
253
267
  function authFileConflictError(wanted, other) {
@@ -61,7 +61,6 @@ function startProcess(request) {
61
61
  let started = false;
62
62
  let completed = false;
63
63
  let terminated = false;
64
- let drainExpired = false;
65
64
  let drainTimer;
66
65
  let processExit;
67
66
  let stdinOpen = request.stdin === "pipe";
@@ -78,19 +77,14 @@ function startProcess(request) {
78
77
  clearTimeout(drainTimer);
79
78
  resolveExit(exit);
80
79
  };
81
- const stopDraining = () => {
82
- if (!drainExpired || processExit === undefined)
83
- return;
84
- complete({ ...processExit, outputComplete: false });
85
- child.stdout?.destroy();
86
- child.stderr?.destroy();
87
- };
88
80
  const startDrainTimer = () => {
89
81
  if (!terminated || processExit === undefined || drainTimer !== undefined || completed)
90
82
  return;
83
+ const exit = processExit;
91
84
  drainTimer = setTimeout(() => {
92
- drainExpired = true;
93
- stopDraining();
85
+ complete({ ...exit, outputComplete: false });
86
+ child.stdout?.destroy();
87
+ child.stderr?.destroy();
94
88
  }, TERMINATE_DRAIN_MS);
95
89
  };
96
90
  // A write racing the process's exit fails with EPIPE; the invoker learns of the exit from `exited`.
@@ -1,8 +1,9 @@
1
1
  // The `vercel` CLI's session id, read from a request record's headers. The Vercel CLI invoker's failure report counts
2
- // proxy records by it, and the Testserver Vitest fixtures' request lines name it. A record shows a header's value only
3
- // when its proxy's `recordHeaders` names it, so the Testserver Vitest fixtures' `proxy` adds this one; a proxy that
4
- // doesn't leaves every record without a session id. It belongs with the `vercel` CLI's own tests, and moves to
5
- // vercel-internal with the invoker. It loads no other file at run time.
2
+ // proxy records by it, and a suite using the Testserver Vitest fixtures can pass `VERCEL_CLI_SESSION_ID_HEADER` to
3
+ // `proxySessionHeader` so the proxy records it and prints `, session <id>` on request lines. A record shows a header's
4
+ // value only when its proxy's `recordHeaders` names it; a proxy that doesn't leaves every record without a session id.
5
+ // It belongs with the `vercel` CLI's own tests, and moves to vercel-internal with the invoker. It loads no other file
6
+ // at run time.
6
7
  import { REDACTED_HEADER } from "../../../vendor/testserver-sdk/index.js";
7
8
  /** The header the `vercel` CLI sends with the same id on every request of one invocation. */
8
9
  export const VERCEL_CLI_SESSION_ID_HEADER = "x-vercel-cli-session-id";
@@ -10,14 +10,15 @@ export type Redact = (text: string) => string;
10
10
  type RequestLine = ProxyRequestRecord | ApiRequestRecord | ExternalCallRecord;
11
11
  /**
12
12
  * One request record as a line: its method, URL as sent, result, whether it carried an `authorization` header,
13
- * duration and any `vercel` CLI session id (both read from its `requestHeaders`), such as `GET /v2/user → 200, authorization sent, 412ms, session 7f3a`; an external call's starts
14
- * with its external service, such as `external github POST /scenarios → 204, …`. A proxy record whose
15
- * exchange was still open reads `open`, its duration counted to the read. A proxy record of a request a fault rule
16
- * matched tags its result with the action and what Testserver answered, such as `500 (fault: replace, Testserver
17
- * 200)`. A status that fails the call (a record's `failure`) reads with why, such as `503 (the container stopped: …)`,
18
- * and an answer that broke off after its status with `then failed`, such as `200, then failed (aborted)`.
13
+ * duration, and any session id from `sessionHeader` (both read from its `requestHeaders`, ignoring `<redacted>`),
14
+ * such as `GET /v2/user → 200, authorization sent, 412ms, session 7f3a`; an external call's starts with its external
15
+ * service, such as `external github POST /scenarios → 204, …`. A proxy record whose exchange was still open reads
16
+ * `open`, its duration counted to the read. A proxy record of a request a fault rule matched tags its result with the
17
+ * action and what Testserver answered, such as `500 (fault: replace, Testserver 200)`. A status that fails the call
18
+ * (a record's `failure`) reads with why, such as `503 (the container stopped: …)`, and an answer that broke off after
19
+ * its status with `then failed`, such as `200, then failed (aborted)`.
19
20
  */
20
- export declare function describeRequest(request: RequestLine): string;
21
+ export declare function describeRequest(request: RequestLine, sessionHeader?: string): string;
21
22
  /**
22
23
  * A recorded body on one line, cut at `BODY_REPORT_CHARS`: JSON compact, a form as its encoded fields, text
23
24
  * quoted, and an omitted body as its note, such as `[binary, 5 bytes, image/png]`.
@@ -142,7 +143,7 @@ export declare function sharedContainerFailureReport(container: Omit<ContainerRe
142
143
  * What a verbose run prints as the proxy records a request: the request line with its bodies, as a failure report
143
144
  * would show it, naming the test id.
144
145
  */
145
- export declare function proxyRequestReport(testId: string, request: ProxyRequestRecord, redact: Redact): string;
146
+ export declare function proxyRequestReport(testId: string, request: ProxyRequestRecord, redact: Redact, sessionHeader?: string): string;
146
147
  /**
147
148
  * One warmup as a failure report's line: how many services, how long, and each that failed with why, such as
148
149
  * `warmup: 3 services in 2140ms, 1 failed (api-projects: HTTP 500: …)`.
@@ -173,7 +174,7 @@ export declare function containerStartReport(start: {
173
174
  * container's, so a secret the proxy's own redaction can't know of, such as another seeded token, reads `<token>`
174
175
  * too).
175
176
  */
176
- export declare function proxyFailureReport(testId: string, requests: readonly ProxyRequestRecord[], redact: Redact, faults?: readonly FaultHandle[]): string;
177
+ export declare function proxyFailureReport(testId: string, requests: readonly ProxyRequestRecord[], redact: Redact, faults?: readonly FaultHandle[], sessionHeader?: string): string;
177
178
  /**
178
179
  * Why a test fails when Testserver failed a request its proxy forwarded, naming each such request, through
179
180
  * `redact`; `undefined` when none did. Testserver failed a request a fault rule forwarded when it gave no answer, one
@@ -1,19 +1,19 @@
1
- import { describeFailure, FEATURE_FLAG_CLIENTS, REDACTED, redactTokenFields, TestserverCallError, } from "../../../vendor/testserver-sdk/index.js";
2
- import { vercelCliSessionId } from "../vercel-cli/session-id.js";
1
+ import { describeFailure, FEATURE_FLAG_CLIENTS, REDACTED, REDACTED_HEADER, redactTokenFields, TestserverCallError, } from "../../../vendor/testserver-sdk/index.js";
3
2
  /** The most characters of one body, input, response or container log line a failure report prints. */
4
3
  export const BODY_REPORT_CHARS = 1000;
5
4
  /** The most container log records a failure report prints, the last ones. */
6
5
  export const LOG_REPORT_RECORDS = 50;
7
6
  /**
8
7
  * One request record as a line: its method, URL as sent, result, whether it carried an `authorization` header,
9
- * duration and any `vercel` CLI session id (both read from its `requestHeaders`), such as `GET /v2/user → 200, authorization sent, 412ms, session 7f3a`; an external call's starts
10
- * with its external service, such as `external github POST /scenarios → 204, …`. A proxy record whose
11
- * exchange was still open reads `open`, its duration counted to the read. A proxy record of a request a fault rule
12
- * matched tags its result with the action and what Testserver answered, such as `500 (fault: replace, Testserver
13
- * 200)`. A status that fails the call (a record's `failure`) reads with why, such as `503 (the container stopped: …)`,
14
- * and an answer that broke off after its status with `then failed`, such as `200, then failed (aborted)`.
8
+ * duration, and any session id from `sessionHeader` (both read from its `requestHeaders`, ignoring `<redacted>`),
9
+ * such as `GET /v2/user → 200, authorization sent, 412ms, session 7f3a`; an external call's starts with its external
10
+ * service, such as `external github POST /scenarios → 204, …`. A proxy record whose exchange was still open reads
11
+ * `open`, its duration counted to the read. A proxy record of a request a fault rule matched tags its result with the
12
+ * action and what Testserver answered, such as `500 (fault: replace, Testserver 200)`. A status that fails the call
13
+ * (a record's `failure`) reads with why, such as `503 (the container stopped: …)`, and an answer that broke off after
14
+ * its status with `then failed`, such as `200, then failed (aborted)`.
15
15
  */
16
- export function describeRequest(request) {
16
+ export function describeRequest(request, sessionHeader) {
17
17
  const result = "open" in request
18
18
  ? "open"
19
19
  : !("status" in request)
@@ -24,7 +24,8 @@ export function describeRequest(request) {
24
24
  ? `${request.status}, then failed (${request.error})`
25
25
  : `${request.status} (${request.error})`;
26
26
  const authorization = "authorization" in request.requestHeaders ? "authorization sent" : "no authorization";
27
- const sessionId = vercelCliSessionId(request.requestHeaders);
27
+ const rawSessionId = sessionHeader === undefined ? undefined : request.requestHeaders[sessionHeader.toLowerCase()];
28
+ const sessionId = rawSessionId === REDACTED_HEADER ? undefined : rawSessionId;
28
29
  const session = sessionId === undefined ? "" : `, session ${sessionId}`;
29
30
  const fault = "fault" in request && request.fault !== undefined ? ` ${faultTag(request.fault)}` : "";
30
31
  const external = "externalId" in request ? `external ${request.externalId} ` : "";
@@ -80,10 +81,10 @@ function cut(text, max) {
80
81
  * One request record as its line, then a line for each body it has: what the client sent and got, and what
81
82
  * Testserver answered under a forwarding fault.
82
83
  */
83
- function describeExchange(request, redact) {
84
+ function describeExchange(request, redact, sessionHeader) {
84
85
  const upstreamBody = "fault" in request ? request.fault?.upstream?.responseBody : undefined;
85
86
  return [
86
- redact(describeRequest(request)),
87
+ redact(describeRequest(request, sessionHeader)),
87
88
  ...(request.requestBody === undefined ? [] : [` request body: ${describeBody(request.requestBody, redact)}`]),
88
89
  ...(request.responseBody === undefined ? [] : [` response body: ${describeBody(request.responseBody, redact)}`]),
89
90
  ...(upstreamBody === undefined ? [] : [` Testserver response body: ${describeBody(upstreamBody, redact)}`]),
@@ -305,8 +306,8 @@ function listed(items) {
305
306
  * What a verbose run prints as the proxy records a request: the request line with its bodies, as a failure report
306
307
  * would show it, naming the test id.
307
308
  */
308
- export function proxyRequestReport(testId, request, redact) {
309
- return [`storm: the proxy for test id ${testId} received:`, ...describeExchange(request, redact)].join("\n ");
309
+ export function proxyRequestReport(testId, request, redact, sessionHeader) {
310
+ return [`storm: the proxy for test id ${testId} received:`, ...describeExchange(request, redact, sessionHeader)].join("\n ");
310
311
  }
311
312
  /**
312
313
  * One warmup as a failure report's line: how many services, how long, and each that failed with why, such as
@@ -353,12 +354,12 @@ function services(count) {
353
354
  * container's, so a secret the proxy's own redaction can't know of, such as another seeded token, reads `<token>`
354
355
  * too).
355
356
  */
356
- export function proxyFailureReport(testId, requests, redact, faults = []) {
357
+ export function proxyFailureReport(testId, requests, redact, faults = [], sessionHeader) {
357
358
  const received = requests.length === 0
358
359
  ? [`storm: the proxy for test id ${testId} received no requests`]
359
360
  : [
360
361
  `storm: requests the proxy received for test id ${testId}:`,
361
- ...requests.flatMap((request) => describeExchange(request, redact)).map((line) => ` ${line}`),
362
+ ...requests.flatMap((request) => describeExchange(request, redact, sessionHeader)).map((line) => ` ${line}`),
362
363
  ];
363
364
  const unused = faults.filter((handle) => handle.remaining > 0);
364
365
  const rules = unused.length === 0
@@ -44,12 +44,16 @@ declare module "vitest" {
44
44
  * test whose feature flags differ from those of the file's container ends it and starts a new one.
45
45
  * - `recordHeaders`: the headers whose values the container's and the proxy's records show as sent besides the
46
46
  * SDK's defaults (`DEFAULT_RECORD_HEADERS`, such as `content-type`), such as `["dpop"]`, by default none. Every other header's value reads `<redacted>`, but `authorization`,
47
- * which shows its scheme, and cookies, which show their names (`ContainerOptions.recordHeaders`). The proxy's
48
- * records also show `x-vercel-cli-session-id`, the Vercel CLI invoker's session id. A suite sets it on its own
47
+ * which shows its scheme, and cookies, which show their names (`ContainerOptions.recordHeaders`). A suite sets it on its own
49
48
  * `test` with `.override("recordHeaders", [...])`, a file or `describe` with `test.override({ recordHeaders })`.
50
49
  * In `'file'` scope, a test whose list shows other headers than that of the file's container ends it and starts a
51
50
  * new one, as for `featureFlags`; the proxy is the test's own. A bad list fails the test with a `TypeError` before
52
51
  * any container is acquired.
52
+ * - `proxySessionHeader`: an optional request header name that `proxy` records in addition to `recordHeaders` and
53
+ * prints as `, session <value>` on proxied request lines (such as `VERCEL_CLI_SESSION_ID_HEADER`), by default
54
+ * `undefined`. A suite sets it on its own `test` with `.override("proxySessionHeader", ...)`, a file or `describe`
55
+ * with `test.override({ proxySessionHeader })`. Unlike `recordHeaders`, it applies only to `proxy`, survives
56
+ * per-test `recordHeaders` overrides, and never replaces a file-scoped container.
53
57
  * - `container`: in `'file'` scope, the file's container, labeled with the file's path, started by the file's first
54
58
  * test that asks for it. A failed test that used it ends it when its failure may come from the container, such as
55
59
  * a failed factory call or API request, a fault rule's forwarded request Testserver failed, or a timeout, so the
@@ -6,7 +6,6 @@ import { containerStartReport, proxyFailureReport, proxyRequestReport, proxyTest
6
6
  import { workerTestserverUrl } from "./worker-sandbox.js";
7
7
  import { acquireOwned, Acquisitions, countTests, testEventReporter, testEventState } from "../../../vitest/index.js";
8
8
  import { reportedStart } from "./container-start.js";
9
- import { VERCEL_CLI_SESSION_ID_HEADER } from "../vercel-cli/session-id.js";
10
9
  /** The default `warmServices`: no service is warmed. */
11
10
  const NO_SERVICES = [];
12
11
  /** The default `featureFlags`: none. */
@@ -75,6 +74,7 @@ const fixtures = vitestTest
75
74
  .extend("warmServices", NO_SERVICES)
76
75
  .extend("featureFlags", NO_FEATURE_FLAGS)
77
76
  .extend("recordHeaders", NO_RECORD_HEADERS)
77
+ .extend("proxySessionHeader", undefined)
78
78
  // How the test's container is set up, for the fixture that hands it `onCleanup` (`stormContainer`, or `container`
79
79
  // in its place). Setting this up starts nothing and never throws.
80
80
  .extend("stormContainerSetup", ({ containerScope, warmServices, featureFlags, recordHeaders, stormFile, stormTestserverFailure, stormEvents, testserverUrl, verbose, task, signal, onTestFailed, }) => async (onCleanup) => {
@@ -134,11 +134,11 @@ const fixtures = vitestTest
134
134
  const provided = stormContainer;
135
135
  return provided ?? stormContainerSetup(onCleanup);
136
136
  })
137
- .extend("proxy", async ({ container, recordHeaders, stormFile, stormTestserverFailure, verbose, signal, onTestFailed, onTestFinished }, { onCleanup }) => {
137
+ .extend("proxy", async ({ container, recordHeaders, proxySessionHeader, stormFile, stormTestserverFailure, verbose, signal, onTestFailed, onTestFinished, }, { onCleanup }) => {
138
138
  startedContainer(container);
139
139
  // Under a verbose run, each request prints as the proxy records it, for passing tests too.
140
140
  const onRequest = verbose
141
- ? (record) => console.error(proxyRequestReport(container.testId, record, (text) => container.redact(text)))
141
+ ? (record) => console.error(proxyRequestReport(container.testId, record, (text) => container.redact(text), proxySessionHeader))
142
142
  : undefined;
143
143
  // Why Testserver failed the test through the proxy, once it has closed. The cleanup only notes it, and this
144
144
  // handler, which Vitest runs after every cleanup and before the failure handlers, fails the test with it: a
@@ -149,11 +149,10 @@ const fixtures = vitestTest
149
149
  if (failure.message !== undefined)
150
150
  throw new Error(failure.message);
151
151
  });
152
- const proxy = await stormFile.acquisitions.track(signal, acquireOwned(signal, onCleanup,
153
- // The proxy's records also show the Vercel CLI invoker's session id header, which its report counts by.
154
- () => startProxy({
152
+ const proxyRecordHeaders = proxySessionHeader === undefined ? recordHeaders : [proxySessionHeader, ...recordHeaders];
153
+ const proxy = await stormFile.acquisitions.track(signal, acquireOwned(signal, onCleanup, () => startProxy({
155
154
  container,
156
- recordHeaders: [VERCEL_CLI_SESSION_ID_HEADER, ...recordHeaders],
155
+ recordHeaders: proxyRecordHeaders,
157
156
  ...(onRequest === undefined ? {} : { onRequest }),
158
157
  }),
159
158
  // Checked once closed, when every record has ended: a test whose fault rule forwarded a request Testserver
@@ -169,7 +168,7 @@ const fixtures = vitestTest
169
168
  failure.message = message;
170
169
  }));
171
170
  onTestFailed(() => {
172
- console.error(proxyFailureReport(container.testId, proxy.requests, (text) => proxy.redact(text), proxy.faults));
171
+ console.error(proxyFailureReport(container.testId, proxy.requests, (text) => proxy.redact(text), proxy.faults, proxySessionHeader));
173
172
  });
174
173
  return proxy;
175
174
  });
@@ -206,12 +205,16 @@ const fixtures = vitestTest
206
205
  * test whose feature flags differ from those of the file's container ends it and starts a new one.
207
206
  * - `recordHeaders`: the headers whose values the container's and the proxy's records show as sent besides the
208
207
  * SDK's defaults (`DEFAULT_RECORD_HEADERS`, such as `content-type`), such as `["dpop"]`, by default none. Every other header's value reads `<redacted>`, but `authorization`,
209
- * which shows its scheme, and cookies, which show their names (`ContainerOptions.recordHeaders`). The proxy's
210
- * records also show `x-vercel-cli-session-id`, the Vercel CLI invoker's session id. A suite sets it on its own
208
+ * which shows its scheme, and cookies, which show their names (`ContainerOptions.recordHeaders`). A suite sets it on its own
211
209
  * `test` with `.override("recordHeaders", [...])`, a file or `describe` with `test.override({ recordHeaders })`.
212
210
  * In `'file'` scope, a test whose list shows other headers than that of the file's container ends it and starts a
213
211
  * new one, as for `featureFlags`; the proxy is the test's own. A bad list fails the test with a `TypeError` before
214
212
  * any container is acquired.
213
+ * - `proxySessionHeader`: an optional request header name that `proxy` records in addition to `recordHeaders` and
214
+ * prints as `, session <value>` on proxied request lines (such as `VERCEL_CLI_SESSION_ID_HEADER`), by default
215
+ * `undefined`. A suite sets it on its own `test` with `.override("proxySessionHeader", ...)`, a file or `describe`
216
+ * with `test.override({ proxySessionHeader })`. Unlike `recordHeaders`, it applies only to `proxy`, survives
217
+ * per-test `recordHeaders` overrides, and never replaces a file-scoped container.
215
218
  * - `container`: in `'file'` scope, the file's container, labeled with the file's path, started by the file's first
216
219
  * test that asks for it. A failed test that used it ends it when its failure may come from the container, such as
217
220
  * a failed factory call or API request, a fault rule's forwarded request Testserver failed, or a timeout, so the
@@ -28,12 +28,19 @@ export interface TestserverTestFixtureSet {
28
28
  /**
29
29
  * The headers whose values the container's and the proxy's records show as sent besides the SDK's defaults
30
30
  * (`DEFAULT_RECORD_HEADERS`, such as `content-type`), such as `["dpop"]`; by default none, so every other header's
31
- * value reads `<redacted>`. The proxy's records also show the `vercel` CLI's
32
- * `x-vercel-cli-session-id`. Set it with `.override("recordHeaders", [...])` on a suite's `test`, or
31
+ * value reads `<redacted>`. Set it with `.override("recordHeaders", [...])` on a suite's `test`, or
33
32
  * `test.override({ recordHeaders })`. In `'file'` scope, a test whose list shows other headers than that of the
34
33
  * file's container ends it and gets a new one, as for `featureFlags`.
35
34
  */
36
35
  recordHeaders: readonly string[];
36
+ /**
37
+ * An optional request header name that `proxy` records in addition to `recordHeaders` and prints as
38
+ * `, session <value>` on proxied request lines (such as `VERCEL_CLI_SESSION_ID_HEADER`); by default `undefined`.
39
+ * Set it with `.override("proxySessionHeader", ...)` on a suite's `test`, or
40
+ * `test.override({ proxySessionHeader })`. Unlike `recordHeaders`, it applies only to `proxy`, survives per-test
41
+ * `recordHeaders` overrides, and never replaces a file-scoped container.
42
+ */
43
+ proxySessionHeader: string | undefined;
37
44
  /** The file's container in `'file'` scope, or the test's own in `'test'` scope. */
38
45
  container: Container;
39
46
  /** A proxy adding `container`'s test id, closed after the test. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cnc-tools/storm",
3
- "version": "0.14.0",
3
+ "version": "0.14.1",
4
4
  "description": "A test orchestrator: run your tests in the inner loop of development, in the cloud, in a test environment that you define",
5
5
  "repository": {
6
6
  "type": "git",