@terreno/api 0.30.0 → 0.31.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 (49) hide show
  1. package/CHANGELOG.md +2 -122
  2. package/LICENSE +21 -202
  3. package/dist/actions.openApi.test.js +1 -3
  4. package/dist/actions.test.js +0 -2
  5. package/dist/api.coverage.test.js +0 -2
  6. package/dist/api.d.ts +3 -2
  7. package/dist/api.errorPaths.test.js +86 -0
  8. package/dist/betterAuthSetup.d.ts +15 -1
  9. package/dist/betterAuthSetup.js +4 -6
  10. package/dist/configurationPlugin.js +2 -2
  11. package/dist/consentApp.test.js +1 -5
  12. package/dist/expressServer.js +11 -5
  13. package/dist/githubAuth.js +1 -4
  14. package/dist/openApiBuilder.test.js +0 -2
  15. package/dist/openApiValidator.test.js +34 -0
  16. package/dist/plugins.d.ts +3 -2
  17. package/dist/plugins.js +5 -1
  18. package/dist/plugins.test.js +12 -0
  19. package/dist/populate.test.js +9 -12
  20. package/dist/realtime/realtime.test.js +231 -0
  21. package/dist/realtime/realtimeApp.d.ts +1 -1
  22. package/dist/realtime/realtimeApp.js +6 -2
  23. package/dist/realtime/realtimeAppSetup.test.d.ts +1 -0
  24. package/dist/realtime/realtimeAppSetup.test.js +213 -0
  25. package/dist/tests/models.d.ts +27 -11
  26. package/dist/tests/models.js +5 -3
  27. package/dist/tests/testHelper.d.ts +9 -3
  28. package/package.json +4 -5
  29. package/src/actions.openApi.test.ts +7 -10
  30. package/src/actions.test.ts +19 -12
  31. package/src/actions.ts +2 -2
  32. package/src/api.coverage.test.ts +7 -9
  33. package/src/api.errorPaths.test.ts +47 -1
  34. package/src/api.ts +22 -11
  35. package/src/betterAuthSetup.ts +7 -7
  36. package/src/configurationPlugin.ts +2 -2
  37. package/src/consentApp.test.ts +12 -12
  38. package/src/expressServer.ts +11 -5
  39. package/src/githubAuth.ts +1 -3
  40. package/src/models/versionConfig.ts +1 -1
  41. package/src/openApiBuilder.test.ts +24 -9
  42. package/src/openApiValidator.test.ts +41 -0
  43. package/src/plugins.test.ts +14 -0
  44. package/src/plugins.ts +9 -4
  45. package/src/populate.test.ts +25 -16
  46. package/src/realtime/realtime.test.ts +239 -0
  47. package/src/realtime/realtimeApp.ts +8 -5
  48. package/src/realtime/realtimeAppSetup.test.ts +161 -0
  49. package/src/tests/models.ts +8 -6
@@ -104,6 +104,7 @@ var express_1 = __importDefault(require("express"));
104
104
  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
+ var errors_1 = require("./errors");
107
108
  var logger_1 = require("./logger");
108
109
  var slackNotifier_1 = require("./notifiers/slackNotifier");
109
110
  var SLOW_READ_MAX = 200;
@@ -111,16 +112,16 @@ var SLOW_WRITE_MAX = 500;
111
112
  var IS_JEST = process.env.JEST_WORKER_ID !== undefined;
112
113
  var setupEnvironment = function () {
113
114
  if (!process.env.TOKEN_ISSUER) {
114
- throw new Error("TOKEN_ISSUER must be set in env.");
115
+ throw new errors_1.APIError({ status: 500, title: "TOKEN_ISSUER must be set in env." });
115
116
  }
116
117
  if (!process.env.TOKEN_SECRET) {
117
- throw new Error("TOKEN_SECRET must be set.");
118
+ throw new errors_1.APIError({ status: 500, title: "TOKEN_SECRET must be set." });
118
119
  }
119
120
  if (!process.env.REFRESH_TOKEN_SECRET) {
120
- throw new Error("REFRESH_TOKEN_SECRET must be set.");
121
+ throw new errors_1.APIError({ status: 500, title: "REFRESH_TOKEN_SECRET must be set." });
121
122
  }
122
123
  if (!process.env.SESSION_SECRET) {
123
- throw new Error("SESSION_SECRET must be set.");
124
+ throw new errors_1.APIError({ status: 500, title: "SESSION_SECRET must be set." });
124
125
  }
125
126
  if (!process.env.TOKEN_EXPIRES_IN && !IS_JEST) {
126
127
  logger_1.logger.warn("TOKEN_EXPIRES_IN is not set so using default.");
@@ -228,7 +229,12 @@ var cronjob = function (name, schedule, callback) {
228
229
  new cron_1.default.CronJob(cronSchedule, callback, null, true, "America/Chicago");
229
230
  }
230
231
  catch (error) {
231
- throw new Error("Failed to create cronjob: ".concat(error));
232
+ throw new errors_1.APIError({
233
+ cause: error,
234
+ detail: "Failed to create cronjob ".concat(name, " with schedule ").concat(cronSchedule, ": ").concat(error),
235
+ status: 500,
236
+ title: "Failed to create cronjob",
237
+ });
232
238
  }
233
239
  };
234
240
  exports.cronjob = cronjob;
@@ -82,10 +82,7 @@ exports.githubUserPlugin = githubUserPlugin;
82
82
  var setupGitHubAuth = function (_app, userModel, githubOptions) {
83
83
  var _a;
84
84
  var scope = (_a = githubOptions.scope) !== null && _a !== void 0 ? _a : ["user:email"];
85
- passport_1.default.use("github",
86
- // noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
87
- // biome-ignore lint/suspicious/noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
88
- new passport_github2_1.Strategy({
85
+ passport_1.default.use("github", new passport_github2_1.Strategy({
89
86
  callbackURL: githubOptions.callbackURL,
90
87
  clientID: githubOptions.clientId,
91
88
  clientSecret: githubOptions.clientSecret,
@@ -50,8 +50,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
50
50
  return (mod && mod.__esModule) ? mod : { "default": mod };
51
51
  };
52
52
  Object.defineProperty(exports, "__esModule", { value: true });
53
- // noExplicitAny: test mock typing
54
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
55
53
  var bun_test_1 = require("bun:test");
56
54
  var supertest_1 = __importDefault(require("supertest"));
57
55
  var api_1 = require("./api");
@@ -595,6 +595,40 @@ var setupFreshApp = function () { return __awaiter(void 0, void 0, void 0, funct
595
595
  (0, bun_test_1.expect)(nextCalled).toBe(true);
596
596
  (0, bun_test_1.expect)(req.query.page).toBe(5);
597
597
  });
598
+ (0, bun_test_1.it)("runs only body validation when no query schema is provided", function () {
599
+ (0, openApiValidator_1.configureOpenApiValidator)({ coerceTypes: true });
600
+ var middleware = (0, openApiValidator_1.createValidator)({
601
+ body: { count: { type: "number" }, name: { required: true, type: "string" } },
602
+ });
603
+ var req = {
604
+ body: { count: "3", name: "ok" },
605
+ method: "POST",
606
+ path: "/test",
607
+ query: { unchecked: "kept" },
608
+ };
609
+ var res = {};
610
+ var nextCalls = [];
611
+ middleware(req, res, (function () {
612
+ var args = [];
613
+ for (var _i = 0; _i < arguments.length; _i++) {
614
+ args[_i] = arguments[_i];
615
+ }
616
+ nextCalls.push(args);
617
+ }));
618
+ (0, bun_test_1.expect)(nextCalls).toEqual([[]]);
619
+ (0, bun_test_1.expect)(req.body.count).toBe(3);
620
+ // Query params are untouched when no query schema is configured.
621
+ (0, bun_test_1.expect)(req.query.unchecked).toBe("kept");
622
+ });
623
+ (0, bun_test_1.it)("throws body validation errors when only a body schema is provided", function () {
624
+ (0, openApiValidator_1.configureOpenApiValidator)({});
625
+ var middleware = (0, openApiValidator_1.createValidator)({
626
+ body: { name: { required: true, type: "string" } },
627
+ });
628
+ var req = { body: {}, method: "POST", path: "/test", query: {} };
629
+ var res = {};
630
+ (0, bun_test_1.expect)(function () { return middleware(req, res, (function () { })); }).toThrow("Request validation failed");
631
+ });
598
632
  (0, bun_test_1.it)("propagates body validation error via next", function () {
599
633
  var capturedErrors = [];
600
634
  (0, openApiValidator_1.configureOpenApiValidator)({
package/dist/plugins.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import mongoose, { type Document, type FilterQuery, type Schema, SchemaType, type SchemaTypeOptions } from "mongoose";
1
+ import mongoose, { type Document, type Schema, SchemaType, type SchemaTypeOptions } from "mongoose";
2
2
  import { type APIErrorOptions } from "./errors";
3
+ export type ModelQuery<T> = Partial<Record<keyof T, unknown>> & Record<string, unknown>;
3
4
  export interface BaseUser {
4
5
  admin: boolean;
5
6
  email: string;
@@ -41,7 +42,7 @@ export declare const findOneOrNone: <T>(schema: Schema<T>) => void;
41
42
  * @param query Mongoose query object
42
43
  * @param errorArgs Optional overrides for the thrown {@link APIError} when multiple match
43
44
  */
44
- export declare const findOneOrNoneFor: <T>(model: mongoose.Model<T>, query: FilterQuery<T>, errorArgs?: Partial<APIErrorOptions>) => Promise<(Document & T) | null>;
45
+ export declare const findOneOrNoneFor: <T>(model: mongoose.Model<T>, query: ModelQuery<T>, errorArgs?: Partial<APIErrorOptions>) => Promise<(Document & T) | null>;
45
46
  /**
46
47
  * This adds a static method `Model.findExactlyOne` to the schema. This or findOneOrNone should replace `Model.findOne`
47
48
  * in most instances.
package/dist/plugins.js CHANGED
@@ -374,7 +374,11 @@ var DateOnly = /** @class */ (function (_super) {
374
374
  }
375
375
  var handler = this.$conditionalHandlers[$conditional];
376
376
  if (!handler) {
377
- throw new Error("Can't use ".concat($conditional, " with DateOnly."));
377
+ throw new errors_1.APIError({
378
+ detail: "Can't use ".concat($conditional, " with DateOnly."),
379
+ status: 400,
380
+ title: "Unsupported query conditional for DateOnly",
381
+ });
378
382
  }
379
383
  return handler.call(this, val);
380
384
  };
@@ -58,6 +58,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
58
58
  // noExplicitAny: test mock typing
59
59
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
60
60
  var bun_test_1 = require("bun:test");
61
+ var chai_1 = require("chai");
61
62
  var mongoose_1 = require("mongoose");
62
63
  var supertest_1 = __importDefault(require("supertest"));
63
64
  var api_1 = require("./api");
@@ -752,6 +753,17 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
752
753
  }); });
753
754
  });
754
755
  (0, bun_test_1.describe)("DateOnly", function () {
756
+ (0, bun_test_1.it)("strips the time portion when getting a Date value", function () {
757
+ var dateOnly = new plugins_1.DateOnly("date", {});
758
+ var value = dateOnly.get(new Date("2005-10-10T17:17:17.017Z"));
759
+ chai_1.assert.instanceOf(value, Date);
760
+ chai_1.assert.equal(value.toISOString(), "2005-10-10T00:00:00.000Z");
761
+ });
762
+ (0, bun_test_1.it)("returns non-Date values unchanged when getting a value", function () {
763
+ var dateOnly = new plugins_1.DateOnly("date", {});
764
+ chai_1.assert.isNull(dateOnly.get(null));
765
+ chai_1.assert.equal(dateOnly.get("2005-10-10"), "2005-10-10");
766
+ });
755
767
  (0, bun_test_1.it)("throws error with invalid date", function () { return __awaiter(void 0, void 0, void 0, function () {
756
768
  var error_7;
757
769
  return __generator(this, function (_a) {
@@ -69,8 +69,6 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
69
69
  }
70
70
  };
71
71
  Object.defineProperty(exports, "__esModule", { value: true });
72
- // noExplicitAny: test mock typing
73
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
74
72
  var bun_test_1 = require("bun:test");
75
73
  var mongoose_1 = __importStar(require("mongoose"));
76
74
  var populate_1 = require("./populate");
@@ -78,7 +76,6 @@ var tests_1 = require("./tests");
78
76
  (0, bun_test_1.describe)("populate functions", function () {
79
77
  var admin;
80
78
  var notAdmin;
81
- // noExplicitAny: typing as HydratedDocument<Food> causes cascading errors on populated field access patterns (e.g. populated.ownerId.name)
82
79
  var spinach;
83
80
  (0, bun_test_1.beforeEach)(function () { return __awaiter(void 0, void 0, void 0, function () {
84
81
  var testData;
@@ -101,13 +98,14 @@ var tests_1 = require("./tests");
101
98
  switch (_c.label) {
102
99
  case 0: return [4 /*yield*/, spinach.populate("ownerId")];
103
100
  case 1:
104
- populated = _c.sent();
105
- return [4 /*yield*/, populated.populate("eatenBy")];
101
+ _c.sent();
102
+ return [4 /*yield*/, spinach.populate("eatenBy")];
106
103
  case 2:
107
- populated = _c.sent();
108
- return [4 /*yield*/, populated.populate("likesIds.userId")];
104
+ _c.sent();
105
+ return [4 /*yield*/, spinach.populate("likesIds.userId")];
109
106
  case 3:
110
- populated = _c.sent();
107
+ _c.sent();
108
+ populated = spinach;
111
109
  (0, bun_test_1.expect)(populated.ownerId.name).toBe("Not Admin");
112
110
  (0, bun_test_1.expect)(populated.eatenBy[0].id).toBe(admin.id);
113
111
  (0, bun_test_1.expect)(populated.eatenBy[0].name).toBe("Admin");
@@ -116,17 +114,17 @@ var tests_1 = require("./tests");
116
114
  (0, bun_test_1.expect)(populated.likesIds[1].userId.id).toBe(notAdmin.id);
117
115
  (0, bun_test_1.expect)(populated.likesIds[1].userId.name).toBe("Not Admin");
118
116
  unpopulated = (0, populate_1.unpopulate)(populated, "ownerId");
119
- (0, bun_test_1.expect)(spinach.ownerId.name).toBeUndefined();
117
+ (0, bun_test_1.expect)(populated.ownerId.name).toBeUndefined();
120
118
  (0, bun_test_1.expect)(unpopulated.ownerId.toString()).toBe(notAdmin.id);
121
119
  // Ensure nothing else was touched.
122
120
  (0, bun_test_1.expect)(populated.likesIds[0].userId.id).toBe(admin.id);
123
121
  (0, bun_test_1.expect)(populated.likesIds[0].userId.name).toBe("Admin");
124
122
  (0, bun_test_1.expect)(populated.likesIds[1].userId.id).toBe(notAdmin.id);
125
123
  (0, bun_test_1.expect)(populated.likesIds[1].userId.name).toBe("Not Admin");
126
- unpopulated = (0, populate_1.unpopulate)(populated, "eatenBy");
124
+ (0, populate_1.unpopulate)(populated, "eatenBy");
127
125
  (0, bun_test_1.expect)(populated.eatenBy.toString()).toBe(admin.id);
128
126
  (0, bun_test_1.expect)((_a = populated.eatenBy[0]) === null || _a === void 0 ? void 0 : _a.name).toBeUndefined();
129
- unpopulated = (0, populate_1.unpopulate)(populated, "likesIds.userId");
127
+ (0, populate_1.unpopulate)(populated, "likesIds.userId");
130
128
  (0, bun_test_1.expect)(populated.likesIds[0].userId.toString()).toBe(admin.id);
131
129
  (0, bun_test_1.expect)((_b = populated.likesIds[0].userId) === null || _b === void 0 ? void 0 : _b.name).toBeUndefined();
132
130
  (0, bun_test_1.expect)(populated.likesIds[1].userId.toString()).toBe(notAdmin.id);
@@ -364,7 +362,6 @@ var tests_1 = require("./tests");
364
362
  populatePaths: [{ fields: ["__proto__.polluted"], path: "ownerId" }],
365
363
  });
366
364
  (0, bun_test_1.expect)(result.properties).toBeDefined();
367
- // noExplicitAny: testing that prototype pollution did not add a 'polluted' property to Object.prototype
368
365
  (0, bun_test_1.expect)(Object.prototype.polluted).toBeUndefined();
369
366
  var ownerProps = result.properties.ownerId.properties;
370
367
  (0, bun_test_1.expect)(ownerProps).toBeDefined();
@@ -2180,6 +2180,112 @@ var createMockSocket = function (decodedToken) {
2180
2180
  }
2181
2181
  });
2182
2182
  }); });
2183
+ (0, bun_test_1.describe)("query room fanout with a registry entry", function () {
2184
+ var modelEntry = {
2185
+ collectionName: "todos",
2186
+ config: { methods: ["create", "update", "delete"], roomStrategy: "model" },
2187
+ modelName: "Todo",
2188
+ options: {
2189
+ permissions: {
2190
+ create: [function () { return true; }],
2191
+ delete: [function () { return true; }],
2192
+ list: [function () { return true; }],
2193
+ read: [function () { return true; }],
2194
+ update: [function () { return true; }],
2195
+ },
2196
+ },
2197
+ routePath: "/todos",
2198
+ };
2199
+ var makeEvent = function (method) { return ({
2200
+ collection: "todos",
2201
+ id: "doc-1",
2202
+ method: method,
2203
+ model: "Todo",
2204
+ timestamp: 1,
2205
+ }); };
2206
+ (0, bun_test_1.it)("emits creates through the permission-filtered path", function () { return __awaiter(void 0, void 0, void 0, function () {
2207
+ var queryId, _a, addSocketToRoom, emissions, io, queryEmissions;
2208
+ return __generator(this, function (_b) {
2209
+ switch (_b.label) {
2210
+ case 0:
2211
+ queryId = (0, queryStore_1.computeQueryId)("todos", { priority: 1 });
2212
+ (0, queryStore_1.addQuerySubscription)("socket-a", "todos", { priority: 1 }, queryId);
2213
+ _a = makeIo(), addSocketToRoom = _a.addSocketToRoom, emissions = _a.emissions, io = _a.io;
2214
+ addSocketToRoom("query:".concat(queryId), { id: "user-1" });
2215
+ return [4 /*yield*/, (0, changeStreamWatcher_1.emitToDocumentAndQueryRooms)(io, "todos", makeEvent("create"), { priority: 1 }, function () { }, modelEntry)];
2216
+ case 1:
2217
+ _b.sent();
2218
+ queryEmissions = emissions.filter(function (e) { return e.room === "query:".concat(queryId); });
2219
+ (0, bun_test_1.expect)(queryEmissions).toHaveLength(1);
2220
+ (0, bun_test_1.expect)(queryEmissions[0].payload).toMatchObject({ data: { priority: 1 }, method: "create" });
2221
+ return [2 /*return*/];
2222
+ }
2223
+ });
2224
+ }); });
2225
+ (0, bun_test_1.it)("emits updates through the permission-filtered path when the doc still matches", function () { return __awaiter(void 0, void 0, void 0, function () {
2226
+ var queryId, _a, addSocketToRoom, emissions, io, queryEmissions;
2227
+ return __generator(this, function (_b) {
2228
+ switch (_b.label) {
2229
+ case 0:
2230
+ queryId = (0, queryStore_1.computeQueryId)("todos", { priority: 1 });
2231
+ (0, queryStore_1.addQuerySubscription)("socket-a", "todos", { priority: 1 }, queryId);
2232
+ _a = makeIo(), addSocketToRoom = _a.addSocketToRoom, emissions = _a.emissions, io = _a.io;
2233
+ addSocketToRoom("query:".concat(queryId), { id: "user-1" });
2234
+ return [4 /*yield*/, (0, changeStreamWatcher_1.emitToDocumentAndQueryRooms)(io, "todos", makeEvent("update"), { priority: 1 }, function () { }, modelEntry)];
2235
+ case 1:
2236
+ _b.sent();
2237
+ queryEmissions = emissions.filter(function (e) { return e.room === "query:".concat(queryId); });
2238
+ (0, bun_test_1.expect)(queryEmissions).toHaveLength(1);
2239
+ (0, bun_test_1.expect)(queryEmissions[0].payload).toMatchObject({ method: "update" });
2240
+ return [2 /*return*/];
2241
+ }
2242
+ });
2243
+ }); });
2244
+ (0, bun_test_1.it)("converts non-matching updates into deletes through the permission-filtered path", function () { return __awaiter(void 0, void 0, void 0, function () {
2245
+ var queryId, _a, addSocketToRoom, emissions, io, queryEmissions;
2246
+ return __generator(this, function (_b) {
2247
+ switch (_b.label) {
2248
+ case 0:
2249
+ queryId = (0, queryStore_1.computeQueryId)("todos", { priority: 1 });
2250
+ (0, queryStore_1.addQuerySubscription)("socket-a", "todos", { priority: 1 }, queryId);
2251
+ _a = makeIo(), addSocketToRoom = _a.addSocketToRoom, emissions = _a.emissions, io = _a.io;
2252
+ addSocketToRoom("query:".concat(queryId), { id: "user-1" });
2253
+ return [4 /*yield*/, (0, changeStreamWatcher_1.emitToDocumentAndQueryRooms)(io, "todos", makeEvent("update"), { priority: 9 }, function () { }, modelEntry)];
2254
+ case 1:
2255
+ _b.sent();
2256
+ queryEmissions = emissions.filter(function (e) { return e.room === "query:".concat(queryId); });
2257
+ (0, bun_test_1.expect)(queryEmissions).toHaveLength(1);
2258
+ (0, bun_test_1.expect)(queryEmissions[0].payload).toMatchObject({ method: "delete" });
2259
+ return [2 /*return*/];
2260
+ }
2261
+ });
2262
+ }); });
2263
+ (0, bun_test_1.it)("skips query rooms whose subscribers cannot read the document", function () { return __awaiter(void 0, void 0, void 0, function () {
2264
+ var queryId, _a, addSocketToRoom, emissions, io, ownerEntry;
2265
+ return __generator(this, function (_b) {
2266
+ switch (_b.label) {
2267
+ case 0:
2268
+ queryId = (0, queryStore_1.computeQueryId)("todos", { priority: 1 });
2269
+ (0, queryStore_1.addQuerySubscription)("socket-a", "todos", { priority: 1 }, queryId);
2270
+ _a = makeIo(), addSocketToRoom = _a.addSocketToRoom, emissions = _a.emissions, io = _a.io;
2271
+ addSocketToRoom("query:".concat(queryId), { id: "other-user" });
2272
+ ownerEntry = __assign(__assign({}, modelEntry), { options: {
2273
+ permissions: __assign(__assign({}, modelEntry.options.permissions), { read: [
2274
+ function (_method, user, obj) {
2275
+ return (user === null || user === void 0 ? void 0 : user.admin) === true ||
2276
+ (user === null || user === void 0 ? void 0 : user.id) === (obj === null || obj === void 0 ? void 0 : obj.ownerId);
2277
+ },
2278
+ ] }),
2279
+ } });
2280
+ return [4 /*yield*/, (0, changeStreamWatcher_1.emitToDocumentAndQueryRooms)(io, "todos", makeEvent("create"), { ownerId: "user-1", priority: 1 }, function () { }, ownerEntry)];
2281
+ case 1:
2282
+ _b.sent();
2283
+ (0, bun_test_1.expect)(emissions.some(function (e) { return e.room === "query:".concat(queryId); })).toBe(false);
2284
+ return [2 /*return*/];
2285
+ }
2286
+ });
2287
+ }); });
2288
+ });
2183
2289
  });
2184
2290
  // ─────────────────────────────────────────────────────────────────────────────
2185
2291
  // redactCredentials — Redis URL logging
@@ -2535,6 +2641,131 @@ var createMockSocket = function (decodedToken) {
2535
2641
  }
2536
2642
  });
2537
2643
  }); });
2644
+ // Records every emission so hard-delete room routing can be asserted.
2645
+ var createRecordingIo = function (room, decodedToken) {
2646
+ if (decodedToken === void 0) { decodedToken = { admin: true, id: "admin" }; }
2647
+ var emissions = [];
2648
+ var rooms = new Map([[room, new Set(["socket-1"])]]);
2649
+ var sockets = new Map([
2650
+ [
2651
+ "socket-1",
2652
+ {
2653
+ decodedToken: decodedToken,
2654
+ emit: function (event, payload) {
2655
+ emissions.push({ event: event, payload: payload });
2656
+ },
2657
+ id: "socket-1",
2658
+ },
2659
+ ],
2660
+ ]);
2661
+ return {
2662
+ emissions: emissions,
2663
+ io: {
2664
+ sockets: { adapter: { rooms: rooms }, sockets: sockets },
2665
+ to: function (_room) { return ({ emit: function (_event, _data) { } }); },
2666
+ },
2667
+ };
2668
+ };
2669
+ (0, bun_test_1.it)("routes hard deletes for model-strategy models to the model room", function () { return __awaiter(void 0, void 0, void 0, function () {
2670
+ var mockStream, mockDb, startChangeStreamWatcher, _a, emissions, io;
2671
+ return __generator(this, function (_b) {
2672
+ switch (_b.label) {
2673
+ case 0:
2674
+ mockStream = createMockChangeStream();
2675
+ mockDb = {
2676
+ watch: (0, bun_test_1.mock)(function () { return mockStream; }),
2677
+ };
2678
+ mongoose_1.default.connection.db = mockDb;
2679
+ (0, registry_1.registerRealtime)({
2680
+ collectionName: "todos",
2681
+ config: {
2682
+ methods: ["create", "update", "delete"],
2683
+ roomStrategy: "model",
2684
+ },
2685
+ modelName: "Todo",
2686
+ options: {
2687
+ permissions: {
2688
+ create: [function () { return true; }],
2689
+ delete: [function () { return true; }],
2690
+ list: [function () { return true; }],
2691
+ read: [function () { return true; }],
2692
+ update: [function () { return true; }],
2693
+ },
2694
+ },
2695
+ routePath: "/todos",
2696
+ });
2697
+ return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require("./changeStreamWatcher")); })];
2698
+ case 1:
2699
+ startChangeStreamWatcher = (_b.sent()).startChangeStreamWatcher;
2700
+ _a = createRecordingIo("model:todos"), emissions = _a.emissions, io = _a.io;
2701
+ startChangeStreamWatcher(io, {}, true);
2702
+ return [4 /*yield*/, invokeRegisteredChangeHandler(mockStream, {
2703
+ documentKey: { _id: "doc-1" },
2704
+ ns: { coll: "todos" },
2705
+ operationType: "delete",
2706
+ })];
2707
+ case 2:
2708
+ _b.sent();
2709
+ (0, bun_test_1.expect)(emissions).toHaveLength(1);
2710
+ (0, bun_test_1.expect)(emissions[0].payload).toMatchObject({ id: "doc-1", method: "delete", model: "Todo" });
2711
+ return [2 /*return*/];
2712
+ }
2713
+ });
2714
+ }); });
2715
+ (0, bun_test_1.it)("swallows errors thrown while processing a change event", function () { return __awaiter(void 0, void 0, void 0, function () {
2716
+ var mockStream, mockDb, startChangeStreamWatcher, roomLookup, io;
2717
+ return __generator(this, function (_a) {
2718
+ switch (_a.label) {
2719
+ case 0:
2720
+ mockStream = createMockChangeStream();
2721
+ mockDb = {
2722
+ watch: (0, bun_test_1.mock)(function () { return mockStream; }),
2723
+ };
2724
+ mongoose_1.default.connection.db = mockDb;
2725
+ (0, registry_1.registerRealtime)({
2726
+ collectionName: "todos",
2727
+ config: {
2728
+ methods: ["create", "update", "delete"],
2729
+ roomStrategy: "model",
2730
+ },
2731
+ modelName: "Todo",
2732
+ options: {
2733
+ permissions: {
2734
+ create: [function () { return true; }],
2735
+ delete: [function () { return true; }],
2736
+ list: [function () { return true; }],
2737
+ read: [function () { return true; }],
2738
+ update: [function () { return true; }],
2739
+ },
2740
+ },
2741
+ routePath: "/todos",
2742
+ });
2743
+ return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require("./changeStreamWatcher")); })];
2744
+ case 1:
2745
+ startChangeStreamWatcher = (_a.sent()).startChangeStreamWatcher;
2746
+ roomLookup = (0, bun_test_1.mock)(function () {
2747
+ throw new Error("adapter unavailable");
2748
+ });
2749
+ io = {
2750
+ sockets: { adapter: { rooms: { get: roomLookup } }, sockets: new Map() },
2751
+ to: function (_room) { return ({ emit: function (_event, _data) { } }); },
2752
+ };
2753
+ startChangeStreamWatcher(io, {}, true);
2754
+ // The handler must not reject — a failed emission cannot take down the change stream.
2755
+ return [4 /*yield*/, invokeRegisteredChangeHandler(mockStream, {
2756
+ documentKey: { _id: "doc-1" },
2757
+ fullDocument: { _id: "doc-1", name: "Test Todo" },
2758
+ ns: { coll: "todos" },
2759
+ operationType: "insert",
2760
+ })];
2761
+ case 2:
2762
+ // The handler must not reject — a failed emission cannot take down the change stream.
2763
+ _a.sent();
2764
+ (0, bun_test_1.expect)(roomLookup).toHaveBeenCalled();
2765
+ return [2 /*return*/];
2766
+ }
2767
+ });
2768
+ }); });
2538
2769
  (0, bun_test_1.it)("includes updatedFields in event for update operations", function () { return __awaiter(void 0, void 0, void 0, function () {
2539
2770
  var mockStream, mockDb, startChangeStreamWatcher, io;
2540
2771
  return __generator(this, function (_a) {
@@ -28,7 +28,7 @@ export interface RealtimeSocketLike extends SocketWithDecodedToken {
28
28
  join: (room: string) => Promise<void> | void;
29
29
  leave: (room: string) => Promise<void> | void;
30
30
  emit: (event: string, payload: unknown) => void;
31
- on: (event: string, handler: (...args: any[]) => any) => void;
31
+ on: (event: string, handler: (...args: never[]) => void | Promise<void>) => void;
32
32
  }
33
33
  /**
34
34
  * Install the realtime subscription handlers on a single socket. Extracted from the
@@ -84,6 +84,7 @@ exports.RealtimeApp = exports.installRealtimeSocketHandlers = exports.redactCred
84
84
  var Sentry = __importStar(require("@sentry/bun"));
85
85
  var socketio_jwt_1 = require("@thream/socketio-jwt");
86
86
  var socket_io_1 = require("socket.io");
87
+ var errors_1 = require("../errors");
87
88
  var logger_1 = require("../logger");
88
89
  var permissions_1 = require("../permissions");
89
90
  var changeStreamWatcher_1 = require("./changeStreamWatcher");
@@ -462,8 +463,11 @@ var RealtimeApp = /** @class */ (function () {
462
463
  // JWT authentication middleware
463
464
  var tokenSecret = (_c = this.config.tokenSecret) !== null && _c !== void 0 ? _c : process.env.TOKEN_SECRET;
464
465
  if (!tokenSecret) {
465
- throw new Error("[realtime] TOKEN_SECRET is required for socket authentication. " +
466
- "Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions.");
466
+ throw new errors_1.APIError({
467
+ status: 500,
468
+ title: "[realtime] TOKEN_SECRET is required for socket authentication. " +
469
+ "Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions.",
470
+ });
467
471
  }
468
472
  this.io.use((0, socketio_jwt_1.authorize)({
469
473
  secret: tokenSecret,
@@ -0,0 +1 @@
1
+ export {};