@terreno/api 0.29.0 → 0.30.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.
Files changed (45) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/dist/actions.js +17 -8
  3. package/dist/actions.test.js +8 -3
  4. package/dist/api.arrayOperations.test.js +16 -8
  5. package/dist/api.coverage.test.js +2 -1
  6. package/dist/api.errorPaths.test.js +522 -1
  7. package/dist/api.errors.test.js +9 -0
  8. package/dist/api.js +137 -170
  9. package/dist/api.query.test.js +20 -8
  10. package/dist/api.test.js +12 -6
  11. package/dist/auth.coverage.test.d.ts +1 -0
  12. package/dist/auth.coverage.test.js +202 -0
  13. package/dist/auth.test.js +159 -0
  14. package/dist/docLoader.js +5 -1
  15. package/dist/envConfigurationPlugin.d.ts +1 -1
  16. package/dist/envConfigurationPlugin.js +0 -2
  17. package/dist/errors.d.ts +14 -0
  18. package/dist/errors.js +24 -2
  19. package/dist/errors.test.js +137 -0
  20. package/dist/httpClient.js +5 -1
  21. package/dist/plugins.d.ts +4 -4
  22. package/dist/plugins.js +51 -9
  23. package/dist/plugins.test.js +61 -17
  24. package/dist/realtime/registry.d.ts +3 -2
  25. package/package.json +2 -2
  26. package/src/actions.test.ts +8 -3
  27. package/src/actions.ts +19 -10
  28. package/src/api.arrayOperations.test.ts +16 -8
  29. package/src/api.coverage.test.ts +2 -1
  30. package/src/api.errorPaths.test.ts +313 -3
  31. package/src/api.errors.test.ts +12 -0
  32. package/src/api.query.test.ts +20 -8
  33. package/src/api.test.ts +12 -6
  34. package/src/api.ts +141 -161
  35. package/src/auth.coverage.test.ts +101 -0
  36. package/src/auth.test.ts +125 -2
  37. package/src/docLoader.ts +6 -2
  38. package/src/envConfigurationPlugin.ts +2 -6
  39. package/src/errors.test.ts +106 -1
  40. package/src/errors.ts +25 -1
  41. package/src/httpClient.ts +6 -2
  42. package/src/plugins.test.ts +45 -9
  43. package/src/plugins.ts +72 -35
  44. package/src/realtime/changeStreamWatcher.ts +8 -1
  45. package/src/realtime/registry.ts +3 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,84 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.29.1
4
+
5
+ Patch release for `@terreno/api` 0.28.0's `APIError` rework. In 0.28.0 `Error.message` became exactly
6
+ `title`, so anywhere the framework re-wrapped an inner error and rebuilt the wrapper's text with
7
+ `errorMessage(inner)`, the inner error's `detail`, `code`, `meta`, `fields`, and `status` were
8
+ silently dropped. This release makes `modelRouter` pass those errors through instead.
9
+
10
+ ### Fixed
11
+
12
+ - **`modelRouter` no longer re-wraps an `APIError` raised inside your code.** Every catch that used
13
+ to build a generic wrapper now re-throws an `APIError` untouched, so its `status`, `title`,
14
+ `detail`, `code`, and `meta` reach the client. This covers `model.create()`, the create/update
15
+ `doc.save()`, populate-after-create, `postCreate`, `postUpdate`, `postDelete`, `queryFilter`, the
16
+ list query, list serialization, `doc.deleteOne()`, every `responseHandler` call, and the
17
+ `preUpdate` / `doc.save()` / `postUpdate` steps of the array-operation `PATCH` helper. Previously
18
+ only the `transform`, `preCreate`, `preUpdate`, and `preDelete` catches had the guard. The most
19
+ common casualty was an `APIError` thrown from Mongoose document middleware (`pre("save")`,
20
+ `pre("validate")`), which reached the client as `{status: 400, title: "Create error", code:
21
+ "create-error"}` with the consumer's `code` and `meta` gone.
22
+ - **Mongoose validation and cast errors from `modelRouter` writes now carry per-field messages
23
+ again.** The `model.create()` and `doc.save()` catches run `mongooseErrorToAPIError` before falling
24
+ back to a generic wrapper, so a `ValidationError` surfaces as
25
+ `{status: 400, title: "Validation failed", meta: {fields: {...}}}` rather than
26
+ `{title: "Create error", detail: "Validation failed: name: Path \`name\` is required."}`. These
27
+ errors are also marked `disableExternalErrorTracking`, so bad client input stops paging Sentry.
28
+ - **`queryFilter` wrapper details are readable.** That catch used `String(error)`, which emitted
29
+ `"Error: <message>"` for an `Error` and `"[object Object]"` for a thrown non-`Error`. It now uses
30
+ the same message extraction as every other catch.
31
+ - **Framework-thrown errors follow the 0.28.0 contract.** `api.ts`, `plugins.ts`, `actions.ts`, and
32
+ `docLoader.ts` no longer interpolate per-occurrence values into `title`; the specific text moved to
33
+ `detail` (plus `meta` / `source` where it is structured), and each error carries a kebab-case
34
+ `code` and, where applicable, a status subclass (`BadRequestError`, `ForbiddenError`,
35
+ `NotFoundError`, `ValidationError`, `InternalServerError`). Titles are now stable strings, so
36
+ Sentry groups them by logical error instead of by occurrence.
37
+ - **`findOneOrNone`, `findOneOrNoneFor`, and `findExactlyOne` accept `Partial<APIErrorOptions>`** for
38
+ `errorArgs` instead of the deprecated `Partial<APIErrorConstructor>`. `errorArgs` is still applied
39
+ last, so every field including `status` remains overridable.
40
+
41
+ ### Added
42
+
43
+ - **`errorDetail(error)`** — returns `` `${title}: ${detail}` `` for an `APIError` and
44
+ `errorMessage(error)` for anything else. Used for the `detail` of framework wrapper errors so a
45
+ nested `APIError`'s text is never lost if one does reach a wrapper.
46
+
47
+ ### Changed (behavior)
48
+
49
+ - **`apiUnauthorizedMiddleware` only matches a plain `Error("Unauthorized")`.** It is registered
50
+ ahead of `apiErrorMiddleware`, and because `message` is now exactly `title`, it was rewriting **any**
51
+ `APIError` titled `"Unauthorized"` into a bare 401 and discarding its status, `code`, and `detail`.
52
+ A `new ForbiddenError({title: "Unauthorized"})` now stays a **403** with its own body; Passport's
53
+ plain `Error("Unauthorized")` still becomes a quiet 401.
54
+ - **An `APIError` thrown from a hook or from Mongoose middleware now returns its own status.**
55
+ Previously the wrapper's hardcoded status (usually 400, or 403 for `transform`/`preDelete`) won.
56
+ If you throw a non-4xx `APIError` from `postCreate`, `postUpdate`, `postDelete`, `queryFilter`,
57
+ `responseHandler`, or a `pre("save")` hook, clients now see that status instead of 400.
58
+ - **Framework error titles changed** where they used to embed per-occurrence values. The old text is
59
+ preserved in `detail`. Notable renames: `` `${param} is not allowed as a query param.` `` →
60
+ `"Query parameter not allowed"`; `` `Invalid page: ${page}` `` → `"Invalid page"`;
61
+ `` `Invalid date for query parameter ${key}` `` → `"Invalid date query parameter"`;
62
+ `` `Could not find ${field}/${itemId}` `` → `"Array item not found"`;
63
+ `` `Could not find document to PATCH: ${id}` `` → `"Document not found"`;
64
+ `` `Malformed body, array operations…` `` → `"Malformed array operation body"`;
65
+ `` `Invalid array operation: ${op}` `` → `"Invalid array operation"`;
66
+ `` `Patch not allowed for user…` `` → `"Update not allowed"`;
67
+ `` `Access to ${method} on ${model}…denied` `` → `"Access denied"` (both `modelRouter` array
68
+ operations and `runActionPermissions`); and the `plugins.ts` query statics now use
69
+ `"findExactlyOne query returned no documents"`, `"findExactlyOne query returned multiple
70
+ documents"`, `"findOne query returned multiple documents"`, and `"upsert find query returned
71
+ multiple documents"` with the model name in `detail`/`meta`. Clients that string-match on `title`
72
+ should match on `code` instead.
73
+ - **A Mongoose validation failure on an array-operation `PATCH` returns `"Validation failed"`** with
74
+ `meta.fields` rather than `"PATCH Pre Update error"`.
75
+
76
+ ### Unchanged
77
+
78
+ No HTTP statuses were changed. The 405 that `runActionPermissions` returns when a pre-document
79
+ permission check fails is kept as-is: `modelRouter`'s array operations return 405 for the same check,
80
+ so it is an existing (if odd) convention rather than a typo to fix in a patch release.
81
+
3
82
  ## 0.20.0
4
83
 
5
84
  ### Changed (breaking)
package/dist/actions.js CHANGED
@@ -121,15 +121,22 @@ var runActionPermissions = function (action, scope, model, req, doc) { return __
121
121
  return [2 /*return*/];
122
122
  }
123
123
  if (!doc) {
124
+ // Status kept at 405 for backwards compatibility with the same pre-document permission denial
125
+ // in modelRouter's array operations; changing it would break consumers matching on it.
124
126
  throw new errors_1.APIError({
127
+ code: "action-access-denied",
128
+ detail: "Access to ".concat(method.toUpperCase(), " on ").concat(model.modelName, " ") + "denied for ".concat((_a = req.user) === null || _a === void 0 ? void 0 : _a.id),
129
+ meta: { action: method.toUpperCase(), model: model.modelName },
125
130
  status: 405,
126
- title: "Access to ".concat(method.toUpperCase(), " on ").concat(model.modelName, " ") + "denied for ".concat((_a = req.user) === null || _a === void 0 ? void 0 : _a.id),
131
+ title: "Access denied",
127
132
  });
128
133
  }
129
- throw new errors_1.APIError({
130
- status: 403,
131
- title: "Access to ".concat(method.toUpperCase(), " on ").concat(model.modelName, ":").concat(req.params.id, " ") +
134
+ throw new errors_1.ForbiddenError({
135
+ code: "action-access-denied",
136
+ detail: "Access to ".concat(method.toUpperCase(), " on ").concat(model.modelName, ":").concat(req.params.id, " ") +
132
137
  "denied for ".concat((_b = req.user) === null || _b === void 0 ? void 0 : _b.id),
138
+ meta: { action: method.toUpperCase(), model: model.modelName },
139
+ title: "Access denied",
133
140
  });
134
141
  }
135
142
  });
@@ -161,9 +168,10 @@ var validateActionRequest = function (_a) {
161
168
  if (action.body) {
162
169
  var parsedBody = action.body.safeParse(req.body);
163
170
  if (!parsedBody.success) {
164
- throw new errors_1.APIError({
171
+ throw new errors_1.ValidationError({
172
+ code: "action-body-validation-failed",
173
+ detail: "The request body did not match the action's schema",
165
174
  fields: flattenZodFieldErrors(parsedBody.error.flatten().fieldErrors),
166
- status: 400,
167
175
  title: "Validation failed",
168
176
  });
169
177
  }
@@ -176,9 +184,10 @@ var validateActionRequest = function (_a) {
176
184
  if (action.query) {
177
185
  var parsedQuery = action.query.safeParse(req.query);
178
186
  if (!parsedQuery.success) {
179
- throw new errors_1.APIError({
187
+ throw new errors_1.ValidationError({
188
+ code: "action-query-validation-failed",
189
+ detail: "The query parameters did not match the action's schema",
180
190
  fields: flattenZodFieldErrors(parsedQuery.error.flatten().fieldErrors),
181
- status: 400,
182
191
  title: "Validation failed",
183
192
  });
184
193
  }
@@ -265,7 +265,8 @@ var allPermissions = {
265
265
  return [4 /*yield*/, agent.post("/food/disabled").send({}).expect(405)];
266
266
  case 2:
267
267
  res = _a.sent();
268
- (0, bun_test_1.expect)(res.body.title).toContain("Access to CREATE on Food denied");
268
+ (0, bun_test_1.expect)(res.body.title).toBe("Access denied");
269
+ (0, bun_test_1.expect)(res.body.detail).toContain("Access to CREATE on Food denied");
269
270
  return [2 /*return*/];
270
271
  }
271
272
  });
@@ -485,7 +486,8 @@ var allPermissions = {
485
486
  return [4 /*yield*/, agent.post("/food/adminOnly").send({}).expect(405)];
486
487
  case 2:
487
488
  res = _a.sent();
488
- (0, bun_test_1.expect)(res.body.title).toContain("Access to CREATE on Food denied");
489
+ (0, bun_test_1.expect)(res.body.title).toBe("Access denied");
490
+ (0, bun_test_1.expect)(res.body.detail).toContain("Access to CREATE on Food denied");
489
491
  return [2 /*return*/];
490
492
  }
491
493
  });
@@ -522,7 +524,8 @@ var allPermissions = {
522
524
  return [4 /*yield*/, agent.post("/food/".concat(adminFood._id, "/ownerOnly")).send({}).expect(403)];
523
525
  case 3:
524
526
  res = _a.sent();
525
- (0, bun_test_1.expect)(res.body.title).toContain("Access to UPDATE on Food:".concat(adminFood._id, " denied"));
527
+ (0, bun_test_1.expect)(res.body.title).toBe("Access denied");
528
+ (0, bun_test_1.expect)(res.body.detail).toContain("Access to UPDATE on Food:".concat(adminFood._id, " denied"));
526
529
  return [2 /*return*/];
527
530
  }
528
531
  });
@@ -607,6 +610,7 @@ var allPermissions = {
607
610
  case 1:
608
611
  res = _a.sent();
609
612
  (0, bun_test_1.expect)(res.body.title).toBe("Validation failed");
613
+ (0, bun_test_1.expect)(res.body.code).toBe("action-body-validation-failed");
610
614
  (0, bun_test_1.expect)(res.body.meta.fields.email).toBeDefined();
611
615
  return [2 /*return*/];
612
616
  }
@@ -666,6 +670,7 @@ var allPermissions = {
666
670
  case 1:
667
671
  res = _a.sent();
668
672
  (0, bun_test_1.expect)(res.body.title).toBe("Validation failed");
673
+ (0, bun_test_1.expect)(res.body.code).toBe("action-query-validation-failed");
669
674
  (0, bun_test_1.expect)(res.body.meta.fields.email).toBeDefined();
670
675
  return [2 /*return*/];
671
676
  }
@@ -145,7 +145,8 @@ var transformers_1 = require("./transformers");
145
145
  .expect(400)];
146
146
  case 1:
147
147
  res = _a.sent();
148
- (0, bun_test_1.expect)(res.body.title).toBe("Malformed body, array operations should have a single, top level key, got: name,show");
148
+ (0, bun_test_1.expect)(res.body.title).toBe("Malformed array operation body");
149
+ (0, bun_test_1.expect)(res.body.detail).toBe("Malformed body, array operations should have a single, top level key, got: name,show");
149
150
  return [4 /*yield*/, agent
150
151
  .post("/food/".concat(apple._id, "/categories"))
151
152
  .send({ categories: { name: "Good Seller", show: false } })
@@ -175,7 +176,8 @@ var transformers_1 = require("./transformers");
175
176
  .expect(404)];
176
177
  case 1:
177
178
  res = _a.sent();
178
- (0, bun_test_1.expect)(res.body.title).toBe("Could not find categories/xyz");
179
+ (0, bun_test_1.expect)(res.body.title).toBe("Array item not found");
180
+ (0, bun_test_1.expect)(res.body.detail).toBe("Could not find categories/xyz");
179
181
  return [4 /*yield*/, agent
180
182
  .patch("/food/".concat(apple._id, "/categories/").concat(apple.categories[1]._id))
181
183
  .send({ categories: { name: "Good Seller", show: false } })
@@ -195,7 +197,8 @@ var transformers_1 = require("./transformers");
195
197
  case 0: return [4 /*yield*/, agent.delete("/food/".concat(apple._id, "/categories/xyz")).expect(404)];
196
198
  case 1:
197
199
  res = _a.sent();
198
- (0, bun_test_1.expect)(res.body.title).toBe("Could not find categories/xyz");
200
+ (0, bun_test_1.expect)(res.body.title).toBe("Array item not found");
201
+ (0, bun_test_1.expect)(res.body.detail).toBe("Could not find categories/xyz");
199
202
  return [4 /*yield*/, agent
200
203
  .delete("/food/".concat(apple._id, "/categories/").concat(apple.categories[0]._id))
201
204
  .expect(200)];
@@ -234,7 +237,8 @@ var transformers_1 = require("./transformers");
234
237
  .expect(404)];
235
238
  case 1:
236
239
  res = _a.sent();
237
- (0, bun_test_1.expect)(res.body.title).toBe("Could not find tags/xyz");
240
+ (0, bun_test_1.expect)(res.body.title).toBe("Array item not found");
241
+ (0, bun_test_1.expect)(res.body.detail).toBe("Could not find tags/xyz");
238
242
  return [4 /*yield*/, agent
239
243
  .patch("/food/".concat(apple._id, "/tags/healthy"))
240
244
  .send({ tags: "unhealthy" })
@@ -253,7 +257,8 @@ var transformers_1 = require("./transformers");
253
257
  case 0: return [4 /*yield*/, agent.delete("/food/".concat(apple._id, "/tags/xyz")).expect(404)];
254
258
  case 1:
255
259
  res = _a.sent();
256
- (0, bun_test_1.expect)(res.body.title).toBe("Could not find tags/xyz");
260
+ (0, bun_test_1.expect)(res.body.title).toBe("Array item not found");
261
+ (0, bun_test_1.expect)(res.body.detail).toBe("Could not find tags/xyz");
257
262
  return [4 /*yield*/, agent.delete("/food/".concat(apple._id, "/tags/healthy")).expect(200)];
258
263
  case 2:
259
264
  res = _a.sent();
@@ -650,7 +655,8 @@ var transformers_1 = require("./transformers");
650
655
  return [4 /*yield*/, agent.post("/food/".concat(apple._id, "/tags")).send({ tags: "organic" }).expect(405)];
651
656
  case 2:
652
657
  res = _a.sent();
653
- (0, bun_test_1.expect)(res.body.title).toContain("Access to PATCH");
658
+ (0, bun_test_1.expect)(res.body.title).toBe("Access denied");
659
+ (0, bun_test_1.expect)(res.body.detail).toContain("Access to PATCH");
654
660
  return [2 /*return*/];
655
661
  }
656
662
  });
@@ -678,7 +684,8 @@ var transformers_1 = require("./transformers");
678
684
  return [4 /*yield*/, agent.post("/food/".concat(fakeId, "/tags")).send({ tags: "organic" }).expect(404)];
679
685
  case 2:
680
686
  res = _a.sent();
681
- (0, bun_test_1.expect)(res.body.title).toContain("Could not find document to PATCH");
687
+ (0, bun_test_1.expect)(res.body.title).toBe("Document not found");
688
+ (0, bun_test_1.expect)(res.body.detail).toContain("Could not find document to PATCH");
682
689
  return [2 /*return*/];
683
690
  }
684
691
  });
@@ -707,7 +714,8 @@ var transformers_1 = require("./transformers");
707
714
  return [4 /*yield*/, agent.post("/food/".concat(apple._id, "/tags")).send({ tags: "organic" }).expect(403)];
708
715
  case 2:
709
716
  res = _a.sent();
710
- (0, bun_test_1.expect)(res.body.title).toContain("Patch not allowed");
717
+ (0, bun_test_1.expect)(res.body.title).toBe("Update not allowed");
718
+ (0, bun_test_1.expect)(res.body.detail).toContain("Patch not allowed");
711
719
  return [2 /*return*/];
712
720
  }
713
721
  });
@@ -158,7 +158,8 @@ var ExplosiveModel = mongoose_1.default.model("ExplosiveCoverage", explosiveSche
158
158
  .expect(400)];
159
159
  case 1:
160
160
  res = _a.sent();
161
- (0, bun_test_1.expect)(res.body.title).toContain("PATCH Pre Update error");
161
+ (0, bun_test_1.expect)(res.body.title).toBe("Validation failed");
162
+ (0, bun_test_1.expect)(res.body.meta.fields["eatenBy.0"]).toContain("ObjectId");
162
163
  return [2 /*return*/];
163
164
  }
164
165
  });