@zgeoff/testing 0.1.0 → 0.2.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.
Files changed (38) hide show
  1. package/README.md +23 -0
  2. package/dist/helpers/create-blocking-stub-kit.d.ts +5 -0
  3. package/dist/helpers/create-git-commit.d.ts +2 -0
  4. package/dist/helpers/create-stub-sudo.d.ts +1 -0
  5. package/dist/helpers/env-originals.d.ts +1 -0
  6. package/dist/helpers/index.d.ts +19 -0
  7. package/dist/helpers/make-answer-queue.d.ts +1 -0
  8. package/dist/helpers/make-rejecting-stub.d.ts +1 -0
  9. package/dist/helpers/make-repeating-answer-queue.d.ts +1 -0
  10. package/dist/helpers/make-resolving-stub.d.ts +1 -0
  11. package/dist/helpers/read-git-env.d.ts +2 -0
  12. package/dist/helpers/read-git-head.d.ts +2 -0
  13. package/dist/helpers/read-run-folder-prefix.d.ts +5 -0
  14. package/dist/helpers/read-stream-until.d.ts +1 -0
  15. package/dist/helpers/remove-env-overrides.d.ts +1 -0
  16. package/dist/helpers/run-git.d.ts +2 -0
  17. package/dist/helpers/update-env.d.ts +1 -0
  18. package/dist/helpers/wait-for.d.ts +6 -0
  19. package/dist/helpers/write-tree-files.d.ts +1 -0
  20. package/package.json +6 -2
  21. package/src/helpers/create-blocking-stub-kit.ts +24 -0
  22. package/src/helpers/create-git-commit.ts +17 -0
  23. package/src/helpers/create-stub-sudo.ts +25 -0
  24. package/src/helpers/env-originals.ts +3 -0
  25. package/src/helpers/index.ts +19 -0
  26. package/src/helpers/make-answer-queue.ts +19 -0
  27. package/src/helpers/make-rejecting-stub.ts +8 -0
  28. package/src/helpers/make-repeating-answer-queue.ts +19 -0
  29. package/src/helpers/make-resolving-stub.ts +8 -0
  30. package/src/helpers/read-git-env.ts +38 -0
  31. package/src/helpers/read-git-head.ts +22 -0
  32. package/src/helpers/read-run-folder-prefix.ts +31 -0
  33. package/src/helpers/read-stream-until.ts +18 -0
  34. package/src/helpers/remove-env-overrides.ts +15 -0
  35. package/src/helpers/run-git.ts +11 -0
  36. package/src/helpers/update-env.ts +16 -0
  37. package/src/helpers/wait-for.ts +87 -0
  38. package/src/helpers/write-tree-files.ts +14 -0
package/README.md CHANGED
@@ -56,6 +56,27 @@ await using ledger = await start(command, { ready: { url: '/health' } });
56
56
  await fetch(`${ledger.url}/entries`);
57
57
  ```
58
58
 
59
+ Small helpers for any Bun test live in `@zgeoff/testing/helpers`. `waitFor` retries a check until it
60
+ stops throwing, and `updateEnv` overrides an environment variable that a hook restores:
61
+
62
+ ```ts
63
+ import { updateEnv, waitFor } from '@zgeoff/testing/helpers';
64
+
65
+ updateEnv('LEDGER_REGION', 'north');
66
+
67
+ await waitFor(() => expect(readEntries()).toHaveLength(2), { label: 'two entries' });
68
+ ```
69
+
70
+ Call `removeEnvOverrides` in an `afterEach` hook of the test preload, so no override outlives its
71
+ test:
72
+
73
+ ```ts
74
+ import { afterEach } from 'bun:test';
75
+ import { removeEnvOverrides } from '@zgeoff/testing/helpers';
76
+
77
+ afterEach(removeEnvOverrides);
78
+ ```
79
+
59
80
  ## Features
60
81
 
61
82
  - `spawnCLI` runs a program in a pseudo-terminal, with `screen` queries, `user` keystrokes, `resize`
@@ -63,6 +84,8 @@ await fetch(`${ledger.url}/entries`);
63
84
  - `run` runs a program to its exit, with `input` on stdin and a time limit.
64
85
  - `start` picks a free port, waits until the program is ready, and stops the whole process group.
65
86
  - Each handle kills its program when the test ends.
87
+ - `@zgeoff/testing/helpers` holds the stubs, git fixtures, run-folder names, `waitFor` and the env
88
+ helpers that tests in several repos share.
66
89
  - An exit code is 128 plus the signal number when a signal killed the program.
67
90
 
68
91
  ## Documentation
@@ -0,0 +1,5 @@
1
+ export declare function createBlockingStubKit<Value>(value: Value): {
2
+ stub: import("bun:test").Mock<(...callArguments: readonly unknown[]) => Promise<Value>>;
3
+ firstCall: Promise<readonly unknown[]>;
4
+ release: () => void;
5
+ };
@@ -0,0 +1,2 @@
1
+ import type { GitEnv } from './read-git-env.ts';
2
+ export declare function createGitCommit(repo: string, env: GitEnv, files: Readonly<Record<string, string>>): Promise<string>;
@@ -0,0 +1 @@
1
+ export declare function createStubSudo(directory: string, record: string): Promise<void>;
@@ -0,0 +1 @@
1
+ export declare const envOriginals: Map<string, string | undefined>;
@@ -0,0 +1,19 @@
1
+ export { createBlockingStubKit } from './create-blocking-stub-kit.ts';
2
+ export { createGitCommit } from './create-git-commit.ts';
3
+ export { createStubSudo } from './create-stub-sudo.ts';
4
+ export { makeAnswerQueue } from './make-answer-queue.ts';
5
+ export { makeRepeatingAnswerQueue } from './make-repeating-answer-queue.ts';
6
+ export { makeRejectingStub } from './make-rejecting-stub.ts';
7
+ export { makeResolvingStub } from './make-resolving-stub.ts';
8
+ export { readGitEnv } from './read-git-env.ts';
9
+ export type { GitEnv } from './read-git-env.ts';
10
+ export { readGitHead } from './read-git-head.ts';
11
+ export { readRunFolderPrefix } from './read-run-folder-prefix.ts';
12
+ export type { PIDNamespaceSource } from './read-run-folder-prefix.ts';
13
+ export { readStreamUntil } from './read-stream-until.ts';
14
+ export { removeEnvOverrides } from './remove-env-overrides.ts';
15
+ export { runGit } from './run-git.ts';
16
+ export { updateEnv } from './update-env.ts';
17
+ export { waitFor } from './wait-for.ts';
18
+ export type { WaitForOptions } from './wait-for.ts';
19
+ export { writeTreeFiles } from './write-tree-files.ts';
@@ -0,0 +1 @@
1
+ export declare function makeAnswerQueue<T>(answers: readonly T[]): () => T;
@@ -0,0 +1 @@
1
+ export declare function makeRejectingStub(failure: Error): import("bun:test").Mock<(...callArguments: readonly unknown[]) => Promise<never>>;
@@ -0,0 +1 @@
1
+ export declare function makeRepeatingAnswerQueue<T>(answers: readonly [T, ...T[]]): () => T;
@@ -0,0 +1 @@
1
+ export declare function makeResolvingStub<Value>(value: Value): import("bun:test").Mock<(...callArguments: readonly unknown[]) => Promise<Value>>;
@@ -0,0 +1,2 @@
1
+ export type GitEnv = Readonly<Record<string, string | undefined>>;
2
+ export declare function readGitEnv(home: string, outerEnv?: GitEnv): GitEnv;
@@ -0,0 +1,2 @@
1
+ import type { GitEnv } from './read-git-env.ts';
2
+ export declare function readGitHead(repo: string, env: GitEnv): Promise<string>;
@@ -0,0 +1,5 @@
1
+ export interface PIDNamespaceSource {
2
+ readonly platform: NodeJS.Platform;
3
+ readonly readLink: (path: string) => string;
4
+ }
5
+ export declare function readRunFolderPrefix(name: string, source?: PIDNamespaceSource): string;
@@ -0,0 +1 @@
1
+ export declare function readStreamUntil(stream: ReadableStream<Uint8Array>, text: string): Promise<string>;
@@ -0,0 +1 @@
1
+ export declare function removeEnvOverrides(): void;
@@ -0,0 +1,2 @@
1
+ import type { GitEnv } from './read-git-env.ts';
2
+ export declare function runGit(cwd: string, env: GitEnv, args: readonly string[]): Promise<void>;
@@ -0,0 +1 @@
1
+ export declare function updateEnv(name: string, value: string | undefined): void;
@@ -0,0 +1,6 @@
1
+ export interface WaitForOptions {
2
+ readonly intervalMs?: number;
3
+ readonly timeoutMs?: number;
4
+ readonly label?: string;
5
+ }
6
+ export declare function waitFor<T>(attempt: () => T | Promise<T>, options?: WaitForOptions): Promise<T>;
@@ -0,0 +1 @@
1
+ export declare function writeTreeFiles(directory: string, files: Readonly<Record<string, string>>): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zgeoff/testing",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Drive a real program from a Bun test, in a pseudo-terminal or as a process with a ready check",
5
5
  "keywords": [
6
6
  "bun",
@@ -28,6 +28,11 @@
28
28
  "bun": "./src/cli/index.ts",
29
29
  "default": "./src/cli/index.ts"
30
30
  },
31
+ "./helpers": {
32
+ "types": "./dist/helpers/index.d.ts",
33
+ "bun": "./src/helpers/index.ts",
34
+ "default": "./src/helpers/index.ts"
35
+ },
31
36
  "./process": {
32
37
  "types": "./dist/process/index.d.ts",
33
38
  "bun": "./src/process/index.ts",
@@ -46,7 +51,6 @@
46
51
  },
47
52
  "devDependencies": {
48
53
  "@types/bun": "1.4.4",
49
- "@zgeoff/std": "0.3.2",
50
54
  "tsrs": "0.18.0-ts7.1.0-dev.20260929",
51
55
  "typescript": "7.0.2"
52
56
  },
@@ -0,0 +1,24 @@
1
+ import { mock } from 'bun:test';
2
+
3
+ // A stand-in that records each call, reports its first call, and settles every call with the value
4
+ // only once the test releases it, so a test can act while a caller is inside it.
5
+ export function createBlockingStubKit<Value>(value: Value) {
6
+ const firstCall = Promise.withResolvers<readonly unknown[]>();
7
+ const released = Promise.withResolvers<void>();
8
+
9
+ const stub = mock(async (...callArguments: readonly unknown[]): Promise<Value> => {
10
+ firstCall.resolve(callArguments);
11
+
12
+ await released.promise;
13
+
14
+ return value;
15
+ });
16
+
17
+ return {
18
+ stub,
19
+ firstCall: firstCall.promise,
20
+ release: () => {
21
+ released.resolve();
22
+ },
23
+ };
24
+ }
@@ -0,0 +1,17 @@
1
+ import type { GitEnv } from './read-git-env.ts';
2
+ import { readGitHead } from './read-git-head.ts';
3
+ import { runGit } from './run-git.ts';
4
+ import { writeTreeFiles } from './write-tree-files.ts';
5
+
6
+ // Commits even when nothing changed, and returns the new commit.
7
+ export async function createGitCommit(
8
+ repo: string,
9
+ env: GitEnv,
10
+ files: Readonly<Record<string, string>>,
11
+ ): Promise<string> {
12
+ await writeTreeFiles(repo, files);
13
+ await runGit(repo, env, ['add', '-A']);
14
+ await runGit(repo, env, ['commit', '--quiet', '--allow-empty', '-m', 'change']);
15
+
16
+ return readGitHead(repo, env);
17
+ }
@@ -0,0 +1,25 @@
1
+ import { chmod, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+
4
+ // Writes a stand-in for sudo into the folder. It answers the probe `sudo -n true` with success. Any
5
+ // other call appends a line per argument to the record, `file <argument>` when the argument names a
6
+ // file that exists and `text <argument>` otherwise, then fails as a command that never starts does.
7
+ export async function createStubSudo(directory: string, record: string): Promise<void> {
8
+ const path = join(directory, 'sudo');
9
+
10
+ await writeFile(
11
+ path,
12
+ [
13
+ '#!/bin/bash',
14
+ `[ "$*" = '-n true' ] && exit 0`,
15
+ 'for argument in "$@"; do',
16
+ ' if [ -f "$argument" ]; then kind=file; else kind=text; fi',
17
+ ` printf '%s %s\\n' "$kind" "$argument" >> '${record.replaceAll("'", String.raw`'\''`)}'`,
18
+ 'done',
19
+ 'exit 1',
20
+ '',
21
+ ].join('\n'),
22
+ );
23
+
24
+ await chmod(path, 0o755);
25
+ }
@@ -0,0 +1,3 @@
1
+ // The original value of each variable that updateEnv has overridden, or undefined when it was
2
+ // unset. A variable is recorded the first time its name is overridden.
3
+ export const envOriginals = new Map<string, string | undefined>();
@@ -0,0 +1,19 @@
1
+ export { createBlockingStubKit } from './create-blocking-stub-kit.ts';
2
+ export { createGitCommit } from './create-git-commit.ts';
3
+ export { createStubSudo } from './create-stub-sudo.ts';
4
+ export { makeAnswerQueue } from './make-answer-queue.ts';
5
+ export { makeRepeatingAnswerQueue } from './make-repeating-answer-queue.ts';
6
+ export { makeRejectingStub } from './make-rejecting-stub.ts';
7
+ export { makeResolvingStub } from './make-resolving-stub.ts';
8
+ export { readGitEnv } from './read-git-env.ts';
9
+ export type { GitEnv } from './read-git-env.ts';
10
+ export { readGitHead } from './read-git-head.ts';
11
+ export { readRunFolderPrefix } from './read-run-folder-prefix.ts';
12
+ export type { PIDNamespaceSource } from './read-run-folder-prefix.ts';
13
+ export { readStreamUntil } from './read-stream-until.ts';
14
+ export { removeEnvOverrides } from './remove-env-overrides.ts';
15
+ export { runGit } from './run-git.ts';
16
+ export { updateEnv } from './update-env.ts';
17
+ export { waitFor } from './wait-for.ts';
18
+ export type { WaitForOptions } from './wait-for.ts';
19
+ export { writeTreeFiles } from './write-tree-files.ts';
@@ -0,0 +1,19 @@
1
+ // Returns a function that answers each call with the next of the answers, in order. A call past
2
+ // the last answer throws, so a test fails when the code under test asks more often than expected.
3
+ // An answer may be null or undefined.
4
+ export function makeAnswerQueue<T>(answers: readonly T[]): () => T {
5
+ const boxes = answers.map((value) => ({ value }));
6
+ let calls = 0;
7
+
8
+ return () => {
9
+ const box = boxes[calls];
10
+
11
+ if (box === undefined) {
12
+ throw new Error(`the answer queue ran out after ${boxes.length} answer(s)`);
13
+ }
14
+
15
+ calls += 1;
16
+
17
+ return box.value;
18
+ };
19
+ }
@@ -0,0 +1,8 @@
1
+ import { mock } from 'bun:test';
2
+
3
+ // A stand-in that records each call and rejects with the failure, whatever its arguments.
4
+ export function makeRejectingStub(failure: Error) {
5
+ return mock<(...callArguments: readonly unknown[]) => Promise<never>>(() =>
6
+ Promise.reject(failure),
7
+ );
8
+ }
@@ -0,0 +1,19 @@
1
+ // Returns a function that answers each call with the next of the answers, in order, and with the
2
+ // last one again once they run out. Use it for code that polls until a deadline, where the number
3
+ // of calls depends on the clock. An answer may be null or undefined.
4
+ export function makeRepeatingAnswerQueue<T>(answers: readonly [T, ...T[]]): () => T {
5
+ const boxes = answers.map((value) => ({ value }));
6
+ let calls = 0;
7
+
8
+ return () => {
9
+ const box = boxes[Math.min(calls, boxes.length - 1)];
10
+
11
+ if (box === undefined) {
12
+ throw new Error('the answer queue holds no answer');
13
+ }
14
+
15
+ calls += 1;
16
+
17
+ return box.value;
18
+ };
19
+ }
@@ -0,0 +1,8 @@
1
+ import { mock } from 'bun:test';
2
+
3
+ // A stand-in that records each call and resolves with the value, whatever its arguments.
4
+ export function makeResolvingStub<Value>(value: Value) {
5
+ return mock<(...callArguments: readonly unknown[]) => Promise<Value>>(() =>
6
+ Promise.resolve(value),
7
+ );
8
+ }
@@ -0,0 +1,38 @@
1
+ import { join } from 'node:path';
2
+
3
+ export type GitEnv = Readonly<Record<string, string | undefined>>;
4
+
5
+ // A pre-push hook in a linked worktree exports GIT_DIR, which would point a test's git calls at
6
+ // the real repository.
7
+ export function readGitEnv(home: string, outerEnv: GitEnv = process.env): GitEnv {
8
+ return {
9
+ PATH: outerEnv['PATH'],
10
+ HOME: home,
11
+ GIT_CONFIG_GLOBAL: '/dev/null',
12
+ GIT_CONFIG_NOSYSTEM: '1',
13
+ GIT_AUTHOR_NAME: 'Test',
14
+ GIT_AUTHOR_EMAIL: 'test@example.com',
15
+ GIT_COMMITTER_NAME: 'Test',
16
+ GIT_COMMITTER_EMAIL: 'test@example.com',
17
+ ...buildMiseEnv(outerEnv),
18
+ };
19
+ }
20
+
21
+ // A tool on PATH can be a mise shim. mise keeps its installs and the configs it trusts under HOME,
22
+ // so a shim run with the test's HOME refuses the real global config as untrusted.
23
+ function buildMiseEnv(outerEnv: GitEnv): GitEnv {
24
+ const realHome = outerEnv['HOME'];
25
+
26
+ if (realHome === undefined) {
27
+ return {};
28
+ }
29
+
30
+ return {
31
+ MISE_DATA_DIR:
32
+ outerEnv['MISE_DATA_DIR'] ??
33
+ join(outerEnv['XDG_DATA_HOME'] ?? join(realHome, '.local', 'share'), 'mise'),
34
+ MISE_STATE_DIR:
35
+ outerEnv['MISE_STATE_DIR'] ??
36
+ join(outerEnv['XDG_STATE_HOME'] ?? join(realHome, '.local', 'state'), 'mise'),
37
+ };
38
+ }
@@ -0,0 +1,22 @@
1
+ import type { GitEnv } from './read-git-env.ts';
2
+
3
+ export async function readGitHead(repo: string, env: GitEnv): Promise<string> {
4
+ const subprocess = Bun.spawn(['git', 'rev-parse', 'HEAD'], {
5
+ cwd: repo,
6
+ env,
7
+ stdout: 'pipe',
8
+ stderr: 'pipe',
9
+ });
10
+
11
+ const [exitCode, stdout, stderr] = await Promise.all([
12
+ subprocess.exited,
13
+ new Response(subprocess.stdout).text(),
14
+ new Response(subprocess.stderr).text(),
15
+ ]);
16
+
17
+ if (exitCode !== 0) {
18
+ throw new Error(`git rev-parse HEAD failed: ${stderr}`);
19
+ }
20
+
21
+ return stdout.trim();
22
+ }
@@ -0,0 +1,31 @@
1
+ import { readlinkSync } from 'node:fs';
2
+
3
+ export interface PIDNamespaceSource {
4
+ readonly platform: NodeJS.Platform;
5
+
6
+ readonly readLink: (path: string) => string;
7
+ }
8
+
9
+ const hostSource: PIDNamespaceSource = { platform: process.platform, readLink: readlinkSync };
10
+
11
+ export function readRunFolderPrefix(name: string, source = hostSource): string {
12
+ return `${name}pid${process.pid}-ns${readPIDNamespace(source)}-`;
13
+ }
14
+
15
+ const namespaceLinkPattern = /^pid:\[(?<inode>\d+)\]$/u;
16
+
17
+ function readPIDNamespace(source: PIDNamespaceSource): string {
18
+ // Only Linux has PID namespaces, so elsewhere every process shares one.
19
+ if (source.platform !== 'linux') {
20
+ return 'host';
21
+ }
22
+
23
+ try {
24
+ return (
25
+ namespaceLinkPattern.exec(source.readLink('/proc/self/ns/pid'))?.groups?.['inode'] ??
26
+ 'unknown'
27
+ );
28
+ } catch {
29
+ return 'unknown';
30
+ }
31
+ }
@@ -0,0 +1,18 @@
1
+ export async function readStreamUntil(
2
+ stream: ReadableStream<Uint8Array>,
3
+ text: string,
4
+ ): Promise<string> {
5
+ const decoder = new TextDecoder();
6
+
7
+ let output = '';
8
+
9
+ for await (const chunk of stream.values({ preventCancel: true })) {
10
+ output += decoder.decode(chunk, { stream: true });
11
+
12
+ if (output.includes(text)) {
13
+ return output;
14
+ }
15
+ }
16
+
17
+ return output;
18
+ }
@@ -0,0 +1,15 @@
1
+ import { envOriginals } from './env-originals.ts';
2
+
3
+ // Puts back every variable that updateEnv overrode, deleting it when it was unset, and clears the
4
+ // record. Call it in an afterEach hook of the test preload: afterEach(removeEnvOverrides).
5
+ export function removeEnvOverrides(): void {
6
+ for (const [name, original] of envOriginals) {
7
+ if (original === undefined) {
8
+ delete process.env[name];
9
+ } else {
10
+ process.env[name] = original;
11
+ }
12
+ }
13
+
14
+ envOriginals.clear();
15
+ }
@@ -0,0 +1,11 @@
1
+ import type { GitEnv } from './read-git-env.ts';
2
+
3
+ export async function runGit(cwd: string, env: GitEnv, args: readonly string[]): Promise<void> {
4
+ const subprocess = Bun.spawn(['git', ...args], { cwd, env, stdout: 'ignore', stderr: 'pipe' });
5
+
6
+ if ((await subprocess.exited) !== 0) {
7
+ throw new Error(
8
+ `git ${args.join(' ')} failed: ${await new Response(subprocess.stderr).text()}`,
9
+ );
10
+ }
11
+ }
@@ -0,0 +1,16 @@
1
+ import { envOriginals } from './env-originals.ts';
2
+
3
+ // Sets process.env[name], or deletes it when value is undefined, and records the original so
4
+ // removeEnvOverrides can put it back. Call removeEnvOverrides in an afterEach hook of the test
5
+ // preload, so no override outlives its test.
6
+ export function updateEnv(name: string, value: string | undefined): void {
7
+ if (!envOriginals.has(name)) {
8
+ envOriginals.set(name, process.env[name]);
9
+ }
10
+
11
+ if (value === undefined) {
12
+ delete process.env[name];
13
+ } else {
14
+ process.env[name] = value;
15
+ }
16
+ }
@@ -0,0 +1,87 @@
1
+ export interface WaitForOptions {
2
+ readonly intervalMs?: number;
3
+
4
+ readonly timeoutMs?: number;
5
+
6
+ // Names what the test waits for, in the timeout message.
7
+ readonly label?: string;
8
+ }
9
+
10
+ const defaultIntervalMs = 20;
11
+ const defaultTimeoutMs = 5000;
12
+
13
+ const pendingAttempt = new Error('the attempt had not finished');
14
+
15
+ // Calls attempt at once, and again every intervalMs while it throws or rejects. Resolves with the
16
+ // first value it returns. Once timeoutMs passes, even while an attempt is pending, throws an error
17
+ // whose cause is the last error. No attempt starts after the deadline.
18
+ export async function waitFor<T>(
19
+ attempt: () => T | Promise<T>,
20
+ options: WaitForOptions = {},
21
+ ): Promise<T> {
22
+ const intervalMs = options.intervalMs ?? defaultIntervalMs;
23
+ const timeoutMs = options.timeoutMs ?? defaultTimeoutMs;
24
+ const deadline = Date.now() + timeoutMs;
25
+ let lastError: unknown = pendingAttempt;
26
+
27
+ for (;;) {
28
+ const remainingMs = deadline - Date.now();
29
+
30
+ if (remainingMs <= 0) {
31
+ throw buildTimeoutError(timeoutMs, options.label, lastError);
32
+ }
33
+
34
+ const outcome = await raceDeadline(attempt, remainingMs);
35
+
36
+ if (outcome.kind === 'value') {
37
+ return outcome.value;
38
+ }
39
+
40
+ if (outcome.kind === 'error') {
41
+ lastError = outcome.error;
42
+ }
43
+
44
+ const leftMs = Math.max(deadline - Date.now(), 0);
45
+
46
+ await Bun.sleep(Math.min(intervalMs, leftMs));
47
+ }
48
+ }
49
+
50
+ function buildTimeoutError(timeoutMs: number, label: string | undefined, cause: unknown): Error {
51
+ const reason = cause instanceof Error ? cause.message : String(cause);
52
+ const subject = label === undefined ? '' : ` waiting for ${label}`;
53
+
54
+ return new Error(`timed out after ${timeoutMs} ms${subject}: ${reason}`, { cause });
55
+ }
56
+
57
+ type Outcome<T> =
58
+ | { readonly kind: 'value'; readonly value: T }
59
+ | { readonly kind: 'error'; readonly error: unknown }
60
+ | { readonly kind: 'deadline' };
61
+
62
+ async function raceDeadline<T>(
63
+ attempt: () => T | Promise<T>,
64
+ remainingMs: number,
65
+ ): Promise<Outcome<T>> {
66
+ let timer: ReturnType<typeof setTimeout> | undefined;
67
+
68
+ const deadline = new Promise<Outcome<T>>((resolve) => {
69
+ timer = setTimeout(() => {
70
+ resolve({ kind: 'deadline' });
71
+ }, remainingMs);
72
+ });
73
+
74
+ const settled = (async (): Promise<Outcome<T>> => {
75
+ try {
76
+ return { kind: 'value', value: await attempt() };
77
+ } catch (error) {
78
+ return { kind: 'error', error };
79
+ }
80
+ })();
81
+
82
+ try {
83
+ return await Promise.race([settled, deadline]);
84
+ } finally {
85
+ clearTimeout(timer);
86
+ }
87
+ }
@@ -0,0 +1,14 @@
1
+ import { mkdir, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+
4
+ export async function writeTreeFiles(
5
+ directory: string,
6
+ files: Readonly<Record<string, string>>,
7
+ ): Promise<void> {
8
+ await Promise.all(
9
+ Object.entries(files).map(async ([path, content]: readonly [string, string]) => {
10
+ await mkdir(dirname(join(directory, path)), { recursive: true });
11
+ await writeFile(join(directory, path), content);
12
+ }),
13
+ );
14
+ }