@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/src/errors.ts CHANGED
@@ -5,9 +5,53 @@ import mongoose, {Schema} from "mongoose";
5
5
 
6
6
  import {logger} from "./logger";
7
7
 
8
- export interface APIErrorConstructor {
8
+ // Maps common HTTP statuses to a standard Error name so external tools (Sentry, log explorers)
9
+ // show a meaningful error type instead of a generic "APIError".
10
+ const STATUS_ERROR_NAMES: {[status: number]: string} = {
11
+ 400: "BadRequestError",
12
+ 401: "UnauthorizedError",
13
+ 403: "ForbiddenError",
14
+ 404: "NotFoundError",
15
+ 405: "MethodNotAllowedError",
16
+ 409: "ConflictError",
17
+ 410: "GoneError",
18
+ 412: "PreconditionFailedError",
19
+ 413: "PayloadTooLargeError",
20
+ 415: "UnsupportedMediaTypeError",
21
+ 422: "ValidationError",
22
+ 429: "TooManyRequestsError",
23
+ 500: "InternalServerError",
24
+ 501: "NotImplementedError",
25
+ 502: "BadGatewayError",
26
+ 503: "ServiceUnavailableError",
27
+ 504: "GatewayTimeoutError",
28
+ };
29
+
30
+ // Converts an application error code like "update-admin-error" into a PascalCase Error name
31
+ // like "UpdateAdminError" so each logical error gets its own type in external tools.
32
+ const errorNameFromCode = (code: string): string | undefined => {
33
+ const words = code.split(/[^a-zA-Z0-9]+/).filter(Boolean);
34
+ if (words.length === 0) {
35
+ return undefined;
36
+ }
37
+ return words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
38
+ };
39
+
40
+ const normalizeStatus = (status: number | undefined): number => {
41
+ if (status === undefined || status === null) {
42
+ return 500;
43
+ }
44
+ const truncated = Math.trunc(status);
45
+ if (!Number.isFinite(truncated) || truncated < 400 || truncated > 599) {
46
+ return 500;
47
+ }
48
+ return truncated;
49
+ };
50
+
51
+ export interface APIErrorOptions {
9
52
  // Required. A short, human-readable summary of the problem that SHOULD NOT change from
10
53
  // occurrence to occurrence of the problem, except for purposes of localization.
54
+ // Becomes the standard `Error.message`.
11
55
  title: string;
12
56
 
13
57
  // error messages to be displayed by a field in a form. this isn't in the JSONAPI spec.
@@ -21,11 +65,12 @@ export interface APIErrorConstructor {
21
65
  links?: {about?: string; type?: string} | undefined;
22
66
  // The HTTP status code applicable to this problem. defaults to 500. must be between 400 and 599.
23
67
  status?: number;
24
- // An application-specific error code, expressed as a string value.
68
+ // An application-specific error code, expressed as a string value (kebab-case recommended).
69
+ // Also drives the standard `Error.name` (e.g. "update-admin-error" -> "UpdateAdminError").
25
70
  code?: string;
26
71
 
27
72
  // A human-readable explanation specific to this occurrence of the problem. Like title,
28
- // this field’s value can be localized.
73
+ // this field’s value can be localized. Unlike title, it is NOT folded into `Error.message`.
29
74
  detail?: string;
30
75
  // An object containing references to the source of the error,
31
76
  // optionally including any of the following members:
@@ -41,9 +86,32 @@ export interface APIErrorConstructor {
41
86
  header?: string;
42
87
  };
43
88
  // A meta object containing non-standard meta-information about the error.
44
- meta?: {[id: string]: string};
89
+ meta?: {[id: string]: unknown};
90
+ // The original error being wrapped, exposed as the standard ES2022 `Error.cause` so external
91
+ // tools (e.g. Sentry linked exceptions) can display the original error with its own stack.
92
+ cause?: unknown;
93
+ /** @deprecated Use `cause` instead. Kept as an alias for backwards compatibility. */
45
94
  error?: unknown;
46
95
  // If true, this error will not be sent to external error reporting tools like Sentry.
96
+ // Never serialized to clients.
97
+ disableExternalErrorTracking?: boolean;
98
+ }
99
+
100
+ /** @deprecated Use {@link APIErrorOptions} instead. */
101
+ export type APIErrorConstructor = APIErrorOptions;
102
+
103
+ // The client-facing JSONAPI error body. Standard Error fields (name, stack, cause) are
104
+ // intentionally excluded. disableExternalErrorTracking is included when true so clients can
105
+ // suppress duplicate Sentry reporting for expected errors.
106
+ export interface APIErrorBody {
107
+ status: number;
108
+ title: string;
109
+ id?: string;
110
+ links?: {about?: string; type?: string};
111
+ code?: string;
112
+ detail?: string;
113
+ source?: {pointer?: string; parameter?: string; header?: string};
114
+ meta?: {[id: string]: unknown};
47
115
  disableExternalErrorTracking?: boolean;
48
116
  }
49
117
 
@@ -52,6 +120,12 @@ export interface APIErrorConstructor {
52
120
  * HTTP code displayed. It follows the JSONAPI spec to standardize the fields,
53
121
  * allowing the UI to show more consistent, better error messages.
54
122
  *
123
+ * It uses the standard `Error` fields the way external tools (e.g. Sentry) expect:
124
+ * - `message` is exactly `title` — a stable, human-readable summary of the problem type.
125
+ * - `name` is the error type, derived from the subclass name, `code`, or `status`
126
+ * (e.g. a 404 becomes "NotFoundError").
127
+ * - `cause` holds the wrapped original error, so linked exceptions keep their own stack.
128
+ *
55
129
  * ```ts
56
130
  * throw new APIError({
57
131
  * title: "Only an admin can update that!",
@@ -62,7 +136,9 @@ export interface APIErrorConstructor {
62
136
  * ```
63
137
  */
64
138
  export class APIError extends Error {
65
- title: string;
139
+ // Brand for detection across duplicate copies of @terreno/api in node_modules, where
140
+ // `instanceof` checks fail. See isAPIError.
141
+ readonly isTerrenoAPIError = true;
66
142
 
67
143
  id: string | undefined;
68
144
 
@@ -84,48 +160,122 @@ export class APIError extends Error {
84
160
 
85
161
  meta: {[id: string]: unknown} | undefined;
86
162
 
87
- error?: unknown;
88
-
89
163
  disableExternalErrorTracking?: boolean;
90
164
 
91
- constructor(data: APIErrorConstructor) {
92
- const errorStack =
93
- data.error instanceof Error && data.error.stack ? `\n${data.error.stack}` : "";
94
- // Include details in when the error is printed to the console or sent to Sentry.
95
- super(`${data.title}${data.detail ? `: ${data.detail}` : ""}${errorStack}`);
96
- this.name = "APIError";
165
+ constructor(options: APIErrorOptions) {
166
+ const cause = options.cause ?? options.error;
167
+ // message is exactly the stable title; detail and cause stacks are separate fields.
168
+ super(options.title, cause === undefined ? undefined : {cause});
169
+ // The package compiles to ES5, where extending built-ins loses the prototype chain (the
170
+ // original reason isAPIError checked `name` instead of using `instanceof`). Repair it so
171
+ // getters, methods, and instanceof work on compiled output too.
172
+ Object.setPrototypeOf(this, new.target.prototype);
173
+
174
+ this.status = normalizeStatus(options.status);
175
+ this.code = options.code;
176
+ // name precedence: subclass name (from new.target) > code > status-derived > "APIError".
177
+ const subclassName =
178
+ new.target !== APIError && new.target.name && new.target.name !== "APIError"
179
+ ? new.target.name
180
+ : undefined;
181
+ this.name =
182
+ subclassName ??
183
+ (options.code ? errorNameFromCode(options.code) : undefined) ??
184
+ STATUS_ERROR_NAMES[this.status] ??
185
+ "APIError";
186
+
187
+ this.id = options.id;
188
+ this.links = options.links;
189
+ this.detail = options.detail;
190
+ this.source = options.source;
191
+ this.meta = options.meta ?? {};
192
+ this.disableExternalErrorTracking = options.disableExternalErrorTracking;
193
+ if (options.fields) {
194
+ this.meta.fields = options.fields;
195
+ }
196
+ }
197
+
198
+ /** @deprecated Use the standard `cause` field instead. */
199
+ get error(): unknown {
200
+ return this.cause;
201
+ }
97
202
 
98
- let {title, id, links, status, code, detail, source, meta, fields, error} = data;
203
+ // JSONAPI title is the same stable summary as the standard Error message. A getter keeps the
204
+ // two from ever drifting.
205
+ get title(): string {
206
+ return this.message;
207
+ }
99
208
 
100
- if (!status) {
101
- status = 500;
102
- } else if (status && (status < 400 || status > 599)) {
103
- logger.error(`Invalid ApiError status code: ${status}, using 500`);
104
- status = 500;
105
- }
106
- this.status = status;
107
-
108
- this.title = title;
109
- this.id = id;
110
- this.links = links;
111
-
112
- this.code = code;
113
- this.detail = detail;
114
- this.source = source;
115
- this.meta = meta ?? {};
116
- this.disableExternalErrorTracking = data.disableExternalErrorTracking;
117
- if (fields) {
118
- this.meta.fields = fields;
119
- }
120
- this.error = error;
121
- const dataErrorStack =
122
- data.error instanceof Error && data.error.stack ? `\n${data.error.stack}` : "";
123
- const logMessage = `APIError(${status}): ${title} ${detail ? detail : ""}${dataErrorStack}`;
124
- if (data.disableExternalErrorTracking) {
125
- logger.warn(logMessage);
126
- } else {
127
- logger.error(logMessage);
128
- }
209
+ // Client-facing JSONAPI body. Excludes name/stack/cause; includes
210
+ // disableExternalErrorTracking only when true (client Sentry suppression).
211
+ toJSON(): APIErrorBody {
212
+ return serializeAPIError(this);
213
+ }
214
+ }
215
+
216
+ // Convenience subclasses for the most common statuses. They are sugar only — everything works
217
+ // with plain APIError.
218
+
219
+ /** Options accepted by the status-specific APIError subclasses: a title string or full options. */
220
+ export type APIErrorSubclassOptions = Omit<APIErrorOptions, "status"> | string;
221
+
222
+ const withStatus = (options: APIErrorSubclassOptions, status: number): APIErrorOptions => {
223
+ return typeof options === "string" ? {status, title: options} : {...options, status};
224
+ };
225
+
226
+ /** 400 Bad Request. */
227
+ export class BadRequestError extends APIError {
228
+ constructor(options: APIErrorSubclassOptions) {
229
+ super(withStatus(options, 400));
230
+ this.name = "BadRequestError";
231
+ }
232
+ }
233
+
234
+ /** 401 Unauthorized. */
235
+ export class UnauthorizedError extends APIError {
236
+ constructor(options: APIErrorSubclassOptions) {
237
+ super(withStatus(options, 401));
238
+ this.name = "UnauthorizedError";
239
+ }
240
+ }
241
+
242
+ /** 403 Forbidden. */
243
+ export class ForbiddenError extends APIError {
244
+ constructor(options: APIErrorSubclassOptions) {
245
+ super(withStatus(options, 403));
246
+ this.name = "ForbiddenError";
247
+ }
248
+ }
249
+
250
+ /** 404 Not Found. */
251
+ export class NotFoundError extends APIError {
252
+ constructor(options: APIErrorSubclassOptions) {
253
+ super(withStatus(options, 404));
254
+ this.name = "NotFoundError";
255
+ }
256
+ }
257
+
258
+ /** 409 Conflict. */
259
+ export class ConflictError extends APIError {
260
+ constructor(options: APIErrorSubclassOptions) {
261
+ super(withStatus(options, 409));
262
+ this.name = "ConflictError";
263
+ }
264
+ }
265
+
266
+ /** 400 Bad Request with a "ValidationError" type, for request/schema validation failures. */
267
+ export class ValidationError extends APIError {
268
+ constructor(options: APIErrorSubclassOptions) {
269
+ super(withStatus(options, 400));
270
+ this.name = "ValidationError";
271
+ }
272
+ }
273
+
274
+ /** 500 Internal Server Error. */
275
+ export class InternalServerError extends APIError {
276
+ constructor(options: APIErrorSubclassOptions) {
277
+ super(withStatus(options, 500));
278
+ this.name = "InternalServerError";
129
279
  }
130
280
  }
131
281
 
@@ -167,7 +317,18 @@ export const errorsPlugin = (schema: Schema): void => {
167
317
  };
168
318
 
169
319
  export const isAPIError = (error: unknown): error is APIError => {
170
- return error instanceof Error && error.name === "APIError";
320
+ if (error instanceof APIError) {
321
+ return true;
322
+ }
323
+ if (error instanceof Error) {
324
+ // Brand check survives duplicate copies of @terreno/api in node_modules; the name check is a
325
+ // transition fallback for instances from older versions of the package.
326
+ return (
327
+ (error as {isTerrenoAPIError?: boolean}).isTerrenoAPIError === true ||
328
+ error.name === "APIError"
329
+ );
330
+ }
331
+ return false;
171
332
  };
172
333
 
173
334
  /** Extract a human-readable message from an unknown error. */
@@ -203,27 +364,46 @@ export const getDisableExternalErrorTracking = (error: unknown): boolean | undef
203
364
  return undefined;
204
365
  };
205
366
 
206
- // Creates an APIError body to send to clients as JSON. Errors don't have a toJSON defined,
207
- // and we want to strip out things like message, name, and stack for the client.
208
- // There is almost certainly a more elegant solution to this.
209
- export const getAPIErrorBody = (error: APIError): Record<string, unknown> => {
210
- const errorData: Record<string, unknown> = {status: error.status, title: error.title};
367
+ // Builds the client-facing JSONAPI body from any APIError-shaped error, including instances from
368
+ // older/duplicate copies of @terreno/api that may not have toJSON.
369
+ const serializeAPIError = (error: APIError): APIErrorBody => {
211
370
  const indexable = error as unknown as Record<string, unknown>;
212
- for (const key of [
213
- "id",
214
- "links",
215
- "status",
216
- "code",
217
- "detail",
218
- "source",
219
- "meta",
220
- "disableExternalErrorTracking",
221
- ]) {
222
- if (indexable[key]) {
223
- errorData[key] = indexable[key];
371
+ // Prefer an explicit title property for legacy/duplicate-package instances whose message was
372
+ // polluted with detail/cause stacks but still carry a clean title field.
373
+ const title =
374
+ typeof indexable.title === "string" && indexable.title.length > 0
375
+ ? indexable.title
376
+ : error.message;
377
+ const body: Record<string, unknown> = {
378
+ status: typeof indexable.status === "number" ? indexable.status : 500,
379
+ title,
380
+ };
381
+ for (const key of ["id", "links", "code", "detail", "source", "meta"]) {
382
+ const value = indexable[key];
383
+ if (
384
+ key === "meta" &&
385
+ value &&
386
+ typeof value === "object" &&
387
+ Object.keys(value as object).length === 0
388
+ ) {
389
+ continue;
390
+ }
391
+ if (value) {
392
+ body[key] = value;
224
393
  }
225
394
  }
226
- return errorData;
395
+ if (indexable.disableExternalErrorTracking === true) {
396
+ body.disableExternalErrorTracking = true;
397
+ }
398
+ return body as unknown as APIErrorBody;
399
+ };
400
+
401
+ /**
402
+ * Creates an APIError body to send to clients as JSON.
403
+ * @deprecated Use `error.toJSON()` instead.
404
+ */
405
+ export const getAPIErrorBody = (error: APIError): Record<string, unknown> => {
406
+ return serializeAPIError(error) as unknown as Record<string, unknown>;
227
407
  };
228
408
 
229
409
  export const apiUnauthorizedMiddleware = (
@@ -249,24 +429,24 @@ export const mongooseErrorToAPIError = (err: Error): APIError | null => {
249
429
  for (const [path, subErr] of Object.entries(err.errors)) {
250
430
  fields[path] = subErr.message;
251
431
  }
252
- return new APIError({
432
+ return new ValidationError({
433
+ cause: err,
253
434
  detail: err.message,
254
435
  disableExternalErrorTracking: true,
255
436
  fields,
256
- status: 400,
257
437
  title: "Validation failed",
258
438
  });
259
439
  }
260
440
 
261
441
  if (err instanceof mongoose.Error.CastError) {
262
442
  const path = err.path ?? "field";
263
- return new APIError({
443
+ return new ValidationError({
444
+ cause: err,
264
445
  detail: `Invalid value for ${path}`,
265
446
  disableExternalErrorTracking: true,
266
447
  fields: {
267
448
  [path]: `Expected ${err.kind ?? "a valid value"}, got ${JSON.stringify(err.value)}`,
268
449
  },
269
- status: 400,
270
450
  title: "Validation failed",
271
451
  });
272
452
  }
@@ -274,27 +454,46 @@ export const mongooseErrorToAPIError = (err: Error): APIError | null => {
274
454
  return null;
275
455
  };
276
456
 
457
+ // Logs the error (warn for 4xx client errors, error for 5xx server errors) and captures it with
458
+ // Sentry unless external tracking is disabled. Fingerprints on the logical error type
459
+ // (name + code/title + status) so unrelated errors constructed at the same framework lines don't
460
+ // group together, while the `cause` chain preserves each occurrence's real origin stack.
461
+ const logAndCaptureAPIError = (err: APIError): void => {
462
+ const cause = err.cause;
463
+ const causeStack = cause instanceof Error && cause.stack ? `\n${cause.stack}` : "";
464
+ const logMessage = `${err.name}(${err.status}): ${err.message}${
465
+ err.detail ? ` — ${err.detail}` : ""
466
+ }${causeStack}`;
467
+ const logFn = err.status >= 500 ? logger.error.bind(logger) : logger.warn.bind(logger);
468
+ if (err.disableExternalErrorTracking) {
469
+ logFn(logMessage);
470
+ return;
471
+ }
472
+ logFn(logMessage);
473
+ Sentry.withScope((scope) => {
474
+ scope.setFingerprint([err.name, err.code ?? err.name, String(err.status)]);
475
+ scope.setTag("http.status_code", String(err.status));
476
+ if (err.code) {
477
+ scope.setTag("api_error.code", err.code);
478
+ }
479
+ scope.setContext("apiError", serializeAPIError(err) as unknown as Record<string, unknown>);
480
+ Sentry.captureException(err);
481
+ });
482
+ };
483
+
277
484
  export const apiErrorMiddleware = (
278
485
  err: Error,
279
486
  _req: Request,
280
487
  res: Response,
281
488
  next: NextFunction
282
489
  ) => {
283
- if (isAPIError(err)) {
284
- if (!err.disableExternalErrorTracking) {
285
- Sentry.captureException(err);
286
- }
287
- res.status(err.status).json(getAPIErrorBody(err)).send();
288
- return;
289
- }
290
-
291
- const mongooseError = mongooseErrorToAPIError(err);
292
- if (mongooseError) {
293
- res.status(mongooseError.status).json(getAPIErrorBody(mongooseError)).send();
490
+ const apiError = isAPIError(err) ? err : mongooseErrorToAPIError(err);
491
+ if (!apiError) {
492
+ next(err);
294
493
  return;
295
494
  }
296
-
297
- next(err);
495
+ logAndCaptureAPIError(apiError);
496
+ res.status(apiError.status).json(serializeAPIError(apiError)).send();
298
497
  };
299
498
 
300
499
  /**
package/src/example.ts CHANGED
@@ -45,8 +45,9 @@ const userSchema = new Schema<User>(
45
45
  {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
46
46
  );
47
47
 
48
- // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose's plugin type is incompatible with mongoose Schema generics
49
- userSchema.plugin(passportLocalMongoose as any, {usernameField: "email"});
48
+ userSchema.plugin(passportLocalMongoose as unknown as Parameters<typeof userSchema.plugin>[0], {
49
+ usernameField: "email",
50
+ });
50
51
  userSchema.plugin(createdUpdatedPlugin);
51
52
  userSchema.plugin(isDeletedPlugin);
52
53
  userSchema.plugin(findOneOrNone);
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {afterEach, beforeEach, describe, expect, it, mock} from "bun:test";
3
4
  import {Writable} from "node:stream";
@@ -171,9 +171,11 @@ export interface AuthOptions {
171
171
  // noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
172
172
  // biome-ignore lint/suspicious/noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
173
173
  generateJWTPayload?: (user: any) => Record<string, unknown>;
174
- // biome-ignore lint/suspicious/noExplicitAny: see above
174
+ // noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
175
+ // biome-ignore lint/suspicious/noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
175
176
  generateTokenExpiration?: (user: any) => number | jwt.SignOptions["expiresIn"];
176
- // biome-ignore lint/suspicious/noExplicitAny: see above
177
+ // noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
178
+ // biome-ignore lint/suspicious/noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
177
179
  generateRefreshTokenExpiration?: (user: any) => number | jwt.SignOptions["expiresIn"];
178
180
  }
179
181
 
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {afterEach, beforeEach, describe, expect, it, setSystemTime} from "bun:test";
3
4
  import type express from "express";
package/src/githubAuth.ts CHANGED
@@ -60,6 +60,7 @@ export interface GitHubUserFields {
60
60
  * userSchema.plugin(githubUserPlugin);
61
61
  * ```
62
62
  */
63
+ // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
63
64
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
64
65
  export const githubUserPlugin = (schema: Schema<any, any, any, any>): void => {
65
66
  schema.add({
@@ -89,6 +90,7 @@ export const setupGitHubAuth = (
89
90
 
90
91
  passport.use(
91
92
  "github",
93
+ // noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
92
94
  // biome-ignore lint/suspicious/noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
93
95
  new (GitHubStrategy as any)(
94
96
  {
@@ -226,7 +226,7 @@ describe("withApiErrorHandling", () => {
226
226
  expect(normalized.classification).toBe("notFound");
227
227
  });
228
228
 
229
- it("converts to an APIError when rethrowAs is apiError, logging via APIError only", async () => {
229
+ it("converts to an APIError when rethrowAs is apiError without logging itself", async () => {
230
230
  const {logger, entries} = createRecordingLogger();
231
231
  const original = buildAxiosError({data: {message: "Rate limit exceeded"}, status: 429});
232
232
  let caught: unknown;
@@ -247,7 +247,8 @@ describe("withApiErrorHandling", () => {
247
247
  expect(apiError.detail).toBe("Rate limit exceeded");
248
248
  expect(apiError.error).toBe(original);
249
249
  expect(apiError.meta?.classification).toBe("rateLimited");
250
- // Logged exactly once: the APIError constructor logs, so the wrapper must not.
250
+ // The wrapper stays silent — apiErrorMiddleware logs the APIError, so logging here
251
+ // too would produce two log entries for the same failure.
251
252
  expect(entries).toHaveLength(0);
252
253
  });
253
254
 
package/src/httpClient.ts CHANGED
@@ -193,9 +193,8 @@ export interface WithApiErrorHandlingOptions {
193
193
  *
194
194
  * In "raw" mode (default) the wrapper logs the normalized shape via the injected logger
195
195
  * and rethrows the original error. In "apiError" mode the wrapper throws a terreno
196
- * APIError — whose constructor already logs — so the wrapper itself stays silent to
197
- * preserve the log-once contract. The APIError title is stable per JSONAPI convention;
198
- * per-occurrence text goes in `detail`, built from the (redacted) normalized messages.
196
+ * APIError with a stable title (per-occurrence text goes in `detail`) and stays silent
197
+ * itself — apiErrorMiddleware logs APIErrors, so logging here too would double-log.
199
198
  */
200
199
  export const withApiErrorHandling = async <T>(
201
200
  fn: () => Promise<T>,
@@ -215,8 +214,9 @@ export const withApiErrorHandling = async <T>(
215
214
  if (options.rethrowAs === "apiError") {
216
215
  const statusCode = normalized.statusCode;
217
216
  throw new APIError({
217
+ cause: error,
218
+ code: "http-client-error",
218
219
  detail: normalized.messages[0] ?? "unknown error",
219
- error,
220
220
  meta: {classification: normalized.classification},
221
221
  status: statusCode !== undefined && statusCode >= 400 ? statusCode : 500,
222
222
  title: `${options.apiName} ${options.operation} request failed`,
@@ -3,6 +3,7 @@ import fs from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import {Writable} from "node:stream";
6
+ import * as Sentry from "@sentry/bun";
6
7
  import winston from "winston";
7
8
 
8
9
  import {
@@ -57,6 +58,59 @@ describe("logger", () => {
57
58
  });
58
59
  });
59
60
 
61
+ describe("logger Sentry structured logging", () => {
62
+ afterEach(() => {
63
+ Reflect.deleteProperty(process.env, "USE_SENTRY_LOGGING");
64
+ });
65
+
66
+ it("forwards every level to Sentry.logger when USE_SENTRY_LOGGING is true", () => {
67
+ process.env.USE_SENTRY_LOGGING = "true";
68
+ logger.debug("sentry-debug-message");
69
+ logger.info("sentry-info-message");
70
+ logger.warn("sentry-warn-message");
71
+ logger.error("sentry-error-message");
72
+ expect(Sentry.logger?.debug).toHaveBeenCalledWith("sentry-debug-message", expect.anything());
73
+ expect(Sentry.logger?.info).toHaveBeenCalledWith("sentry-info-message", expect.anything());
74
+ expect(Sentry.logger?.warn).toHaveBeenCalledWith("sentry-warn-message", expect.anything());
75
+ expect(Sentry.logger?.error).toHaveBeenCalledWith("sentry-error-message", expect.anything());
76
+ });
77
+
78
+ it("does not forward to Sentry.logger when USE_SENTRY_LOGGING is unset", () => {
79
+ Reflect.deleteProperty(process.env, "USE_SENTRY_LOGGING");
80
+ expect(() => logger.info("no-sentry-message")).not.toThrow();
81
+ expect(Sentry.logger?.info).not.toHaveBeenCalledWith("no-sentry-message", expect.anything());
82
+ });
83
+
84
+ it("attaches terrenoRequestLog to Sentry attributes inside a request scope", () => {
85
+ process.env.USE_SENTRY_LOGGING = "true";
86
+ runWithRequestContext({requestId: "sentry-req-1", userId: "sentry-user-1"}, () => {
87
+ logger.info("sentry-request-scoped-message");
88
+ });
89
+ expect(Sentry.logger?.info).toHaveBeenCalledWith(
90
+ "sentry-request-scoped-message",
91
+ expect.objectContaining({
92
+ terrenoRequestLog: expect.objectContaining({
93
+ requestId: "sentry-req-1",
94
+ userId: "sentry-user-1",
95
+ }),
96
+ })
97
+ );
98
+ });
99
+
100
+ it("logs a caught non-Error value via Sentry.logger.error when enabled", () => {
101
+ process.env.USE_SENTRY_LOGGING = "true";
102
+ expect(() => logger.catch("plain-string-failure")).not.toThrow();
103
+ expect(Sentry.logger?.error).toHaveBeenCalled();
104
+ });
105
+
106
+ it("scoped logger catch logs a non-Error value via Sentry.logger.error when enabled", () => {
107
+ process.env.USE_SENTRY_LOGGING = "true";
108
+ const scoped = createScopedLogger({labels: {jobId: "j1"}, prefix: "[SentryScoped]"});
109
+ expect(() => scoped.catch("scoped-plain-failure")).not.toThrow();
110
+ expect(Sentry.logger?.error).toHaveBeenCalled();
111
+ });
112
+ });
113
+
60
114
  describe("formatLogContextSuffix", () => {
61
115
  it("includes request ids and sorts terrenoLabels for stable output", () => {
62
116
  const suffix = formatLogContextSuffix({
@@ -611,4 +665,28 @@ describe("setupLogging", () => {
611
665
  })
612
666
  ).not.toThrow();
613
667
  });
668
+
669
+ it("attaches the dev JSONL transport when TERRENO_LOG_FILE forces it on", () => {
670
+ const originalCwd = process.cwd();
671
+ process.env.TERRENO_LOG_FILE = "true";
672
+ try {
673
+ process.chdir(tempDir);
674
+ setupLogging({disableConsoleLogging: true, disableFileLogging: true});
675
+ expect(fs.existsSync(path.join(tempDir, ".terreno", "logs"))).toBe(true);
676
+ } finally {
677
+ process.chdir(originalCwd);
678
+ Reflect.deleteProperty(process.env, "TERRENO_LOG_FILE");
679
+ }
680
+ });
681
+
682
+ it("skips the dev JSONL transport when TERRENO_LOG_FILE forces it off", () => {
683
+ process.env.TERRENO_LOG_FILE = "false";
684
+ try {
685
+ expect(() =>
686
+ setupLogging({disableConsoleLogging: true, disableFileLogging: true})
687
+ ).not.toThrow();
688
+ } finally {
689
+ Reflect.deleteProperty(process.env, "TERRENO_LOG_FILE");
690
+ }
691
+ });
614
692
  });