@terreno/api 57.4.0 → 57.6.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 (208) hide show
  1. package/README.md +5 -5
  2. package/bunfig.toml +1 -1
  3. package/dist/actions.js +197 -368
  4. package/dist/adminModelRouter.js +88 -173
  5. package/dist/api.js +598 -852
  6. package/dist/audit/auditApp.js +48 -89
  7. package/dist/audit/auditEventModel.js +15 -16
  8. package/dist/audit/cloudTasksEnqueue.js +56 -149
  9. package/dist/audit/diff.js +70 -160
  10. package/dist/audit/processQueue.js +25 -70
  11. package/dist/audit/rbacSink.js +25 -66
  12. package/dist/audit/record.js +129 -251
  13. package/dist/auth.js +432 -681
  14. package/dist/authRecovery.js +155 -269
  15. package/dist/authTokens.js +43 -118
  16. package/dist/betterAuthApp.js +25 -26
  17. package/dist/betterAuthSetup.js +258 -413
  18. package/dist/browserLogsRoute.d.ts +6 -0
  19. package/dist/browserLogsRoute.js +97 -0
  20. package/dist/collectionRegistry.js +32 -47
  21. package/dist/config.js +53 -122
  22. package/dist/configurationApp.js +180 -361
  23. package/dist/configurationPlugin.js +130 -302
  24. package/dist/consentApp.js +276 -421
  25. package/dist/docLoader.js +78 -126
  26. package/dist/envConfigurationPlugin.js +25 -147
  27. package/dist/errors.js +151 -247
  28. package/dist/example.js +28 -34
  29. package/dist/expressServer.d.ts +10 -0
  30. package/dist/expressServer.js +109 -255
  31. package/dist/frameworkModelNames.d.ts +24 -0
  32. package/dist/frameworkModelNames.js +31 -0
  33. package/dist/githubAuth.js +152 -216
  34. package/dist/httpClient.js +176 -264
  35. package/dist/index.d.ts +2 -0
  36. package/dist/index.js +7 -2
  37. package/dist/logger.js +145 -278
  38. package/dist/mcp/auth.js +76 -128
  39. package/dist/mcp/createMCPRequest.js +4 -5
  40. package/dist/mcp/handlers.js +268 -480
  41. package/dist/mcp/query.js +56 -150
  42. package/dist/mcp/registry.js +17 -30
  43. package/dist/mcp/schemaGenerator.js +95 -181
  44. package/dist/mcp/server.js +28 -100
  45. package/dist/mcp/serviceTokens.js +102 -191
  46. package/dist/mcp/toolGenerator.js +78 -191
  47. package/dist/middleware.js +15 -27
  48. package/dist/migrations/fixtures/all-down/20260910120000-one.js +2 -42
  49. package/dist/migrations/fixtures/all-down/20260910120001-two.js +2 -42
  50. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +1 -39
  51. package/dist/migrations/fixtures/bad-name/not-a-migration.js +1 -39
  52. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +1 -39
  53. package/dist/migrations/fixtures/valid/20260910120001-beta.js +2 -42
  54. package/dist/migrations/generate.js +107 -229
  55. package/dist/migrations/load.js +75 -201
  56. package/dist/migrations/lock.js +54 -126
  57. package/dist/migrations/runner.js +192 -446
  58. package/dist/migrations/schemaCatalog.js +122 -263
  59. package/dist/models/consentForm.js +6 -6
  60. package/dist/models/consentResponse.js +5 -5
  61. package/dist/models/mcpServiceToken.js +66 -156
  62. package/dist/models/notification.js +6 -6
  63. package/dist/models/notificationPreference.js +6 -6
  64. package/dist/models/versionConfig.js +5 -5
  65. package/dist/notifications/notificationService.js +133 -273
  66. package/dist/notifications/notificationsApp.js +85 -179
  67. package/dist/notifications/notificationsBeforeSend.js +19 -64
  68. package/dist/notifiers/googleChatNotifier.js +36 -117
  69. package/dist/notifiers/slackNotifier.d.ts +31 -2
  70. package/dist/notifiers/slackNotifier.js +170 -119
  71. package/dist/notifiers/zoomNotifier.js +60 -111
  72. package/dist/openApi.js +107 -122
  73. package/dist/openApiBuilder.js +117 -159
  74. package/dist/openApiCompat.js +81 -148
  75. package/dist/openApiEtag.js +7 -7
  76. package/dist/openApiValidator.js +177 -286
  77. package/dist/orgs/orgContext.js +87 -157
  78. package/dist/orgs/orgPermissions.js +29 -68
  79. package/dist/orgs/orgPlugin.js +9 -27
  80. package/dist/orgs/organizationModel.js +65 -166
  81. package/dist/orgs/organizationSettings.js +29 -36
  82. package/dist/orgs/orgsApp.js +346 -608
  83. package/dist/permissions.js +88 -181
  84. package/dist/plugins.js +125 -218
  85. package/dist/populate.js +130 -240
  86. package/dist/rateLimit/applyTrustProxy.js +1 -1
  87. package/dist/rateLimit/createStore.js +7 -8
  88. package/dist/rateLimit/memoryStore.js +22 -100
  89. package/dist/rateLimit/middleware.js +48 -99
  90. package/dist/rateLimit/mongoStore.js +54 -112
  91. package/dist/rateLimit/policies.js +41 -75
  92. package/dist/rateLimit/redisStore.js +39 -133
  93. package/dist/rbac/access.js +119 -267
  94. package/dist/rbac/assertAllowed.js +95 -171
  95. package/dist/rbac/auditModel.js +14 -58
  96. package/dist/rbac/backfillAdmins.js +24 -130
  97. package/dist/rbac/fieldViews.js +46 -141
  98. package/dist/rbac/membershipOrgAdminSource.js +28 -99
  99. package/dist/rbac/middleware.js +30 -96
  100. package/dist/rbac/modelRouterAccess.js +130 -307
  101. package/dist/rbac/permissionUtils.js +40 -179
  102. package/dist/rbac/realtimeAccess.js +81 -147
  103. package/dist/rbac/resolve.d.ts +1 -1
  104. package/dist/rbac/resolve.js +148 -342
  105. package/dist/rbac/roleManager.js +318 -700
  106. package/dist/rbac/roleModel.js +44 -171
  107. package/dist/rbac/routes.js +93 -196
  108. package/dist/rbac/scopes.js +39 -133
  109. package/dist/rbac/statements.js +23 -91
  110. package/dist/rbac/userPlugin.js +3 -29
  111. package/dist/realtime/changeStreamWatcher.js +489 -800
  112. package/dist/realtime/deprecation.js +8 -10
  113. package/dist/realtime/queryMatcher.js +110 -191
  114. package/dist/realtime/queryStore.js +35 -118
  115. package/dist/realtime/realtimeApp.js +247 -401
  116. package/dist/realtime/registry.js +19 -30
  117. package/dist/realtime/sessionRevalidation.js +132 -358
  118. package/dist/realtime/socketAuth.js +89 -208
  119. package/dist/realtime/socketUser.js +10 -56
  120. package/dist/requestContext.js +93 -139
  121. package/dist/schemaMetadata.js +179 -274
  122. package/dist/scriptRunner.js +96 -266
  123. package/dist/scrubAdminFields.js +36 -108
  124. package/dist/secretProviders.js +130 -299
  125. package/dist/seedRunner.js +221 -514
  126. package/dist/sync/adminBroadcastScope.js +58 -170
  127. package/dist/sync/adminWindowAccess.js +15 -86
  128. package/dist/sync/adminWindowMutation.js +110 -181
  129. package/dist/sync/executors.js +425 -629
  130. package/dist/sync/loadHarness.js +392 -689
  131. package/dist/sync/models.js +181 -341
  132. package/dist/sync/mutationHandler.js +533 -801
  133. package/dist/sync/registrationSideEffects.js +41 -95
  134. package/dist/sync/registry.js +29 -49
  135. package/dist/sync/routes.js +484 -817
  136. package/dist/sync/scripts/compactTombstones.js +83 -228
  137. package/dist/sync/serialize.js +18 -58
  138. package/dist/sync/socketHandlers.js +253 -478
  139. package/dist/sync/streams.js +49 -117
  140. package/dist/sync/syncApp.js +12 -15
  141. package/dist/sync/syncBatch.js +63 -168
  142. package/dist/sync/syncSeqPlugin.js +430 -702
  143. package/dist/syncConsents.js +113 -253
  144. package/dist/terrenoApp.js +166 -276
  145. package/dist/tests/createTestData.js +146 -256
  146. package/dist/tests/models.js +14 -54
  147. package/dist/tests/mongoTestSetup.js +42 -103
  148. package/dist/tests/testHelper.js +31 -93
  149. package/dist/tests.js +12 -51
  150. package/dist/transformers.js +61 -164
  151. package/dist/utils.js +31 -93
  152. package/dist/vendor/wesleytodd-openapi/index.js +37 -51
  153. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
  154. package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
  155. package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
  156. package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
  157. package/dist/versionCheckPlugin.js +52 -100
  158. package/dist/webhooks/headerValue.js +2 -2
  159. package/dist/webhooks/idempotency/memoryStore.js +16 -59
  160. package/dist/webhooks/idempotency/mongoStore.js +55 -130
  161. package/dist/webhooks/idempotency/webhookReceipt.js +9 -9
  162. package/dist/webhooks/rawBody.js +1 -1
  163. package/dist/webhooks/timingSafeEqual.js +4 -5
  164. package/dist/webhooks/verifiers/hmac.js +17 -18
  165. package/dist/webhooks/verifiers/sendgrid.js +20 -22
  166. package/dist/webhooks/verifiers/stripe.js +31 -65
  167. package/dist/webhooks/verifiers/twilio.js +23 -73
  168. package/dist/webhooks/webhooksApp.js +78 -177
  169. package/dist/zodOpenApi.js +2 -2
  170. package/package.json +6 -6
  171. package/src/__tests__/browserLogsRoute.test.ts +165 -0
  172. package/src/audit/auditApp.test.ts +5 -5
  173. package/src/audit/auditEventModel.ts +7 -3
  174. package/src/audit/auditRouter.test.ts +5 -5
  175. package/src/audit/rbacSink.test.ts +2 -2
  176. package/src/audit/record.test.ts +2 -2
  177. package/src/audit/record.ts +3 -2
  178. package/src/auth.ts +1 -1
  179. package/src/authRecovery.test.ts +43 -0
  180. package/src/authRecovery.ts +16 -10
  181. package/src/authTokens.ts +6 -2
  182. package/src/authVerification.test.ts +22 -0
  183. package/src/browserLogsRoute.ts +110 -0
  184. package/src/configurationPlugin.test.ts +1 -11
  185. package/src/expressServer.ts +10 -0
  186. package/src/frameworkModelNames.test.ts +62 -0
  187. package/src/frameworkModelNames.ts +33 -0
  188. package/src/index.ts +7 -0
  189. package/src/isolated/migrateCliConnect.isolated.ts +51 -0
  190. package/src/mcp/auth.test.ts +34 -1
  191. package/src/migrations/cli.test.ts +0 -23
  192. package/src/models/mcpServiceToken.ts +4 -3
  193. package/src/models/notification.ts +3 -2
  194. package/src/models/notificationPreference.ts +1 -1
  195. package/src/notifications/notificationsApp.test.ts +24 -1
  196. package/src/notifiers/slackNotifier.test.ts +186 -1
  197. package/src/notifiers/slackNotifier.ts +167 -8
  198. package/src/orgs/orgPlugin.ts +1 -1
  199. package/src/orgs/organizationModel.ts +11 -6
  200. package/src/plugins.test.ts +5 -0
  201. package/src/plugins.ts +3 -0
  202. package/src/realtime/realtimeApp.ts +1 -1
  203. package/src/sync/integration.test.ts +2 -2
  204. package/src/terrenoApp.ts +3 -0
  205. package/src/types.d.ts +1 -0
  206. package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
  207. package/tsconfig.json +13 -54
  208. package/tsconfig.typedoc.json +2 -0
package/dist/errors.js CHANGED
@@ -1,30 +1,4 @@
1
1
  "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
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
- };
28
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
29
3
  if (k2 === undefined) k2 = k;
30
4
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -58,42 +32,15 @@ var __importStar = (this && this.__importStar) || (function () {
58
32
  return result;
59
33
  };
60
34
  })();
61
- var __values = (this && this.__values) || function(o) {
62
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
63
- if (m) return m.call(o);
64
- if (o && typeof o.length === "number") return {
65
- next: function () {
66
- if (o && i >= o.length) o = void 0;
67
- return { value: o && o[i++], done: !o };
68
- }
69
- };
70
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
71
- };
72
- var __read = (this && this.__read) || function (o, n) {
73
- var m = typeof Symbol === "function" && o[Symbol.iterator];
74
- if (!m) return o;
75
- var i = m.call(o), r, ar = [], e;
76
- try {
77
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
78
- }
79
- catch (error) { e = { error: error }; }
80
- finally {
81
- try {
82
- if (r && !r.done && (m = i["return"])) m.call(i);
83
- }
84
- finally { if (e) throw e.error; }
85
- }
86
- return ar;
87
- };
88
35
  Object.defineProperty(exports, "__esModule", { value: true });
89
36
  exports.apiFallthroughErrorMiddleware = exports.apiErrorMiddleware = exports.passthroughOrWrapWrite = exports.passthroughOrWrap = exports.mongooseErrorToAPIError = exports.apiUnauthorizedMiddleware = exports.getAPIErrorBody = exports.getDisableExternalErrorTracking = exports.errorStack = exports.errorDetail = exports.errorMessage = exports.isAPIError = exports.errorsPlugin = exports.InternalServerError = exports.ValidationError = exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorizedError = exports.BadRequestError = exports.APIError = void 0;
90
37
  // https://jsonapi.org/format/#errors
91
- var Sentry = __importStar(require("@sentry/bun"));
92
- var mongoose_1 = __importStar(require("mongoose"));
93
- var logger_1 = require("./logger");
38
+ const Sentry = __importStar(require("@sentry/bun"));
39
+ const mongoose_1 = __importStar(require("mongoose"));
40
+ const logger_1 = require("./logger");
94
41
  // Maps common HTTP statuses to a standard Error name so external tools (Sentry, log explorers)
95
42
  // show a meaningful error type instead of a generic "APIError".
96
- var STATUS_ERROR_NAMES = {
43
+ const STATUS_ERROR_NAMES = {
97
44
  400: "BadRequestError",
98
45
  401: "UnauthorizedError",
99
46
  403: "ForbiddenError",
@@ -114,18 +61,18 @@ var STATUS_ERROR_NAMES = {
114
61
  };
115
62
  // Converts an application error code like "update-admin-error" into a PascalCase Error name
116
63
  // 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);
64
+ const errorNameFromCode = (code) => {
65
+ const words = code.split(/[^a-zA-Z0-9]+/).filter(Boolean);
119
66
  if (words.length === 0) {
120
67
  return undefined;
121
68
  }
122
- return words.map(function (word) { return word.charAt(0).toUpperCase() + word.slice(1); }).join("");
69
+ return words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
123
70
  };
124
- var normalizeStatus = function (status) {
71
+ const normalizeStatus = (status) => {
125
72
  if (status === undefined || status === null) {
126
73
  return 500;
127
74
  }
128
- var truncated = Math.trunc(status);
75
+ const truncated = Math.trunc(status);
129
76
  if (!Number.isFinite(truncated) || truncated < 400 || truncated > 599) {
130
77
  return 500;
131
78
  }
@@ -151,153 +98,129 @@ var normalizeStatus = function (status) {
151
98
  * });
152
99
  * ```
153
100
  */
154
- var APIError = /** @class */ (function (_super) {
155
- __extends(APIError, _super);
156
- function APIError(options) {
157
- var _newTarget = this.constructor;
158
- var _this = this;
159
- var _a, _b, _c, _d;
160
- var cause = (_a = options.cause) !== null && _a !== void 0 ? _a : options.error;
101
+ class APIError extends Error {
102
+ // Brand for detection across duplicate copies of @terreno/api in node_modules, where
103
+ // `instanceof` checks fail. See isAPIError.
104
+ isTerrenoAPIError = true;
105
+ id;
106
+ links;
107
+ status;
108
+ code;
109
+ detail;
110
+ source;
111
+ meta;
112
+ disableExternalErrorTracking;
113
+ constructor(options) {
114
+ const cause = options.cause ?? options.error;
161
115
  // 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;
116
+ super(options.title, cause === undefined ? undefined : { cause });
166
117
  // The package compiles to ES5, where extending built-ins loses the prototype chain (the
167
118
  // original reason isAPIError checked `name` instead of using `instanceof`). Repair it so
168
119
  // 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;
120
+ Object.setPrototypeOf(this, new.target.prototype);
121
+ this.status = normalizeStatus(options.status);
122
+ this.code = options.code;
172
123
  // name precedence: subclass name (from new.target) > code > status-derived > "APIError".
173
- var subclassName = _newTarget !== APIError && _newTarget.name && _newTarget.name !== "APIError"
174
- ? _newTarget.name
124
+ const subclassName = new.target !== APIError && new.target.name && new.target.name !== "APIError"
125
+ ? new.target.name
175
126
  : 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;
127
+ this.name =
128
+ subclassName ??
129
+ (options.code ? errorNameFromCode(options.code) : undefined) ??
130
+ STATUS_ERROR_NAMES[this.status] ??
131
+ "APIError";
132
+ this.id = options.id;
133
+ this.links = options.links;
134
+ this.detail = options.detail;
135
+ this.source = options.source;
136
+ this.meta = options.meta ?? {};
137
+ this.disableExternalErrorTracking = options.disableExternalErrorTracking;
184
138
  if (options.fields) {
185
- _this.meta.fields = options.fields;
139
+ this.meta.fields = options.fields;
186
140
  }
187
- return _this;
188
141
  }
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
- });
142
+ /** @deprecated Use the standard `cause` field instead. */
143
+ get error() {
144
+ return this.cause;
145
+ }
146
+ // JSONAPI title is the same stable summary as the standard Error message. A getter keeps the
147
+ // two from ever drifting.
148
+ get title() {
149
+ return this.message;
150
+ }
206
151
  // Client-facing JSONAPI body. Excludes name/stack/cause; includes
207
152
  // disableExternalErrorTracking only when true (client Sentry suppression).
208
- APIError.prototype.toJSON = function () {
153
+ toJSON() {
209
154
  return serializeAPIError(this);
210
- };
211
- return APIError;
212
- }(Error));
155
+ }
156
+ }
213
157
  exports.APIError = APIError;
214
- var withStatus = function (options, status) {
215
- return typeof options === "string" ? { status: status, title: options } : __assign(__assign({}, options), { status: status });
158
+ const withStatus = (options, status) => {
159
+ return typeof options === "string" ? { status, title: options } : { ...options, status };
216
160
  };
217
161
  /** 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));
162
+ class BadRequestError extends APIError {
163
+ constructor(options) {
164
+ super(withStatus(options, 400));
165
+ this.name = "BadRequestError";
166
+ }
167
+ }
227
168
  exports.BadRequestError = BadRequestError;
228
169
  /** 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));
170
+ class UnauthorizedError extends APIError {
171
+ constructor(options) {
172
+ super(withStatus(options, 401));
173
+ this.name = "UnauthorizedError";
174
+ }
175
+ }
238
176
  exports.UnauthorizedError = UnauthorizedError;
239
177
  /** 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));
178
+ class ForbiddenError extends APIError {
179
+ constructor(options) {
180
+ super(withStatus(options, 403));
181
+ this.name = "ForbiddenError";
182
+ }
183
+ }
249
184
  exports.ForbiddenError = ForbiddenError;
250
185
  /** 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));
186
+ class NotFoundError extends APIError {
187
+ constructor(options) {
188
+ super(withStatus(options, 404));
189
+ this.name = "NotFoundError";
190
+ }
191
+ }
260
192
  exports.NotFoundError = NotFoundError;
261
193
  /** 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));
194
+ class ConflictError extends APIError {
195
+ constructor(options) {
196
+ super(withStatus(options, 409));
197
+ this.name = "ConflictError";
198
+ }
199
+ }
271
200
  exports.ConflictError = ConflictError;
272
201
  /** 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));
202
+ class ValidationError extends APIError {
203
+ constructor(options) {
204
+ super(withStatus(options, 400));
205
+ this.name = "ValidationError";
206
+ }
207
+ }
282
208
  exports.ValidationError = ValidationError;
283
209
  /** 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));
210
+ class InternalServerError extends APIError {
211
+ constructor(options) {
212
+ super(withStatus(options, 500));
213
+ this.name = "InternalServerError";
214
+ }
215
+ }
293
216
  exports.InternalServerError = InternalServerError;
294
217
  // This can be attached to any schema to store errors compatible with the JSONAPI spec.
295
218
  // Lazily initialize to avoid module loading order issues with Bun where mongoose
296
219
  // may not be fully initialized when this module loads.
297
220
  // Create an errors field for storing error information in a JSONAPI compatible form directly on a
298
221
  // model.
299
- var errorsPlugin = function (schema) {
300
- var errorSchema = new mongoose_1.Schema({
222
+ const errorsPlugin = (schema) => {
223
+ const errorSchema = new mongoose_1.Schema({
301
224
  code: { description: "Application-specific error code", type: String },
302
225
  detail: { description: "Human-readable explanation of the error", type: String },
303
226
  id: { description: "Unique identifier for this error occurrence", type: String },
@@ -323,7 +246,7 @@ var errorsPlugin = function (schema) {
323
246
  schema.add({ apiErrors: errorSchema });
324
247
  };
325
248
  exports.errorsPlugin = errorsPlugin;
326
- var isAPIError = function (error) {
249
+ const isAPIError = (error) => {
327
250
  if (error instanceof APIError) {
328
251
  return true;
329
252
  }
@@ -337,7 +260,7 @@ var isAPIError = function (error) {
337
260
  };
338
261
  exports.isAPIError = isAPIError;
339
262
  /** Extract a human-readable message from an unknown error. */
340
- var errorMessage = function (error) {
263
+ const errorMessage = (error) => {
341
264
  if (error instanceof Error) {
342
265
  return error.message;
343
266
  }
@@ -349,15 +272,15 @@ exports.errorMessage = errorMessage;
349
272
  * wrapper error. An `APIError`'s `message` is exactly its `title`, so `errorMessage` alone would
350
273
  * drop the per-occurrence text the caller put in `detail`.
351
274
  */
352
- var errorDetail = function (error) {
275
+ const errorDetail = (error) => {
353
276
  if ((0, exports.isAPIError)(error) && error.detail) {
354
- return "".concat(error.title, ": ").concat(error.detail);
277
+ return `${error.title}: ${error.detail}`;
355
278
  }
356
279
  return (0, exports.errorMessage)(error);
357
280
  };
358
281
  exports.errorDetail = errorDetail;
359
282
  /** Extract a stack trace string from an unknown error. */
360
- var errorStack = function (error) {
283
+ const errorStack = (error) => {
361
284
  if (error instanceof Error && error.stack) {
362
285
  return error.stack;
363
286
  }
@@ -369,7 +292,7 @@ exports.errorStack = errorStack;
369
292
  * Works with both APIError instances and regular Error objects that may have
370
293
  * this property attached.
371
294
  */
372
- var getDisableExternalErrorTracking = function (error) {
295
+ const getDisableExternalErrorTracking = (error) => {
373
296
  if (error instanceof Error) {
374
297
  if ((0, exports.isAPIError)(error)) {
375
298
  return error.disableExternalErrorTracking;
@@ -383,39 +306,28 @@ var getDisableExternalErrorTracking = function (error) {
383
306
  exports.getDisableExternalErrorTracking = getDisableExternalErrorTracking;
384
307
  // Builds the client-facing JSONAPI body from any APIError-shaped error, including instances from
385
308
  // older/duplicate copies of @terreno/api that may not have toJSON.
386
- var serializeAPIError = function (error) {
387
- var e_1, _a;
388
- var indexable = error;
309
+ const serializeAPIError = (error) => {
310
+ const indexable = error;
389
311
  // Prefer an explicit title property for legacy/duplicate-package instances whose message was
390
312
  // polluted with detail/cause stacks but still carry a clean title field.
391
- var title = typeof indexable.title === "string" && indexable.title.length > 0
313
+ const title = typeof indexable.title === "string" && indexable.title.length > 0
392
314
  ? indexable.title
393
315
  : error.message;
394
- var body = {
316
+ const body = {
395
317
  status: typeof indexable.status === "number" ? indexable.status : 500,
396
- title: title,
318
+ title,
397
319
  };
398
- try {
399
- for (var _b = __values(["id", "links", "code", "detail", "source", "meta"]), _c = _b.next(); !_c.done; _c = _b.next()) {
400
- var key = _c.value;
401
- var value = indexable[key];
402
- if (key === "meta" &&
403
- value &&
404
- typeof value === "object" &&
405
- Object.keys(value).length === 0) {
406
- continue;
407
- }
408
- if (value) {
409
- body[key] = value;
410
- }
320
+ for (const key of ["id", "links", "code", "detail", "source", "meta"]) {
321
+ const value = indexable[key];
322
+ if (key === "meta" &&
323
+ value &&
324
+ typeof value === "object" &&
325
+ Object.keys(value).length === 0) {
326
+ continue;
411
327
  }
412
- }
413
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
414
- finally {
415
- try {
416
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
328
+ if (value) {
329
+ body[key] = value;
417
330
  }
418
- finally { if (e_1) throw e_1.error; }
419
331
  }
420
332
  if (indexable.disableExternalErrorTracking === true) {
421
333
  body.disableExternalErrorTracking = true;
@@ -426,7 +338,7 @@ var serializeAPIError = function (error) {
426
338
  * Creates an APIError body to send to clients as JSON.
427
339
  * @deprecated Use `error.toJSON()` instead.
428
340
  */
429
- var getAPIErrorBody = function (error) {
341
+ const getAPIErrorBody = (error) => {
430
342
  return serializeAPIError(error);
431
343
  };
432
344
  exports.getAPIErrorBody = getAPIErrorBody;
@@ -438,7 +350,7 @@ exports.getAPIErrorBody = getAPIErrorBody;
438
350
  * `apiErrorMiddleware`. A domain-specific `Error` subclass with the same message also falls
439
351
  * through so its own handler can respond.
440
352
  */
441
- var apiUnauthorizedMiddleware = function (err, _req, res, next) {
353
+ const apiUnauthorizedMiddleware = (err, _req, res, next) => {
442
354
  if (!(0, exports.isAPIError)(err) &&
443
355
  err.message === "Unauthorized" &&
444
356
  Object.getPrototypeOf(err) === Error.prototype) {
@@ -453,41 +365,29 @@ exports.apiUnauthorizedMiddleware = apiUnauthorizedMiddleware;
453
365
  /**
454
366
  * Converts Mongoose validation/cast errors into client-friendly APIErrors.
455
367
  */
456
- var mongooseErrorToAPIError = function (err) {
457
- var e_2, _a, _b;
458
- var _c, _d;
368
+ const mongooseErrorToAPIError = (err) => {
459
369
  if (err instanceof mongoose_1.default.Error.ValidationError) {
460
- var fields = {};
461
- try {
462
- for (var _e = __values(Object.entries(err.errors)), _f = _e.next(); !_f.done; _f = _e.next()) {
463
- var _g = __read(_f.value, 2), path = _g[0], subErr = _g[1];
464
- fields[path] = subErr.message;
465
- }
466
- }
467
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
468
- finally {
469
- try {
470
- if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
471
- }
472
- finally { if (e_2) throw e_2.error; }
370
+ const fields = {};
371
+ for (const [path, subErr] of Object.entries(err.errors)) {
372
+ fields[path] = subErr.message;
473
373
  }
474
374
  return new ValidationError({
475
375
  cause: err,
476
376
  detail: err.message,
477
377
  disableExternalErrorTracking: true,
478
- fields: fields,
378
+ fields,
479
379
  title: "Validation failed",
480
380
  });
481
381
  }
482
382
  if (err instanceof mongoose_1.default.Error.CastError) {
483
- var path = (_c = err.path) !== null && _c !== void 0 ? _c : "field";
383
+ const path = err.path ?? "field";
484
384
  return new ValidationError({
485
385
  cause: err,
486
- detail: "Invalid value for ".concat(path),
386
+ detail: `Invalid value for ${path}`,
487
387
  disableExternalErrorTracking: true,
488
- fields: (_b = {},
489
- _b[path] = "Expected ".concat((_d = err.kind) !== null && _d !== void 0 ? _d : "a valid value", ", got ").concat(JSON.stringify(err.value)),
490
- _b),
388
+ fields: {
389
+ [path]: `Expected ${err.kind ?? "a valid value"}, got ${JSON.stringify(err.value)}`,
390
+ },
491
391
  title: "Validation failed",
492
392
  });
493
393
  }
@@ -500,11 +400,16 @@ exports.mongooseErrorToAPIError = mongooseErrorToAPIError;
500
400
  * anything else is wrapped in the given framework error. `wrapper` may override any field,
501
401
  * including `detail`, which defaults to the caught error's text.
502
402
  */
503
- var passthroughOrWrap = function (error, wrapper) {
403
+ const passthroughOrWrap = (error, wrapper) => {
504
404
  if ((0, exports.isAPIError)(error)) {
505
405
  return error;
506
406
  }
507
- return new APIError(__assign({ cause: error, detail: (0, exports.errorDetail)(error), disableExternalErrorTracking: (0, exports.getDisableExternalErrorTracking)(error) }, wrapper));
407
+ return new APIError({
408
+ cause: error,
409
+ detail: (0, exports.errorDetail)(error),
410
+ disableExternalErrorTracking: (0, exports.getDisableExternalErrorTracking)(error),
411
+ ...wrapper,
412
+ });
508
413
  };
509
414
  exports.passthroughOrWrap = passthroughOrWrap;
510
415
  /**
@@ -512,9 +417,9 @@ exports.passthroughOrWrap = passthroughOrWrap;
512
417
  * errors are converted first so their per-field messages survive as `meta.fields` instead of being
513
418
  * flattened into the wrapper's `detail`.
514
419
  */
515
- var passthroughOrWrapWrite = function (error, wrapper) {
420
+ const passthroughOrWrapWrite = (error, wrapper) => {
516
421
  if (!(0, exports.isAPIError)(error) && error instanceof Error) {
517
- var converted = (0, exports.mongooseErrorToAPIError)(error);
422
+ const converted = (0, exports.mongooseErrorToAPIError)(error);
518
423
  if (converted) {
519
424
  return converted;
520
425
  }
@@ -526,19 +431,18 @@ exports.passthroughOrWrapWrite = passthroughOrWrapWrite;
526
431
  // Sentry unless external tracking is disabled. Fingerprints on the logical error type
527
432
  // (name + code/title + status) so unrelated errors constructed at the same framework lines don't
528
433
  // group together, while the `cause` chain preserves each occurrence's real origin stack.
529
- var logAndCaptureAPIError = function (err) {
530
- var cause = err.cause;
531
- var causeStack = cause instanceof Error && cause.stack ? "\n".concat(cause.stack) : "";
532
- var logMessage = "".concat(err.name, "(").concat(err.status, "): ").concat(err.message).concat(err.detail ? " \u2014 ".concat(err.detail) : "").concat(causeStack);
533
- var logFn = err.status >= 500 ? logger_1.logger.error.bind(logger_1.logger) : logger_1.logger.warn.bind(logger_1.logger);
434
+ const logAndCaptureAPIError = (err) => {
435
+ const cause = err.cause;
436
+ const causeStack = cause instanceof Error && cause.stack ? `\n${cause.stack}` : "";
437
+ const logMessage = `${err.name}(${err.status}): ${err.message}${err.detail ? ` — ${err.detail}` : ""}${causeStack}`;
438
+ const logFn = err.status >= 500 ? logger_1.logger.error.bind(logger_1.logger) : logger_1.logger.warn.bind(logger_1.logger);
534
439
  if (err.disableExternalErrorTracking) {
535
440
  logFn(logMessage);
536
441
  return;
537
442
  }
538
443
  logFn(logMessage);
539
- Sentry.withScope(function (scope) {
540
- var _a;
541
- scope.setFingerprint([err.name, (_a = err.code) !== null && _a !== void 0 ? _a : err.name, String(err.status)]);
444
+ Sentry.withScope((scope) => {
445
+ scope.setFingerprint([err.name, err.code ?? err.name, String(err.status)]);
542
446
  scope.setTag("http.status_code", String(err.status));
543
447
  if (err.code) {
544
448
  scope.setTag("api_error.code", err.code);
@@ -547,8 +451,8 @@ var logAndCaptureAPIError = function (err) {
547
451
  Sentry.captureException(err);
548
452
  });
549
453
  };
550
- var apiErrorMiddleware = function (err, _req, res, next) {
551
- var apiError = (0, exports.isAPIError)(err) ? err : (0, exports.mongooseErrorToAPIError)(err);
454
+ const apiErrorMiddleware = (err, _req, res, next) => {
455
+ const apiError = (0, exports.isAPIError)(err) ? err : (0, exports.mongooseErrorToAPIError)(err);
552
456
  if (!apiError) {
553
457
  next(err);
554
458
  return;
@@ -561,8 +465,8 @@ exports.apiErrorMiddleware = apiErrorMiddleware;
561
465
  * Final Express error handler for unexpected errors. Always returns JSON so
562
466
  * clients (e.g. RTK Query) can parse the response.
563
467
  */
564
- var apiFallthroughErrorMiddleware = function (err, _req, res, _next) {
565
- logger_1.logger.error("Fallthrough error: ".concat(err).concat(err.stack ? "\n".concat(err.stack) : ""));
468
+ const apiFallthroughErrorMiddleware = (err, _req, res, _next) => {
469
+ logger_1.logger.error(`Fallthrough error: ${err}${err.stack ? `\n${err.stack}` : ""}`);
566
470
  Sentry.captureException(err);
567
471
  if (res.headersSent) {
568
472
  return;