@terreno/test 57.20.0 → 57.21.0

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.
package/CHANGELOG.md CHANGED
@@ -20,6 +20,56 @@ Upgrade notes for consumer action live in [`mcp-server/src/docs/upgrades/`](mcp-
20
20
 
21
21
  Unreleased changes live in [`changelog/unreleased/`](changelog/unreleased/). Add one Markdown file per feature (see that directory's README) instead of editing this section.
22
22
 
23
+ ## [57.21.0] - 2026-11-01
24
+
25
+ Upgrade note: [`mcp-server/src/docs/upgrades/57.21.0.md`](mcp-server/src/docs/upgrades/57.21.0.md).
26
+
27
+ ### Breaking
28
+
29
+ - The `terreno-scan` plugin is now `terreno-loop`, and its skills are renamed from `terreno-scan-*` to `terreno-loop-*`. The resident loop `terreno-scan-loop` is now `terreno-loop-run`: `/terreno-loop:run` in Claude Code, `/terreno-loop-run` in Cursor, `$terreno-loop-run` in Codex. Claude Code moves existing installs over through the marketplace `renames` entry. In Cursor and Codex, uninstall `terreno-scan` and install `terreno-loop`. Campaign state stays at `.terreno/scan/<goal>.json`, so campaigns already in progress resume.
30
+
31
+ ### Added
32
+
33
+ - `@terreno/admin-spa` serves an MCP OAuth consent screen at `/console/oauth/consent`, so a backend with no product frontend can set `mcpOAuth.consentUrl` to `${issuer}/console/oauth/consent`. Any signed-in user can approve or deny a request with their Better Auth session; signed-out users sign in and return through the login screen's new `returnTo` parameter, which accepts only in-app paths.
34
+ - Claude Code plugins now publish to npm with every release, as `@terreno/agent-plugin` and `@terreno/agent-plugin-loop`. A new `terreno-releases` marketplace installs them at the latest stable release. To pin one release, add `TerrenoLabs/terreno#<version>` instead. See [Install agent skills](docs/how-to/install-agent-skills.md#pick-a-channel).
35
+ - The generated Claude plugin manifest no longer pins `version`. Before this change, plugins installed from the `TerrenoLabs/terreno` marketplace stayed on the `2.12.0` copy, because their version never changed. They now update on every commit. Run `/plugin update terreno@terreno-plugins` once to leave `2.12.0`.
36
+ - The `terreno-planning` lifecycle plugin (2.13.0) plans e2e tests and manual regression cases in every IP:
37
+
38
+ - Grow requires `## E2E tests` and `## Regression cases` sections (either may be `None — <reason>`), read from the e2e guide at `docs/testing/e2e.md` or a `## Testing conventions` override in AGENTS.md or CLAUDE.md.
39
+ - Regression cases stay minimal: most features add none. A case is only for what a developer or QA must check by hand, such as push notifications, and Roast fails one that repeats an existing case.
40
+ - Pick writes each planned spec in the task that delivers it, and Roast runs it; a missing or failing row is `FAIL`.
41
+ - Brew gates on every planned spec and merges regression cases into `docs/regression/<area>.md` with the next free ID.
42
+ - Taste re-checks both sections after behaviour-changing fixes and renumbers regression ID collisions with `master`.
43
+ - `bun run check:lifecycle-skills` enforces these phrases in every stage.
44
+ - New `backfill-regression` skill proposes manual regression cases one area at a time and writes only the sets the human approves.
45
+ - A consumer opts out of manual regression suites with `Regression suites | none` in its `## Testing conventions` table.
46
+ - The `terreno-planning` lifecycle plugin (2.14.0) grows an end-user guide with every feature:
47
+
48
+ - Every IP has a `## User guide` section listing the guide pages it adds, updates, or retires, or `None — <reason>`. Pages live in `docs/user-guide/<area>/<feature>.md`, one feature per page, with `title`, `audience`, `platforms`, and `questions` frontmatter that chat agents use to answer "how do I…" questions.
49
+ - Pick writes each page in the task that ships the feature, Roast checks it against the shipped screens, Brew gates on it and the index, and Taste keeps it current after fixes.
50
+ - A repo opts out with `| User guide | none — <reason> |` in a `## User guide conventions` table in AGENTS.md or CLAUDE.md.
51
+ - New `backfill-user-guide` skill drafts pages for features that shipped without one, one area at a time, and writes only the pages the human approves.
52
+ - `bun run check:user-guide` validates the pages and index (CI `repo-policies`); `--uncovered <app dir>` lists screens no page names.
53
+ - Terreno's own guide covers the example app's main features.
54
+ - `@terreno/api`: opt-in `mcpRequestLog` on `TerrenoApp` records one metadata-only `McpRequestLog` row per MCP tool call (tool, user, credential, service token or OAuth client, duration, outcome, error class; never arguments, results, or error text), expiring after `retentionDays` (default 30).
55
+ - `@terreno/api`: opt-in `mcpToolSettings` on `TerrenoApp` registers every MCP tool in `McpToolSetting` at startup; tools an admin switches off are hidden from `tools/list` and rejected by `tools/call`.
56
+ - `@terreno/api`: deleting an `McpOAuthToken` row revokes its whole connection (token family) and keeps the rows. New `McpOAuthToken.revokeAllForUser` and `McpServiceToken.revokeAllForUser`.
57
+ - `@terreno/admin-backend`: `mcpAdminModels()` adds MCP admin screens (service tokens, OAuth clients, OAuth connections, request log, tool switches), `mcpAdminStatements` for RBAC, and `mcpAdminScripts()` adds `mcp-sign-out-everywhere`. See [Manage MCP from the admin panel](docs/how-to/manage-mcp-in-admin.md).
58
+ - Docs: [Expose an MCP server safely](docs/how-to/expose-mcp-server-safely.md) (OAuth, service tokens, Cloudflare Tunnel, Access) and the `bootstrap-mcp-server` skill for a single-binary MCP server with the admin console embedded.
59
+ - Every workspace package has a real-process smoke test and an e2e page:
60
+
61
+ - Each package's `e2e/smoke.ts` (or `smoke.spec.ts` for browser packages) runs its built output through its public entry: a server on a real port, the compiled binary, or a page in Chromium. `bun run --cwd <package> smoke` runs one; `bun run smoke` runs them all and prints each package's time. The CircleCI `smoke` job runs them on every package change.
62
+ - `@terreno/test` adds the smoke helpers `smokeMongoUri()`, `spawnUntilReady()`, `spawnExampleBackend()`, `runBin()`, and `freePort()`.
63
+ - The [E2E testing guide](docs/testing/e2e.md) explains the test tiers and links one page per package under `docs/testing/e2e/`.
64
+ - Manual regression cases live in `docs/regression/<area>.md`, one file per area, and `bun run check:regression-suites` validates them.
65
+ - example-frontend's smoke serves a web export that `bun run --cwd example-frontend export:smoke` builds once with a placeholder API URL; the smoke swaps in a `freePort()` API URL as it serves the bundle, so the 30 s smoke no longer rebuilds the export. `spawnUntilReady()` takes `stopGraceMs`, and `spawnExampleBackend()` stops example-backend after 0.5 s instead of 5 s.
66
+ - Every workspace package has a `typecheck` script that runs `tsc` over source and test files through a new `tsconfig.typecheck.json`. Root `bun run lint` ends with `bun run typecheck`, and CircleCI runs it in a new `typecheck` job. Test files that had type errors were fixed.
67
+
68
+ ### Changed
69
+
70
+ - `@terreno/api`: deleting an `McpOAuthToken` row with document or query `deleteOne` now revokes that row's whole token family (the connection) and keeps the rows instead of removing one pair. `deleteMany` is unchanged.
71
+ - `@terreno/ui`: new `theme.field` tokens (`background`, `backgroundDisabled`, `border`, `borderFocus`, `borderError`, `borderDisabled`) style form inputs. `TextField`, `SelectField`, `DateTimeField`, `HeightField`, and `OtpField` read them instead of `surface.base` and `border.dark`. Defaults equal the old colors, but overriding `surface` or `border` no longer recolors those fields; use `setTheme({field: ...})`.
72
+
23
73
  ## [57.20.0] - 2026-10-30
24
74
 
25
75
  Upgrade note: [`mcp-server/src/docs/upgrades/57.20.0.md`](mcp-server/src/docs/upgrades/57.20.0.md).
package/dist/index.d.ts CHANGED
@@ -19,6 +19,11 @@ export { buildDatabaseUri, DEFAULT_LOCAL_MONGO_URI, type EnsureTestMongooseConne
19
19
  export { ensureMongoBinary } from "./mongo/ensureMongoBinary";
20
20
  export { getMongoServerUri, initializeModels, type MemoryMongoHandle, type MongoServerOptions, resolveMongoLaunchTimeoutMs, restartMongoServer, startMongoServer, stopMongoServer, waitForDatabaseReady, } from "./mongo/mongoServer";
21
21
  export { type BackendPreloadOptions, registerBackendPreload, registerSimpleMongoPreload, type SimpleMongoPreloadOptions, } from "./preload/registerBackendPreload";
22
+ export { freePort } from "./smoke/freePort";
23
+ export { type RunBinOptions, type RunBinResult, runBin } from "./smoke/runBin";
24
+ export { type SmokeMongoUriOptions, smokeMongoUri, stopSmokeMongo } from "./smoke/smokeMongoUri";
25
+ export { type ExampleBackend, type SpawnExampleBackendOptions, spawnExampleBackend, } from "./smoke/spawnExampleBackend";
26
+ export { type SpawnedProcess, type SpawnUntilReadyOptions, spawnUntilReady, } from "./smoke/spawnUntilReady";
22
27
  export { type FreezeTimeInput, type FreezeTimeOptions, freezeTime } from "./time/freezeTime";
23
28
  export { type AbortTestTransactionOptions, abortTestTransaction, getTestSession, installTransactionPatches, isTestTransactionOperationCancelled, resetTestSessionAfterReconnect, startTestTransaction, TestTransactionOperationCancelledError, } from "./transaction/testTransaction";
24
29
  export { ensureAllIndexes } from "./utils/ensureAllIndexes";
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.waitUntil = exports.waitForCalls = exports.waitForDocuments = exports.waitForDocument = exports.timeout = exports.ensureAllIndexes = exports.TestTransactionOperationCancelledError = exports.startTestTransaction = exports.resetTestSessionAfterReconnect = exports.isTestTransactionOperationCancelled = exports.installTransactionPatches = exports.getTestSession = exports.abortTestTransaction = exports.freezeTime = exports.registerSimpleMongoPreload = exports.registerBackendPreload = exports.waitForDatabaseReady = exports.stopMongoServer = exports.startMongoServer = exports.restartMongoServer = exports.resolveMongoLaunchTimeoutMs = exports.initializeModels = exports.getMongoServerUri = exports.ensureMongoBinary = exports.splitMongoUri = exports.ensureTestMongooseConnected = exports.DEFAULT_LOCAL_MONGO_URI = exports.buildDatabaseUri = exports.registerTwilioMock = exports.registerSentryBunMock = exports.registerSendGridMock = exports.registerTerrenoNotifierMocks = exports.registerGoogleAuthMock = exports.registerGcsMock = exports.registerExpoPushMock = exports.registerCloudTasksMock = exports.decodeCloudTaskBody = exports.mockLanguageModelStreamParts = exports.createMockLanguageModel = exports.registerLogSilencing = exports.createLogSilencer = exports.getBaseServer = exports.authWithToken = exports.authAsUser = exports.setTerrenoTestEnv = exports.createMongoTestCache = exports.collectPropertyPaths = exports.assertStrictResponseProperties = exports.expectAPIError = void 0;
3
+ exports.ensureAllIndexes = exports.TestTransactionOperationCancelledError = exports.startTestTransaction = exports.resetTestSessionAfterReconnect = exports.isTestTransactionOperationCancelled = exports.installTransactionPatches = exports.getTestSession = exports.abortTestTransaction = exports.freezeTime = exports.spawnUntilReady = exports.spawnExampleBackend = exports.stopSmokeMongo = exports.smokeMongoUri = exports.runBin = exports.freePort = exports.registerSimpleMongoPreload = exports.registerBackendPreload = exports.waitForDatabaseReady = exports.stopMongoServer = exports.startMongoServer = exports.restartMongoServer = exports.resolveMongoLaunchTimeoutMs = exports.initializeModels = exports.getMongoServerUri = exports.ensureMongoBinary = exports.splitMongoUri = exports.ensureTestMongooseConnected = exports.DEFAULT_LOCAL_MONGO_URI = exports.buildDatabaseUri = exports.registerTwilioMock = exports.registerSentryBunMock = exports.registerSendGridMock = exports.registerTerrenoNotifierMocks = exports.registerGoogleAuthMock = exports.registerGcsMock = exports.registerExpoPushMock = exports.registerCloudTasksMock = exports.decodeCloudTaskBody = exports.mockLanguageModelStreamParts = exports.createMockLanguageModel = exports.registerLogSilencing = exports.createLogSilencer = exports.getBaseServer = exports.authWithToken = exports.authAsUser = exports.setTerrenoTestEnv = exports.createMongoTestCache = exports.collectPropertyPaths = exports.assertStrictResponseProperties = exports.expectAPIError = void 0;
4
+ exports.waitUntil = exports.waitForCalls = exports.waitForDocuments = exports.waitForDocument = exports.timeout = void 0;
4
5
  var expectAPIError_1 = require("./assertions/expectAPIError");
5
6
  Object.defineProperty(exports, "expectAPIError", { enumerable: true, get: function () { return expectAPIError_1.expectAPIError; } });
6
7
  var strictResponseProperties_1 = require("./assertions/strictResponseProperties");
@@ -57,6 +58,17 @@ Object.defineProperty(exports, "waitForDatabaseReady", { enumerable: true, get:
57
58
  var registerBackendPreload_1 = require("./preload/registerBackendPreload");
58
59
  Object.defineProperty(exports, "registerBackendPreload", { enumerable: true, get: function () { return registerBackendPreload_1.registerBackendPreload; } });
59
60
  Object.defineProperty(exports, "registerSimpleMongoPreload", { enumerable: true, get: function () { return registerBackendPreload_1.registerSimpleMongoPreload; } });
61
+ var freePort_1 = require("./smoke/freePort");
62
+ Object.defineProperty(exports, "freePort", { enumerable: true, get: function () { return freePort_1.freePort; } });
63
+ var runBin_1 = require("./smoke/runBin");
64
+ Object.defineProperty(exports, "runBin", { enumerable: true, get: function () { return runBin_1.runBin; } });
65
+ var smokeMongoUri_1 = require("./smoke/smokeMongoUri");
66
+ Object.defineProperty(exports, "smokeMongoUri", { enumerable: true, get: function () { return smokeMongoUri_1.smokeMongoUri; } });
67
+ Object.defineProperty(exports, "stopSmokeMongo", { enumerable: true, get: function () { return smokeMongoUri_1.stopSmokeMongo; } });
68
+ var spawnExampleBackend_1 = require("./smoke/spawnExampleBackend");
69
+ Object.defineProperty(exports, "spawnExampleBackend", { enumerable: true, get: function () { return spawnExampleBackend_1.spawnExampleBackend; } });
70
+ var spawnUntilReady_1 = require("./smoke/spawnUntilReady");
71
+ Object.defineProperty(exports, "spawnUntilReady", { enumerable: true, get: function () { return spawnUntilReady_1.spawnUntilReady; } });
60
72
  var freezeTime_1 = require("./time/freezeTime");
61
73
  Object.defineProperty(exports, "freezeTime", { enumerable: true, get: function () { return freezeTime_1.freezeTime; } });
62
74
  var testTransaction_1 = require("./transaction/testTransaction");
@@ -0,0 +1,32 @@
1
+ import type { Subprocess } from "bun";
2
+ type SmokeChild = Subprocess<"ignore", "pipe", "pipe">;
3
+ export interface ChildOutput {
4
+ /** stdout and stderr together, in arrival order. */
5
+ combined: () => string;
6
+ stdout: () => string;
7
+ stderr: () => string;
8
+ /** Resolves once both streams have closed. */
9
+ drained: Promise<void>;
10
+ }
11
+ /**
12
+ * Signals the child's whole process group, so a wrapper (`sh -c`, `bun run`) and the server it
13
+ * started both get it. Falls back to the child alone when the group is already gone.
14
+ */
15
+ export declare const killGroup: (child: SmokeChild, signal: NodeJS.Signals) => void;
16
+ /**
17
+ * Kills every tracked child that is still running; the smoke's exit and signal handlers call it.
18
+ * @internal Exported for tests.
19
+ */
20
+ export declare const killLiveChildren: () => void;
21
+ /**
22
+ * Starts a child in its own process group and tracks it, so it and anything it starts die with
23
+ * the smoke, even when the smoke crashes or is interrupted.
24
+ */
25
+ export declare const spawnTracked: ({ cmd, cwd, env, }: {
26
+ cmd: string[];
27
+ cwd?: string;
28
+ env?: Record<string, string | undefined>;
29
+ }) => SmokeChild;
30
+ /** Reads a child's stdout and stderr as they arrive. */
31
+ export declare const collectOutput: (child: SmokeChild) => ChildOutput;
32
+ export {};
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.collectOutput = exports.spawnTracked = exports.killLiveChildren = exports.killGroup = void 0;
4
+ const liveChildren = new Set();
5
+ let isCleanupRegistered = false;
6
+ /**
7
+ * Signals the child's whole process group, so a wrapper (`sh -c`, `bun run`) and the server it
8
+ * started both get it. Falls back to the child alone when the group is already gone.
9
+ */
10
+ const killGroup = (child, signal) => {
11
+ try {
12
+ process.kill(-child.pid, signal);
13
+ }
14
+ catch {
15
+ child.kill(signal);
16
+ }
17
+ };
18
+ exports.killGroup = killGroup;
19
+ /**
20
+ * Kills every tracked child that is still running; the smoke's exit and signal handlers call it.
21
+ * @internal Exported for tests.
22
+ */
23
+ const killLiveChildren = () => {
24
+ for (const child of liveChildren) {
25
+ (0, exports.killGroup)(child, "SIGKILL");
26
+ }
27
+ liveChildren.clear();
28
+ };
29
+ exports.killLiveChildren = killLiveChildren;
30
+ const registerCleanup = () => {
31
+ if (isCleanupRegistered) {
32
+ return;
33
+ }
34
+ isCleanupRegistered = true;
35
+ process.on("exit", exports.killLiveChildren);
36
+ for (const [signal, code] of [
37
+ ["SIGINT", 130],
38
+ ["SIGTERM", 143],
39
+ ]) {
40
+ process.once(signal, () => {
41
+ (0, exports.killLiveChildren)();
42
+ process.exit(code);
43
+ });
44
+ }
45
+ };
46
+ /**
47
+ * Starts a child in its own process group and tracks it, so it and anything it starts die with
48
+ * the smoke, even when the smoke crashes or is interrupted.
49
+ */
50
+ const spawnTracked = ({ cmd, cwd, env, }) => {
51
+ registerCleanup();
52
+ const child = Bun.spawn({
53
+ cmd,
54
+ cwd,
55
+ detached: true,
56
+ env: { ...process.env, ...env },
57
+ stderr: "pipe",
58
+ stdin: "ignore",
59
+ stdout: "pipe",
60
+ });
61
+ liveChildren.add(child);
62
+ void child.exited.then(() => liveChildren.delete(child));
63
+ return child;
64
+ };
65
+ exports.spawnTracked = spawnTracked;
66
+ /** Reads a child's stdout and stderr as they arrive. */
67
+ const collectOutput = (child) => {
68
+ let combined = "";
69
+ const streams = { stderr: "", stdout: "" };
70
+ const drain = async (name) => {
71
+ const decoder = new TextDecoder();
72
+ for await (const chunk of child[name]) {
73
+ const text = decoder.decode(chunk, { stream: true });
74
+ streams[name] += text;
75
+ combined += text;
76
+ }
77
+ };
78
+ return {
79
+ combined: () => combined,
80
+ drained: Promise.all([drain("stdout"), drain("stderr")]).then(() => undefined),
81
+ stderr: () => streams.stderr,
82
+ stdout: () => streams.stdout,
83
+ };
84
+ };
85
+ exports.collectOutput = collectOutput;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Asks the OS for an unused TCP port on 127.0.0.1 so parallel or repeated smokes never fight
3
+ * over a fixed port. The port is free when this resolves; bind it promptly.
4
+ */
5
+ export declare const freePort: () => Promise<number>;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.freePort = void 0;
4
+ const node_net_1 = require("node:net");
5
+ /**
6
+ * Asks the OS for an unused TCP port on 127.0.0.1 so parallel or repeated smokes never fight
7
+ * over a fixed port. The port is free when this resolves; bind it promptly.
8
+ */
9
+ const freePort = async () => {
10
+ const server = (0, node_net_1.createServer)();
11
+ await new Promise((resolve, reject) => {
12
+ server.once("error", reject);
13
+ server.listen(0, "127.0.0.1", () => resolve());
14
+ });
15
+ const address = server.address();
16
+ await new Promise((resolve) => server.close(() => resolve()));
17
+ if (!address || typeof address === "string") {
18
+ throw new Error("freePort: the OS did not assign a TCP port");
19
+ }
20
+ return address.port;
21
+ };
22
+ exports.freePort = freePort;
@@ -0,0 +1,21 @@
1
+ export interface RunBinOptions {
2
+ /** A command on PATH, or a path to a script. `.js`, `.mjs`, `.cjs`, and `.ts` files run with Bun. */
3
+ bin: string;
4
+ args?: string[];
5
+ cwd?: string;
6
+ /** Merged over the parent environment. */
7
+ env?: Record<string, string | undefined>;
8
+ /** The process and everything it started are killed, and the call rejects, after this long. Default 30 000 ms. */
9
+ timeoutMs?: number;
10
+ }
11
+ export interface RunBinResult {
12
+ exitCode: number;
13
+ stdout: string;
14
+ stderr: string;
15
+ }
16
+ /**
17
+ * Runs a binary to completion and returns its exit code and output. A non-zero exit resolves;
18
+ * assert on `exitCode`. Running longer than `timeoutMs` rejects. Background processes the
19
+ * binary leaves behind are killed when it exits.
20
+ */
21
+ export declare const runBin: ({ bin, args, cwd, env, timeoutMs, }: RunBinOptions) => Promise<RunBinResult>;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runBin = void 0;
4
+ const childProcesses_1 = require("./childProcesses");
5
+ const DEFAULT_TIMEOUT_MS = 30000;
6
+ const SCRIPT_EXTENSION = /\.(c|m)?(j|t)s$/;
7
+ /**
8
+ * Runs a binary to completion and returns its exit code and output. A non-zero exit resolves;
9
+ * assert on `exitCode`. Running longer than `timeoutMs` rejects. Background processes the
10
+ * binary leaves behind are killed when it exits.
11
+ */
12
+ const runBin = async ({ bin, args = [], cwd, env, timeoutMs = DEFAULT_TIMEOUT_MS, }) => {
13
+ const cmd = SCRIPT_EXTENSION.test(bin) ? [process.execPath, bin, ...args] : [bin, ...args];
14
+ const child = (0, childProcesses_1.spawnTracked)({ cmd, cwd, env });
15
+ const output = (0, childProcesses_1.collectOutput)(child);
16
+ let timer;
17
+ const isTimedOut = await Promise.race([
18
+ child.exited.then(() => false),
19
+ new Promise((resolve) => {
20
+ timer = setTimeout(() => resolve(true), timeoutMs);
21
+ }),
22
+ ]);
23
+ clearTimeout(timer);
24
+ // Grandchildren keep the pipes open, so the whole group goes before reading the rest.
25
+ (0, childProcesses_1.killGroup)(child, "SIGKILL");
26
+ const exitCode = await child.exited;
27
+ await output.drained;
28
+ if (isTimedOut) {
29
+ throw new Error(`${cmd.join(" ")} timed out after ${timeoutMs} ms.\n${output.combined()}`);
30
+ }
31
+ return { exitCode, stderr: output.stderr(), stdout: output.stdout() };
32
+ };
33
+ exports.runBin = runBin;
@@ -0,0 +1,11 @@
1
+ export interface SmokeMongoUriOptions {
2
+ /** Database name written into the URI. Default `terrenoSmoke`. */
3
+ databaseName?: string;
4
+ }
5
+ /**
6
+ * MongoDB URI for a smoke's server. Uses `TERRENO_TEST_MONGODB_URI` when set (the CI sidecar);
7
+ * otherwise starts one single-node in-memory replica set per process, so change streams work.
8
+ */
9
+ export declare const smokeMongoUri: ({ databaseName, }?: SmokeMongoUriOptions) => Promise<string>;
10
+ /** Stops the in-memory replica set that `smokeMongoUri` started, if any. */
11
+ export declare const stopSmokeMongo: () => Promise<void>;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stopSmokeMongo = exports.smokeMongoUri = void 0;
4
+ const connection_1 = require("../mongo/connection");
5
+ const mongoServer_1 = require("../mongo/mongoServer");
6
+ let replSet;
7
+ const startReplSet = async () => {
8
+ const { MongoMemoryReplSet } = await import("mongodb-memory-server-global");
9
+ const started = new MongoMemoryReplSet({
10
+ instanceOpts: [{ launchTimeout: (0, mongoServer_1.resolveMongoLaunchTimeoutMs)() }],
11
+ replSet: { args: ["--wiredTigerCacheSizeGB", "0.25"], count: 1, storageEngine: "wiredTiger" },
12
+ });
13
+ await started.start();
14
+ await started.waitUntilRunning();
15
+ return started;
16
+ };
17
+ /**
18
+ * MongoDB URI for a smoke's server. Uses `TERRENO_TEST_MONGODB_URI` when set (the CI sidecar);
19
+ * otherwise starts one single-node in-memory replica set per process, so change streams work.
20
+ */
21
+ const smokeMongoUri = async ({ databaseName = "terrenoSmoke", } = {}) => {
22
+ const externalUri = process.env.TERRENO_TEST_MONGODB_URI?.trim();
23
+ if (externalUri) {
24
+ return (0, connection_1.buildDatabaseUri)({ databaseName, uri: externalUri });
25
+ }
26
+ replSet ??= startReplSet().catch((error) => {
27
+ replSet = undefined;
28
+ throw error;
29
+ });
30
+ const handle = await replSet;
31
+ return (0, connection_1.buildDatabaseUri)({ databaseName, uri: handle.getUri() });
32
+ };
33
+ exports.smokeMongoUri = smokeMongoUri;
34
+ /** Stops the in-memory replica set that `smokeMongoUri` started, if any. */
35
+ const stopSmokeMongo = async () => {
36
+ const pending = replSet;
37
+ replSet = undefined;
38
+ if (!pending) {
39
+ return;
40
+ }
41
+ const handle = await pending;
42
+ await handle.stop({ doCleanup: true, force: true });
43
+ };
44
+ exports.stopSmokeMongo = stopSmokeMongo;
@@ -0,0 +1,23 @@
1
+ import { type SpawnedProcess } from "./spawnUntilReady";
2
+ export interface SpawnExampleBackendOptions {
3
+ /** From `smokeMongoUri()`. */
4
+ mongoUri: string;
5
+ /** Default: a free port. */
6
+ port?: number;
7
+ /** Merged over the defaults, e.g. `{AUTH_PROVIDER: "better-auth"}`. */
8
+ env?: Record<string, string | undefined>;
9
+ /** How long the backend may take to answer `/health`. Default 60 000 ms. */
10
+ timeoutMs?: number;
11
+ /** Directory holding `src/index.ts`. Default: the monorepo's example-backend. */
12
+ backendDir?: string;
13
+ }
14
+ export interface ExampleBackend extends SpawnedProcess {
15
+ baseUrl: string;
16
+ port: number;
17
+ }
18
+ /**
19
+ * Starts the monorepo's example-backend by path and resolves once `/health` answers 2xx. Client
20
+ * smokes (rtk, syncdb, admin-frontend) use it so they get a real server without importing
21
+ * `@terreno/api`. Auth secrets are fixed dev values; the clinic demo model avoids AI providers.
22
+ */
23
+ export declare const spawnExampleBackend: ({ mongoUri, port, env, timeoutMs, backendDir, }: SpawnExampleBackendOptions) => Promise<ExampleBackend>;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.spawnExampleBackend = void 0;
4
+ const node_path_1 = require("node:path");
5
+ const freePort_1 = require("./freePort");
6
+ const spawnUntilReady_1 = require("./spawnUntilReady");
7
+ /**
8
+ * example-backend's SIGTERM hook stops the jobs worker and leaves the HTTP server running, so the
9
+ * process never exits on SIGTERM alone. Its smoke database is disposable, so `stop()` waits only
10
+ * briefly before SIGKILL instead of the default 5 s.
11
+ */
12
+ const STOP_GRACE_MS = 500;
13
+ /** Same depth from `src/smoke` and `dist/smoke`, so source and compiled helpers agree. */
14
+ const EXAMPLE_BACKEND_DIR = (0, node_path_1.resolve)(__dirname, "../../../example-backend");
15
+ /**
16
+ * Starts the monorepo's example-backend by path and resolves once `/health` answers 2xx. Client
17
+ * smokes (rtk, syncdb, admin-frontend) use it so they get a real server without importing
18
+ * `@terreno/api`. Auth secrets are fixed dev values; the clinic demo model avoids AI providers.
19
+ */
20
+ const spawnExampleBackend = async ({ mongoUri, port, env, timeoutMs = 60000, backendDir = EXAMPLE_BACKEND_DIR, }) => {
21
+ const resolvedPort = port ?? (await (0, freePort_1.freePort)());
22
+ const baseUrl = `http://127.0.0.1:${resolvedPort}`;
23
+ const backend = await (0, spawnUntilReady_1.spawnUntilReady)({
24
+ cmd: [process.execPath, "src/index.ts"],
25
+ cwd: backendDir,
26
+ env: {
27
+ BETTER_AUTH_SECRET: "terreno-smoke-better-auth-secret-32",
28
+ BETTER_AUTH_URL: baseUrl,
29
+ CLINIC_DEMO_MODEL: "true",
30
+ MONGO_URI: mongoUri,
31
+ PORT: String(resolvedPort),
32
+ REFRESH_TOKEN_SECRET: "terreno-smoke-refresh-secret",
33
+ SESSION_SECRET: "terreno-smoke-session-secret",
34
+ TOKEN_ISSUER: "terreno-smoke",
35
+ TOKEN_SECRET: "terreno-smoke-token-secret",
36
+ ...env,
37
+ },
38
+ stopGraceMs: STOP_GRACE_MS,
39
+ timeoutMs,
40
+ url: `${baseUrl}/health`,
41
+ });
42
+ return { ...backend, baseUrl, port: resolvedPort };
43
+ };
44
+ exports.spawnExampleBackend = spawnExampleBackend;
@@ -0,0 +1,29 @@
1
+ export interface SpawnUntilReadyOptions {
2
+ /** Command and arguments, e.g. `[process.execPath, "e2e/smoke.ts", "serve"]`. */
3
+ cmd: string[];
4
+ /** URL polled until it answers 2xx. */
5
+ url: string;
6
+ /** How long the child may take to answer 2xx. Default 20 000 ms. */
7
+ timeoutMs?: number;
8
+ cwd?: string;
9
+ /** Merged over the parent environment. */
10
+ env?: Record<string, string | undefined>;
11
+ /** How long `stop()` waits after SIGTERM before SIGKILL. Default 5 000 ms. */
12
+ stopGraceMs?: number;
13
+ }
14
+ export interface SpawnedProcess {
15
+ pid: number;
16
+ /** Everything the child wrote to stdout and stderr so far. */
17
+ output: () => string;
18
+ /**
19
+ * Sends SIGTERM to the child's process group, then SIGKILL after `stopGraceMs`. Safe to call
20
+ * more than once.
21
+ */
22
+ stop: () => Promise<void>;
23
+ }
24
+ /**
25
+ * Starts a long-running child (a server) and resolves once `url` answers 2xx. Rejects with the
26
+ * child's output when it exits first or is not ready within `timeoutMs`, and kills it. The
27
+ * child's process group is also killed when the smoke process exits.
28
+ */
29
+ export declare const spawnUntilReady: ({ cmd, url, timeoutMs, cwd, env, stopGraceMs, }: SpawnUntilReadyOptions) => Promise<SpawnedProcess>;
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.spawnUntilReady = void 0;
4
+ const luxon_1 = require("luxon");
5
+ const timeout_1 = require("../utils/timeout");
6
+ const childProcesses_1 = require("./childProcesses");
7
+ const DEFAULT_TIMEOUT_MS = 20000;
8
+ const POLL_INTERVAL_MS = 100;
9
+ const DEFAULT_STOP_GRACE_MS = 5000;
10
+ const OUTPUT_TAIL_CHARS = 4000;
11
+ const tail = (text) => text.length > OUTPUT_TAIL_CHARS ? `…${text.slice(-OUTPUT_TAIL_CHARS)}` : text;
12
+ /**
13
+ * Starts a long-running child (a server) and resolves once `url` answers 2xx. Rejects with the
14
+ * child's output when it exits first or is not ready within `timeoutMs`, and kills it. The
15
+ * child's process group is also killed when the smoke process exits.
16
+ */
17
+ const spawnUntilReady = async ({ cmd, url, timeoutMs = DEFAULT_TIMEOUT_MS, cwd, env, stopGraceMs = DEFAULT_STOP_GRACE_MS, }) => {
18
+ const child = (0, childProcesses_1.spawnTracked)({ cmd, cwd, env });
19
+ const output = (0, childProcesses_1.collectOutput)(child);
20
+ let isStopped = false;
21
+ const stop = async () => {
22
+ if (isStopped) {
23
+ return;
24
+ }
25
+ isStopped = true;
26
+ (0, childProcesses_1.killGroup)(child, "SIGTERM");
27
+ const exited = await Promise.race([
28
+ child.exited.then(() => true),
29
+ (0, timeout_1.timeout)(stopGraceMs).then(() => false),
30
+ ]);
31
+ // Anything the child started and left behind goes too.
32
+ (0, childProcesses_1.killGroup)(child, "SIGKILL");
33
+ if (!exited) {
34
+ await child.exited;
35
+ }
36
+ };
37
+ const command = cmd.join(" ");
38
+ const deadline = luxon_1.DateTime.now().plus({ milliseconds: timeoutMs });
39
+ let lastResult = "no response";
40
+ while (luxon_1.DateTime.now() < deadline) {
41
+ if (child.exitCode !== null || child.signalCode !== null) {
42
+ await stop();
43
+ await output.drained;
44
+ throw new Error(`${command} exited with code ${child.exitCode ?? child.signalCode} before ${url} was ready.\n${tail(output.combined())}`);
45
+ }
46
+ try {
47
+ // The bun and node type packages each declare AbortSignal; fetch expects the global one.
48
+ const signal = AbortSignal.timeout(1000);
49
+ const res = await fetch(url, { signal });
50
+ await res.body?.cancel();
51
+ if (res.ok) {
52
+ return { output: output.combined, pid: child.pid, stop };
53
+ }
54
+ lastResult = `status ${res.status}`;
55
+ }
56
+ catch (error) {
57
+ lastResult = error instanceof Error ? error.message : String(error);
58
+ }
59
+ await (0, timeout_1.timeout)(POLL_INTERVAL_MS);
60
+ }
61
+ await stop();
62
+ throw new Error(`${command} (pid ${child.pid}) was not ready at ${url} within ${timeoutMs} ms (last: ${lastResult}).\n${tail(output.combined())}`);
63
+ };
64
+ exports.spawnUntilReady = spawnUntilReady;
package/package.json CHANGED
@@ -23,7 +23,7 @@
23
23
  "devDependencies": {
24
24
  "@biomejs/biome": "^2.3.6",
25
25
  "@reduxjs/toolkit": "^2.11.1",
26
- "@terreno/ui": "57.20.0",
26
+ "@terreno/ui": "57.21.0",
27
27
  "@testing-library/react-native": "^13.2.0",
28
28
  "@types/bun": "^1.4.0",
29
29
  "@types/express": "^5.0.6",
@@ -65,7 +65,7 @@
65
65
  "main": "dist/index.js",
66
66
  "name": "@terreno/test",
67
67
  "peerDependencies": {
68
- "@terreno/ui": "57.20.0",
68
+ "@terreno/ui": "57.21.0",
69
69
  "@testing-library/react-native": "^13.2.0",
70
70
  "mongoose": "^8.0.0 || ^9.0.0",
71
71
  "react": "19.2.3",
@@ -101,13 +101,15 @@
101
101
  "compile:watch": "bun tsc -w",
102
102
  "dev": "bun tsc -w",
103
103
  "ensure-mongo-binary": "bun ./src/mongo/ensureMongoBinary.ts",
104
- "lint": "biome check ./src",
105
- "lint:fix": "biome check --write ./src",
104
+ "lint": "biome check ./src ./e2e",
105
+ "lint:fix": "biome check --write ./src ./e2e",
106
+ "smoke": "bun e2e/smoke.ts",
106
107
  "test": "bun test",
107
108
  "test:agent": "AGENT=1 bun test --only-failures",
108
109
  "test:ci": "bun test",
109
- "test:coverage": "bun run ../scripts/check-coverage.ts"
110
+ "test:coverage": "bun run ../scripts/check-coverage.ts",
111
+ "typecheck": "tsc -p tsconfig.typecheck.json"
110
112
  },
111
113
  "types": "dist/index.d.ts",
112
- "version": "57.20.0"
114
+ "version": "57.21.0"
113
115
  }
package/src/index.ts CHANGED
@@ -116,6 +116,19 @@ export {
116
116
  registerSimpleMongoPreload,
117
117
  type SimpleMongoPreloadOptions,
118
118
  } from "./preload/registerBackendPreload";
119
+ export {freePort} from "./smoke/freePort";
120
+ export {type RunBinOptions, type RunBinResult, runBin} from "./smoke/runBin";
121
+ export {type SmokeMongoUriOptions, smokeMongoUri, stopSmokeMongo} from "./smoke/smokeMongoUri";
122
+ export {
123
+ type ExampleBackend,
124
+ type SpawnExampleBackendOptions,
125
+ spawnExampleBackend,
126
+ } from "./smoke/spawnExampleBackend";
127
+ export {
128
+ type SpawnedProcess,
129
+ type SpawnUntilReadyOptions,
130
+ spawnUntilReady,
131
+ } from "./smoke/spawnUntilReady";
119
132
  export {type FreezeTimeInput, type FreezeTimeOptions, freezeTime} from "./time/freezeTime";
120
133
  export {
121
134
  type AbortTestTransactionOptions,
@@ -0,0 +1,103 @@
1
+ import type {Subprocess} from "bun";
2
+
3
+ type SmokeChild = Subprocess<"ignore", "pipe", "pipe">;
4
+
5
+ export interface ChildOutput {
6
+ /** stdout and stderr together, in arrival order. */
7
+ combined: () => string;
8
+ stdout: () => string;
9
+ stderr: () => string;
10
+ /** Resolves once both streams have closed. */
11
+ drained: Promise<void>;
12
+ }
13
+
14
+ const liveChildren = new Set<SmokeChild>();
15
+ let isCleanupRegistered = false;
16
+
17
+ /**
18
+ * Signals the child's whole process group, so a wrapper (`sh -c`, `bun run`) and the server it
19
+ * started both get it. Falls back to the child alone when the group is already gone.
20
+ */
21
+ export const killGroup = (child: SmokeChild, signal: NodeJS.Signals): void => {
22
+ try {
23
+ process.kill(-child.pid, signal);
24
+ } catch {
25
+ child.kill(signal);
26
+ }
27
+ };
28
+
29
+ /**
30
+ * Kills every tracked child that is still running; the smoke's exit and signal handlers call it.
31
+ * @internal Exported for tests.
32
+ */
33
+ export const killLiveChildren = (): void => {
34
+ for (const child of liveChildren) {
35
+ killGroup(child, "SIGKILL");
36
+ }
37
+ liveChildren.clear();
38
+ };
39
+
40
+ const registerCleanup = (): void => {
41
+ if (isCleanupRegistered) {
42
+ return;
43
+ }
44
+ isCleanupRegistered = true;
45
+ process.on("exit", killLiveChildren);
46
+ for (const [signal, code] of [
47
+ ["SIGINT", 130],
48
+ ["SIGTERM", 143],
49
+ ] as const) {
50
+ process.once(signal, () => {
51
+ killLiveChildren();
52
+ process.exit(code);
53
+ });
54
+ }
55
+ };
56
+
57
+ /**
58
+ * Starts a child in its own process group and tracks it, so it and anything it starts die with
59
+ * the smoke, even when the smoke crashes or is interrupted.
60
+ */
61
+ export const spawnTracked = ({
62
+ cmd,
63
+ cwd,
64
+ env,
65
+ }: {
66
+ cmd: string[];
67
+ cwd?: string;
68
+ env?: Record<string, string | undefined>;
69
+ }): SmokeChild => {
70
+ registerCleanup();
71
+ const child = Bun.spawn({
72
+ cmd,
73
+ cwd,
74
+ detached: true,
75
+ env: {...process.env, ...env},
76
+ stderr: "pipe",
77
+ stdin: "ignore",
78
+ stdout: "pipe",
79
+ });
80
+ liveChildren.add(child);
81
+ void child.exited.then(() => liveChildren.delete(child));
82
+ return child;
83
+ };
84
+
85
+ /** Reads a child's stdout and stderr as they arrive. */
86
+ export const collectOutput = (child: SmokeChild): ChildOutput => {
87
+ let combined = "";
88
+ const streams = {stderr: "", stdout: ""};
89
+ const drain = async (name: "stderr" | "stdout"): Promise<void> => {
90
+ const decoder = new TextDecoder();
91
+ for await (const chunk of child[name]) {
92
+ const text = decoder.decode(chunk, {stream: true});
93
+ streams[name] += text;
94
+ combined += text;
95
+ }
96
+ };
97
+ return {
98
+ combined: (): string => combined,
99
+ drained: Promise.all([drain("stdout"), drain("stderr")]).then(() => undefined),
100
+ stderr: (): string => streams.stderr,
101
+ stdout: (): string => streams.stdout,
102
+ };
103
+ };
@@ -0,0 +1,19 @@
1
+ import {createServer} from "node:net";
2
+
3
+ /**
4
+ * Asks the OS for an unused TCP port on 127.0.0.1 so parallel or repeated smokes never fight
5
+ * over a fixed port. The port is free when this resolves; bind it promptly.
6
+ */
7
+ export const freePort = async (): Promise<number> => {
8
+ const server = createServer();
9
+ await new Promise<void>((resolve, reject) => {
10
+ server.once("error", reject);
11
+ server.listen(0, "127.0.0.1", () => resolve());
12
+ });
13
+ const address = server.address();
14
+ await new Promise<void>((resolve) => server.close(() => resolve()));
15
+ if (!address || typeof address === "string") {
16
+ throw new Error("freePort: the OS did not assign a TCP port");
17
+ }
18
+ return address.port;
19
+ };
@@ -0,0 +1,57 @@
1
+ import {collectOutput, killGroup, spawnTracked} from "./childProcesses";
2
+
3
+ export interface RunBinOptions {
4
+ /** A command on PATH, or a path to a script. `.js`, `.mjs`, `.cjs`, and `.ts` files run with Bun. */
5
+ bin: string;
6
+ args?: string[];
7
+ cwd?: string;
8
+ /** Merged over the parent environment. */
9
+ env?: Record<string, string | undefined>;
10
+ /** The process and everything it started are killed, and the call rejects, after this long. Default 30 000 ms. */
11
+ timeoutMs?: number;
12
+ }
13
+
14
+ export interface RunBinResult {
15
+ exitCode: number;
16
+ stdout: string;
17
+ stderr: string;
18
+ }
19
+
20
+ const DEFAULT_TIMEOUT_MS = 30000;
21
+ const SCRIPT_EXTENSION = /\.(c|m)?(j|t)s$/;
22
+
23
+ /**
24
+ * Runs a binary to completion and returns its exit code and output. A non-zero exit resolves;
25
+ * assert on `exitCode`. Running longer than `timeoutMs` rejects. Background processes the
26
+ * binary leaves behind are killed when it exits.
27
+ */
28
+ export const runBin = async ({
29
+ bin,
30
+ args = [],
31
+ cwd,
32
+ env,
33
+ timeoutMs = DEFAULT_TIMEOUT_MS,
34
+ }: RunBinOptions): Promise<RunBinResult> => {
35
+ const cmd = SCRIPT_EXTENSION.test(bin) ? [process.execPath, bin, ...args] : [bin, ...args];
36
+ const child = spawnTracked({cmd, cwd, env});
37
+ const output = collectOutput(child);
38
+
39
+ let timer: ReturnType<typeof setTimeout> | undefined;
40
+ const isTimedOut = await Promise.race([
41
+ child.exited.then(() => false),
42
+ new Promise<boolean>((resolve) => {
43
+ timer = setTimeout(() => resolve(true), timeoutMs);
44
+ }),
45
+ ]);
46
+ clearTimeout(timer);
47
+
48
+ // Grandchildren keep the pipes open, so the whole group goes before reading the rest.
49
+ killGroup(child, "SIGKILL");
50
+ const exitCode = await child.exited;
51
+ await output.drained;
52
+
53
+ if (isTimedOut) {
54
+ throw new Error(`${cmd.join(" ")} timed out after ${timeoutMs} ms.\n${output.combined()}`);
55
+ }
56
+ return {exitCode, stderr: output.stderr(), stdout: output.stdout()};
57
+ };
@@ -0,0 +1,55 @@
1
+ import {buildDatabaseUri} from "../mongo/connection";
2
+ import {resolveMongoLaunchTimeoutMs} from "../mongo/mongoServer";
3
+
4
+ export interface SmokeMongoUriOptions {
5
+ /** Database name written into the URI. Default `terrenoSmoke`. */
6
+ databaseName?: string;
7
+ }
8
+
9
+ interface ReplSetHandle {
10
+ getUri: () => string;
11
+ stop: (options: {doCleanup: boolean; force: boolean}) => Promise<boolean>;
12
+ }
13
+
14
+ let replSet: Promise<ReplSetHandle> | undefined;
15
+
16
+ const startReplSet = async (): Promise<ReplSetHandle> => {
17
+ const {MongoMemoryReplSet} = await import("mongodb-memory-server-global");
18
+ const started = new MongoMemoryReplSet({
19
+ instanceOpts: [{launchTimeout: resolveMongoLaunchTimeoutMs()}],
20
+ replSet: {args: ["--wiredTigerCacheSizeGB", "0.25"], count: 1, storageEngine: "wiredTiger"},
21
+ });
22
+ await started.start();
23
+ await started.waitUntilRunning();
24
+ return started;
25
+ };
26
+
27
+ /**
28
+ * MongoDB URI for a smoke's server. Uses `TERRENO_TEST_MONGODB_URI` when set (the CI sidecar);
29
+ * otherwise starts one single-node in-memory replica set per process, so change streams work.
30
+ */
31
+ export const smokeMongoUri = async ({
32
+ databaseName = "terrenoSmoke",
33
+ }: SmokeMongoUriOptions = {}): Promise<string> => {
34
+ const externalUri = process.env.TERRENO_TEST_MONGODB_URI?.trim();
35
+ if (externalUri) {
36
+ return buildDatabaseUri({databaseName, uri: externalUri});
37
+ }
38
+ replSet ??= startReplSet().catch((error: unknown) => {
39
+ replSet = undefined;
40
+ throw error;
41
+ });
42
+ const handle = await replSet;
43
+ return buildDatabaseUri({databaseName, uri: handle.getUri()});
44
+ };
45
+
46
+ /** Stops the in-memory replica set that `smokeMongoUri` started, if any. */
47
+ export const stopSmokeMongo = async (): Promise<void> => {
48
+ const pending = replSet;
49
+ replSet = undefined;
50
+ if (!pending) {
51
+ return;
52
+ }
53
+ const handle = await pending;
54
+ await handle.stop({doCleanup: true, force: true});
55
+ };
@@ -0,0 +1,68 @@
1
+ import {resolve} from "node:path";
2
+
3
+ import {freePort} from "./freePort";
4
+ import {type SpawnedProcess, spawnUntilReady} from "./spawnUntilReady";
5
+
6
+ export interface SpawnExampleBackendOptions {
7
+ /** From `smokeMongoUri()`. */
8
+ mongoUri: string;
9
+ /** Default: a free port. */
10
+ port?: number;
11
+ /** Merged over the defaults, e.g. `{AUTH_PROVIDER: "better-auth"}`. */
12
+ env?: Record<string, string | undefined>;
13
+ /** How long the backend may take to answer `/health`. Default 60 000 ms. */
14
+ timeoutMs?: number;
15
+ /** Directory holding `src/index.ts`. Default: the monorepo's example-backend. */
16
+ backendDir?: string;
17
+ }
18
+
19
+ export interface ExampleBackend extends SpawnedProcess {
20
+ baseUrl: string;
21
+ port: number;
22
+ }
23
+
24
+ /**
25
+ * example-backend's SIGTERM hook stops the jobs worker and leaves the HTTP server running, so the
26
+ * process never exits on SIGTERM alone. Its smoke database is disposable, so `stop()` waits only
27
+ * briefly before SIGKILL instead of the default 5 s.
28
+ */
29
+ const STOP_GRACE_MS = 500;
30
+
31
+ /** Same depth from `src/smoke` and `dist/smoke`, so source and compiled helpers agree. */
32
+ const EXAMPLE_BACKEND_DIR = resolve(__dirname, "../../../example-backend");
33
+
34
+ /**
35
+ * Starts the monorepo's example-backend by path and resolves once `/health` answers 2xx. Client
36
+ * smokes (rtk, syncdb, admin-frontend) use it so they get a real server without importing
37
+ * `@terreno/api`. Auth secrets are fixed dev values; the clinic demo model avoids AI providers.
38
+ */
39
+ export const spawnExampleBackend = async ({
40
+ mongoUri,
41
+ port,
42
+ env,
43
+ timeoutMs = 60000,
44
+ backendDir = EXAMPLE_BACKEND_DIR,
45
+ }: SpawnExampleBackendOptions): Promise<ExampleBackend> => {
46
+ const resolvedPort = port ?? (await freePort());
47
+ const baseUrl = `http://127.0.0.1:${resolvedPort}`;
48
+ const backend = await spawnUntilReady({
49
+ cmd: [process.execPath, "src/index.ts"],
50
+ cwd: backendDir,
51
+ env: {
52
+ BETTER_AUTH_SECRET: "terreno-smoke-better-auth-secret-32",
53
+ BETTER_AUTH_URL: baseUrl,
54
+ CLINIC_DEMO_MODEL: "true",
55
+ MONGO_URI: mongoUri,
56
+ PORT: String(resolvedPort),
57
+ REFRESH_TOKEN_SECRET: "terreno-smoke-refresh-secret",
58
+ SESSION_SECRET: "terreno-smoke-session-secret",
59
+ TOKEN_ISSUER: "terreno-smoke",
60
+ TOKEN_SECRET: "terreno-smoke-token-secret",
61
+ ...env,
62
+ },
63
+ stopGraceMs: STOP_GRACE_MS,
64
+ timeoutMs,
65
+ url: `${baseUrl}/health`,
66
+ });
67
+ return {...backend, baseUrl, port: resolvedPort};
68
+ };
@@ -0,0 +1,103 @@
1
+ import {DateTime} from "luxon";
2
+
3
+ import {timeout} from "../utils/timeout";
4
+ import {collectOutput, killGroup, spawnTracked} from "./childProcesses";
5
+
6
+ export interface SpawnUntilReadyOptions {
7
+ /** Command and arguments, e.g. `[process.execPath, "e2e/smoke.ts", "serve"]`. */
8
+ cmd: string[];
9
+ /** URL polled until it answers 2xx. */
10
+ url: string;
11
+ /** How long the child may take to answer 2xx. Default 20 000 ms. */
12
+ timeoutMs?: number;
13
+ cwd?: string;
14
+ /** Merged over the parent environment. */
15
+ env?: Record<string, string | undefined>;
16
+ /** How long `stop()` waits after SIGTERM before SIGKILL. Default 5 000 ms. */
17
+ stopGraceMs?: number;
18
+ }
19
+
20
+ export interface SpawnedProcess {
21
+ pid: number;
22
+ /** Everything the child wrote to stdout and stderr so far. */
23
+ output: () => string;
24
+ /**
25
+ * Sends SIGTERM to the child's process group, then SIGKILL after `stopGraceMs`. Safe to call
26
+ * more than once.
27
+ */
28
+ stop: () => Promise<void>;
29
+ }
30
+
31
+ const DEFAULT_TIMEOUT_MS = 20000;
32
+ const POLL_INTERVAL_MS = 100;
33
+ const DEFAULT_STOP_GRACE_MS = 5000;
34
+ const OUTPUT_TAIL_CHARS = 4000;
35
+
36
+ const tail = (text: string): string =>
37
+ text.length > OUTPUT_TAIL_CHARS ? `…${text.slice(-OUTPUT_TAIL_CHARS)}` : text;
38
+
39
+ /**
40
+ * Starts a long-running child (a server) and resolves once `url` answers 2xx. Rejects with the
41
+ * child's output when it exits first or is not ready within `timeoutMs`, and kills it. The
42
+ * child's process group is also killed when the smoke process exits.
43
+ */
44
+ export const spawnUntilReady = async ({
45
+ cmd,
46
+ url,
47
+ timeoutMs = DEFAULT_TIMEOUT_MS,
48
+ cwd,
49
+ env,
50
+ stopGraceMs = DEFAULT_STOP_GRACE_MS,
51
+ }: SpawnUntilReadyOptions): Promise<SpawnedProcess> => {
52
+ const child = spawnTracked({cmd, cwd, env});
53
+ const output = collectOutput(child);
54
+ let isStopped = false;
55
+
56
+ const stop = async (): Promise<void> => {
57
+ if (isStopped) {
58
+ return;
59
+ }
60
+ isStopped = true;
61
+ killGroup(child, "SIGTERM");
62
+ const exited = await Promise.race([
63
+ child.exited.then(() => true),
64
+ timeout(stopGraceMs).then(() => false),
65
+ ]);
66
+ // Anything the child started and left behind goes too.
67
+ killGroup(child, "SIGKILL");
68
+ if (!exited) {
69
+ await child.exited;
70
+ }
71
+ };
72
+
73
+ const command = cmd.join(" ");
74
+ const deadline = DateTime.now().plus({milliseconds: timeoutMs});
75
+ let lastResult = "no response";
76
+ while (DateTime.now() < deadline) {
77
+ if (child.exitCode !== null || child.signalCode !== null) {
78
+ await stop();
79
+ await output.drained;
80
+ throw new Error(
81
+ `${command} exited with code ${child.exitCode ?? child.signalCode} before ${url} was ready.\n${tail(output.combined())}`
82
+ );
83
+ }
84
+ try {
85
+ // The bun and node type packages each declare AbortSignal; fetch expects the global one.
86
+ const signal = AbortSignal.timeout(1000) as unknown as RequestInit["signal"];
87
+ const res = await fetch(url, {signal});
88
+ await res.body?.cancel();
89
+ if (res.ok) {
90
+ return {output: output.combined, pid: child.pid, stop};
91
+ }
92
+ lastResult = `status ${res.status}`;
93
+ } catch (error: unknown) {
94
+ lastResult = error instanceof Error ? error.message : String(error);
95
+ }
96
+ await timeout(POLL_INTERVAL_MS);
97
+ }
98
+
99
+ await stop();
100
+ throw new Error(
101
+ `${command} (pid ${child.pid}) was not ready at ${url} within ${timeoutMs} ms (last: ${lastResult}).\n${tail(output.combined())}`
102
+ );
103
+ };