@terreno/api 0.26.0 → 0.28.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 (122) hide show
  1. package/dist/__tests__/openApiCompat.test.js +8 -2
  2. package/dist/actions.openApi.test.js +1 -0
  3. package/dist/actions.test.js +3 -1
  4. package/dist/api.arrayOperations.test.js +1 -0
  5. package/dist/api.coverage.test.d.ts +1 -0
  6. package/dist/api.coverage.test.js +193 -0
  7. package/dist/api.errorPaths.test.d.ts +1 -0
  8. package/dist/api.errorPaths.test.js +280 -0
  9. package/dist/api.errors.test.js +7 -7
  10. package/dist/api.hooks.test.js +66 -8
  11. package/dist/api.js +245 -206
  12. package/dist/api.query.test.js +1 -0
  13. package/dist/api.test.js +11 -4
  14. package/dist/auth.js +1 -0
  15. package/dist/auth.test.js +123 -1
  16. package/dist/betterAuthSetup.js +1 -0
  17. package/dist/betterAuthSetup.test.js +1 -0
  18. package/dist/config.js +7 -4
  19. package/dist/config.test.js +28 -3
  20. package/dist/configuration.test.js +1 -0
  21. package/dist/configurationApp.js +1 -0
  22. package/dist/configurationPlugin.test.js +80 -0
  23. package/dist/consentApp.test.js +1 -0
  24. package/dist/docLoader.js +16 -54
  25. package/dist/docLoader.test.js +2 -1
  26. package/dist/envConfigurationPlugin.js +1 -0
  27. package/dist/errors.d.ts +72 -5
  28. package/dist/errors.js +265 -67
  29. package/dist/errors.test.js +163 -13
  30. package/dist/example.js +3 -2
  31. package/dist/expressServer.test.js +1 -0
  32. package/dist/githubAuth.js +2 -0
  33. package/dist/githubAuth.test.js +1 -0
  34. package/dist/httpClient.d.ts +2 -3
  35. package/dist/httpClient.js +4 -4
  36. package/dist/httpClient.test.js +3 -2
  37. package/dist/logger.test.js +107 -0
  38. package/dist/notifiers/googleChatNotifier.test.js +2 -1
  39. package/dist/notifiers/slackNotifier.test.js +1 -1
  40. package/dist/notifiers/zoomNotifier.test.js +2 -1
  41. package/dist/openApi.test.js +1 -0
  42. package/dist/openApiBuilder.js +2 -1
  43. package/dist/openApiBuilder.test.js +3 -2
  44. package/dist/openApiValidator.js +1 -0
  45. package/dist/openApiValidator.test.js +41 -0
  46. package/dist/permissions.js +0 -2
  47. package/dist/permissions.middleware.test.js +8 -42
  48. package/dist/permissions.test.js +1 -0
  49. package/dist/plugins.js +8 -0
  50. package/dist/plugins.test.js +5 -2
  51. package/dist/populate.js +4 -2
  52. package/dist/populate.test.js +1 -0
  53. package/dist/realtime/realtime.test.js +13 -3
  54. package/dist/realtime/types.d.ts +1 -1
  55. package/dist/requestContext.test.js +28 -0
  56. package/dist/terrenoApp.js +1 -0
  57. package/dist/tests/createTestData.js +11 -6
  58. package/dist/tests/models.js +1 -0
  59. package/dist/transformers.js +4 -2
  60. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +3 -1
  61. package/package.json +7 -7
  62. package/src/__tests__/openApiCompat.test.ts +8 -2
  63. package/src/actions.openApi.test.ts +1 -0
  64. package/src/actions.test.ts +3 -1
  65. package/src/api.arrayOperations.test.ts +1 -0
  66. package/src/api.coverage.test.ts +123 -0
  67. package/src/api.errorPaths.test.ts +173 -0
  68. package/src/api.errors.test.ts +7 -7
  69. package/src/api.hooks.test.ts +25 -1
  70. package/src/api.query.test.ts +1 -0
  71. package/src/api.test.ts +11 -4
  72. package/src/api.ts +106 -57
  73. package/src/auth.test.ts +92 -3
  74. package/src/auth.ts +6 -0
  75. package/src/betterAuthSetup.test.ts +1 -0
  76. package/src/betterAuthSetup.ts +3 -0
  77. package/src/config.test.ts +25 -3
  78. package/src/config.ts +7 -4
  79. package/src/configuration.test.ts +1 -0
  80. package/src/configurationApp.ts +2 -0
  81. package/src/configurationPlugin.test.ts +46 -1
  82. package/src/consentApp.test.ts +1 -0
  83. package/src/docLoader.test.ts +2 -1
  84. package/src/docLoader.ts +17 -20
  85. package/src/envConfigurationPlugin.ts +2 -0
  86. package/src/errors.test.ts +178 -13
  87. package/src/errors.ts +278 -79
  88. package/src/example.ts +3 -2
  89. package/src/expressServer.test.ts +1 -0
  90. package/src/expressServer.ts +4 -2
  91. package/src/githubAuth.test.ts +1 -0
  92. package/src/githubAuth.ts +2 -0
  93. package/src/httpClient.test.ts +3 -2
  94. package/src/httpClient.ts +4 -4
  95. package/src/logger.test.ts +78 -0
  96. package/src/notifiers/googleChatNotifier.test.ts +2 -2
  97. package/src/notifiers/slackNotifier.test.ts +2 -2
  98. package/src/notifiers/zoomNotifier.test.ts +2 -2
  99. package/src/openApi.test.ts +1 -0
  100. package/src/openApiBuilder.test.ts +7 -6
  101. package/src/openApiBuilder.ts +2 -1
  102. package/src/openApiValidator.test.ts +64 -0
  103. package/src/openApiValidator.ts +1 -0
  104. package/src/permissions.middleware.test.ts +8 -11
  105. package/src/permissions.test.ts +1 -0
  106. package/src/permissions.ts +0 -2
  107. package/src/plugins.test.ts +5 -2
  108. package/src/plugins.ts +9 -0
  109. package/src/populate.test.ts +1 -0
  110. package/src/populate.ts +4 -2
  111. package/src/realtime/realtime.test.ts +13 -3
  112. package/src/realtime/realtimeApp.ts +1 -0
  113. package/src/realtime/registry.ts +1 -0
  114. package/src/realtime/types.ts +1 -2
  115. package/src/requestContext.test.ts +32 -0
  116. package/src/terrenoApp.ts +1 -0
  117. package/src/tests/createTestData.ts +11 -6
  118. package/src/tests/models.ts +1 -0
  119. package/src/transformers.ts +4 -2
  120. package/src/vendor/wesleytodd-openapi/lib/generate-doc.js +4 -1
  121. package/tsconfig.json +4 -4
  122. /package/{types.d.ts → src/types.d.ts} +0 -0
package/dist/errors.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { NextFunction, Request, Response } from "express";
2
2
  import { Schema } from "mongoose";
3
- export interface APIErrorConstructor {
3
+ export interface APIErrorOptions {
4
4
  title: string;
5
5
  fields?: {
6
6
  [id: string]: string;
@@ -19,16 +19,46 @@ export interface APIErrorConstructor {
19
19
  header?: string;
20
20
  };
21
21
  meta?: {
22
- [id: string]: string;
22
+ [id: string]: unknown;
23
23
  };
24
+ cause?: unknown;
25
+ /** @deprecated Use `cause` instead. Kept as an alias for backwards compatibility. */
24
26
  error?: unknown;
25
27
  disableExternalErrorTracking?: boolean;
26
28
  }
29
+ /** @deprecated Use {@link APIErrorOptions} instead. */
30
+ export type APIErrorConstructor = APIErrorOptions;
31
+ export interface APIErrorBody {
32
+ status: number;
33
+ title: string;
34
+ id?: string;
35
+ links?: {
36
+ about?: string;
37
+ type?: string;
38
+ };
39
+ code?: string;
40
+ detail?: string;
41
+ source?: {
42
+ pointer?: string;
43
+ parameter?: string;
44
+ header?: string;
45
+ };
46
+ meta?: {
47
+ [id: string]: unknown;
48
+ };
49
+ disableExternalErrorTracking?: boolean;
50
+ }
27
51
  /**
28
52
  * APIError is a simple way to throw an error in an API route and control what is shown and the
29
53
  * HTTP code displayed. It follows the JSONAPI spec to standardize the fields,
30
54
  * allowing the UI to show more consistent, better error messages.
31
55
  *
56
+ * It uses the standard `Error` fields the way external tools (e.g. Sentry) expect:
57
+ * - `message` is exactly `title` — a stable, human-readable summary of the problem type.
58
+ * - `name` is the error type, derived from the subclass name, `code`, or `status`
59
+ * (e.g. a 404 becomes "NotFoundError").
60
+ * - `cause` holds the wrapped original error, so linked exceptions keep their own stack.
61
+ *
32
62
  * ```ts
33
63
  * throw new APIError({
34
64
  * title: "Only an admin can update that!",
@@ -39,7 +69,7 @@ export interface APIErrorConstructor {
39
69
  * ```
40
70
  */
41
71
  export declare class APIError extends Error {
42
- title: string;
72
+ readonly isTerrenoAPIError = true;
43
73
  id: string | undefined;
44
74
  links: {
45
75
  about?: string;
@@ -56,9 +86,42 @@ export declare class APIError extends Error {
56
86
  meta: {
57
87
  [id: string]: unknown;
58
88
  } | undefined;
59
- error?: unknown;
60
89
  disableExternalErrorTracking?: boolean;
61
- constructor(data: APIErrorConstructor);
90
+ constructor(options: APIErrorOptions);
91
+ /** @deprecated Use the standard `cause` field instead. */
92
+ get error(): unknown;
93
+ get title(): string;
94
+ toJSON(): APIErrorBody;
95
+ }
96
+ /** Options accepted by the status-specific APIError subclasses: a title string or full options. */
97
+ export type APIErrorSubclassOptions = Omit<APIErrorOptions, "status"> | string;
98
+ /** 400 Bad Request. */
99
+ export declare class BadRequestError extends APIError {
100
+ constructor(options: APIErrorSubclassOptions);
101
+ }
102
+ /** 401 Unauthorized. */
103
+ export declare class UnauthorizedError extends APIError {
104
+ constructor(options: APIErrorSubclassOptions);
105
+ }
106
+ /** 403 Forbidden. */
107
+ export declare class ForbiddenError extends APIError {
108
+ constructor(options: APIErrorSubclassOptions);
109
+ }
110
+ /** 404 Not Found. */
111
+ export declare class NotFoundError extends APIError {
112
+ constructor(options: APIErrorSubclassOptions);
113
+ }
114
+ /** 409 Conflict. */
115
+ export declare class ConflictError extends APIError {
116
+ constructor(options: APIErrorSubclassOptions);
117
+ }
118
+ /** 400 Bad Request with a "ValidationError" type, for request/schema validation failures. */
119
+ export declare class ValidationError extends APIError {
120
+ constructor(options: APIErrorSubclassOptions);
121
+ }
122
+ /** 500 Internal Server Error. */
123
+ export declare class InternalServerError extends APIError {
124
+ constructor(options: APIErrorSubclassOptions);
62
125
  }
63
126
  export declare const errorsPlugin: (schema: Schema) => void;
64
127
  export declare const isAPIError: (error: unknown) => error is APIError;
@@ -72,6 +135,10 @@ export declare const errorStack: (error: unknown) => string;
72
135
  * this property attached.
73
136
  */
74
137
  export declare const getDisableExternalErrorTracking: (error: unknown) => boolean | undefined;
138
+ /**
139
+ * Creates an APIError body to send to clients as JSON.
140
+ * @deprecated Use `error.toJSON()` instead.
141
+ */
75
142
  export declare const getAPIErrorBody: (error: APIError) => Record<string, unknown>;
76
143
  export declare const apiUnauthorizedMiddleware: (err: Error, _req: Request, res: Response, next: NextFunction) => void;
77
144
  /**
package/dist/errors.js CHANGED
@@ -14,6 +14,17 @@ var __extends = (this && this.__extends) || (function () {
14
14
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
15
  };
16
16
  })();
17
+ var __assign = (this && this.__assign) || function () {
18
+ __assign = Object.assign || function(t) {
19
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
20
+ s = arguments[i];
21
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
+ t[p] = s[p];
23
+ }
24
+ return t;
25
+ };
26
+ return __assign.apply(this, arguments);
27
+ };
17
28
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
29
  if (k2 === undefined) k2 = k;
19
30
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -75,16 +86,62 @@ var __read = (this && this.__read) || function (o, n) {
75
86
  return ar;
76
87
  };
77
88
  Object.defineProperty(exports, "__esModule", { value: true });
78
- exports.apiFallthroughErrorMiddleware = exports.apiErrorMiddleware = exports.mongooseErrorToAPIError = exports.apiUnauthorizedMiddleware = exports.getAPIErrorBody = exports.getDisableExternalErrorTracking = exports.errorStack = exports.errorMessage = exports.isAPIError = exports.errorsPlugin = exports.APIError = void 0;
89
+ exports.apiFallthroughErrorMiddleware = exports.apiErrorMiddleware = exports.mongooseErrorToAPIError = exports.apiUnauthorizedMiddleware = exports.getAPIErrorBody = exports.getDisableExternalErrorTracking = exports.errorStack = exports.errorMessage = exports.isAPIError = exports.errorsPlugin = exports.InternalServerError = exports.ValidationError = exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorizedError = exports.BadRequestError = exports.APIError = void 0;
79
90
  // https://jsonapi.org/format/#errors
80
91
  var Sentry = __importStar(require("@sentry/bun"));
81
92
  var mongoose_1 = __importStar(require("mongoose"));
82
93
  var logger_1 = require("./logger");
94
+ // Maps common HTTP statuses to a standard Error name so external tools (Sentry, log explorers)
95
+ // show a meaningful error type instead of a generic "APIError".
96
+ var STATUS_ERROR_NAMES = {
97
+ 400: "BadRequestError",
98
+ 401: "UnauthorizedError",
99
+ 403: "ForbiddenError",
100
+ 404: "NotFoundError",
101
+ 405: "MethodNotAllowedError",
102
+ 409: "ConflictError",
103
+ 410: "GoneError",
104
+ 412: "PreconditionFailedError",
105
+ 413: "PayloadTooLargeError",
106
+ 415: "UnsupportedMediaTypeError",
107
+ 422: "ValidationError",
108
+ 429: "TooManyRequestsError",
109
+ 500: "InternalServerError",
110
+ 501: "NotImplementedError",
111
+ 502: "BadGatewayError",
112
+ 503: "ServiceUnavailableError",
113
+ 504: "GatewayTimeoutError",
114
+ };
115
+ // Converts an application error code like "update-admin-error" into a PascalCase Error name
116
+ // like "UpdateAdminError" so each logical error gets its own type in external tools.
117
+ var errorNameFromCode = function (code) {
118
+ var words = code.split(/[^a-zA-Z0-9]+/).filter(Boolean);
119
+ if (words.length === 0) {
120
+ return undefined;
121
+ }
122
+ return words.map(function (word) { return word.charAt(0).toUpperCase() + word.slice(1); }).join("");
123
+ };
124
+ var normalizeStatus = function (status) {
125
+ if (status === undefined || status === null) {
126
+ return 500;
127
+ }
128
+ var truncated = Math.trunc(status);
129
+ if (!Number.isFinite(truncated) || truncated < 400 || truncated > 599) {
130
+ return 500;
131
+ }
132
+ return truncated;
133
+ };
83
134
  /**
84
135
  * APIError is a simple way to throw an error in an API route and control what is shown and the
85
136
  * HTTP code displayed. It follows the JSONAPI spec to standardize the fields,
86
137
  * allowing the UI to show more consistent, better error messages.
87
138
  *
139
+ * It uses the standard `Error` fields the way external tools (e.g. Sentry) expect:
140
+ * - `message` is exactly `title` — a stable, human-readable summary of the problem type.
141
+ * - `name` is the error type, derived from the subclass name, `code`, or `status`
142
+ * (e.g. a 404 becomes "NotFoundError").
143
+ * - `cause` holds the wrapped original error, so linked exceptions keep their own stack.
144
+ *
88
145
  * ```ts
89
146
  * throw new APIError({
90
147
  * title: "Only an admin can update that!",
@@ -96,46 +153,144 @@ var logger_1 = require("./logger");
96
153
  */
97
154
  var APIError = /** @class */ (function (_super) {
98
155
  __extends(APIError, _super);
99
- function APIError(data) {
156
+ function APIError(options) {
157
+ var _newTarget = this.constructor;
100
158
  var _this = this;
101
- var errorStack = data.error instanceof Error && data.error.stack ? "\n".concat(data.error.stack) : "";
102
- // Include details in when the error is printed to the console or sent to Sentry.
103
- _this = _super.call(this, "".concat(data.title).concat(data.detail ? ": ".concat(data.detail) : "").concat(errorStack)) || this;
104
- _this.name = "APIError";
105
- var title = data.title, id = data.id, links = data.links, status = data.status, code = data.code, detail = data.detail, source = data.source, meta = data.meta, fields = data.fields, error = data.error;
106
- if (!status) {
107
- status = 500;
108
- }
109
- else if (status && (status < 400 || status > 599)) {
110
- logger_1.logger.error("Invalid ApiError status code: ".concat(status, ", using 500"));
111
- status = 500;
112
- }
113
- _this.status = status;
114
- _this.title = title;
115
- _this.id = id;
116
- _this.links = links;
117
- _this.code = code;
118
- _this.detail = detail;
119
- _this.source = source;
120
- _this.meta = meta !== null && meta !== void 0 ? meta : {};
121
- _this.disableExternalErrorTracking = data.disableExternalErrorTracking;
122
- if (fields) {
123
- _this.meta.fields = fields;
124
- }
125
- _this.error = error;
126
- var dataErrorStack = data.error instanceof Error && data.error.stack ? "\n".concat(data.error.stack) : "";
127
- var logMessage = "APIError(".concat(status, "): ").concat(title, " ").concat(detail ? detail : "").concat(dataErrorStack);
128
- if (data.disableExternalErrorTracking) {
129
- logger_1.logger.warn(logMessage);
130
- }
131
- else {
132
- logger_1.logger.error(logMessage);
159
+ var _a, _b, _c, _d;
160
+ var cause = (_a = options.cause) !== null && _a !== void 0 ? _a : options.error;
161
+ // message is exactly the stable title; detail and cause stacks are separate fields.
162
+ _this = _super.call(this, options.title, cause === undefined ? undefined : { cause: cause }) || this;
163
+ // Brand for detection across duplicate copies of @terreno/api in node_modules, where
164
+ // `instanceof` checks fail. See isAPIError.
165
+ _this.isTerrenoAPIError = true;
166
+ // The package compiles to ES5, where extending built-ins loses the prototype chain (the
167
+ // original reason isAPIError checked `name` instead of using `instanceof`). Repair it so
168
+ // getters, methods, and instanceof work on compiled output too.
169
+ Object.setPrototypeOf(_this, _newTarget.prototype);
170
+ _this.status = normalizeStatus(options.status);
171
+ _this.code = options.code;
172
+ // name precedence: subclass name (from new.target) > code > status-derived > "APIError".
173
+ var subclassName = _newTarget !== APIError && _newTarget.name && _newTarget.name !== "APIError"
174
+ ? _newTarget.name
175
+ : undefined;
176
+ _this.name =
177
+ (_c = (_b = subclassName !== null && subclassName !== void 0 ? subclassName : (options.code ? errorNameFromCode(options.code) : undefined)) !== null && _b !== void 0 ? _b : STATUS_ERROR_NAMES[_this.status]) !== null && _c !== void 0 ? _c : "APIError";
178
+ _this.id = options.id;
179
+ _this.links = options.links;
180
+ _this.detail = options.detail;
181
+ _this.source = options.source;
182
+ _this.meta = (_d = options.meta) !== null && _d !== void 0 ? _d : {};
183
+ _this.disableExternalErrorTracking = options.disableExternalErrorTracking;
184
+ if (options.fields) {
185
+ _this.meta.fields = options.fields;
133
186
  }
134
187
  return _this;
135
188
  }
189
+ Object.defineProperty(APIError.prototype, "error", {
190
+ /** @deprecated Use the standard `cause` field instead. */
191
+ get: function () {
192
+ return this.cause;
193
+ },
194
+ enumerable: false,
195
+ configurable: true
196
+ });
197
+ Object.defineProperty(APIError.prototype, "title", {
198
+ // JSONAPI title is the same stable summary as the standard Error message. A getter keeps the
199
+ // two from ever drifting.
200
+ get: function () {
201
+ return this.message;
202
+ },
203
+ enumerable: false,
204
+ configurable: true
205
+ });
206
+ // Client-facing JSONAPI body. Excludes name/stack/cause; includes
207
+ // disableExternalErrorTracking only when true (client Sentry suppression).
208
+ APIError.prototype.toJSON = function () {
209
+ return serializeAPIError(this);
210
+ };
136
211
  return APIError;
137
212
  }(Error));
138
213
  exports.APIError = APIError;
214
+ var withStatus = function (options, status) {
215
+ return typeof options === "string" ? { status: status, title: options } : __assign(__assign({}, options), { status: status });
216
+ };
217
+ /** 400 Bad Request. */
218
+ var BadRequestError = /** @class */ (function (_super) {
219
+ __extends(BadRequestError, _super);
220
+ function BadRequestError(options) {
221
+ var _this = _super.call(this, withStatus(options, 400)) || this;
222
+ _this.name = "BadRequestError";
223
+ return _this;
224
+ }
225
+ return BadRequestError;
226
+ }(APIError));
227
+ exports.BadRequestError = BadRequestError;
228
+ /** 401 Unauthorized. */
229
+ var UnauthorizedError = /** @class */ (function (_super) {
230
+ __extends(UnauthorizedError, _super);
231
+ function UnauthorizedError(options) {
232
+ var _this = _super.call(this, withStatus(options, 401)) || this;
233
+ _this.name = "UnauthorizedError";
234
+ return _this;
235
+ }
236
+ return UnauthorizedError;
237
+ }(APIError));
238
+ exports.UnauthorizedError = UnauthorizedError;
239
+ /** 403 Forbidden. */
240
+ var ForbiddenError = /** @class */ (function (_super) {
241
+ __extends(ForbiddenError, _super);
242
+ function ForbiddenError(options) {
243
+ var _this = _super.call(this, withStatus(options, 403)) || this;
244
+ _this.name = "ForbiddenError";
245
+ return _this;
246
+ }
247
+ return ForbiddenError;
248
+ }(APIError));
249
+ exports.ForbiddenError = ForbiddenError;
250
+ /** 404 Not Found. */
251
+ var NotFoundError = /** @class */ (function (_super) {
252
+ __extends(NotFoundError, _super);
253
+ function NotFoundError(options) {
254
+ var _this = _super.call(this, withStatus(options, 404)) || this;
255
+ _this.name = "NotFoundError";
256
+ return _this;
257
+ }
258
+ return NotFoundError;
259
+ }(APIError));
260
+ exports.NotFoundError = NotFoundError;
261
+ /** 409 Conflict. */
262
+ var ConflictError = /** @class */ (function (_super) {
263
+ __extends(ConflictError, _super);
264
+ function ConflictError(options) {
265
+ var _this = _super.call(this, withStatus(options, 409)) || this;
266
+ _this.name = "ConflictError";
267
+ return _this;
268
+ }
269
+ return ConflictError;
270
+ }(APIError));
271
+ exports.ConflictError = ConflictError;
272
+ /** 400 Bad Request with a "ValidationError" type, for request/schema validation failures. */
273
+ var ValidationError = /** @class */ (function (_super) {
274
+ __extends(ValidationError, _super);
275
+ function ValidationError(options) {
276
+ var _this = _super.call(this, withStatus(options, 400)) || this;
277
+ _this.name = "ValidationError";
278
+ return _this;
279
+ }
280
+ return ValidationError;
281
+ }(APIError));
282
+ exports.ValidationError = ValidationError;
283
+ /** 500 Internal Server Error. */
284
+ var InternalServerError = /** @class */ (function (_super) {
285
+ __extends(InternalServerError, _super);
286
+ function InternalServerError(options) {
287
+ var _this = _super.call(this, withStatus(options, 500)) || this;
288
+ _this.name = "InternalServerError";
289
+ return _this;
290
+ }
291
+ return InternalServerError;
292
+ }(APIError));
293
+ exports.InternalServerError = InternalServerError;
139
294
  // This can be attached to any schema to store errors compatible with the JSONAPI spec.
140
295
  // Lazily initialize to avoid module loading order issues with Bun where mongoose
141
296
  // may not be fully initialized when this module loads.
@@ -169,7 +324,16 @@ var errorsPlugin = function (schema) {
169
324
  };
170
325
  exports.errorsPlugin = errorsPlugin;
171
326
  var isAPIError = function (error) {
172
- return error instanceof Error && error.name === "APIError";
327
+ if (error instanceof APIError) {
328
+ return true;
329
+ }
330
+ if (error instanceof Error) {
331
+ // Brand check survives duplicate copies of @terreno/api in node_modules; the name check is a
332
+ // transition fallback for instances from older versions of the package.
333
+ return (error.isTerrenoAPIError === true ||
334
+ error.name === "APIError");
335
+ }
336
+ return false;
173
337
  };
174
338
  exports.isAPIError = isAPIError;
175
339
  /** Extract a human-readable message from an unknown error. */
@@ -205,27 +369,32 @@ var getDisableExternalErrorTracking = function (error) {
205
369
  return undefined;
206
370
  };
207
371
  exports.getDisableExternalErrorTracking = getDisableExternalErrorTracking;
208
- // Creates an APIError body to send to clients as JSON. Errors don't have a toJSON defined,
209
- // and we want to strip out things like message, name, and stack for the client.
210
- // There is almost certainly a more elegant solution to this.
211
- var getAPIErrorBody = function (error) {
372
+ // Builds the client-facing JSONAPI body from any APIError-shaped error, including instances from
373
+ // older/duplicate copies of @terreno/api that may not have toJSON.
374
+ var serializeAPIError = function (error) {
212
375
  var e_1, _a;
213
- var errorData = { status: error.status, title: error.title };
214
376
  var indexable = error;
377
+ // Prefer an explicit title property for legacy/duplicate-package instances whose message was
378
+ // polluted with detail/cause stacks but still carry a clean title field.
379
+ var title = typeof indexable.title === "string" && indexable.title.length > 0
380
+ ? indexable.title
381
+ : error.message;
382
+ var body = {
383
+ status: typeof indexable.status === "number" ? indexable.status : 500,
384
+ title: title,
385
+ };
215
386
  try {
216
- for (var _b = __values([
217
- "id",
218
- "links",
219
- "status",
220
- "code",
221
- "detail",
222
- "source",
223
- "meta",
224
- "disableExternalErrorTracking",
225
- ]), _c = _b.next(); !_c.done; _c = _b.next()) {
387
+ for (var _b = __values(["id", "links", "code", "detail", "source", "meta"]), _c = _b.next(); !_c.done; _c = _b.next()) {
226
388
  var key = _c.value;
227
- if (indexable[key]) {
228
- errorData[key] = indexable[key];
389
+ var value = indexable[key];
390
+ if (key === "meta" &&
391
+ value &&
392
+ typeof value === "object" &&
393
+ Object.keys(value).length === 0) {
394
+ continue;
395
+ }
396
+ if (value) {
397
+ body[key] = value;
229
398
  }
230
399
  }
231
400
  }
@@ -236,7 +405,17 @@ var getAPIErrorBody = function (error) {
236
405
  }
237
406
  finally { if (e_1) throw e_1.error; }
238
407
  }
239
- return errorData;
408
+ if (indexable.disableExternalErrorTracking === true) {
409
+ body.disableExternalErrorTracking = true;
410
+ }
411
+ return body;
412
+ };
413
+ /**
414
+ * Creates an APIError body to send to clients as JSON.
415
+ * @deprecated Use `error.toJSON()` instead.
416
+ */
417
+ var getAPIErrorBody = function (error) {
418
+ return serializeAPIError(error);
240
419
  };
241
420
  exports.getAPIErrorBody = getAPIErrorBody;
242
421
  var apiUnauthorizedMiddleware = function (err, _req, res, next) {
@@ -270,43 +449,62 @@ var mongooseErrorToAPIError = function (err) {
270
449
  }
271
450
  finally { if (e_2) throw e_2.error; }
272
451
  }
273
- return new APIError({
452
+ return new ValidationError({
453
+ cause: err,
274
454
  detail: err.message,
275
455
  disableExternalErrorTracking: true,
276
456
  fields: fields,
277
- status: 400,
278
457
  title: "Validation failed",
279
458
  });
280
459
  }
281
460
  if (err instanceof mongoose_1.default.Error.CastError) {
282
461
  var path = (_c = err.path) !== null && _c !== void 0 ? _c : "field";
283
- return new APIError({
462
+ return new ValidationError({
463
+ cause: err,
284
464
  detail: "Invalid value for ".concat(path),
285
465
  disableExternalErrorTracking: true,
286
466
  fields: (_b = {},
287
467
  _b[path] = "Expected ".concat((_d = err.kind) !== null && _d !== void 0 ? _d : "a valid value", ", got ").concat(JSON.stringify(err.value)),
288
468
  _b),
289
- status: 400,
290
469
  title: "Validation failed",
291
470
  });
292
471
  }
293
472
  return null;
294
473
  };
295
474
  exports.mongooseErrorToAPIError = mongooseErrorToAPIError;
296
- var apiErrorMiddleware = function (err, _req, res, next) {
297
- if ((0, exports.isAPIError)(err)) {
298
- if (!err.disableExternalErrorTracking) {
299
- Sentry.captureException(err);
300
- }
301
- res.status(err.status).json((0, exports.getAPIErrorBody)(err)).send();
475
+ // Logs the error (warn for 4xx client errors, error for 5xx server errors) and captures it with
476
+ // Sentry unless external tracking is disabled. Fingerprints on the logical error type
477
+ // (name + code/title + status) so unrelated errors constructed at the same framework lines don't
478
+ // group together, while the `cause` chain preserves each occurrence's real origin stack.
479
+ var logAndCaptureAPIError = function (err) {
480
+ var cause = err.cause;
481
+ var causeStack = cause instanceof Error && cause.stack ? "\n".concat(cause.stack) : "";
482
+ var logMessage = "".concat(err.name, "(").concat(err.status, "): ").concat(err.message).concat(err.detail ? " \u2014 ".concat(err.detail) : "").concat(causeStack);
483
+ var logFn = err.status >= 500 ? logger_1.logger.error.bind(logger_1.logger) : logger_1.logger.warn.bind(logger_1.logger);
484
+ if (err.disableExternalErrorTracking) {
485
+ logFn(logMessage);
302
486
  return;
303
487
  }
304
- var mongooseError = (0, exports.mongooseErrorToAPIError)(err);
305
- if (mongooseError) {
306
- res.status(mongooseError.status).json((0, exports.getAPIErrorBody)(mongooseError)).send();
488
+ logFn(logMessage);
489
+ Sentry.withScope(function (scope) {
490
+ var _a;
491
+ scope.setFingerprint([err.name, (_a = err.code) !== null && _a !== void 0 ? _a : err.name, String(err.status)]);
492
+ scope.setTag("http.status_code", String(err.status));
493
+ if (err.code) {
494
+ scope.setTag("api_error.code", err.code);
495
+ }
496
+ scope.setContext("apiError", serializeAPIError(err));
497
+ Sentry.captureException(err);
498
+ });
499
+ };
500
+ var apiErrorMiddleware = function (err, _req, res, next) {
501
+ var apiError = (0, exports.isAPIError)(err) ? err : (0, exports.mongooseErrorToAPIError)(err);
502
+ if (!apiError) {
503
+ next(err);
307
504
  return;
308
505
  }
309
- next(err);
506
+ logAndCaptureAPIError(apiError);
507
+ res.status(apiError.status).json(serializeAPIError(apiError)).send();
310
508
  };
311
509
  exports.apiErrorMiddleware = apiErrorMiddleware;
312
510
  /**