@terreno/test 58.0.6 → 58.1.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,58 @@ 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
+ ## [58.1.0] - 2026-11-21
24
+
25
+ Upgrade note: [`mcp-server/src/docs/upgrades/58.1.0.md`](mcp-server/src/docs/upgrades/58.1.0.md).
26
+
27
+ ### Breaking
28
+
29
+ - **@terreno/ui:** `GPTChat` now reads as a transcript: user messages in a light bubble, assistant text on the page in a 760px column, and tool calls as one expandable row capped at 240px. Breaking changes for apps and e2e suites that select these elements:
30
+
31
+ - `gpt-copy-image` is removed. Use `gpt-copy-msg-<index>` for copy. It copies the image for an image-only reply and the text when a reply has both.
32
+ - Tool rows are labeled `Tool: <name>` instead of `Result: <name>`.
33
+ - **Tools** (`gpt-tools-button`) appears beside the composer only when `mcpTools` has entries.
34
+ - A user or assistant message with no text, content parts, or blocks renders nothing, including its action row.
35
+
36
+ Download for an image reply is `gpt-download-image-<index>`. The **Tools** modal hides arguments until **Show arguments** is checked, and it resets to hidden when closed.
37
+ - **Upgrade:** switching an app with connected clients from the default `mcp` scope to `grants` ends access for live `mcp`-scoped tokens (users reconnect), and confidential clients stored with `scope: "mcp"` get `invalid_scope` at `/oauth/token` until their stored scope is updated. Custom tools from `registerMCPTool` default to `write`, so add `access: "read"` to read-only tools or read-only grants will not see them. Bearer-mode web apps add the consent path to `oauthHandoff.callbackPaths`. See [Enable MCP OAuth](docs/how-to/enable-mcp-oauth.md).
38
+ - **Behavior change, even without `grants`:** a confidential client whose stored `scope` lists only scopes the server no longer supports now gets `invalid_scope` from `client_credentials`, where it used to get a token. Update the client's `scope`, or leave it unset to receive every supported scope.
39
+
40
+ ### Added
41
+
42
+ - **@terreno/admin-frontend:** AI Prompts nest by folder. A slash in a prompt name is a folder level: each folder is a table row you open, and an up row returns to the parent. Tag and search filters match prompts in every folder. The list filters by one tag.
43
+ - **@terreno/ai:** `GET /ai/observability/prompts` returns each prompt's `tags`, which the admin list filters on.
44
+ - **@terreno/admin-frontend:** dataset items open on their own page. Expected output is a form built from `expectedOutputSchema`, or from the stored JSON when no schema is set. The expected output is the golden label, and **Save and next** moves through the Needs review queue in list order.
45
+ - **@terreno/admin-frontend:** `AdminRolesList` takes `isActionVisible({resource, action})`. Return false to hide a statement action from the role list and the role editor. Hidden actions stay on a saved role and are written back unchanged. The predicate receives the resource, so the same verb can be hidden on one model and shown on another.
46
+ - **@terreno/ai:** end users can give feedback on any AI output. `POST /ai/observability/traces/:id/feedback` (trace owner only) records thumbs with an optional comment and outcome class as `user-feedback` scores, passive signals (`accepted`, `dismissed`, `copied`, `edited`, `regenerated`) as the new `user-signal` score source, and `flagDataset`. `recordTraceFeedback` exposes the same logic to server code.
47
+ - **@terreno/ai:** `createTraceId()` and the `traceId` generate option let a route return an output's trace id. `/gpt/prompt` stores `traceId` on each assistant reply, and `PATCH /gpt/histories/:id/rating` accepts a `comment` and records the rating on the reply's trace.
48
+ - **@terreno/ai:** `ObservabilityApp({feedbackReview: {evaluatorName}})` queues every thumbs-down trace in the review queue with reason `feedback`.
49
+ - **@terreno/ai:** `GET /ai/observability/traces` filters by `thumbs`, `signal`, and `hasComment`. Adding a trace the user rejected to a dataset now lands it `proofread: false` with a `user:` tag and `metadata.userFeedback`, so known-bad outputs never become gold labels.
50
+ - **@terreno/ui:** `ThumbsUpDownFeedback` takes `onCommentSubmit` for an optional comment (new `FeedbackCommentField`), and `GPTChat` takes `onRateComment` and `onMessageSignal`.
51
+ - **@terreno/admin-frontend:** AI Observability Traces adds **Thumbs**, **Signal**, and **Has comment** filters, shows each score's source, and shows user comments (collapsed on sensitive traces).
52
+ - **@terreno/admin-frontend:** dataset items open with review steps and an explanation of the golden label. **Save and next** on a Needs review item opens the next unproofread item in list order (wrapping), and the last one returns to the Needs review tab. The dataset shows a golden-label note and a Needs review empty state, and `?tab=needsReview` opens that tab.
53
+ - **@terreno/cli:** every MCP tool is now a `terreno` command, so an agent with a shell needs no MCP configuration. New commands: `terreno syncdb action` and `terreno syncdb snapshot`, `terreno storage read|write`, `terreno dev list|run`, `terreno dispatch`, `terreno docs notes search|get|ask`, and `terreno validate blocks`. `terreno tool list|schema|call` reaches any tool by its MCP name.
54
+ - **@terreno/cli:** `terreno browser <action>` drives one web page across separate commands. The page and SyncDB snapshots live in a background CLI session (`terreno session start|stop|status`) that those commands start themselves.
55
+ - **@terreno/cli:** `terreno login` signs in with Better Auth or JWT and saves a token that `terreno api` sends to the same API origin. `terreno logout` removes it.
56
+ - **@terreno/mcp:** new exports `@terreno/mcp/project-root` (`resolveTerrenoProjectRoot`) and `@terreno/mcp/local-tool-names` (`LOCAL_TOOL_NAMES`), and `checkUiBlocks` on `@terreno/mcp/tools`, which reports whether a block document is valid along with the `terreno-blocks validate` text.
57
+ - **@terreno/api:** `mcpOAuth.grants` enforces MCP OAuth scopes. Pass `"readOnly"` (`mcp:read`), `"readWrite"` (`mcp:read`, `mcp:write`), or your own `McpOAuthGrant[]` (`{scope, label, description?, access: "read" | "write"}`). Every MCP tool is `read` or `write` (CRUD `list`/`read` and GET actions are `read`; the rest are `write`), and an OAuth token sees and can call only the tools its grants allow. Write implies read. `MCPConfig.scopes`, an action's `mcp.scope`, and `registerMCPTool({access, scope})` tag tools; `canUseMcpTool` and `MCP_OAUTH_GRANT_PRESETS` are exported. Without `grants`, nothing changes.
58
+ - **@terreno/api:** `POST /oauth/authorize/:request/approve` accepts an optional `{scope}` so the user can approve a subset of the requested scopes, and `GET /oauth/authorize/:request` returns `grants` with each grant's label and description. `client_credentials` now intersects a client's stored scope with the supported scopes and answers `invalid_scope` when nothing is left.
59
+ - **@terreno/syncdb:** `TerrenoOAuthConsentScreen` is a drop-in MCP OAuth consent page: `TerrenoLoginScreen` inline while signed out, then the client, redirect host, a checkbox per grant, and Approve and Deny. `useMcpOAuthConsent` is the hook behind it. `TerrenoLoginScreen` and `useLoginController` take `methods` to show only some of the server's sign-in methods.
60
+ - **@terreno/api:** `modelRouter` takes an opt-in `bulk` option (`true` or `{maxItems, methods}`) that mounts `POST /<route>/bulk`. One request carries up to 100 create, update, and delete operations, each run through the router's permissions, hooks, validation, audit, and `responseHandler`. By default the batch runs in one MongoDB transaction and commits or rolls back together (replica set required); `"atomic": false` runs each operation on its own and returns a status per operation. See `docs/reference/api.md` ("modelRouter bulk writes").
61
+ - **@terreno/api:** `validateModelRouterBody`, which validates one create or update body the way `POST /` and `PATCH /:id` do.
62
+ - Role permissions can carry an optional description. `createAccess({ statementDescriptions })` merges app labels over the framework labels, and `GET /rbac/statements` returns them as `data.statementDescriptions`. The admin roles screen shows each label beside its action badge. Pass `showActionBadges={false}` to hide the badges and stack one label per line.
63
+
64
+ ### Fixed
65
+
66
+ - Admin shell content padding uses longhand values. react-native-web drops a multi-value `padding` string, so admin pages sat flush against the sidebar.
67
+ - Data table alternate rows in light mode use `neutral100` (`#E6E6E6`) instead of `neutralLight` (`#CDCDCD`).
68
+ - **@terreno/ui:** `DraggableList` accepts `variableHeight`. Each row is as tall as its content, and the next row starts below it. During a drag, rows use their measured heights to pick the drop slot. `itemHeight` is the placeholder until a row is measured.
69
+ - **@terreno/admin-frontend:** arrays of subdocuments, such as feature-flag rules and variants, use `variableHeight`. A rule with a long user list no longer covers the Type and Variants fields below it.
70
+ - **@terreno/admin-frontend:** reordering an array of subdocuments by drag keeps the new order. Before, the rows snapped back to their original order after release.
71
+ - `@terreno/test`: `registerBackendPreload` and `registerSimpleMongoPreload` apply `testEnv` when they are called, not only in `beforeEach`. An app built in a test file's `beforeAll` used to miss it, so the first file in a run built its app without `TOKEN_SECRET`: `TerrenoApp` skipped the JWT strategy, and anonymous requests got 500 `Unknown authentication strategy "jwt"`.
72
+ - `@terreno/test`: new `testRequest(app)`, a drop-in for `supertest(app)` that binds 127.0.0.1. Under Bun, `supertest(app)` listens on the IPv6 wildcard only and sends to `127.0.0.1`, so on macOS another local process holding that port could answer, failing random tests with its 404 or 401. Bun also left each supertest server open after its request; these now close. `authAsUser` and `authWithToken` use the same server. `createLoopbackServer(app)` returns it for your own use.
73
+ - Web spell check is on again for prose `TextField` and `TextArea` values; browser autocorrect stays off on web so controlled inputs do not oscillate between two spellings.
74
+
23
75
  ## [58.0.6] - 2026-11-14
24
76
 
25
77
  ### Fixed
package/README.md CHANGED
@@ -42,6 +42,7 @@ Then run `bun test` in the package. The preload starts `mongodb-memory-server` w
42
42
  - `registerBackendPreload` — full lifecycle with optional transactions and fixture cache
43
43
  - `setTerrenoTestEnv` — canonical auth secrets for tests
44
44
  - `getBaseServer` / `authAsUser` — Express + supertest helpers
45
+ - `testRequest` — `supertest(app)` bound to 127.0.0.1, so other local apps can't answer test requests
45
46
  - `authWithToken` — authenticate with a pre-minted token, skipping the login round-trip
46
47
  - `waitUntil` / `waitForCalls` / `freezeTime` — poll instead of sleeping; freeze the clock
47
48
  - `expectAPIError` / `assertStrictResponseProperties` — error-body and field-leak assertions
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.authAsUser = void 0;
7
7
  const supertest_1 = __importDefault(require("supertest"));
8
+ const testRequest_1 = require("./testRequest");
8
9
  /**
9
10
  * Logs in via POST /auth/login (by default) and returns a supertest agent with Bearer auth.
10
11
  */
@@ -12,7 +13,7 @@ const authAsUser = async (app, credentials, options = {}) => {
12
13
  const loginPath = options.loginPath ?? "/auth/login";
13
14
  const tokenPath = options.tokenPath ?? "data.token";
14
15
  const timeoutMs = options.timeoutMs ?? 5000;
15
- const agent = supertest_1.default.agent(app);
16
+ const agent = supertest_1.default.agent((0, testRequest_1.createLoopbackServer)(app));
16
17
  const request = agent.post(loginPath).send({
17
18
  email: credentials.email,
18
19
  password: credentials.password,
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.authWithToken = void 0;
7
7
  const supertest_1 = __importDefault(require("supertest"));
8
+ const testRequest_1 = require("./testRequest");
8
9
  /**
9
10
  * Returns a supertest agent that sends `Authorization: Bearer <token>` on every request.
10
11
  *
@@ -20,7 +21,7 @@ const authWithToken = async (app, { token, headers = {} }) => {
20
21
  if (!token) {
21
22
  throw new Error("authWithToken: token is empty; check that the user exists and TOKEN_SECRET is set");
22
23
  }
23
- const agent = supertest_1.default.agent(app);
24
+ const agent = supertest_1.default.agent((0, testRequest_1.createLoopbackServer)(app));
24
25
  await agent.set("authorization", `Bearer ${token}`);
25
26
  for (const [key, value] of Object.entries(headers)) {
26
27
  await agent.set(key, value);
@@ -0,0 +1,19 @@
1
+ import { type RequestListener, type Server } from "node:http";
2
+ import supertest from "supertest";
3
+ /**
4
+ * An HTTP server for supertest that binds 127.0.0.1 and closes after each request under Bun.
5
+ *
6
+ * `supertest(app)` starts its server with `listen(0)`, which under Bun binds only the IPv6
7
+ * wildcard (`*:<port>`), and then sends the request to `127.0.0.1:<port>`. On macOS another
8
+ * process can hold that same port on 127.0.0.1 at the same time, so the request reaches that
9
+ * process and the test sees its 404 or 401. Binding 127.0.0.1 keeps the port ours.
10
+ *
11
+ * supertest closes its server after a request only when `server._handle` is set, a Node
12
+ * internal that Bun leaves undefined, so under Bun every request leaked a listening server.
13
+ * The server marks `_handle` once listening so supertest closes it as it does under Node.
14
+ */
15
+ export declare const createLoopbackServer: (app: RequestListener) => Server;
16
+ /**
17
+ * `supertest(app)`, bound to 127.0.0.1. Use it in place of `supertest(app)` in Bun tests.
18
+ */
19
+ export declare const testRequest: (app: RequestListener) => ReturnType<typeof supertest>;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.testRequest = exports.createLoopbackServer = void 0;
7
+ const node_http_1 = require("node:http");
8
+ const supertest_1 = __importDefault(require("supertest"));
9
+ /**
10
+ * An HTTP server for supertest that binds 127.0.0.1 and closes after each request under Bun.
11
+ *
12
+ * `supertest(app)` starts its server with `listen(0)`, which under Bun binds only the IPv6
13
+ * wildcard (`*:<port>`), and then sends the request to `127.0.0.1:<port>`. On macOS another
14
+ * process can hold that same port on 127.0.0.1 at the same time, so the request reaches that
15
+ * process and the test sees its 404 or 401. Binding 127.0.0.1 keeps the port ours.
16
+ *
17
+ * supertest closes its server after a request only when `server._handle` is set, a Node
18
+ * internal that Bun leaves undefined, so under Bun every request leaked a listening server.
19
+ * The server marks `_handle` once listening so supertest closes it as it does under Node.
20
+ */
21
+ const createLoopbackServer = (app) => {
22
+ const server = (0, node_http_1.createServer)(app);
23
+ const listen = server.listen.bind(server);
24
+ const internal = server;
25
+ // supertest calls listen(0); any further arguments (a callback) pass through.
26
+ server.listen = ((port, ...rest) => {
27
+ const result = listen(port, "127.0.0.1", ...rest);
28
+ if (internal._handle === undefined) {
29
+ internal._handle = true;
30
+ }
31
+ return result;
32
+ });
33
+ return server;
34
+ };
35
+ exports.createLoopbackServer = createLoopbackServer;
36
+ /**
37
+ * `supertest(app)`, bound to 127.0.0.1. Use it in place of `supertest(app)` in Bun tests.
38
+ */
39
+ const testRequest = (app) => (0, supertest_1.default)((0, exports.createLoopbackServer)(app));
40
+ exports.testRequest = testRequest;
package/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export { setTerrenoTestEnv, type TerrenoTestEnvOptions } from "./env/setTerrenoT
5
5
  export { type AuthAsUserOptions, type AuthUserCredentials, authAsUser } from "./http/authAsUser";
6
6
  export { type AuthWithTokenOptions, authWithToken } from "./http/authWithToken";
7
7
  export { type GetBaseServerOptions, getBaseServer } from "./http/getBaseServer";
8
+ export { createLoopbackServer, testRequest } from "./http/testRequest";
8
9
  export { createLogSilencer, registerLogSilencing, type SilenceLogsController, type SilenceLogsOptions, } from "./logging/silenceLogs";
9
10
  export { type CreateMockLanguageModelOptions, createMockLanguageModel, type MockLanguageModel, type MockLanguageModelFinishReason, type MockLanguageModelGenerateResult, type MockLanguageModelResponse, type MockLanguageModelStreamPart, type MockLanguageModelToolCall, type MockLanguageModelUsage, mockLanguageModelStreamParts, } from "./mocks/aiSdk";
10
11
  export { type CloudTasksCreateTaskRequest, type CloudTasksHttpRequest, type CloudTasksMock, type CloudTasksMockClient, type CloudTasksTask, type CloudTasksTime, type DrainCloudTasksOptions, type DrainedCloudTask, decodeCloudTaskBody, type EnqueuedCloudTask, registerCloudTasksMock, } from "./mocks/cloudTasks";
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
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;
3
+ 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.testRequest = exports.createLoopbackServer = 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 = exports.ensureAllIndexes = exports.TestTransactionOperationCancelledError = void 0;
5
5
  var expectAPIError_1 = require("./assertions/expectAPIError");
6
6
  Object.defineProperty(exports, "expectAPIError", { enumerable: true, get: function () { return expectAPIError_1.expectAPIError; } });
7
7
  var strictResponseProperties_1 = require("./assertions/strictResponseProperties");
@@ -17,6 +17,9 @@ var authWithToken_1 = require("./http/authWithToken");
17
17
  Object.defineProperty(exports, "authWithToken", { enumerable: true, get: function () { return authWithToken_1.authWithToken; } });
18
18
  var getBaseServer_1 = require("./http/getBaseServer");
19
19
  Object.defineProperty(exports, "getBaseServer", { enumerable: true, get: function () { return getBaseServer_1.getBaseServer; } });
20
+ var testRequest_1 = require("./http/testRequest");
21
+ Object.defineProperty(exports, "createLoopbackServer", { enumerable: true, get: function () { return testRequest_1.createLoopbackServer; } });
22
+ Object.defineProperty(exports, "testRequest", { enumerable: true, get: function () { return testRequest_1.testRequest; } });
20
23
  var silenceLogs_1 = require("./logging/silenceLogs");
21
24
  Object.defineProperty(exports, "createLogSilencer", { enumerable: true, get: function () { return silenceLogs_1.createLogSilencer; } });
22
25
  Object.defineProperty(exports, "registerLogSilencing", { enumerable: true, get: function () { return silenceLogs_1.registerLogSilencing; } });
@@ -31,6 +31,10 @@ const beforeAllTimeoutMs = () => (0, mongoServer_1.resolveMongoLaunchTimeoutMs)(
31
31
  */
32
32
  const registerBackendPreload = (options = {}) => {
33
33
  const connectMongoInBeforeAll = options.connectMongoInBeforeAll ?? true;
34
+ // Test files often build their app in beforeAll, which runs before any beforeEach. Code that
35
+ // reads env at build time (TerrenoApp registers the JWT strategy only when TOKEN_SECRET is set)
36
+ // must see the test env there too, so apply it now rather than waiting for the first test.
37
+ (0, setTerrenoTestEnv_1.setTerrenoTestEnv)(options.testEnv);
34
38
  if (options.sentryMock !== false) {
35
39
  (0, sentryBun_1.registerSentryBunMock)();
36
40
  }
package/package.json CHANGED
@@ -23,7 +23,7 @@
23
23
  "devDependencies": {
24
24
  "@biomejs/biome": "2.5.13",
25
25
  "@reduxjs/toolkit": "^2.11.1",
26
- "@terreno/ui": "58.0.6",
26
+ "@terreno/ui": "58.1.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": "58.0.6",
68
+ "@terreno/ui": "58.1.0",
69
69
  "@testing-library/react-native": "^13.2.0",
70
70
  "mongoose": "^8.0.0 || ^9.0.0",
71
71
  "react": "19.3.0",
@@ -111,5 +111,5 @@
111
111
  "typecheck": "tsc -p tsconfig.typecheck.json"
112
112
  },
113
113
  "types": "dist/index.d.ts",
114
- "version": "58.0.6"
114
+ "version": "58.1.0"
115
115
  }
@@ -2,6 +2,8 @@ import type express from "express";
2
2
  import supertest from "supertest";
3
3
  import type TestAgent from "supertest/lib/agent";
4
4
 
5
+ import {createLoopbackServer} from "./testRequest";
6
+
5
7
  export interface AuthUserCredentials {
6
8
  email: string;
7
9
  password: string;
@@ -27,7 +29,7 @@ export const authAsUser = async (
27
29
  const tokenPath = options.tokenPath ?? "data.token";
28
30
  const timeoutMs = options.timeoutMs ?? 5000;
29
31
 
30
- const agent = supertest.agent(app);
32
+ const agent = supertest.agent(createLoopbackServer(app));
31
33
  const request = agent.post(loginPath).send({
32
34
  email: credentials.email,
33
35
  password: credentials.password,
@@ -2,6 +2,8 @@ import type express from "express";
2
2
  import supertest from "supertest";
3
3
  import type TestAgent from "supertest/lib/agent";
4
4
 
5
+ import {createLoopbackServer} from "./testRequest";
6
+
5
7
  export interface AuthWithTokenOptions {
6
8
  /** Access token to send, usually minted with `@terreno/api`'s `generateTokens(user, authOptions)`. */
7
9
  token: string | null | undefined;
@@ -29,7 +31,7 @@ export const authWithToken = async (
29
31
  "authWithToken: token is empty; check that the user exists and TOKEN_SECRET is set"
30
32
  );
31
33
  }
32
- const agent = supertest.agent(app);
34
+ const agent = supertest.agent(createLoopbackServer(app));
33
35
  await agent.set("authorization", `Bearer ${token}`);
34
36
  for (const [key, value] of Object.entries(headers)) {
35
37
  await agent.set(key, value);
@@ -0,0 +1,35 @@
1
+ import {createServer, type RequestListener, type Server} from "node:http";
2
+ import supertest from "supertest";
3
+
4
+ /**
5
+ * An HTTP server for supertest that binds 127.0.0.1 and closes after each request under Bun.
6
+ *
7
+ * `supertest(app)` starts its server with `listen(0)`, which under Bun binds only the IPv6
8
+ * wildcard (`*:<port>`), and then sends the request to `127.0.0.1:<port>`. On macOS another
9
+ * process can hold that same port on 127.0.0.1 at the same time, so the request reaches that
10
+ * process and the test sees its 404 or 401. Binding 127.0.0.1 keeps the port ours.
11
+ *
12
+ * supertest closes its server after a request only when `server._handle` is set, a Node
13
+ * internal that Bun leaves undefined, so under Bun every request leaked a listening server.
14
+ * The server marks `_handle` once listening so supertest closes it as it does under Node.
15
+ */
16
+ export const createLoopbackServer = (app: RequestListener): Server => {
17
+ const server = createServer(app);
18
+ const listen = server.listen.bind(server) as (...args: unknown[]) => Server;
19
+ const internal = server as unknown as {_handle?: unknown};
20
+ // supertest calls listen(0); any further arguments (a callback) pass through.
21
+ server.listen = ((port?: number, ...rest: unknown[]): Server => {
22
+ const result = listen(port, "127.0.0.1", ...rest);
23
+ if (internal._handle === undefined) {
24
+ internal._handle = true;
25
+ }
26
+ return result;
27
+ }) as Server["listen"];
28
+ return server;
29
+ };
30
+
31
+ /**
32
+ * `supertest(app)`, bound to 127.0.0.1. Use it in place of `supertest(app)` in Bun tests.
33
+ */
34
+ export const testRequest = (app: RequestListener): ReturnType<typeof supertest> =>
35
+ supertest(createLoopbackServer(app));
package/src/index.ts CHANGED
@@ -12,6 +12,7 @@ export {setTerrenoTestEnv, type TerrenoTestEnvOptions} from "./env/setTerrenoTes
12
12
  export {type AuthAsUserOptions, type AuthUserCredentials, authAsUser} from "./http/authAsUser";
13
13
  export {type AuthWithTokenOptions, authWithToken} from "./http/authWithToken";
14
14
  export {type GetBaseServerOptions, getBaseServer} from "./http/getBaseServer";
15
+ export {createLoopbackServer, testRequest} from "./http/testRequest";
15
16
  export {
16
17
  createLogSilencer,
17
18
  registerLogSilencing,
@@ -65,6 +65,11 @@ const beforeAllTimeoutMs = (): number => resolveMongoLaunchTimeoutMs() * 2 + 300
65
65
  export const registerBackendPreload = (options: BackendPreloadOptions = {}): void => {
66
66
  const connectMongoInBeforeAll = options.connectMongoInBeforeAll ?? true;
67
67
 
68
+ // Test files often build their app in beforeAll, which runs before any beforeEach. Code that
69
+ // reads env at build time (TerrenoApp registers the JWT strategy only when TOKEN_SECRET is set)
70
+ // must see the test env there too, so apply it now rather than waiting for the first test.
71
+ setTerrenoTestEnv(options.testEnv);
72
+
68
73
  if (options.sentryMock !== false) {
69
74
  registerSentryBunMock();
70
75
  }