@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.
- package/dist/__tests__/openApiCompat.test.js +8 -2
- package/dist/actions.openApi.test.js +1 -0
- package/dist/actions.test.js +3 -1
- package/dist/api.arrayOperations.test.js +1 -0
- package/dist/api.coverage.test.d.ts +1 -0
- package/dist/api.coverage.test.js +193 -0
- package/dist/api.errorPaths.test.d.ts +1 -0
- package/dist/api.errorPaths.test.js +280 -0
- package/dist/api.errors.test.js +7 -7
- package/dist/api.hooks.test.js +66 -8
- package/dist/api.js +245 -206
- package/dist/api.query.test.js +1 -0
- package/dist/api.test.js +11 -4
- package/dist/auth.js +1 -0
- package/dist/auth.test.js +123 -1
- package/dist/betterAuthSetup.js +1 -0
- package/dist/betterAuthSetup.test.js +1 -0
- package/dist/config.js +7 -4
- package/dist/config.test.js +28 -3
- package/dist/configuration.test.js +1 -0
- package/dist/configurationApp.js +1 -0
- package/dist/configurationPlugin.test.js +80 -0
- package/dist/consentApp.test.js +1 -0
- package/dist/docLoader.js +16 -54
- package/dist/docLoader.test.js +2 -1
- package/dist/envConfigurationPlugin.js +1 -0
- package/dist/errors.d.ts +72 -5
- package/dist/errors.js +265 -67
- package/dist/errors.test.js +163 -13
- package/dist/example.js +3 -2
- package/dist/expressServer.test.js +1 -0
- package/dist/githubAuth.js +2 -0
- package/dist/githubAuth.test.js +1 -0
- package/dist/httpClient.d.ts +2 -3
- package/dist/httpClient.js +4 -4
- package/dist/httpClient.test.js +3 -2
- package/dist/logger.test.js +107 -0
- package/dist/notifiers/googleChatNotifier.test.js +2 -1
- package/dist/notifiers/slackNotifier.test.js +1 -1
- package/dist/notifiers/zoomNotifier.test.js +2 -1
- package/dist/openApi.test.js +1 -0
- package/dist/openApiBuilder.js +2 -1
- package/dist/openApiBuilder.test.js +3 -2
- package/dist/openApiValidator.js +1 -0
- package/dist/openApiValidator.test.js +41 -0
- package/dist/permissions.js +0 -2
- package/dist/permissions.middleware.test.js +8 -42
- package/dist/permissions.test.js +1 -0
- package/dist/plugins.js +8 -0
- package/dist/plugins.test.js +5 -2
- package/dist/populate.js +4 -2
- package/dist/populate.test.js +1 -0
- package/dist/realtime/realtime.test.js +13 -3
- package/dist/realtime/types.d.ts +1 -1
- package/dist/requestContext.test.js +28 -0
- package/dist/terrenoApp.js +1 -0
- package/dist/tests/createTestData.js +11 -6
- package/dist/tests/models.js +1 -0
- package/dist/transformers.js +4 -2
- package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +3 -1
- package/package.json +7 -7
- package/src/__tests__/openApiCompat.test.ts +8 -2
- package/src/actions.openApi.test.ts +1 -0
- package/src/actions.test.ts +3 -1
- package/src/api.arrayOperations.test.ts +1 -0
- package/src/api.coverage.test.ts +123 -0
- package/src/api.errorPaths.test.ts +173 -0
- package/src/api.errors.test.ts +7 -7
- package/src/api.hooks.test.ts +25 -1
- package/src/api.query.test.ts +1 -0
- package/src/api.test.ts +11 -4
- package/src/api.ts +106 -57
- package/src/auth.test.ts +92 -3
- package/src/auth.ts +6 -0
- package/src/betterAuthSetup.test.ts +1 -0
- package/src/betterAuthSetup.ts +3 -0
- package/src/config.test.ts +25 -3
- package/src/config.ts +7 -4
- package/src/configuration.test.ts +1 -0
- package/src/configurationApp.ts +2 -0
- package/src/configurationPlugin.test.ts +46 -1
- package/src/consentApp.test.ts +1 -0
- package/src/docLoader.test.ts +2 -1
- package/src/docLoader.ts +17 -20
- package/src/envConfigurationPlugin.ts +2 -0
- package/src/errors.test.ts +178 -13
- package/src/errors.ts +278 -79
- package/src/example.ts +3 -2
- package/src/expressServer.test.ts +1 -0
- package/src/expressServer.ts +4 -2
- package/src/githubAuth.test.ts +1 -0
- package/src/githubAuth.ts +2 -0
- package/src/httpClient.test.ts +3 -2
- package/src/httpClient.ts +4 -4
- package/src/logger.test.ts +78 -0
- package/src/notifiers/googleChatNotifier.test.ts +2 -2
- package/src/notifiers/slackNotifier.test.ts +2 -2
- package/src/notifiers/zoomNotifier.test.ts +2 -2
- package/src/openApi.test.ts +1 -0
- package/src/openApiBuilder.test.ts +7 -6
- package/src/openApiBuilder.ts +2 -1
- package/src/openApiValidator.test.ts +64 -0
- package/src/openApiValidator.ts +1 -0
- package/src/permissions.middleware.test.ts +8 -11
- package/src/permissions.test.ts +1 -0
- package/src/permissions.ts +0 -2
- package/src/plugins.test.ts +5 -2
- package/src/plugins.ts +9 -0
- package/src/populate.test.ts +1 -0
- package/src/populate.ts +4 -2
- package/src/realtime/realtime.test.ts +13 -3
- package/src/realtime/realtimeApp.ts +1 -0
- package/src/realtime/registry.ts +1 -0
- package/src/realtime/types.ts +1 -2
- package/src/requestContext.test.ts +32 -0
- package/src/terrenoApp.ts +1 -0
- package/src/tests/createTestData.ts +11 -6
- package/src/tests/models.ts +1 -0
- package/src/transformers.ts +4 -2
- package/src/vendor/wesleytodd-openapi/lib/generate-doc.js +4 -1
- package/tsconfig.json +4 -4
- /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
|
-
|
|
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]:
|
|
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
|
-
|
|
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(
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
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
|
-
|
|
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
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
207
|
-
//
|
|
208
|
-
|
|
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
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
"
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
"
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
284
|
-
|
|
285
|
-
|
|
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
|
-
|
|
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
|
-
|
|
49
|
-
|
|
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);
|
package/src/expressServer.ts
CHANGED
|
@@ -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
|
-
//
|
|
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
|
-
//
|
|
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
|
|
package/src/githubAuth.test.ts
CHANGED
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
|
{
|
package/src/httpClient.test.ts
CHANGED
|
@@ -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
|
|
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
|
-
//
|
|
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
|
|
197
|
-
*
|
|
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`,
|
package/src/logger.test.ts
CHANGED
|
@@ -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
|
});
|