@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/api.ts CHANGED
@@ -20,7 +20,6 @@ import {
20
20
  APIError,
21
21
  apiErrorMiddleware,
22
22
  errorMessage,
23
- errorStack,
24
23
  getDisableExternalErrorTracking,
25
24
  isAPIError,
26
25
  } from "./errors";
@@ -58,6 +57,7 @@ export interface JSONObject {
58
57
  export type JSONValue = JSONPrimitive | JSONObject | JSONArray;
59
58
 
60
59
  export const addPopulateToQuery = (
60
+ // noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
61
61
  // biome-ignore lint/suspicious/noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
62
62
  builtQuery: mongoose.Query<any[], any, Record<string, never>, any>,
63
63
  populatePaths?: PopulatePath[]
@@ -376,7 +376,7 @@ const mergeDateRangeQueryParams = <T>(
376
376
  }
377
377
  const baseField = match[1];
378
378
  const path = schema.path(baseField);
379
- if (!path || path.instance !== "Date") {
379
+ if (path?.instance !== "Date") {
380
380
  continue;
381
381
  }
382
382
  dateRangeBases.add(baseField);
@@ -654,10 +654,12 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
654
654
  throw error;
655
655
  }
656
656
  throw new APIError({
657
+ cause: error,
658
+ code: "transform-error",
659
+ detail: errorMessage(error),
657
660
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
658
- error,
659
661
  status: 400,
660
- title: errorMessage(error),
662
+ title: "Transform error",
661
663
  });
662
664
  }
663
665
  if (options.preCreate) {
@@ -668,10 +670,12 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
668
670
  throw error;
669
671
  }
670
672
  throw new APIError({
673
+ cause: error,
674
+ code: "pre-create-hook-error",
675
+ detail: errorMessage(error),
671
676
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
672
- error,
673
677
  status: 400,
674
- title: `preCreate hook error: ${errorMessage(error)}`,
678
+ title: "preCreate hook error",
675
679
  });
676
680
  }
677
681
  if (body === undefined) {
@@ -701,25 +705,30 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
701
705
  data = (await model.create(body as T)) as Document<unknown, unknown, unknown> & T;
702
706
  } catch (error: unknown) {
703
707
  throw new APIError({
708
+ cause: error,
709
+ code: "create-error",
710
+ detail: errorMessage(error),
704
711
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
705
- error,
706
712
  status: 400,
707
- title: errorMessage(error),
713
+ title: "Create error",
708
714
  });
709
715
  }
710
716
 
711
717
  if (options.populatePaths) {
712
718
  try {
719
+ // noExplicitAny: mongoose Query type varies based on populatePaths
713
720
  // biome-ignore lint/suspicious/noExplicitAny: mongoose Query type varies based on populatePaths
714
721
  let populateQuery: any = model.findById(data._id);
715
722
  populateQuery = addPopulateToQuery(populateQuery, options.populatePaths);
716
723
  data = await populateQuery.exec();
717
724
  } catch (error: unknown) {
718
725
  throw new APIError({
726
+ cause: error,
727
+ code: "populate-error",
728
+ detail: errorMessage(error),
719
729
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
720
- error,
721
730
  status: 400,
722
- title: `Populate error: ${errorMessage(error)}`,
731
+ title: "Populate error",
723
732
  });
724
733
  }
725
734
  }
@@ -729,10 +738,12 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
729
738
  await options.postCreate(data, req);
730
739
  } catch (error: unknown) {
731
740
  throw new APIError({
741
+ cause: error,
742
+ code: "post-create-hook-error",
743
+ detail: errorMessage(error),
732
744
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
733
- error,
734
745
  status: 400,
735
- title: `postCreate hook error: ${errorMessage(error)}`,
746
+ title: "postCreate hook error",
736
747
  });
737
748
  }
738
749
  }
@@ -741,9 +752,11 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
741
752
  return res.status(201).json({data: serialized});
742
753
  } catch (error: unknown) {
743
754
  throw new APIError({
755
+ cause: error,
756
+ code: "response-handler-error",
757
+ detail: errorMessage(error),
744
758
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
745
- error,
746
- title: `responseHandler error: ${errorMessage(error)}`,
759
+ title: "responseHandler error",
747
760
  });
748
761
  }
749
762
  })
@@ -798,10 +811,12 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
798
811
  queryFilter = await options.queryFilter(req.user, query);
799
812
  } catch (error: unknown) {
800
813
  throw new APIError({
814
+ cause: error,
815
+ code: "query-filter-error",
816
+ detail: String(error),
801
817
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
802
- error,
803
818
  status: 400,
804
- title: `Query filter error: ${error}`,
819
+ title: "Query filter error",
805
820
  });
806
821
  }
807
822
 
@@ -850,9 +865,11 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
850
865
  data = (await populatedQuery.exec()) as (Document<unknown, unknown, unknown> & T)[];
851
866
  } catch (error: unknown) {
852
867
  throw new APIError({
868
+ cause: error,
869
+ code: "list-error",
870
+ detail: errorMessage(error),
853
871
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
854
- error,
855
- title: `List error: ${errorStack(error)}`,
872
+ title: "List error",
856
873
  });
857
874
  }
858
875
 
@@ -862,9 +879,11 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
862
879
  serialized = await responseHandler(data, "list", req, options);
863
880
  } catch (error: unknown) {
864
881
  throw new APIError({
882
+ cause: error,
883
+ code: "response-handler-error",
884
+ detail: errorMessage(error),
865
885
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
866
- error,
867
- title: `responseHandler error: ${errorMessage(error)}`,
886
+ title: "responseHandler error",
868
887
  });
869
888
  }
870
889
 
@@ -897,9 +916,11 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
897
916
  return res.json({data: serialized});
898
917
  } catch (error: unknown) {
899
918
  throw new APIError({
919
+ cause: error,
920
+ code: "serialization-error",
921
+ detail: errorMessage(error),
900
922
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
901
- error,
902
- title: `Serialization error: ${errorMessage(error)}`,
923
+ title: "Serialization error",
903
924
  });
904
925
  }
905
926
  })
@@ -920,9 +941,11 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
920
941
  return res.json({data: serialized});
921
942
  } catch (error: unknown) {
922
943
  throw new APIError({
944
+ cause: error,
945
+ code: "response-handler-error",
946
+ detail: errorMessage(error),
923
947
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
924
- error,
925
- title: `responseHandler error: ${errorMessage(error)}`,
948
+ title: "responseHandler error",
926
949
  });
927
950
  }
928
951
  })
@@ -959,10 +982,12 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
959
982
  throw error;
960
983
  }
961
984
  throw new APIError({
985
+ cause: error,
986
+ code: "transform-error",
987
+ detail: `PATCH failed on ${req.params.id} for user ${req.user?.id}: ${errorMessage(error)}`,
962
988
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
963
- error,
964
989
  status: 403,
965
- title: `PATCH failed on ${req.params.id} for user ${req.user?.id}: ${errorMessage(error)}`,
990
+ title: "PATCH failed",
966
991
  });
967
992
  }
968
993
 
@@ -981,10 +1006,12 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
981
1006
  throw error;
982
1007
  }
983
1008
  throw new APIError({
1009
+ cause: error,
1010
+ code: "pre-update-hook-error",
1011
+ detail: `preUpdate hook error on ${req.params.id}: ${errorMessage(error)}`,
984
1012
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
985
- error,
986
1013
  status: 400,
987
- title: `preUpdate hook error on ${req.params.id}: ${errorMessage(error)}`,
1014
+ title: "preUpdate hook error",
988
1015
  });
989
1016
  }
990
1017
  if (body === undefined) {
@@ -1071,14 +1098,17 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
1071
1098
  await doc.save();
1072
1099
  } catch (error: unknown) {
1073
1100
  throw new APIError({
1101
+ cause: error,
1102
+ code: "update-save-error",
1103
+ detail: `preUpdate hook save error on ${req.params.id}: ${errorMessage(error)}`,
1074
1104
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
1075
- error,
1076
1105
  status: 400,
1077
- title: `preUpdate hook save error on ${req.params.id}: ${errorMessage(error)}`,
1106
+ title: "preUpdate hook save error",
1078
1107
  });
1079
1108
  }
1080
1109
 
1081
1110
  if (options.populatePaths) {
1111
+ // noExplicitAny: mongoose Query type varies based on populatePaths
1082
1112
  // biome-ignore lint/suspicious/noExplicitAny: mongoose Query type varies based on populatePaths
1083
1113
  let populateQuery: any = model.findById(doc._id);
1084
1114
  populateQuery = addPopulateToQuery(populateQuery, options.populatePaths);
@@ -1090,10 +1120,12 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
1090
1120
  await options.postUpdate(doc, body, req, prevDoc);
1091
1121
  } catch (error: unknown) {
1092
1122
  throw new APIError({
1123
+ cause: error,
1124
+ code: "post-update-hook-error",
1125
+ detail: `postUpdate hook error on ${req.params.id}: ${errorMessage(error)}`,
1093
1126
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
1094
- error,
1095
1127
  status: 400,
1096
- title: `postUpdate hook error on ${req.params.id}: ${errorMessage(error)}`,
1128
+ title: "postUpdate hook error",
1097
1129
  });
1098
1130
  }
1099
1131
  }
@@ -1103,9 +1135,11 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
1103
1135
  return res.json({data: serialized});
1104
1136
  } catch (error: unknown) {
1105
1137
  throw new APIError({
1138
+ cause: error,
1139
+ code: "response-handler-error",
1140
+ detail: errorMessage(error),
1106
1141
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
1107
- error,
1108
- title: `responseHandler error: ${errorMessage(error)}`,
1142
+ title: "responseHandler error",
1109
1143
  });
1110
1144
  }
1111
1145
  })
@@ -1132,10 +1166,12 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
1132
1166
  throw error;
1133
1167
  }
1134
1168
  throw new APIError({
1169
+ cause: error,
1170
+ code: "pre-delete-hook-error",
1171
+ detail: `preDelete hook error on ${req.params.id}: ${errorMessage(error)}`,
1135
1172
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
1136
- error,
1137
1173
  status: 403,
1138
- title: `preDelete hook error on ${req.params.id}: ${errorMessage(error)}`,
1174
+ title: "preDelete hook error",
1139
1175
  });
1140
1176
  }
1141
1177
  if (body === undefined) {
@@ -1167,10 +1203,12 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
1167
1203
  await doc.deleteOne();
1168
1204
  } catch (error: unknown) {
1169
1205
  throw new APIError({
1206
+ cause: error,
1207
+ code: "delete-error",
1208
+ detail: errorMessage(error),
1170
1209
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
1171
- error,
1172
1210
  status: 400,
1173
- title: errorMessage(error),
1211
+ title: "Delete error",
1174
1212
  });
1175
1213
  }
1176
1214
  }
@@ -1180,10 +1218,12 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
1180
1218
  await options.postDelete(req, doc);
1181
1219
  } catch (error: unknown) {
1182
1220
  throw new APIError({
1221
+ cause: error,
1222
+ code: "post-delete-hook-error",
1223
+ detail: errorMessage(error),
1183
1224
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
1184
- error,
1185
1225
  status: 400,
1186
- title: `postDelete hook error: ${errorMessage(error)}`,
1226
+ title: "postDelete hook error",
1187
1227
  });
1188
1228
  }
1189
1229
  }
@@ -1192,11 +1232,11 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
1192
1232
  })
1193
1233
  );
1194
1234
 
1195
- async function arrayOperation(
1235
+ const arrayOperation = async (
1196
1236
  req: Request,
1197
1237
  res: Response,
1198
1238
  operation: "POST" | "PATCH" | "DELETE"
1199
- ) {
1239
+ ) => {
1200
1240
  // TODO Combine array operations and .patch(), as they are very similar.
1201
1241
 
1202
1242
  if (!(await checkPermissions("update", options.permissions.update, req.user))) {
@@ -1279,10 +1319,12 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
1279
1319
  throw error;
1280
1320
  }
1281
1321
  throw new APIError({
1322
+ cause: error,
1323
+ code: "transform-error",
1324
+ detail: errorMessage(error),
1282
1325
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
1283
- error,
1284
1326
  status: 403,
1285
- title: errorMessage(error),
1327
+ title: "Transform error",
1286
1328
  });
1287
1329
  }
1288
1330
 
@@ -1291,10 +1333,12 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
1291
1333
  body = await options.preUpdate(body, req);
1292
1334
  } catch (error: unknown) {
1293
1335
  throw new APIError({
1336
+ cause: error,
1337
+ code: "pre-update-hook-error",
1338
+ detail: `preUpdate hook error on ${req.params.id}: ${errorMessage(error)}`,
1294
1339
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
1295
- error,
1296
1340
  status: 400,
1297
- title: `preUpdate hook error on ${req.params.id}: ${errorMessage(error)}`,
1341
+ title: "preUpdate hook error",
1298
1342
  });
1299
1343
  }
1300
1344
  if (body === undefined) {
@@ -1320,10 +1364,12 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
1320
1364
  await doc.save();
1321
1365
  } catch (error: unknown) {
1322
1366
  throw new APIError({
1367
+ cause: error,
1368
+ code: "update-save-error",
1369
+ detail: `PATCH Pre Update error on ${req.params.id}: ${errorMessage(error)}`,
1323
1370
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
1324
- error,
1325
1371
  status: 400,
1326
- title: `PATCH Pre Update error on ${req.params.id}: ${errorMessage(error)}`,
1372
+ title: "PATCH Pre Update error",
1327
1373
  });
1328
1374
  }
1329
1375
 
@@ -1337,29 +1383,31 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
1337
1383
  );
1338
1384
  } catch (error: unknown) {
1339
1385
  throw new APIError({
1386
+ cause: error,
1387
+ code: "post-update-hook-error",
1388
+ detail: `PATCH Post Update error on ${req.params.id}: ${errorMessage(error)}`,
1340
1389
  disableExternalErrorTracking: getDisableExternalErrorTracking(error),
1341
- error,
1342
1390
  status: 400,
1343
- title: `PATCH Post Update error on ${req.params.id}: ${errorMessage(error)}`,
1391
+ title: "PATCH Post Update error",
1344
1392
  });
1345
1393
  }
1346
1394
  }
1347
1395
  return res.json({
1348
1396
  data: serialize<T>(req, options, doc as unknown as Document<unknown, unknown, unknown> & T),
1349
1397
  });
1350
- }
1398
+ };
1351
1399
 
1352
- async function arrayPost(req: Request, res: Response) {
1400
+ const arrayPost = async (req: Request, res: Response) => {
1353
1401
  return arrayOperation(req, res, "POST");
1354
- }
1402
+ };
1355
1403
 
1356
- async function arrayPatch(req: Request, res: Response) {
1404
+ const arrayPatch = async (req: Request, res: Response) => {
1357
1405
  return arrayOperation(req, res, "PATCH");
1358
- }
1406
+ };
1359
1407
 
1360
- async function arrayDelete(req: Request, res: Response) {
1408
+ const arrayDelete = async (req: Request, res: Response) => {
1361
1409
  return arrayOperation(req, res, "DELETE");
1362
- }
1410
+ };
1363
1411
  // Set up routes for managing array fields. Check if there any array fields to add this for.
1364
1412
  if (Object.values(model.schema.paths).find((config) => config.instance === "Array")) {
1365
1413
  router.post(
@@ -1439,6 +1487,7 @@ export interface AsyncHandlerOptions {
1439
1487
  * }));
1440
1488
  * ```
1441
1489
  */
1490
+ // noExplicitAny: handlers may have narrower Request<Params> generics — Express's overload signature uses any for the same reason
1442
1491
  // biome-ignore lint/suspicious/noExplicitAny: handlers may have narrower Request<Params> generics — Express's overload signature uses any for the same reason
1443
1492
  type AsyncHandlerFn = (req: any, res: Response, next: NextFunction) => Promise<unknown> | unknown;
1444
1493
 
package/src/auth.test.ts CHANGED
@@ -1,12 +1,13 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
- import {afterEach, beforeEach, describe, expect, it, setSystemTime} from "bun:test";
3
+ import {afterEach, beforeEach, describe, expect, it, setSystemTime, spyOn} from "bun:test";
3
4
  import type express from "express";
4
5
  import type jwt from "jsonwebtoken";
5
6
  import supertest from "supertest";
6
7
  import type TestAgent from "supertest/lib/agent";
7
8
 
8
9
  import {modelRouter} from "./api";
9
- import {addAuthRoutes, addMeRoutes, generateTokens, setupAuth} from "./auth";
10
+ import {addAuthRoutes, addMeRoutes, generateTokens, setupAuth, signupUser} from "./auth";
10
11
  import {Permissions} from "./permissions";
11
12
  import {getCurrentRequestContext} from "./requestContext";
12
13
  import {TerrenoApp} from "./terrenoApp";
@@ -501,7 +502,7 @@ describe("auth tests", () => {
501
502
 
502
503
  it("signup without credentials is a 400, not a fallthrough 500", async () => {
503
504
  const res = await agent.post("/auth/signup").send({email: "new@example.com"}).expect(400);
504
- expect(res.body).toEqual({meta: {}, status: 400, title: "Missing credentials"});
505
+ expect(res.body).toEqual({status: 400, title: "Missing credentials"});
505
506
  });
506
507
 
507
508
  it("signup user with email that is already registered", async () => {
@@ -1390,3 +1391,91 @@ describe("signup disabled", () => {
1390
1391
  expect(res.status).toBe(404);
1391
1392
  });
1392
1393
  });
1394
+
1395
+ describe("signupUser postCreate failures", () => {
1396
+ it("wraps and rethrows errors thrown by user.postCreate", async () => {
1397
+ let saveCalled = false;
1398
+ const failingUser = {
1399
+ postCreate: async () => {
1400
+ throw new Error("postCreate failed");
1401
+ },
1402
+ save: async () => {
1403
+ saveCalled = true;
1404
+ },
1405
+ };
1406
+ const fakeModel = {
1407
+ register: async () => failingUser,
1408
+ } as unknown as Parameters<typeof signupUser>[0];
1409
+
1410
+ await expect(signupUser(fakeModel, "new@example.com", "password123")).rejects.toThrow(
1411
+ "postCreate failed"
1412
+ );
1413
+ expect(saveCalled).toBe(false);
1414
+ });
1415
+ });
1416
+
1417
+ describe("auth error paths when the user lookup fails", () => {
1418
+ let app: express.Application;
1419
+ let agent: TestAgent;
1420
+ let admin: {_id: {toString: () => string}};
1421
+
1422
+ beforeEach(async () => {
1423
+ setSystemTime();
1424
+ const testData = await setupTestData();
1425
+ admin = testData.users.admin;
1426
+ app = new TerrenoApp({
1427
+ configureApp: () => {},
1428
+ skipListen: true,
1429
+ userModel: UserModel as any,
1430
+ }).build();
1431
+ agent = supertest.agent(app);
1432
+ });
1433
+
1434
+ afterEach(() => {
1435
+ setSystemTime();
1436
+ });
1437
+
1438
+ it("responds with an error when userModel.findById throws during authentication", async () => {
1439
+ const jwtLib = (await import("jsonwebtoken")).default;
1440
+ const token = jwtLib.sign({id: admin._id.toString()}, process.env.TOKEN_SECRET as string, {
1441
+ issuer: process.env.TOKEN_ISSUER,
1442
+ });
1443
+ const findSpy = spyOn(UserModel, "findById").mockImplementation(() => {
1444
+ throw new Error("database unavailable");
1445
+ });
1446
+ try {
1447
+ const res = await agent.get("/auth/me").set("authorization", `Bearer ${token}`);
1448
+ expect(res.status).toBeGreaterThanOrEqual(400);
1449
+ } finally {
1450
+ findSpy.mockRestore();
1451
+ }
1452
+ });
1453
+
1454
+ it("calls next(err) when the local login strategy errors", async () => {
1455
+ type Authenticator = (
1456
+ username: string,
1457
+ password: string,
1458
+ done: (err: Error | null) => void
1459
+ ) => void;
1460
+ const authSpy = spyOn(
1461
+ UserModel as unknown as {authenticate: () => Authenticator},
1462
+ "authenticate"
1463
+ ).mockReturnValue((_username, _password, done) => {
1464
+ done(new Error("strategy failure"));
1465
+ });
1466
+ try {
1467
+ const errApp = new TerrenoApp({
1468
+ configureApp: () => {},
1469
+ skipListen: true,
1470
+ userModel: UserModel as any,
1471
+ }).build();
1472
+ const errAgent = supertest.agent(errApp);
1473
+ const res = await errAgent
1474
+ .post("/auth/login")
1475
+ .send({email: "notAdmin@example.com", password: "password"});
1476
+ expect(res.status).toBeGreaterThanOrEqual(400);
1477
+ } finally {
1478
+ authSpy.mockRestore();
1479
+ }
1480
+ });
1481
+ });
package/src/auth.ts CHANGED
@@ -41,12 +41,16 @@ export interface UserModel extends Model<User> {
41
41
  // Allows additional setup during signup. This will be passed the rest of req.body from the signup
42
42
  postCreate?: (body: Record<string, unknown>) => Promise<void>;
43
43
 
44
+ // noExplicitAny: passport-local-mongoose return types are untyped
44
45
  // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
45
46
  createStrategy(): any;
47
+ // noExplicitAny: passport-local-mongoose return types are untyped
46
48
  // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
47
49
  serializeUser(): any;
50
+ // noExplicitAny: passport-local-mongoose return types are untyped
48
51
  // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
49
52
  deserializeUser(): any;
53
+ // noExplicitAny: passport-local-mongoose return types are untyped
50
54
  // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
51
55
  findByUsername(username: string, findOpts: any): any;
52
56
  }
@@ -107,6 +111,7 @@ export const signupUser = async (
107
111
  const {email: _email, password: _password, ...bodyRest} = body ?? {};
108
112
 
109
113
  try {
114
+ // noExplicitAny: passport-local-mongoose's register() is untyped
110
115
  // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose's register() is untyped
111
116
  const user = await (userModel as any).register({email, ...bodyRest}, password);
112
117
 
@@ -349,6 +354,7 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
349
354
  return next();
350
355
  };
351
356
  app.use(decodeJWTMiddleware);
357
+ // noExplicitAny: express 5 type for urlencoded doesn't match RequestHandler
352
358
  // biome-ignore lint/suspicious/noExplicitAny: express 5 type for urlencoded doesn't match RequestHandler
353
359
  app.use(express.urlencoded({extended: false}) as any);
354
360
  };
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {afterAll, afterEach, describe, expect, it, mock} from "bun:test";
3
4
  import express from "express";
@@ -27,6 +27,7 @@ export type BetterAuthInstance = ReturnType<typeof betterAuth>;
27
27
  */
28
28
  // Minimal shape we use from the MongoDB native client returned by mongoose connection
29
29
  export interface MongoClientLike {
30
+ // noExplicitAny: the MongoDB driver Db type is opaque to this layer; it is passed straight to better-auth's adapter
30
31
  // biome-ignore lint/suspicious/noExplicitAny: the MongoDB driver Db type is opaque to this layer; it is passed straight to better-auth's adapter
31
32
  db: () => any;
32
33
  }
@@ -184,6 +185,7 @@ export const syncBetterAuthUser = async (
184
185
  userModel: UserModel,
185
186
  betterAuthUser: BetterAuthUser,
186
187
  oauthProvider?: string
188
+ // noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
187
189
  // biome-ignore lint/suspicious/noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
188
190
  ): Promise<any> => {
189
191
  try {
@@ -217,6 +219,7 @@ export const syncBetterAuthUser = async (
217
219
 
218
220
  // Use Better Auth ID as _id when it's a valid ObjectId (MongoDB adapter) so frontend IDs match
219
221
  const useAsId = mongoose.isValidObjectId(betterAuthUser.id) ? {_id: betterAuthUser.id} : {};
222
+ // noExplicitAny: userModel is generic across consumers — constructor args are runtime-validated
220
223
  // biome-ignore lint/suspicious/noExplicitAny: userModel is generic across consumers — constructor args are runtime-validated
221
224
  const newUser = new (userModel as any)({
222
225
  ...useAsId,
@@ -1,6 +1,7 @@
1
1
  import {afterEach, beforeEach, describe, expect, it} from "bun:test";
2
2
 
3
3
  import {Config} from "./config";
4
+ import {APIError} from "./errors";
4
5
 
5
6
  const KEYS = [
6
7
  "TERRENO_CFG_STRING",
@@ -108,12 +109,26 @@ describe("Config", () => {
108
109
 
109
110
  it("throws on non-numeric values", () => {
110
111
  process.env.TERRENO_CFG_NUM = "not-a-number";
111
- expect(() => Config.getNumber("TERRENO_CFG_NUM")).toThrow(/not a valid number/);
112
+ try {
113
+ Config.getNumber("TERRENO_CFG_NUM");
114
+ expect.unreachable("expected throw");
115
+ } catch (error) {
116
+ expect(error).toBeInstanceOf(APIError);
117
+ expect((error as APIError).title).toBe("Invalid config value");
118
+ expect((error as APIError).detail).toContain("not a valid number");
119
+ }
112
120
  });
113
121
 
114
122
  it("throws on partially-numeric strings like '5000ms'", () => {
115
123
  process.env.TERRENO_CFG_NUM = "5000ms";
116
- expect(() => Config.getNumber("TERRENO_CFG_NUM")).toThrow(/not a valid number/);
124
+ try {
125
+ Config.getNumber("TERRENO_CFG_NUM");
126
+ expect.unreachable("expected throw");
127
+ } catch (error) {
128
+ expect(error).toBeInstanceOf(APIError);
129
+ expect((error as APIError).title).toBe("Invalid config value");
130
+ expect((error as APIError).detail).toContain("not a valid number");
131
+ }
117
132
  });
118
133
 
119
134
  it("supports floats", () => {
@@ -166,7 +181,14 @@ describe("Config", () => {
166
181
 
167
182
  it("throws on malformed JSON instead of silently returning undefined", () => {
168
183
  process.env.TERRENO_CFG_JSON = "{not json";
169
- expect(() => Config.getJSON("TERRENO_CFG_JSON")).toThrow(/not valid JSON/);
184
+ try {
185
+ Config.getJSON("TERRENO_CFG_JSON");
186
+ expect.unreachable("expected throw");
187
+ } catch (error) {
188
+ expect(error).toBeInstanceOf(APIError);
189
+ expect((error as APIError).title).toBe("Invalid config value");
190
+ expect((error as APIError).detail).toContain("not valid JSON");
191
+ }
170
192
  });
171
193
  });
172
194
 
package/src/config.ts CHANGED
@@ -91,9 +91,10 @@ const getNumber = (key: string): number | undefined => {
91
91
  const parsed = Number(raw);
92
92
  if (!Number.isFinite(parsed)) {
93
93
  throw new APIError({
94
- error: new Error(`Config key "${key}" is not a valid number: ${JSON.stringify(raw)}`),
94
+ code: "invalid-config-value",
95
+ detail: `Config key "${key}" is not a valid number: ${JSON.stringify(raw)}`,
95
96
  status: 500,
96
- title: `Config key "${key}" is not a valid number`,
97
+ title: "Invalid config value",
97
98
  });
98
99
  }
99
100
  return parsed;
@@ -122,9 +123,11 @@ const getJSON = <T = unknown>(key: string): T | undefined => {
122
123
  return JSON.parse(raw) as T;
123
124
  } catch (error) {
124
125
  throw new APIError({
125
- error: new Error(`Config key "${key}" is not valid JSON: ${(error as Error).message}`),
126
+ cause: error,
127
+ code: "invalid-config-value",
128
+ detail: `Config key "${key}" is not valid JSON: ${(error as Error).message}`,
126
129
  status: 500,
127
- title: `Config key "${key}" is not valid JSON`,
130
+ title: "Invalid config value",
128
131
  });
129
132
  }
130
133
  };
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {beforeEach, describe, expect, it} from "bun:test";
3
4
  import type express from "express";