@terreno/api 58.0.5 → 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 +58 -0
- package/dist/actions.d.ts +6 -0
- package/dist/api.d.ts +21 -0
- package/dist/api.js +57 -32
- package/dist/bulk.d.ts +79 -0
- package/dist/bulk.js +449 -0
- package/dist/bulkOpenApi.d.ts +15 -0
- package/dist/bulkOpenApi.js +103 -0
- package/dist/bulkTransaction.d.ts +33 -0
- package/dist/bulkTransaction.js +126 -0
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +8 -6
- package/dist/index.d.ts +3 -2
- package/dist/index.js +6 -3
- package/dist/mcp/actionTools.js +2 -0
- package/dist/mcp/grantAccess.d.ts +27 -0
- package/dist/mcp/grantAccess.js +29 -0
- package/dist/mcp/oauth.js +86 -5
- package/dist/mcp/oauthMetadata.d.ts +32 -1
- package/dist/mcp/oauthMetadata.js +53 -2
- package/dist/mcp/registry.d.ts +8 -1
- package/dist/mcp/server.js +6 -1
- package/dist/mcp/toolGenerator.d.ts +5 -1
- package/dist/mcp/toolGenerator.js +11 -0
- package/dist/mcp/types.d.ts +11 -0
- package/dist/modelRouterWrites.d.ts +23 -0
- package/dist/modelRouterWrites.js +54 -0
- package/dist/openApi.d.ts +7 -0
- package/dist/openApi.js +6 -6
- package/dist/permissions.js +5 -4
- package/dist/rbac/access.js +2 -0
- package/dist/rbac/routes.js +1 -0
- package/dist/rbac/statements.d.ts +12 -1
- package/dist/rbac/statements.js +89 -1
- package/dist/rbac/types.d.ts +9 -2
- package/dist/sync/executors.d.ts +6 -4
- package/dist/sync/executors.js +6 -2
- package/package.json +6 -6
- package/src/actions.ts +6 -0
- package/src/api.ts +95 -33
- package/src/bulk.test.ts +1256 -0
- package/src/bulk.ts +680 -0
- package/src/bulkOpenApi.test.ts +172 -0
- package/src/bulkOpenApi.ts +126 -0
- package/src/bulkTransaction.test.ts +197 -0
- package/src/bulkTransaction.ts +149 -0
- package/src/errors.ts +2 -2
- package/src/index.ts +6 -0
- package/src/isolated/bulkAtomic.isolated.ts +630 -0
- package/src/isolated/bulkStandalone.isolated.ts +133 -0
- package/src/isolated/mongoTopology.isolated.ts +29 -0
- package/src/mcp/actionTools.ts +2 -0
- package/src/mcp/grantAccess.test.ts +107 -0
- package/src/mcp/grantAccess.ts +49 -0
- package/src/mcp/oauth.test.ts +327 -0
- package/src/mcp/oauth.ts +113 -5
- package/src/mcp/oauthMetadata.test.ts +125 -1
- package/src/mcp/oauthMetadata.ts +99 -2
- package/src/mcp/registry.ts +8 -1
- package/src/mcp/server.test.ts +419 -2
- package/src/mcp/server.ts +8 -1
- package/src/mcp/toolGenerator.ts +17 -0
- package/src/mcp/types.ts +12 -0
- package/src/modelRouterWrites.ts +72 -0
- package/src/openApi.ts +1 -1
- package/src/permissions.ts +5 -5
- package/src/rbac/access.ts +3 -1
- package/src/rbac/routes.test.ts +15 -0
- package/src/rbac/routes.ts +1 -0
- package/src/rbac/statements.test.ts +23 -0
- package/src/rbac/statements.ts +100 -1
- package/src/rbac/types.ts +9 -2
- package/src/sync/executors.test.ts +27 -0
- package/src/sync/executors.ts +12 -4
- package/src/tests/mongoTopology.ts +53 -0
package/CHANGELOG.md
CHANGED
|
@@ -20,6 +20,64 @@ 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
|
+
|
|
75
|
+
## [58.0.6] - 2026-11-14
|
|
76
|
+
|
|
77
|
+
### Fixed
|
|
78
|
+
|
|
79
|
+
- `@terreno/ai` accepts `@ai-sdk/mcp` from `^1.0.21` again. 58.0.5 required `^1.0.104`, a version published days earlier, which apps that only install packages older than a minimum release age could not resolve.
|
|
80
|
+
|
|
23
81
|
## [58.0.5] - 2026-11-14
|
|
24
82
|
|
|
25
83
|
### Fixed
|
package/dist/actions.d.ts
CHANGED
|
@@ -21,6 +21,12 @@ export interface ActionMCPConfig {
|
|
|
21
21
|
name: string;
|
|
22
22
|
/** Tool description shown to the model. Defaults to the action's description or summary. */
|
|
23
23
|
description?: string;
|
|
24
|
+
/**
|
|
25
|
+
* OAuth scope a token must hold to see and call this tool. Only enforced when
|
|
26
|
+
* `mcpOAuth.grants` is set. Without it, a GET action is a `read` tool and any other a `write`
|
|
27
|
+
* tool.
|
|
28
|
+
*/
|
|
29
|
+
scope?: string;
|
|
24
30
|
}
|
|
25
31
|
export interface BaseActionConfig<TBody, TQuery, TResponse> {
|
|
26
32
|
method: "GET" | "POST";
|
package/dist/api.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { type ModelRouterBuildContext } from "./adminModelRouter";
|
|
|
5
5
|
import type { AdminConfig } from "./adminTypes";
|
|
6
6
|
import { type ModelRouterAuditConfig } from "./audit/record";
|
|
7
7
|
import { type User } from "./auth";
|
|
8
|
+
import { type ModelRouterBulkOptions } from "./bulk";
|
|
8
9
|
import type { MCPConfig } from "./mcp/types";
|
|
9
10
|
import { type ModelRouterValidationOptions } from "./openApiValidator";
|
|
10
11
|
import { type RESTPermissions } from "./permissions";
|
|
@@ -156,6 +157,13 @@ export interface ModelRouterOptions<T> {
|
|
|
156
157
|
instanceActions?: Record<string, InstanceActionConfig<T, unknown, unknown, unknown>>;
|
|
157
158
|
/** Named collection-scoped operations at `/:actionName` (GET or POST). */
|
|
158
159
|
collectionActions?: Record<string, CollectionActionConfig<unknown, unknown, unknown>>;
|
|
160
|
+
/**
|
|
161
|
+
* Opt in to `POST /bulk`: many create/update/delete operations in one request, each run
|
|
162
|
+
* through this router's permissions, hooks, validation, audit, and `responseHandler`.
|
|
163
|
+
* `true` allows all three methods with at most 100 operations per request.
|
|
164
|
+
* See docs/reference/api.md ("modelRouter bulk writes").
|
|
165
|
+
*/
|
|
166
|
+
bulk?: boolean | ModelRouterBulkOptions;
|
|
159
167
|
/**
|
|
160
168
|
* Hook that runs after `transformer.transform` but before the object is created.
|
|
161
169
|
* Can update the body fields based on the request or the user.
|
|
@@ -249,6 +257,7 @@ export interface ModelRouterOptions<T> {
|
|
|
249
257
|
create?: Record<string, unknown>;
|
|
250
258
|
update?: Record<string, unknown>;
|
|
251
259
|
delete?: Record<string, unknown>;
|
|
260
|
+
bulk?: Record<string, unknown>;
|
|
252
261
|
};
|
|
253
262
|
/**
|
|
254
263
|
* Overwrite parts of the model properties for the OpenAPI generator.
|
|
@@ -306,6 +315,18 @@ export interface ModelRouterOptions<T> {
|
|
|
306
315
|
*/
|
|
307
316
|
admin?: AdminConfig;
|
|
308
317
|
}
|
|
318
|
+
/**
|
|
319
|
+
* Validates one create or update body exactly as `POST /` or `PATCH /:id` validate theirs
|
|
320
|
+
* (OpenAPI schema, coercion, additional-property removal), returning the cleaned body or
|
|
321
|
+
* throwing the same 400. A no-op until validation is enabled globally or on the router.
|
|
322
|
+
*/
|
|
323
|
+
export declare const validateModelRouterBody: <T>({ model, options, method, body, req, }: {
|
|
324
|
+
model: ModelLike<T>;
|
|
325
|
+
options: ModelRouterOptions<T>;
|
|
326
|
+
method: "create" | "update";
|
|
327
|
+
body: Record<string, unknown>;
|
|
328
|
+
req?: Request;
|
|
329
|
+
}) => Record<string, unknown>;
|
|
309
330
|
/**
|
|
310
331
|
* Registration object returned by modelRouter when called with a path.
|
|
311
332
|
*
|
package/dist/api.js
CHANGED
|
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
36
36
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
37
|
};
|
|
38
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
-
exports.gooseRestRouter = exports.asyncHandler = exports.addPopulateToQuery = void 0;
|
|
39
|
+
exports.gooseRestRouter = exports.asyncHandler = exports.validateModelRouterBody = exports.addPopulateToQuery = void 0;
|
|
40
40
|
exports.modelRouter = modelRouter;
|
|
41
41
|
/**
|
|
42
42
|
* This is the doc comment for api.ts
|
|
@@ -52,10 +52,12 @@ const actions_1 = require("./actions");
|
|
|
52
52
|
const adminModelRouter_1 = require("./adminModelRouter");
|
|
53
53
|
const record_1 = require("./audit/record");
|
|
54
54
|
const auth_1 = require("./auth");
|
|
55
|
+
const bulk_1 = require("./bulk");
|
|
55
56
|
const collectionRegistry_1 = require("./collectionRegistry");
|
|
56
57
|
const errors_1 = require("./errors");
|
|
57
58
|
const logger_1 = require("./logger");
|
|
58
59
|
const registry_1 = require("./mcp/registry");
|
|
60
|
+
const modelRouterWrites_1 = require("./modelRouterWrites");
|
|
59
61
|
const openApi_1 = require("./openApi");
|
|
60
62
|
const openApiValidator_1 = require("./openApiValidator");
|
|
61
63
|
const permissions_1 = require("./permissions");
|
|
@@ -80,7 +82,6 @@ builtQuery, populatePaths) => {
|
|
|
80
82
|
};
|
|
81
83
|
exports.addPopulateToQuery = addPopulateToQuery;
|
|
82
84
|
// TODOS:
|
|
83
|
-
// Support bulk actions
|
|
84
85
|
// Support more complex query fields
|
|
85
86
|
// Rate limiting
|
|
86
87
|
// These are the query params that are reserved for pagination.
|
|
@@ -275,6 +276,29 @@ const getBodyValidationMiddleware = (model, options, operation) => {
|
|
|
275
276
|
}
|
|
276
277
|
return (0, openApiValidator_1.validateModelRequestBody)(model, validationOptions);
|
|
277
278
|
};
|
|
279
|
+
// Runs a body validation middleware against one body outside the Express chain and returns the
|
|
280
|
+
// cleaned body, throwing what the middleware would have passed to `next` or thrown.
|
|
281
|
+
const runBodyValidator = (middleware, body, req) => {
|
|
282
|
+
const stub = (req ? Object.create(req) : { headers: {} });
|
|
283
|
+
stub.body = (0, cloneDeep_1.default)(body);
|
|
284
|
+
let nextError;
|
|
285
|
+
middleware(stub, {}, (error) => {
|
|
286
|
+
nextError = error;
|
|
287
|
+
});
|
|
288
|
+
if (nextError) {
|
|
289
|
+
throw nextError;
|
|
290
|
+
}
|
|
291
|
+
return stub.body;
|
|
292
|
+
};
|
|
293
|
+
/**
|
|
294
|
+
* Validates one create or update body exactly as `POST /` or `PATCH /:id` validate theirs
|
|
295
|
+
* (OpenAPI schema, coercion, additional-property removal), returning the cleaned body or
|
|
296
|
+
* throwing the same 400. A no-op until validation is enabled globally or on the router.
|
|
297
|
+
*/
|
|
298
|
+
const validateModelRouterBody = ({ model, options, method, body, req, }) => {
|
|
299
|
+
return runBodyValidator(getBodyValidationMiddleware(model, options, method), body, req);
|
|
300
|
+
};
|
|
301
|
+
exports.validateModelRouterBody = validateModelRouterBody;
|
|
278
302
|
// Get query validation middleware if validation is enabled
|
|
279
303
|
const getQueryValidationMiddleware = (model, options) => {
|
|
280
304
|
const querySchema = (0, openApiValidator_1.buildQuerySchemaFromFields)(model, options.queryFields);
|
|
@@ -373,16 +397,37 @@ const _buildModelRouter = (model, options, routePath) => {
|
|
|
373
397
|
(0, registry_1.updateMCPRegistryOptions)(model.modelName, options);
|
|
374
398
|
}
|
|
375
399
|
(0, actions_1.assertNoActionCollisions)(model, options);
|
|
400
|
+
(0, bulk_1.assertNoBulkCollision)(options);
|
|
376
401
|
(0, actions_1.registerActionRoutes)(router, model, options);
|
|
377
|
-
// User endpoints run after actions; actions win on path conflicts.
|
|
378
|
-
if (options.endpoints) {
|
|
379
|
-
options.endpoints(router, options);
|
|
380
|
-
}
|
|
381
402
|
const responseHandler = options.responseHandler ?? transformers_1.defaultResponseHandler;
|
|
382
403
|
// Always install validation middleware — they are no-ops until configureOpenApiValidator() is called
|
|
383
404
|
const createValidation = getBodyValidationMiddleware(model, options, "create");
|
|
384
405
|
const updateValidation = getBodyValidationMiddleware(model, options, "update");
|
|
385
406
|
const queryValidation = getQueryValidationMiddleware(model, options);
|
|
407
|
+
const validateBulkBody = ({ method, body, req }) => runBodyValidator(method === "create" ? createValidation : updateValidation, body, req);
|
|
408
|
+
(0, bulk_1.registerBulkRoute)({
|
|
409
|
+
deps: {
|
|
410
|
+
authenticateMiddleware: auth_1.authenticateMiddleware,
|
|
411
|
+
checkPermissions: permissions_1.checkPermissions,
|
|
412
|
+
executeCreate: executors_1.executeCreate,
|
|
413
|
+
executeDelete: executors_1.executeDelete,
|
|
414
|
+
executeUpdate: executors_1.executeUpdate,
|
|
415
|
+
isExecutorConflictError: executors_1.isExecutorConflictError,
|
|
416
|
+
loadDocOr404: executors_1.loadDocOr404,
|
|
417
|
+
runPostCreate: executors_1.runPostCreate,
|
|
418
|
+
runPostDelete: executors_1.runPostDelete,
|
|
419
|
+
runPostUpdate: executors_1.runPostUpdate,
|
|
420
|
+
},
|
|
421
|
+
model,
|
|
422
|
+
options,
|
|
423
|
+
responseHandler: responseHandler,
|
|
424
|
+
router,
|
|
425
|
+
validateBody: validateBulkBody,
|
|
426
|
+
});
|
|
427
|
+
// User endpoints run after actions and bulk; those win on path conflicts.
|
|
428
|
+
if (options.endpoints) {
|
|
429
|
+
options.endpoints(router, options);
|
|
430
|
+
}
|
|
386
431
|
router.post("/", [
|
|
387
432
|
(0, auth_1.authenticateMiddleware)(options.allowAnonymous),
|
|
388
433
|
(0, openApi_1.createOpenApiMiddleware)(model, options),
|
|
@@ -618,27 +663,11 @@ const _buildModelRouter = (model, options, routePath) => {
|
|
|
618
663
|
const httpTimestampValue = Array.isArray(httpUnmodifiedSince)
|
|
619
664
|
? httpUnmodifiedSince[0]
|
|
620
665
|
: httpUnmodifiedSince;
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
? luxon_1.DateTime.fromISO(timestampValue)
|
|
627
|
-
: httpTimestampValue
|
|
628
|
-
? luxon_1.DateTime.fromHTTP(httpTimestampValue)
|
|
629
|
-
: luxon_1.DateTime.fromISO(bodyUpdatedAt);
|
|
630
|
-
concurrencyCheck = {
|
|
631
|
-
// An unparseable value round-trips as an invalid Date; the executor turns it into
|
|
632
|
-
// the 400 "Invalid conflict-detection timestamp" error after preUpdate has run.
|
|
633
|
-
ifUnmodifiedSince: clientTimestamp.toJSDate(),
|
|
634
|
-
invalidTimestampDetail: usingPreciseHeader
|
|
635
|
-
? "X-Unmodified-Since-ISO header could not be parsed as an ISO date"
|
|
636
|
-
: usingHttpHeader
|
|
637
|
-
? "If-Unmodified-Since header could not be parsed as an HTTP date"
|
|
638
|
-
: "_updatedAt body field could not be parsed as an ISO date",
|
|
639
|
-
type: "timestamp",
|
|
640
|
-
};
|
|
641
|
-
}
|
|
666
|
+
const concurrencyCheck = (0, modelRouterWrites_1.timestampConcurrencyCheck)({
|
|
667
|
+
bodyUpdatedAt,
|
|
668
|
+
httpHeader: httpTimestampValue,
|
|
669
|
+
preciseHeader: timestampValue,
|
|
670
|
+
});
|
|
642
671
|
let doc;
|
|
643
672
|
const previous = (0, record_1.snapshotAuditBefore)({ audit: options.audit, doc: existingDoc });
|
|
644
673
|
try {
|
|
@@ -657,11 +686,7 @@ const _buildModelRouter = (model, options, routePath) => {
|
|
|
657
686
|
// Duck-typed: `instanceof` breaks for Error subclasses in the compiled ES5 dist.
|
|
658
687
|
if ((0, executors_1.isExecutorConflictError)(error)) {
|
|
659
688
|
const serialized = await responseHandler(error.doc, "update", req, options);
|
|
660
|
-
return res.status(409).json(
|
|
661
|
-
data: serialized,
|
|
662
|
-
error: "Conflict",
|
|
663
|
-
message: "Document was modified since your last read",
|
|
664
|
-
});
|
|
689
|
+
return res.status(409).json((0, modelRouterWrites_1.conflictResponseBody)(serialized));
|
|
665
690
|
}
|
|
666
691
|
throw error;
|
|
667
692
|
}
|
package/dist/bulk.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `POST /<route>/bulk` for modelRouter: many create/update/delete operations in one request.
|
|
3
|
+
*
|
|
4
|
+
* Every item runs through the same transport-agnostic executors as `POST /`, `PATCH /:id`, and
|
|
5
|
+
* `DELETE /:id` (`sync/executors.ts`), so it gets the router's method and object permissions,
|
|
6
|
+
* transformer, pre/post hooks, RBAC write guards, Mongoose validation, population, audit, and
|
|
7
|
+
* `responseHandler`. Hooks receive a per-item request whose `body` is the item's body and whose
|
|
8
|
+
* `params.id` is the item's id.
|
|
9
|
+
*
|
|
10
|
+
* Docs: docs/reference/api.md ("modelRouter bulk writes").
|
|
11
|
+
*/
|
|
12
|
+
import type express from "express";
|
|
13
|
+
import type { Request } from "express";
|
|
14
|
+
import type { Model } from "mongoose";
|
|
15
|
+
import type { ModelRouterOptions } from "./api";
|
|
16
|
+
import type { authenticateMiddleware } from "./auth";
|
|
17
|
+
import type { loadDocOr404 } from "./docLoader";
|
|
18
|
+
import { type APIErrorBody } from "./errors";
|
|
19
|
+
import type { checkPermissions } from "./permissions";
|
|
20
|
+
import type { executeCreate, executeDelete, executeUpdate, isExecutorConflictError, runPostCreate, runPostDelete, runPostUpdate } from "./sync/executors";
|
|
21
|
+
/** The write operations a bulk request may carry. */
|
|
22
|
+
export type BulkMethod = "create" | "update" | "delete";
|
|
23
|
+
/** `ModelRouterOptions.bulk` object form. */
|
|
24
|
+
export interface ModelRouterBulkOptions {
|
|
25
|
+
/** Most operations one request may carry. Defaults to {@link DEFAULT_BULK_MAX_ITEMS}. */
|
|
26
|
+
maxItems?: number;
|
|
27
|
+
/** Operations this router accepts in a bulk request. Defaults to all three. */
|
|
28
|
+
methods?: BulkMethod[];
|
|
29
|
+
}
|
|
30
|
+
type ResponseHandler<T> = NonNullable<ModelRouterOptions<T>["responseHandler"]>;
|
|
31
|
+
/** Validates one item body the way the single route's body validation middleware would. */
|
|
32
|
+
export type BulkBodyValidator = (args: {
|
|
33
|
+
method: "create" | "update";
|
|
34
|
+
body: Record<string, unknown>;
|
|
35
|
+
req: Request;
|
|
36
|
+
}) => Record<string, unknown>;
|
|
37
|
+
/**
|
|
38
|
+
* Runtime functions the bulk route needs from modules that themselves import `api.ts`. `api.ts`
|
|
39
|
+
* passes them in so this module never imports them at runtime (no import cycle).
|
|
40
|
+
*/
|
|
41
|
+
export interface BulkRouteDeps {
|
|
42
|
+
authenticateMiddleware: typeof authenticateMiddleware;
|
|
43
|
+
checkPermissions: typeof checkPermissions;
|
|
44
|
+
executeCreate: typeof executeCreate;
|
|
45
|
+
executeDelete: typeof executeDelete;
|
|
46
|
+
executeUpdate: typeof executeUpdate;
|
|
47
|
+
isExecutorConflictError: typeof isExecutorConflictError;
|
|
48
|
+
loadDocOr404: typeof loadDocOr404;
|
|
49
|
+
runPostCreate: typeof runPostCreate;
|
|
50
|
+
runPostDelete: typeof runPostDelete;
|
|
51
|
+
runPostUpdate: typeof runPostUpdate;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Throws at registration when bulk is enabled and a collection action already owns `/bulk`.
|
|
55
|
+
* Actions mount before CRUD and would silently shadow the bulk route.
|
|
56
|
+
*/
|
|
57
|
+
export declare const assertNoBulkCollision: <T>(options: Pick<ModelRouterOptions<T>, "bulk" | "collectionActions">) => void;
|
|
58
|
+
/**
|
|
59
|
+
* @internal Exported for tests.
|
|
60
|
+
* Maps any error from one item to the status and JSON body the single route's error middleware
|
|
61
|
+
* would send, and logs/captures it the same way.
|
|
62
|
+
*/
|
|
63
|
+
export declare const toBulkItemError: (error: unknown) => {
|
|
64
|
+
status: number;
|
|
65
|
+
body: APIErrorBody;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Mounts `POST /bulk` on a modelRouter's router when `options.bulk` is set. Call with the
|
|
69
|
+
* collection actions, before user `endpoints` and the `/:id` routes.
|
|
70
|
+
*/
|
|
71
|
+
export declare const registerBulkRoute: <T>({ deps, router, model, options, responseHandler, validateBody, }: {
|
|
72
|
+
deps: BulkRouteDeps;
|
|
73
|
+
router: express.Router;
|
|
74
|
+
model: Model<T>;
|
|
75
|
+
options: ModelRouterOptions<T>;
|
|
76
|
+
responseHandler: ResponseHandler<T>;
|
|
77
|
+
validateBody: BulkBodyValidator;
|
|
78
|
+
}) => void;
|
|
79
|
+
export {};
|