@terreno/api 57.20.0 → 58.0.0-beta.1

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 (183) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +1 -1
  3. package/biome.jsonc +3 -2
  4. package/dist/api.d.ts +3 -16
  5. package/dist/api.js +0 -9
  6. package/dist/auth.d.ts +3 -2
  7. package/dist/auth.js +95 -5
  8. package/dist/authRecovery.d.ts +2 -1
  9. package/dist/authRecovery.js +35 -17
  10. package/dist/collectionRegistry.d.ts +3 -4
  11. package/dist/collectionRegistry.js +0 -1
  12. package/dist/consentApp.d.ts +1 -1
  13. package/dist/consentApp.js +58 -2
  14. package/dist/frameworkModelNames.d.ts +4 -0
  15. package/dist/frameworkModelNames.js +4 -0
  16. package/dist/index.d.ts +8 -5
  17. package/dist/index.js +14 -20
  18. package/dist/mcp/adminTracking.d.ts +28 -0
  19. package/dist/mcp/adminTracking.js +80 -0
  20. package/dist/mcp/auth.d.ts +6 -0
  21. package/dist/mcp/auth.js +12 -2
  22. package/dist/mcp/server.d.ts +8 -0
  23. package/dist/mcp/server.js +48 -4
  24. package/dist/mcp/serviceTokens.d.ts +21 -1
  25. package/dist/mcp/serviceTokens.js +159 -183
  26. package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
  27. package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
  28. package/dist/models/mcpOAuthToken.js +27 -0
  29. package/dist/models/mcpRequestLog.d.ts +2 -0
  30. package/dist/models/mcpRequestLog.js +73 -0
  31. package/dist/models/mcpServiceToken.js +40 -4
  32. package/dist/models/mcpToolSetting.d.ts +2 -0
  33. package/dist/models/mcpToolSetting.js +119 -0
  34. package/dist/models/versionConfig.d.ts +2 -0
  35. package/dist/openApiBuilder.d.ts +4 -0
  36. package/dist/openApiBuilder.js +2 -0
  37. package/dist/rbac/auditModel.d.ts +2 -1
  38. package/dist/rbac/realtimeAccess.d.ts +5 -4
  39. package/dist/rbac/realtimeAccess.js +17 -64
  40. package/dist/realtime/changeStreamWatcher.d.ts +8 -63
  41. package/dist/realtime/changeStreamWatcher.js +32 -391
  42. package/dist/realtime/realtimeApp.d.ts +14 -27
  43. package/dist/realtime/realtimeApp.js +14 -220
  44. package/dist/realtime/types.d.ts +0 -64
  45. package/dist/sync/executors.js +14 -2
  46. package/dist/sync/socketHandlers.d.ts +1 -1
  47. package/dist/sync/socketHandlers.js +1 -1
  48. package/dist/terrenoApp.d.ts +19 -5
  49. package/dist/terrenoApp.js +21 -14
  50. package/dist/tests/models.d.ts +17 -22
  51. package/dist/tests/models.js +7 -1
  52. package/dist/tests/openApiResponseSchema.d.ts +39 -0
  53. package/dist/tests/openApiResponseSchema.js +56 -0
  54. package/dist/tests/testHelper.d.ts +6 -12
  55. package/dist/tests.d.ts +2 -0
  56. package/dist/tests.js +6 -1
  57. package/dist/types/mcpAdmin.d.ts +58 -0
  58. package/dist/types/mcpAdmin.js +2 -0
  59. package/dist/types/mcpOAuth.d.ts +2 -0
  60. package/dist/types/mcpServiceToken.d.ts +9 -4
  61. package/dist/versionCheckPlugin.d.ts +1 -1
  62. package/dist/versionCheckPlugin.js +25 -2
  63. package/e2e/smoke.ts +193 -0
  64. package/package.json +14 -8
  65. package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
  66. package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
  67. package/src/__tests__/openApiResponseSchema.test.ts +148 -0
  68. package/src/__tests__/versionCheckPlugin.test.ts +72 -0
  69. package/src/adminModelRouter.test.ts +8 -6
  70. package/src/api.arrayOperations.test.ts +31 -22
  71. package/src/api.hooks.test.ts +12 -11
  72. package/src/api.query.test.ts +2 -2
  73. package/src/api.test.ts +17 -14
  74. package/src/api.ts +3 -27
  75. package/src/audit/auditApp.test.ts +1 -1
  76. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  77. package/src/auth.test.ts +21 -7
  78. package/src/auth.ts +116 -5
  79. package/src/authOpenApi.test.ts +316 -0
  80. package/src/authRecovery.test.ts +10 -10
  81. package/src/authRecovery.ts +47 -19
  82. package/src/authVerification.test.ts +7 -7
  83. package/src/betterAuthFeatures.test.ts +3 -2
  84. package/src/betterAuthLinking.test.ts +3 -1
  85. package/src/betterAuthOAuthHandoff.test.ts +13 -5
  86. package/src/betterAuthSetup.test.ts +77 -51
  87. package/src/collectionRegistry.test.ts +4 -4
  88. package/src/collectionRegistry.ts +3 -5
  89. package/src/consentApp.test.ts +98 -0
  90. package/src/consentApp.ts +67 -2
  91. package/src/frameworkModelNames.test.ts +8 -0
  92. package/src/frameworkModelNames.ts +4 -0
  93. package/src/githubAuth.test.ts +11 -11
  94. package/src/index.ts +14 -28
  95. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  96. package/src/mcp/actionTools.test.ts +13 -7
  97. package/src/mcp/adminTracking.test.ts +272 -0
  98. package/src/mcp/adminTracking.ts +104 -0
  99. package/src/mcp/auth.test.ts +7 -3
  100. package/src/mcp/auth.ts +18 -2
  101. package/src/mcp/oauth.test.ts +13 -13
  102. package/src/mcp/server.ts +67 -4
  103. package/src/mcp/serviceTokens.sync.test.ts +230 -0
  104. package/src/mcp/serviceTokens.test.ts +114 -62
  105. package/src/mcp/serviceTokens.ts +193 -212
  106. package/src/mcp/toolGenerator.test.ts +9 -5
  107. package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
  108. package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
  109. package/src/migrations/cli.test.ts +15 -14
  110. package/src/migrations/cli.ts +1 -1
  111. package/src/migrations/generate.test.ts +2 -2
  112. package/src/migrations/load.test.ts +1 -1
  113. package/src/migrations/lock.test.ts +8 -3
  114. package/src/migrations/runner.test.ts +16 -5
  115. package/src/migrations/schemaCatalog.test.ts +4 -1
  116. package/src/models/mcpOAuthToken.test.ts +42 -0
  117. package/src/models/mcpOAuthToken.ts +32 -0
  118. package/src/models/mcpRequestLog.ts +81 -0
  119. package/src/models/mcpServiceToken.test.ts +75 -5
  120. package/src/models/mcpServiceToken.ts +61 -14
  121. package/src/models/mcpToolSetting.test.ts +69 -0
  122. package/src/models/mcpToolSetting.ts +138 -0
  123. package/src/models/versionConfig.ts +2 -0
  124. package/src/notifications/notificationsApp.test.ts +5 -8
  125. package/src/notifiers/slackWebApi.test.ts +30 -8
  126. package/src/openApi.test.ts +4 -4
  127. package/src/openApiBuilder.test.ts +34 -1
  128. package/src/openApiBuilder.ts +5 -0
  129. package/src/openApiValidator.test.ts +3 -3
  130. package/src/orgs/orgPermissions.test.ts +2 -2
  131. package/src/orgs/orgPlugin.test.ts +4 -3
  132. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  133. package/src/orgs/organizationSettings.test.ts +1 -1
  134. package/src/orgs/orgsApp.test.ts +5 -3
  135. package/src/permissions.test.ts +2 -2
  136. package/src/rateLimit/rateLimit.test.ts +25 -10
  137. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  138. package/src/rbac/assertAllowed.test.ts +1 -1
  139. package/src/rbac/auditModel.ts +10 -2
  140. package/src/rbac/realtimeAccess.test.ts +20 -171
  141. package/src/rbac/realtimeAccess.ts +17 -82
  142. package/src/rbac/routes.test.ts +1 -1
  143. package/src/rbac/userWriteGuards.test.ts +8 -5
  144. package/src/realtime/changeStreamWatcher.ts +43 -506
  145. package/src/realtime/realtime.test.ts +211 -2547
  146. package/src/realtime/realtimeApp.ts +16 -295
  147. package/src/realtime/types.ts +0 -72
  148. package/src/scrubAdminFields.test.ts +1 -1
  149. package/src/sync/adminWindowMutation.test.ts +4 -3
  150. package/src/sync/executors.test.ts +29 -1
  151. package/src/sync/executors.ts +23 -2
  152. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  153. package/src/sync/socketHandlers.ts +1 -1
  154. package/src/sync/sync.test.ts +1 -1
  155. package/src/sync/syncPhaseC.test.ts +14 -11
  156. package/src/sync/syncRoutes.test.ts +8 -8
  157. package/src/sync/syncSeqPlugin.test.ts +1 -2
  158. package/src/sync/syncSocket.test.ts +78 -113
  159. package/src/terrenoApp.mcpServiceTokens.test.ts +16 -8
  160. package/src/terrenoApp.migrations.test.ts +8 -7
  161. package/src/terrenoApp.ts +38 -18
  162. package/src/tests/betterAuthStubs.ts +3 -2
  163. package/src/tests/bunSetup.ts +1 -1
  164. package/src/tests/models.ts +10 -0
  165. package/src/tests/openApiResponseSchema.ts +104 -0
  166. package/src/tests/testEnv.ts +7 -0
  167. package/src/tests.ts +8 -0
  168. package/src/types/mcpAdmin.ts +80 -0
  169. package/src/types/mcpOAuth.ts +5 -0
  170. package/src/types/mcpServiceToken.ts +12 -4
  171. package/src/versionCheckPlugin.ts +41 -2
  172. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  173. package/tsconfig.typecheck.json +14 -0
  174. package/dist/realtime/deprecation.d.ts +0 -13
  175. package/dist/realtime/deprecation.js +0 -31
  176. package/dist/realtime/queryStore.d.ts +0 -37
  177. package/dist/realtime/queryStore.js +0 -103
  178. package/dist/realtime/registry.d.ts +0 -15
  179. package/dist/realtime/registry.js +0 -52
  180. package/src/realtime/deprecation.test.ts +0 -60
  181. package/src/realtime/deprecation.ts +0 -33
  182. package/src/realtime/queryStore.ts +0 -122
  183. package/src/realtime/registry.ts +0 -84
@@ -1,103 +0,0 @@
1
- "use strict";
2
- /**
3
- * Manages query subscriptions for Socket.io clients.
4
- *
5
- * When a client subscribes to a query (e.g., `{completed: false}` on the "todos" collection),
6
- * the query is stored here. The change stream watcher consults this store to determine
7
- * which query rooms should receive a given change event.
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.clearQueryStore = exports.getQuerySubscriptionsForCollection = exports.removeAllSocketQueries = exports.removeQuerySubscription = exports.addQuerySubscription = exports.computeQueryId = void 0;
11
- /**
12
- * Compute a deterministic queryId from collection and query on the server side.
13
- * This prevents clients from hijacking other subscriptions by providing a colliding queryId.
14
- */
15
- const computeQueryId = (collection, query) => {
16
- const sortedKeys = Object.keys(query).sort();
17
- const normalized = {};
18
- for (const key of sortedKeys) {
19
- normalized[key] = query[key];
20
- }
21
- return `${collection}:${JSON.stringify(normalized)}`;
22
- };
23
- exports.computeQueryId = computeQueryId;
24
- /** queryId → query subscription details (shared across all sockets in that room) */
25
- const querySubscriptions = new Map();
26
- /** socketId → set of queryIds that socket is subscribed to */
27
- const socketQueries = new Map();
28
- /**
29
- * Register a query subscription for a socket.
30
- * The socket joins the `query:{queryId}` room (handled by the caller).
31
- */
32
- const addQuerySubscription = (socketId, collection, query, queryId) => {
33
- querySubscriptions.set(queryId, { collection, query, queryId });
34
- if (!socketQueries.has(socketId)) {
35
- socketQueries.set(socketId, new Set());
36
- }
37
- socketQueries.get(socketId)?.add(queryId);
38
- };
39
- exports.addQuerySubscription = addQuerySubscription;
40
- /**
41
- * Remove a single query subscription for a socket.
42
- */
43
- const removeQuerySubscription = (socketId, queryId) => {
44
- socketQueries.get(socketId)?.delete(queryId);
45
- // Check if any other socket still has this query
46
- let stillUsed = false;
47
- for (const [, queryIds] of socketQueries) {
48
- if (queryIds.has(queryId)) {
49
- stillUsed = true;
50
- break;
51
- }
52
- }
53
- if (!stillUsed) {
54
- querySubscriptions.delete(queryId);
55
- }
56
- };
57
- exports.removeQuerySubscription = removeQuerySubscription;
58
- /**
59
- * Remove all query subscriptions for a disconnected socket.
60
- */
61
- const removeAllSocketQueries = (socketId) => {
62
- const queryIds = socketQueries.get(socketId);
63
- if (!queryIds) {
64
- return;
65
- }
66
- socketQueries.delete(socketId);
67
- // Clean up any queries that no longer have subscribers
68
- for (const queryId of queryIds) {
69
- let stillUsed = false;
70
- for (const [, otherQueryIds] of socketQueries) {
71
- if (otherQueryIds.has(queryId)) {
72
- stillUsed = true;
73
- break;
74
- }
75
- }
76
- if (!stillUsed) {
77
- querySubscriptions.delete(queryId);
78
- }
79
- }
80
- };
81
- exports.removeAllSocketQueries = removeAllSocketQueries;
82
- /**
83
- * Get all unique query subscriptions for a given collection.
84
- * Used by the change stream watcher to evaluate which query rooms to emit to.
85
- */
86
- const getQuerySubscriptionsForCollection = (collection) => {
87
- const result = [];
88
- for (const [queryId, sub] of querySubscriptions) {
89
- if (sub.collection === collection) {
90
- result.push({ query: sub.query, queryId });
91
- }
92
- }
93
- return result;
94
- };
95
- exports.getQuerySubscriptionsForCollection = getQuerySubscriptionsForCollection;
96
- /**
97
- * Clear all subscriptions (for testing).
98
- */
99
- const clearQueryStore = () => {
100
- querySubscriptions.clear();
101
- socketQueries.clear();
102
- };
103
- exports.clearQueryStore = clearQueryStore;
@@ -1,15 +0,0 @@
1
- import type { ModelRouterOptions } from "../api";
2
- import type { RealtimeConfig } from "./types";
3
- export interface RealtimeRegistryEntry {
4
- modelName: string;
5
- routePath: string;
6
- collectionName: string;
7
- config: RealtimeConfig;
8
- options: ModelRouterOptions<unknown>;
9
- }
10
- export declare const registerRealtime: (entry: RealtimeRegistryEntry) => void;
11
- export declare const updateRealtimeRegistryOptions: (routePath: string, options: ModelRouterOptions<unknown>) => void;
12
- export declare const getRealtimeRegistry: () => RealtimeRegistryEntry[];
13
- export declare const findRegistryEntryByCollection: (collectionName: string) => RealtimeRegistryEntry | undefined;
14
- export declare const findRegistryEntryByRoutePath: (collection: string) => RealtimeRegistryEntry | undefined;
15
- export declare const clearRealtimeRegistry: () => void;
@@ -1,52 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.clearRealtimeRegistry = exports.findRegistryEntryByRoutePath = exports.findRegistryEntryByCollection = exports.getRealtimeRegistry = exports.updateRealtimeRegistryOptions = exports.registerRealtime = void 0;
4
- const collectionRegistry_1 = require("../collectionRegistry");
5
- const toRealtimeEntry = (record) => ({
6
- collectionName: record.model.collection.collectionName,
7
- config: record.options.realtime,
8
- modelName: record.model.modelName,
9
- options: record.options,
10
- routePath: record.routePath,
11
- });
12
- const realtimeModelForEntry = (entry) => {
13
- const registered = (0, collectionRegistry_1.listCollections)().find((record) => record.routePath === entry.routePath)?.model;
14
- if (registered) {
15
- return registered;
16
- }
17
- return {
18
- collection: { collectionName: entry.collectionName },
19
- modelName: entry.modelName,
20
- };
21
- };
22
- const registerRealtime = (entry) => {
23
- (0, collectionRegistry_1.registerCollection)({
24
- model: realtimeModelForEntry(entry),
25
- options: {
26
- ...entry.options,
27
- realtime: entry.config,
28
- },
29
- routePath: entry.routePath,
30
- });
31
- };
32
- exports.registerRealtime = registerRealtime;
33
- const updateRealtimeRegistryOptions = (routePath, options) => {
34
- (0, collectionRegistry_1.replaceCollectionOptions)(routePath, options);
35
- };
36
- exports.updateRealtimeRegistryOptions = updateRealtimeRegistryOptions;
37
- const getRealtimeRegistry = () => (0, collectionRegistry_1.listCollections)()
38
- .filter((record) => record.surfaces.realtime)
39
- .map(toRealtimeEntry);
40
- exports.getRealtimeRegistry = getRealtimeRegistry;
41
- const findRegistryEntryByCollection = (collectionName) => {
42
- return (0, exports.getRealtimeRegistry)().find((entry) => entry.collectionName === collectionName);
43
- };
44
- exports.findRegistryEntryByCollection = findRegistryEntryByCollection;
45
- const findRegistryEntryByRoutePath = (collection) => {
46
- return (0, exports.getRealtimeRegistry)().find((entry) => entry.routePath === `/${collection}` || entry.routePath === collection);
47
- };
48
- exports.findRegistryEntryByRoutePath = findRegistryEntryByRoutePath;
49
- const clearRealtimeRegistry = () => {
50
- (0, collectionRegistry_1.clearCollectionRegistry)();
51
- };
52
- exports.clearRealtimeRegistry = clearRealtimeRegistry;
@@ -1,60 +0,0 @@
1
- import {afterEach, describe, expect, it, spyOn} from "bun:test";
2
-
3
- import {modelRouter} from "../api";
4
- import {logger} from "../logger";
5
- import {Permissions} from "../permissions";
6
- import {FoodModel} from "../tests";
7
- import {
8
- REALTIME_DEPRECATION_MESSAGE,
9
- resetRealtimeDeprecationWarningsForTests,
10
- } from "./deprecation";
11
- import {clearRealtimeRegistry} from "./registry";
12
-
13
- const realtimeConfig = {
14
- methods: ["create", "update", "delete"] as Array<"create" | "update" | "delete">,
15
- roomStrategy: "model" as const,
16
- };
17
-
18
- const permissions = {
19
- create: [Permissions.IsAny],
20
- delete: [Permissions.IsAny],
21
- list: [Permissions.IsAny],
22
- read: [Permissions.IsAny],
23
- update: [Permissions.IsAny],
24
- };
25
-
26
- describe("modelRouter realtime deprecation", () => {
27
- afterEach(() => {
28
- resetRealtimeDeprecationWarningsForTests();
29
- clearRealtimeRegistry();
30
- });
31
-
32
- it("warns once per model and path when realtime is configured", () => {
33
- const warnSpy = spyOn(logger, "warn").mockImplementation(() => logger);
34
-
35
- modelRouter("/foods", FoodModel, {permissions, realtime: realtimeConfig});
36
- modelRouter("/foods", FoodModel, {permissions, realtime: realtimeConfig});
37
-
38
- const deprecationCalls = warnSpy.mock.calls.filter((args) =>
39
- String(args[0]).includes(REALTIME_DEPRECATION_MESSAGE)
40
- );
41
- expect(deprecationCalls).toHaveLength(1);
42
- expect(String(deprecationCalls[0]?.[0])).toContain("Food at /foods");
43
-
44
- warnSpy.mockRestore();
45
- });
46
-
47
- it("warns when realtime is used without the path form", () => {
48
- const warnSpy = spyOn(logger, "warn").mockImplementation(() => logger);
49
-
50
- modelRouter(FoodModel, {permissions, realtime: realtimeConfig});
51
-
52
- const deprecationCalls = warnSpy.mock.calls.filter((args) =>
53
- String(args[0]).includes(REALTIME_DEPRECATION_MESSAGE)
54
- );
55
- expect(deprecationCalls).toHaveLength(1);
56
- expect(String(deprecationCalls[0]?.[0])).toContain("(Food)");
57
-
58
- warnSpy.mockRestore();
59
- });
60
- });
@@ -1,33 +0,0 @@
1
- import {logger} from "../logger";
2
-
3
- /**
4
- * One-line warning for modelRouter `realtime`. Keep in sync with the
5
- * `@terreno/rtk` helpers and `docs/implementationPlans/remove-legacy-realtime.md`.
6
- */
7
- /** @internal */
8
- export const REALTIME_DEPRECATION_MESSAGE =
9
- "modelRouter `realtime` is deprecated and will be removed in Terreno 58. Use `sync` with `@terreno/syncdb` instead. See docs/how-to/migrate-rtk-to-syncdb.md. RealtimeApp remains required for sync sockets.";
10
-
11
- const warnedKeys = new Set<string>();
12
-
13
- const warningKey = (modelName: string, routePath?: string): string =>
14
- `${modelName}:${routePath ?? ""}`;
15
-
16
- /**
17
- * Emits a one-time deprecation warning per model/routePath per process when a
18
- * consumer enables the legacy RTK cache-patching `realtime` option.
19
- */
20
- export const warnRealtimeDeprecated = (modelName: string, routePath?: string): void => {
21
- const key = warningKey(modelName, routePath);
22
- if (warnedKeys.has(key)) {
23
- return;
24
- }
25
- warnedKeys.add(key);
26
- const location = routePath ? `${modelName} at ${routePath}` : modelName;
27
- logger.warn(`[realtime] ${REALTIME_DEPRECATION_MESSAGE} (${location})`);
28
- };
29
-
30
- /** @internal Test helper — clears one-time realtime deprecation warnings. */
31
- export const resetRealtimeDeprecationWarningsForTests = (): void => {
32
- warnedKeys.clear();
33
- };
@@ -1,122 +0,0 @@
1
- /**
2
- * Manages query subscriptions for Socket.io clients.
3
- *
4
- * When a client subscribes to a query (e.g., `{completed: false}` on the "todos" collection),
5
- * the query is stored here. The change stream watcher consults this store to determine
6
- * which query rooms should receive a given change event.
7
- */
8
-
9
- interface QuerySubscription {
10
- collection: string;
11
- query: Record<string, unknown>;
12
- queryId: string;
13
- }
14
-
15
- /**
16
- * Compute a deterministic queryId from collection and query on the server side.
17
- * This prevents clients from hijacking other subscriptions by providing a colliding queryId.
18
- */
19
- export const computeQueryId = (collection: string, query: Record<string, unknown>): string => {
20
- const sortedKeys = Object.keys(query).sort();
21
- const normalized: Record<string, unknown> = {};
22
- for (const key of sortedKeys) {
23
- normalized[key] = query[key];
24
- }
25
- return `${collection}:${JSON.stringify(normalized)}`;
26
- };
27
-
28
- /** queryId → query subscription details (shared across all sockets in that room) */
29
- const querySubscriptions = new Map<string, QuerySubscription>();
30
-
31
- /** socketId → set of queryIds that socket is subscribed to */
32
- const socketQueries = new Map<string, Set<string>>();
33
-
34
- /**
35
- * Register a query subscription for a socket.
36
- * The socket joins the `query:{queryId}` room (handled by the caller).
37
- */
38
- export const addQuerySubscription = (
39
- socketId: string,
40
- collection: string,
41
- query: Record<string, unknown>,
42
- queryId: string
43
- ): void => {
44
- querySubscriptions.set(queryId, {collection, query, queryId});
45
-
46
- if (!socketQueries.has(socketId)) {
47
- socketQueries.set(socketId, new Set());
48
- }
49
- socketQueries.get(socketId)?.add(queryId);
50
- };
51
-
52
- /**
53
- * Remove a single query subscription for a socket.
54
- */
55
- export const removeQuerySubscription = (socketId: string, queryId: string): void => {
56
- socketQueries.get(socketId)?.delete(queryId);
57
-
58
- // Check if any other socket still has this query
59
- let stillUsed = false;
60
- for (const [, queryIds] of socketQueries) {
61
- if (queryIds.has(queryId)) {
62
- stillUsed = true;
63
- break;
64
- }
65
- }
66
-
67
- if (!stillUsed) {
68
- querySubscriptions.delete(queryId);
69
- }
70
- };
71
-
72
- /**
73
- * Remove all query subscriptions for a disconnected socket.
74
- */
75
- export const removeAllSocketQueries = (socketId: string): void => {
76
- const queryIds = socketQueries.get(socketId);
77
- if (!queryIds) {
78
- return;
79
- }
80
-
81
- socketQueries.delete(socketId);
82
-
83
- // Clean up any queries that no longer have subscribers
84
- for (const queryId of queryIds) {
85
- let stillUsed = false;
86
- for (const [, otherQueryIds] of socketQueries) {
87
- if (otherQueryIds.has(queryId)) {
88
- stillUsed = true;
89
- break;
90
- }
91
- }
92
- if (!stillUsed) {
93
- querySubscriptions.delete(queryId);
94
- }
95
- }
96
- };
97
-
98
- /**
99
- * Get all unique query subscriptions for a given collection.
100
- * Used by the change stream watcher to evaluate which query rooms to emit to.
101
- */
102
- export const getQuerySubscriptionsForCollection = (
103
- collection: string
104
- ): {queryId: string; query: Record<string, unknown>}[] => {
105
- const result: {queryId: string; query: Record<string, unknown>}[] = [];
106
-
107
- for (const [queryId, sub] of querySubscriptions) {
108
- if (sub.collection === collection) {
109
- result.push({query: sub.query, queryId});
110
- }
111
- }
112
-
113
- return result;
114
- };
115
-
116
- /**
117
- * Clear all subscriptions (for testing).
118
- */
119
- export const clearQueryStore = (): void => {
120
- querySubscriptions.clear();
121
- socketQueries.clear();
122
- };
@@ -1,84 +0,0 @@
1
- import type {Model} from "mongoose";
2
-
3
- import type {ModelRouterOptions} from "../api";
4
- import {
5
- clearCollectionRegistry,
6
- listCollections,
7
- registerCollection,
8
- replaceCollectionOptions,
9
- } from "../collectionRegistry";
10
- import type {RealtimeConfig} from "./types";
11
-
12
- export interface RealtimeRegistryEntry {
13
- modelName: string;
14
- routePath: string;
15
- collectionName: string;
16
- config: RealtimeConfig;
17
- options: ModelRouterOptions<unknown>;
18
- }
19
-
20
- const toRealtimeEntry = (record: {
21
- model: Model<unknown>;
22
- options: ModelRouterOptions<unknown>;
23
- routePath: string;
24
- }): RealtimeRegistryEntry => ({
25
- collectionName: record.model.collection.collectionName,
26
- config: record.options.realtime as RealtimeConfig,
27
- modelName: record.model.modelName,
28
- options: record.options,
29
- routePath: record.routePath,
30
- });
31
-
32
- const realtimeModelForEntry = (entry: RealtimeRegistryEntry): Model<unknown> => {
33
- const registered = listCollections().find(
34
- (record) => record.routePath === entry.routePath
35
- )?.model;
36
- if (registered) {
37
- return registered;
38
- }
39
- return {
40
- collection: {collectionName: entry.collectionName},
41
- modelName: entry.modelName,
42
- } as Model<unknown>;
43
- };
44
-
45
- export const registerRealtime = (entry: RealtimeRegistryEntry): void => {
46
- registerCollection({
47
- model: realtimeModelForEntry(entry),
48
- options: {
49
- ...entry.options,
50
- realtime: entry.config,
51
- } as ModelRouterOptions<unknown>,
52
- routePath: entry.routePath,
53
- });
54
- };
55
-
56
- export const updateRealtimeRegistryOptions = (
57
- routePath: string,
58
- options: ModelRouterOptions<unknown>
59
- ): void => {
60
- replaceCollectionOptions(routePath, options);
61
- };
62
-
63
- export const getRealtimeRegistry = (): RealtimeRegistryEntry[] =>
64
- listCollections()
65
- .filter((record) => record.surfaces.realtime)
66
- .map(toRealtimeEntry);
67
-
68
- export const findRegistryEntryByCollection = (
69
- collectionName: string
70
- ): RealtimeRegistryEntry | undefined => {
71
- return getRealtimeRegistry().find((entry) => entry.collectionName === collectionName);
72
- };
73
-
74
- export const findRegistryEntryByRoutePath = (
75
- collection: string
76
- ): RealtimeRegistryEntry | undefined => {
77
- return getRealtimeRegistry().find(
78
- (entry) => entry.routePath === `/${collection}` || entry.routePath === collection
79
- );
80
- };
81
-
82
- export const clearRealtimeRegistry = (): void => {
83
- clearCollectionRegistry();
84
- };