@terreno/api 0.24.0 → 0.26.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 (48) hide show
  1. package/.ai/guidelines/core.md +1 -0
  2. package/README.md +5 -3
  3. package/dist/__tests__/versionCheckPlugin.test.js +62 -2
  4. package/dist/api.query.test.js +99 -0
  5. package/dist/auth.compile.test.d.ts +1 -0
  6. package/dist/auth.compile.test.js +201 -0
  7. package/dist/auth.js +38 -7
  8. package/dist/auth.test.js +119 -1
  9. package/dist/betterAuthApp.test.js +1 -2
  10. package/dist/betterAuthSetup.test.js +76 -0
  11. package/dist/expressServer.js +6 -6
  12. package/dist/expressServer.test.js +37 -8
  13. package/dist/httpClient.d.ts +119 -0
  14. package/dist/httpClient.js +412 -0
  15. package/dist/httpClient.test.d.ts +1 -0
  16. package/dist/httpClient.test.js +1470 -0
  17. package/dist/index.d.ts +10 -2
  18. package/dist/index.js +29 -3
  19. package/dist/openApi.test.js +51 -0
  20. package/dist/realtime/queryStore.d.ts +3 -3
  21. package/dist/realtime/queryStore.js +0 -1
  22. package/dist/realtime/realtime.test.js +22 -0
  23. package/dist/tests/fixtures/compileAuthEntry.d.ts +1 -0
  24. package/dist/tests/fixtures/compileAuthEntry.js +37 -0
  25. package/package.json +2 -2
  26. package/src/__tests__/versionCheckPlugin.test.ts +46 -2
  27. package/src/api.query.test.ts +59 -0
  28. package/src/auth.compile.test.ts +106 -0
  29. package/src/auth.test.ts +81 -1
  30. package/src/auth.ts +49 -7
  31. package/src/betterAuthApp.test.ts +3 -3
  32. package/src/betterAuthSetup.test.ts +65 -0
  33. package/src/expressServer.test.ts +29 -8
  34. package/src/expressServer.ts +1 -1
  35. package/src/httpClient.test.ts +979 -0
  36. package/src/httpClient.ts +464 -0
  37. package/src/index.ts +41 -2
  38. package/src/openApi.test.ts +53 -0
  39. package/src/realtime/queryStore.ts +6 -7
  40. package/src/realtime/realtime.test.ts +28 -2
  41. package/src/realtime/realtimeApp.ts +3 -3
  42. package/src/tests/fixtures/compileAuthEntry.ts +43 -0
  43. package/dist/notifiers/index.d.ts +0 -3
  44. package/dist/notifiers/index.js +0 -19
  45. package/dist/realtime/index.d.ts +0 -6
  46. package/dist/realtime/index.js +0 -27
  47. package/src/notifiers/index.ts +0 -3
  48. package/src/realtime/index.ts +0 -34
@@ -83,7 +83,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
83
83
  return (mod && mod.__esModule) ? mod : { "default": mod };
84
84
  };
85
85
  Object.defineProperty(exports, "__esModule", { value: true });
86
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
87
86
  var bun_test_1 = require("bun:test");
88
87
  var express_1 = __importDefault(require("express"));
89
88
  var mongodb_memory_server_1 = require("mongodb-memory-server");
@@ -91,7 +90,6 @@ var mongoose_1 = __importStar(require("mongoose"));
91
90
  var betterAuthApp_1 = require("./betterAuthApp");
92
91
  var conn;
93
92
  var mongod;
94
- var TestUser;
95
93
  var testUserSchema = new mongoose_1.Schema({
96
94
  admin: { default: false, type: Boolean },
97
95
  betterAuthId: { type: String },
@@ -99,6 +97,7 @@ var testUserSchema = new mongoose_1.Schema({
99
97
  name: { type: String },
100
98
  oauthProvider: { type: String },
101
99
  });
100
+ var TestUser;
102
101
  var setup = (function () { return __awaiter(void 0, void 0, void 0, function () {
103
102
  return __generator(this, function (_a) {
104
103
  switch (_a.label) {
@@ -404,6 +404,27 @@ var getClient = function () { return conn.client; };
404
404
  }
405
405
  });
406
406
  }); });
407
+ (0, bun_test_1.it)("logs and rethrows when the lookup fails", function () { return __awaiter(void 0, void 0, void 0, function () {
408
+ var failure, throwingModel, baUser;
409
+ return __generator(this, function (_a) {
410
+ switch (_a.label) {
411
+ case 0: return [4 /*yield*/, setup];
412
+ case 1:
413
+ _a.sent();
414
+ failure = new Error("lookup exploded");
415
+ throwingModel = {
416
+ findOneOrNone: function () {
417
+ throw failure;
418
+ },
419
+ };
420
+ baUser = makeBetterAuthUser();
421
+ return [4 /*yield*/, (0, bun_test_1.expect)((0, betterAuthSetup_1.syncBetterAuthUser)(throwingModel, baUser)).rejects.toThrow("lookup exploded")];
422
+ case 2:
423
+ _a.sent();
424
+ return [2 /*return*/];
425
+ }
426
+ });
427
+ }); });
407
428
  });
408
429
  (0, bun_test_1.describe)("createBetterAuthSessionMiddleware", function () {
409
430
  (0, bun_test_1.it)("calls next when no session exists", function () { return __awaiter(void 0, void 0, void 0, function () {
@@ -634,6 +655,50 @@ var getClient = function () { return conn.client; };
634
655
  }
635
656
  });
636
657
  }); });
658
+ (0, bun_test_1.it)("delegates matched requests to the Better Auth node handler", function () { return __awaiter(void 0, void 0, void 0, function () {
659
+ var config, auth, registered, registeredPath, fakeApp, req, res, _a;
660
+ return __generator(this, function (_b) {
661
+ switch (_b.label) {
662
+ case 0: return [4 /*yield*/, setup];
663
+ case 1:
664
+ _b.sent();
665
+ config = {
666
+ baseURL: "http://localhost:3000",
667
+ enabled: true,
668
+ secret: "test-secret-at-least-32-characters-long",
669
+ };
670
+ auth = (0, betterAuthSetup_1.createBetterAuth)({ config: config, mongoClient: getClient() });
671
+ fakeApp = {
672
+ all: function (path, handler) {
673
+ registeredPath = path;
674
+ registered = handler;
675
+ },
676
+ };
677
+ (0, betterAuthSetup_1.mountBetterAuthRoutes)(fakeApp, auth, "/api/auth");
678
+ (0, bun_test_1.expect)(registeredPath).toBe("/api/auth/*path");
679
+ (0, bun_test_1.expect)(registered).toBeDefined();
680
+ req = { headers: {}, method: "GET", on: function () { }, url: "/api/auth/session" };
681
+ res = {
682
+ end: (0, bun_test_1.mock)(function () { }),
683
+ getHeader: function () { return undefined; },
684
+ setHeader: (0, bun_test_1.mock)(function () { }),
685
+ write: (0, bun_test_1.mock)(function () { }),
686
+ writeHead: (0, bun_test_1.mock)(function () { }),
687
+ };
688
+ _b.label = 2;
689
+ case 2:
690
+ _b.trys.push([2, 4, , 5]);
691
+ return [4 /*yield*/, (registered === null || registered === void 0 ? void 0 : registered(req, res))];
692
+ case 3:
693
+ _b.sent();
694
+ return [3 /*break*/, 5];
695
+ case 4:
696
+ _a = _b.sent();
697
+ return [3 /*break*/, 5];
698
+ case 5: return [2 /*return*/];
699
+ }
700
+ });
701
+ }); });
637
702
  });
638
703
  (0, bun_test_1.describe)("getMongoClientFromMongoose", function () {
639
704
  (0, bun_test_1.it)("returns the mongo client when connected", function () {
@@ -641,6 +706,17 @@ var getClient = function () { return conn.client; };
641
706
  var client = (0, betterAuthSetup_1.getMongoClientFromMongoose)();
642
707
  (0, bun_test_1.expect)(client).toBeDefined();
643
708
  });
709
+ (0, bun_test_1.it)("throws when the mongoose connection has no client", function () {
710
+ var connection = mongoose_1.default.connection;
711
+ var originalClient = connection.client;
712
+ connection.client = undefined;
713
+ try {
714
+ (0, bun_test_1.expect)(function () { return (0, betterAuthSetup_1.getMongoClientFromMongoose)(); }).toThrow("Mongoose is not connected");
715
+ }
716
+ finally {
717
+ connection.client = originalClient;
718
+ }
719
+ });
644
720
  });
645
721
  (0, bun_test_1.describe)("getBetterAuthSession", function () {
646
722
  (0, bun_test_1.it)("returns null when no session is set", function () {
@@ -105,7 +105,7 @@ var cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
105
105
  var on_finished_1 = __importDefault(require("on-finished"));
106
106
  var passport_1 = __importDefault(require("passport"));
107
107
  var logger_1 = require("./logger");
108
- var notifiers_1 = require("./notifiers");
108
+ var slackNotifier_1 = require("./notifiers/slackNotifier");
109
109
  var SLOW_READ_MAX = 200;
110
110
  var SLOW_WRITE_MAX = 500;
111
111
  var IS_JEST = process.env.JEST_WORKER_ID !== undefined;
@@ -246,7 +246,7 @@ var wrapScript = function (func_1) {
246
246
  case 0:
247
247
  name = (_a = require.main) === null || _a === void 0 ? void 0 : _a.filename.split("/").slice(-1)[0].replace(".ts", "");
248
248
  logger_1.logger.info("Running script ".concat(name));
249
- return [4 /*yield*/, (0, notifiers_1.sendToSlack)("Running script ".concat(name), {
249
+ return [4 /*yield*/, (0, slackNotifier_1.sendToSlack)("Running script ".concat(name), {
250
250
  slackChannel: options.slackChannel,
251
251
  })];
252
252
  case 1:
@@ -260,7 +260,7 @@ var wrapScript = function (func_1) {
260
260
  switch (_a.label) {
261
261
  case 0:
262
262
  msg = "Script ".concat(name, " is taking a while, currently ").concat(warnTime_1 / 1000, " seconds");
263
- return [4 /*yield*/, (0, notifiers_1.sendToSlack)(msg)];
263
+ return [4 /*yield*/, (0, slackNotifier_1.sendToSlack)(msg)];
264
264
  case 1:
265
265
  _a.sent();
266
266
  logger_1.logger.warn(msg);
@@ -274,7 +274,7 @@ var wrapScript = function (func_1) {
274
274
  switch (_a.label) {
275
275
  case 0:
276
276
  msg = "Script ".concat(name, " took too long, exiting");
277
- return [4 /*yield*/, (0, notifiers_1.sendToSlack)(msg)];
277
+ return [4 /*yield*/, (0, slackNotifier_1.sendToSlack)(msg)];
278
278
  case 1:
279
279
  _a.sent();
280
280
  logger_1.logger.error(msg);
@@ -304,7 +304,7 @@ var wrapScript = function (func_1) {
304
304
  error_1 = _d.sent();
305
305
  Sentry.captureException(error_1);
306
306
  logger_1.logger.error("Error running script ".concat(name, ": ").concat(error_1, "\n").concat(error_1.stack));
307
- return [4 /*yield*/, (0, notifiers_1.sendToSlack)("Error running script ".concat(name, ": ").concat(error_1, "\n").concat(error_1.stack))];
307
+ return [4 /*yield*/, (0, slackNotifier_1.sendToSlack)("Error running script ".concat(name, ": ").concat(error_1, "\n").concat(error_1.stack))];
308
308
  case 7:
309
309
  _d.sent();
310
310
  return [4 /*yield*/, Sentry.flush()];
@@ -312,7 +312,7 @@ var wrapScript = function (func_1) {
312
312
  _d.sent();
313
313
  process.exit(1);
314
314
  return [3 /*break*/, 9];
315
- case 9: return [4 /*yield*/, (0, notifiers_1.sendToSlack)("Success running script ".concat(name, ": ").concat(result))];
315
+ case 9: return [4 /*yield*/, (0, slackNotifier_1.sendToSlack)("Success running script ".concat(name, ": ").concat(result))];
316
316
  case 10:
317
317
  _d.sent();
318
318
  process.exit(0);
@@ -129,6 +129,7 @@ var expressServer_1 = require("./expressServer");
129
129
  var logger_1 = require("./logger");
130
130
  var terrenoApp_1 = require("./terrenoApp");
131
131
  var tests_1 = require("./tests");
132
+ var typedUserModel = tests_1.UserModel;
132
133
  (0, bun_test_1.describe)("expressServer", function () {
133
134
  (0, bun_test_1.describe)("setupEnvironment", function () {
134
135
  var originalEnv = process.env;
@@ -1054,7 +1055,7 @@ var tests_1 = require("./tests");
1054
1055
  app = new terrenoApp_1.TerrenoApp({
1055
1056
  configureApp: configureApp,
1056
1057
  skipListen: false,
1057
- userModel: tests_1.UserModel,
1058
+ userModel: typedUserModel,
1058
1059
  }).start();
1059
1060
  (0, bun_test_1.expect)(app).toBeDefined();
1060
1061
  }
@@ -1065,22 +1066,28 @@ var tests_1 = require("./tests");
1065
1066
  }
1066
1067
  });
1067
1068
  }); });
1068
- (0, bun_test_1.it)("handles listen error with invalid port", function () {
1069
- process.env.PORT = "-1";
1069
+ (0, bun_test_1.it)("handles listen errors", function () {
1070
1070
  var configureApp = function () { };
1071
+ var http = require("node:http");
1072
+ var originalListen = http.Server.prototype.listen;
1071
1073
  var originalExit = process.exit;
1072
- process.exit = (function () { });
1074
+ var exit = (0, bun_test_1.mock)(function () { return undefined; });
1075
+ process.exit = exit;
1076
+ http.Server.prototype.listen = (0, bun_test_1.mock)(function () {
1077
+ throw new Error("listen failed");
1078
+ });
1073
1079
  try {
1074
1080
  new terrenoApp_1.TerrenoApp({
1075
1081
  configureApp: configureApp,
1076
1082
  skipListen: false,
1077
- userModel: tests_1.UserModel,
1083
+ userModel: typedUserModel,
1078
1084
  }).start();
1085
+ (0, bun_test_1.expect)(exit).toHaveBeenCalledWith(1);
1079
1086
  }
1080
- catch (_a) {
1081
- // May throw
1087
+ finally {
1088
+ http.Server.prototype.listen = originalListen;
1089
+ process.exit = originalExit;
1082
1090
  }
1083
- process.exit = originalExit;
1084
1091
  });
1085
1092
  });
1086
1093
  (0, bun_test_1.describe)("TerrenoApp with listen", function () {
@@ -1194,6 +1201,28 @@ var tests_1 = require("./tests");
1194
1201
  }
1195
1202
  });
1196
1203
  }); });
1204
+ (0, bun_test_1.it)("terminate timeout callback reports the timeout and exits with code 2", function () { return __awaiter(void 0, void 0, void 0, function () {
1205
+ var func, closeTimer, runCloseTimer;
1206
+ return __generator(this, function (_a) {
1207
+ switch (_a.label) {
1208
+ case 0:
1209
+ func = function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
1210
+ return [2 /*return*/, "ok"];
1211
+ }); }); };
1212
+ return [4 /*yield*/, (0, bun_test_1.expect)((0, expressServer_1.wrapScript)(func, { terminateTimeout: 100 })).rejects.toThrow("__EXIT__")];
1213
+ case 1:
1214
+ _a.sent();
1215
+ closeTimer = timerCallbacks.find(function (t) { return t.delay === 100000; });
1216
+ (0, bun_test_1.expect)(closeTimer).toBeDefined();
1217
+ runCloseTimer = closeTimer === null || closeTimer === void 0 ? void 0 : closeTimer.callback;
1218
+ return [4 /*yield*/, (0, bun_test_1.expect)(runCloseTimer()).rejects.toThrow("__EXIT__")];
1219
+ case 2:
1220
+ _a.sent();
1221
+ (0, bun_test_1.expect)(process.exit).toHaveBeenCalledWith(2);
1222
+ return [2 /*return*/];
1223
+ }
1224
+ });
1225
+ }); });
1197
1226
  });
1198
1227
  (0, bun_test_1.describe)("TerrenoApp error handling", function () {
1199
1228
  var originalEnv = process.env;
@@ -0,0 +1,119 @@
1
+ import { type AxiosInstance, type AxiosRequestConfig } from "axios";
2
+ /**
3
+ * Opts a non-idempotent request (POST/PUT/PATCH/DELETE) into the retry policy of a
4
+ * createAuthenticatedClient instance: `client.axios.post(url, body, markRetryUnsafe())`.
5
+ * Callers must be sure the operation is safe to repeat, and the request body must be
6
+ * replayable — JSON objects are fine, but streams/FormData are consumed on first send.
7
+ * Has no effect on axios instances not created by createAuthenticatedClient.
8
+ */
9
+ export declare const markRetryUnsafe: (config?: AxiosRequestConfig) => AxiosRequestConfig;
10
+ /**
11
+ * Minimal logging surface used by the HTTP client utilities so consumers (and tests)
12
+ * can inject their own logger. Defaults to the terreno logger.
13
+ */
14
+ export interface HttpClientLogger {
15
+ debug: (msg: string, ...args: unknown[]) => void;
16
+ warn: (msg: string, ...args: unknown[]) => void;
17
+ error: (msg: string, ...args: unknown[]) => void;
18
+ }
19
+ /**
20
+ * Machine-readable classification of an external API failure, used to drive retry
21
+ * policies and consistent logging across API clients.
22
+ */
23
+ export type ApiErrorClassification = "rateLimited" | "unauthorized" | "notFound" | "validation" | "server" | "network" | "unknown";
24
+ export interface NormalizedApiError {
25
+ isAxios: boolean;
26
+ statusCode: number | undefined;
27
+ messages: string[];
28
+ classification: ApiErrorClassification;
29
+ apiName: string;
30
+ operation: string;
31
+ }
32
+ /**
33
+ * Normalizes an unknown thrown value from an external API call into a stable shape:
34
+ * status code, human-readable messages, and a machine classification. Axios errors are
35
+ * unwrapped (response body messages extracted); axios errors without a response are
36
+ * classified as "network"; non-axios errors fall through to "unknown" with the error
37
+ * message preserved.
38
+ *
39
+ * Raw payload bodies are not carried on the normalized shape — only recognized message
40
+ * fields are extracted, and plain-string bodies are truncated. Consumers whose services
41
+ * put sensitive data inside those message fields should additionally use a redactError
42
+ * hook.
43
+ */
44
+ export declare const normalizeApiError: (error: unknown, context: {
45
+ apiName: string;
46
+ operation: string;
47
+ }) => NormalizedApiError;
48
+ export interface WithApiErrorHandlingOptions {
49
+ apiName: string;
50
+ operation: string;
51
+ rethrowAs?: "apiError" | "raw";
52
+ redactError?: (normalized: NormalizedApiError) => NormalizedApiError;
53
+ logger?: HttpClientLogger;
54
+ }
55
+ /**
56
+ * Wraps an external API call with standardized error handling: failures are normalized
57
+ * via normalizeApiError, passed through the optional redactError hook, logged exactly
58
+ * once, and rethrown.
59
+ *
60
+ * In "raw" mode (default) the wrapper logs the normalized shape via the injected logger
61
+ * and rethrows the original error. In "apiError" mode the wrapper throws a terreno
62
+ * APIError — whose constructor already logs — so the wrapper itself stays silent to
63
+ * preserve the log-once contract. The APIError title is stable per JSONAPI convention;
64
+ * per-occurrence text goes in `detail`, built from the (redacted) normalized messages.
65
+ */
66
+ export declare const withApiErrorHandling: <T>(fn: () => Promise<T>, options: WithApiErrorHandlingOptions) => Promise<T>;
67
+ export type AuthStrategy = {
68
+ type: "bearer";
69
+ getToken: () => Promise<string>;
70
+ } | {
71
+ type: "oauth2";
72
+ tokenUrl: string;
73
+ credentials: {
74
+ clientId: string;
75
+ clientSecret: string;
76
+ };
77
+ refreshOn401: boolean;
78
+ } | {
79
+ type: "apiKey";
80
+ header: string;
81
+ getKey: () => Promise<string>;
82
+ };
83
+ export interface RetryPolicy {
84
+ maxAttempts: number;
85
+ retryOn: ApiErrorClassification[];
86
+ baseDelayMs: number;
87
+ maxDelayMs: number;
88
+ }
89
+ export interface CreateAuthenticatedClientOptions {
90
+ baseURL: string;
91
+ apiName?: string;
92
+ auth: AuthStrategy;
93
+ retry?: Partial<RetryPolicy>;
94
+ logger?: HttpClientLogger;
95
+ redactError?: (normalized: NormalizedApiError) => NormalizedApiError;
96
+ }
97
+ export interface AuthenticatedClient {
98
+ axios: AxiosInstance;
99
+ invalidateToken: () => void;
100
+ }
101
+ /**
102
+ * Creates an axios instance with a pluggable auth strategy, token caching, and a retry
103
+ * policy for transient failures.
104
+ *
105
+ * Auth: tokens/keys are fetched lazily on the first request and cached on the client;
106
+ * `invalidateToken()` drops the cache. The oauth2 strategy fetches a client-credentials
107
+ * token (HTTP Basic auth, form-encoded `grant_type=client_credentials`) and, with
108
+ * `refreshOn401`, refreshes and retries exactly once when a request returns 401.
109
+ *
110
+ * Retries: failures classified in `retry.retryOn` (default: rateLimited, server,
111
+ * network) are retried with exponential backoff and jitter up to `maxAttempts` total
112
+ * attempts, honoring a parseable Retry-After header. Only idempotent methods
113
+ * (GET/HEAD/OPTIONS) are retried unless the request opts in via markRetryUnsafe().
114
+ *
115
+ * Logging: the client logs retries and token refreshes at debug level only and always
116
+ * rejects with the original axios error — error-level logging is left to the call site
117
+ * (typically via withApiErrorHandling) so composed usage logs each failure exactly once.
118
+ */
119
+ export declare const createAuthenticatedClient: (options: CreateAuthenticatedClientOptions) => AuthenticatedClient;