@terreno/api 57.21.0 → 58.0.0-beta.2

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 (121) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +1 -1
  3. package/dist/api.d.ts +0 -13
  4. package/dist/api.js +0 -9
  5. package/dist/auth.d.ts +3 -2
  6. package/dist/auth.js +95 -5
  7. package/dist/authRecovery.d.ts +2 -1
  8. package/dist/authRecovery.js +35 -17
  9. package/dist/collectionRegistry.d.ts +3 -4
  10. package/dist/collectionRegistry.js +0 -1
  11. package/dist/consentApp.d.ts +1 -1
  12. package/dist/consentApp.js +58 -2
  13. package/dist/index.d.ts +4 -5
  14. package/dist/index.js +8 -20
  15. package/dist/mcp/adminTracking.js +1 -1
  16. package/dist/mcp/serviceTokens.d.ts +21 -1
  17. package/dist/mcp/serviceTokens.js +159 -183
  18. package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
  19. package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
  20. package/dist/models/mcpRequestLog.js +1 -1
  21. package/dist/models/mcpServiceToken.js +36 -4
  22. package/dist/openApiBuilder.d.ts +4 -0
  23. package/dist/openApiBuilder.js +2 -0
  24. package/dist/rbac/realtimeAccess.d.ts +5 -4
  25. package/dist/rbac/realtimeAccess.js +17 -64
  26. package/dist/realtime/changeStreamWatcher.d.ts +8 -63
  27. package/dist/realtime/changeStreamWatcher.js +32 -391
  28. package/dist/realtime/realtimeApp.d.ts +14 -27
  29. package/dist/realtime/realtimeApp.js +14 -220
  30. package/dist/realtime/types.d.ts +0 -64
  31. package/dist/sync/entityIds.d.ts +14 -0
  32. package/dist/sync/entityIds.js +17 -0
  33. package/dist/sync/executors.js +14 -2
  34. package/dist/sync/models.d.ts +1 -0
  35. package/dist/sync/models.js +4 -0
  36. package/dist/sync/mutationHandler.js +51 -2
  37. package/dist/sync/routes.js +12 -17
  38. package/dist/sync/socketHandlers.d.ts +1 -1
  39. package/dist/sync/socketHandlers.js +1 -1
  40. package/dist/sync/types.d.ts +8 -0
  41. package/dist/terrenoApp.d.ts +7 -5
  42. package/dist/terrenoApp.js +18 -14
  43. package/dist/tests/openApiResponseSchema.d.ts +39 -0
  44. package/dist/tests/openApiResponseSchema.js +56 -0
  45. package/dist/tests.d.ts +1 -0
  46. package/dist/tests.js +4 -1
  47. package/dist/types/mcpAdmin.d.ts +1 -1
  48. package/dist/types/mcpServiceToken.d.ts +7 -4
  49. package/dist/versionCheckPlugin.d.ts +1 -1
  50. package/dist/versionCheckPlugin.js +25 -2
  51. package/package.json +17 -6
  52. package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
  53. package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
  54. package/src/__tests__/openApiResponseSchema.test.ts +148 -0
  55. package/src/__tests__/versionCheckPlugin.test.ts +72 -0
  56. package/src/api.test.ts +9 -7
  57. package/src/api.ts +0 -24
  58. package/src/auth.ts +116 -5
  59. package/src/authOpenApi.test.ts +316 -0
  60. package/src/authRecovery.ts +47 -19
  61. package/src/betterAuthOAuthHandoff.test.ts +13 -5
  62. package/src/collectionRegistry.ts +3 -5
  63. package/src/consentApp.test.ts +98 -0
  64. package/src/consentApp.ts +67 -2
  65. package/src/index.ts +6 -28
  66. package/src/mcp/actionTools.test.ts +2 -2
  67. package/src/mcp/adminTracking.ts +1 -1
  68. package/src/mcp/auth.test.ts +7 -3
  69. package/src/mcp/oauth.test.ts +12 -12
  70. package/src/mcp/serviceTokens.sync.test.ts +230 -0
  71. package/src/mcp/serviceTokens.test.ts +112 -61
  72. package/src/mcp/serviceTokens.ts +193 -212
  73. package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
  74. package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
  75. package/src/models/mcpRequestLog.ts +1 -1
  76. package/src/models/mcpServiceToken.test.ts +52 -5
  77. package/src/models/mcpServiceToken.ts +51 -14
  78. package/src/openApiBuilder.test.ts +34 -1
  79. package/src/openApiBuilder.ts +5 -0
  80. package/src/rateLimit/rateLimit.test.ts +25 -10
  81. package/src/rbac/realtimeAccess.test.ts +20 -172
  82. package/src/rbac/realtimeAccess.ts +17 -82
  83. package/src/realtime/changeStreamWatcher.ts +43 -506
  84. package/src/realtime/realtime.test.ts +205 -2545
  85. package/src/realtime/realtimeApp.ts +16 -295
  86. package/src/realtime/types.ts +0 -72
  87. package/src/sync/entityIds.ts +18 -0
  88. package/src/sync/executors.test.ts +28 -0
  89. package/src/sync/executors.ts +23 -2
  90. package/src/sync/models.ts +6 -0
  91. package/src/sync/mutationHandler.test.ts +84 -0
  92. package/src/sync/mutationHandler.ts +57 -2
  93. package/src/sync/routes.ts +12 -17
  94. package/src/sync/socketHandlers.ts +1 -1
  95. package/src/sync/syncRoutes.test.ts +8 -4
  96. package/src/sync/syncSocket.test.ts +77 -113
  97. package/src/sync/types.ts +9 -0
  98. package/src/terrenoApp.mcpServiceTokens.test.ts +14 -6
  99. package/src/terrenoApp.ts +24 -18
  100. package/src/tests/openApiResponseSchema.ts +104 -0
  101. package/src/tests.ts +7 -0
  102. package/src/types/mcpAdmin.ts +1 -1
  103. package/src/types/mcpServiceToken.ts +7 -4
  104. package/src/versionCheckPlugin.ts +41 -2
  105. package/biome.jsonc +0 -22
  106. package/bunfig.toml +0 -10
  107. package/bunfig.unit.toml +0 -3
  108. package/dist/realtime/deprecation.d.ts +0 -13
  109. package/dist/realtime/deprecation.js +0 -31
  110. package/dist/realtime/queryStore.d.ts +0 -37
  111. package/dist/realtime/queryStore.js +0 -103
  112. package/dist/realtime/registry.d.ts +0 -15
  113. package/dist/realtime/registry.js +0 -52
  114. package/e2e/smoke.ts +0 -193
  115. package/src/realtime/deprecation.test.ts +0 -60
  116. package/src/realtime/deprecation.ts +0 -33
  117. package/src/realtime/queryStore.ts +0 -122
  118. package/src/realtime/registry.ts +0 -84
  119. package/tsconfig.json +0 -19
  120. package/tsconfig.typecheck.json +0 -14
  121. package/tsconfig.typedoc.json +0 -13
@@ -0,0 +1,104 @@
1
+ import Ajv from "ajv";
2
+ import addFormats from "ajv-formats";
3
+
4
+ /** Raised when a route or response is undocumented, or a body breaks its documented schema. */
5
+ class DocumentedResponseError extends Error {
6
+ name = "DocumentedResponseError";
7
+ }
8
+
9
+ /** The subset of an OpenAPI document needed to look up and validate a response schema. */
10
+ export interface OpenApiResponseSpec {
11
+ components?: Record<string, unknown>;
12
+ paths?: Record<string, Record<string, OpenApiResponseOperation | undefined> | undefined>;
13
+ }
14
+
15
+ interface OpenApiResponseOperation {
16
+ responses?: Record<string, {content?: Record<string, {schema?: unknown}>} | undefined>;
17
+ }
18
+
19
+ export interface DocumentedResponseOptions {
20
+ /** The `/openapi.json` document the app serves. */
21
+ spec: OpenApiResponseSpec;
22
+ /** The OpenAPI path template, e.g. `/announcements/{id}/click`. */
23
+ path: string;
24
+ /** HTTP method, any case. */
25
+ method: string;
26
+ /** The real response: its status picks the documented response, its body is validated. */
27
+ response: {status: number; body: unknown};
28
+ /** Response media type to validate against. Defaults to `application/json`. */
29
+ contentType?: string;
30
+ }
31
+
32
+ export interface DocumentedResponseResult {
33
+ valid: boolean;
34
+ errors: string[];
35
+ }
36
+
37
+ const findResponseSchema = ({
38
+ contentType,
39
+ method,
40
+ path,
41
+ spec,
42
+ status,
43
+ }: {
44
+ contentType: string;
45
+ method: string;
46
+ path: string;
47
+ spec: OpenApiResponseSpec;
48
+ status: number;
49
+ }): unknown => {
50
+ const label = `${method.toUpperCase()} ${path}`;
51
+ const operation = spec.paths?.[path]?.[method.toLowerCase()];
52
+ if (!operation) {
53
+ throw new DocumentedResponseError(`${label} is not documented in the OpenAPI spec`);
54
+ }
55
+ const documented = operation.responses?.[String(status)];
56
+ if (!documented) {
57
+ const statuses = Object.keys(operation.responses ?? {}).join(", ") || "none";
58
+ throw new DocumentedResponseError(
59
+ `${label} has no documented ${status} response (documented: ${statuses})`
60
+ );
61
+ }
62
+ const schema = documented.content?.[contentType]?.schema;
63
+ if (!schema) {
64
+ throw new DocumentedResponseError(`${label} ${status} response has no ${contentType} schema`);
65
+ }
66
+ return schema;
67
+ };
68
+
69
+ /**
70
+ * Validates a real response body against the response schema `/openapi.json` documents for it,
71
+ * resolving `#/components/...` references against the same spec.
72
+ */
73
+ export const validateDocumentedResponse = ({
74
+ contentType = "application/json",
75
+ method,
76
+ path,
77
+ response,
78
+ spec,
79
+ }: DocumentedResponseOptions): DocumentedResponseResult => {
80
+ const schema = findResponseSchema({contentType, method, path, spec, status: response.status});
81
+ const ajv = new Ajv({allErrors: true, strict: false});
82
+ addFormats(ajv as unknown as Parameters<typeof addFormats>[0]);
83
+ // Wrapping keeps `#/components/...` refs resolvable from the root of the compiled schema.
84
+ const validate = ajv.compile({allOf: [schema], components: spec.components ?? {}});
85
+ if (validate(response.body)) {
86
+ return {errors: [], valid: true};
87
+ }
88
+ const errors = (validate.errors ?? []).map(
89
+ (error) => `${error.instancePath || "(root)"} ${error.message ?? "is invalid"}`
90
+ );
91
+ return {errors, valid: false};
92
+ };
93
+
94
+ /** Throws with every schema violation when a response body does not match its documentation. */
95
+ export const expectDocumentedResponse = (options: DocumentedResponseOptions): void => {
96
+ const {errors, valid} = validateDocumentedResponse(options);
97
+ if (valid) {
98
+ return;
99
+ }
100
+ const label = `${options.method.toUpperCase()} ${options.path} ${options.response.status}`;
101
+ throw new DocumentedResponseError(
102
+ `${label} response does not match its OpenAPI schema:\n- ${errors.join("\n- ")}\nBody: ${JSON.stringify(options.response.body)}`
103
+ );
104
+ };
package/src/tests.ts CHANGED
@@ -56,3 +56,10 @@ export const authAsUser = async (
56
56
  };
57
57
 
58
58
  export {loadTestData} from "./tests/mongoTestSetup";
59
+ export {
60
+ type DocumentedResponseOptions,
61
+ type DocumentedResponseResult,
62
+ expectDocumentedResponse,
63
+ type OpenApiResponseSpec,
64
+ validateDocumentedResponse,
65
+ } from "./tests/openApiResponseSchema";
@@ -20,7 +20,7 @@ export interface McpRequestLogDocument extends mongoose.Document {
20
20
  oauthClientId?: string;
21
21
  oauthFamilyId?: string;
22
22
  outcome: McpRequestLogOutcome;
23
- serviceTokenId?: mongoose.Types.ObjectId;
23
+ serviceTokenId?: string;
24
24
  toolName: string;
25
25
  updated: Date;
26
26
  userId?: mongoose.Types.ObjectId;
@@ -15,7 +15,7 @@ export interface McpServiceTokenStatics
15
15
  FindOneOrNonePlugin<McpServiceTokenDocument> {
16
16
  countActiveForUser: (
17
17
  this: McpServiceTokenModel,
18
- userId: mongoose.Types.ObjectId
18
+ userId: mongoose.Types.ObjectId | string
19
19
  ) => Promise<number>;
20
20
  issueFor: (
21
21
  this: McpServiceTokenModel,
@@ -34,7 +34,7 @@ export interface McpServiceTokenStatics
34
34
  revokeForUser: (
35
35
  this: McpServiceTokenModel,
36
36
  user: {_id: {toString(): string}},
37
- tokenId: mongoose.Types.ObjectId
37
+ tokenId: string
38
38
  ) => Promise<McpServiceTokenDocument | null>;
39
39
  verify: (this: McpServiceTokenModel, token: string) => Promise<McpServiceTokenDocument | null>;
40
40
  }
@@ -43,9 +43,12 @@ export interface McpServiceTokenModel
43
43
  extends mongoose.Model<McpServiceTokenDocument, object, McpServiceTokenMethods>,
44
44
  McpServiceTokenStatics {}
45
45
 
46
- export interface McpServiceTokenDocument extends mongoose.Document {
47
- _id: mongoose.Types.ObjectId;
46
+ export interface McpServiceTokenDocument extends mongoose.Document<string> {
47
+ /** UUID for new rows; ObjectId hex for rows migrated by mcp-service-token-string-ids. */
48
+ _id: string;
48
49
  created: Date;
50
+ /** Always false: a delete revokes the token instead of tombstoning it. */
51
+ deleted: boolean;
49
52
  expiresAt?: Date;
50
53
  lastUsedAt?: Date;
51
54
  name: string;
@@ -1,7 +1,8 @@
1
1
  import type express from "express";
2
2
 
3
- import {asyncHandler} from "./api";
3
+ import {asyncHandler, type OpenApiMiddleware} from "./api";
4
4
  import {VersionConfig} from "./models/versionConfig";
5
+ import {createOpenApiBuilder} from "./openApiBuilder";
5
6
  import type {TerrenoPlugin} from "./terrenoPlugin";
6
7
 
7
8
  export type VersionCheckStatus = "ok" | "warning" | "required";
@@ -26,9 +27,47 @@ const DEFAULT_POLLING_INTERVAL_MINUTES = 1440;
26
27
  * Compares client build number against admin-configured thresholds per platform.
27
28
  */
28
29
  export class VersionCheckPlugin implements TerrenoPlugin {
29
- register(app: express.Application): void {
30
+ register(app: express.Application, openApi?: unknown): void {
31
+ // Documentation only: request validation stays off so unparseable versions still get "ok".
32
+ const versionCheckOpenApi = createOpenApiBuilder(
33
+ openApi ? {openApi: openApi as OpenApiMiddleware} : {}
34
+ )
35
+ .withTags(["version"])
36
+ .withSummary("Check whether the client build must or should update")
37
+ .withQueryParameter(
38
+ "platform",
39
+ {enum: ["web", "mobile"], type: "string"},
40
+ {description: "Client platform. Any other value is treated as web."}
41
+ )
42
+ .withQueryParameter(
43
+ "version",
44
+ {type: "integer"},
45
+ {description: "Client build number. When missing or not a number, the status is ok."}
46
+ )
47
+ .withResponse(
48
+ 200,
49
+ {
50
+ message: {
51
+ description: "Message to show when status is warning or required",
52
+ type: "string",
53
+ },
54
+ pollingIntervalMs: {
55
+ description: "How often the client should poll for updates, in milliseconds",
56
+ type: "number",
57
+ },
58
+ requiredVersion: {description: "Minimum supported build number", type: "number"},
59
+ status: {enum: ["ok", "warning", "required"], type: "string"},
60
+ updateUrl: {description: "Where the user can get the update", type: "string"},
61
+ warningVersion: {description: "Builds below this number get a warning", type: "number"},
62
+ },
63
+ {required: ["status"]}
64
+ )
65
+ .withValidation({enabled: false})
66
+ .build();
67
+
30
68
  app.get(
31
69
  "/version-check",
70
+ versionCheckOpenApi,
32
71
  asyncHandler(async (req, res) => {
33
72
  const versionParam = req.query.version;
34
73
  const platform = req.query.platform as string | undefined;
package/biome.jsonc DELETED
@@ -1,22 +0,0 @@
1
- {
2
- "root": true,
3
- "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
4
- "extends": ["../biome.jsonc"],
5
- "files": {
6
- "includes": [
7
- "package.json",
8
- "src/**/*.ts",
9
- "src/**/*.tsx",
10
- "e2e/**/*.ts",
11
- "!!src/populate.ts",
12
- "!!**/node_modules",
13
- "!!node_modules",
14
- "!!**/dist",
15
- "!!dist",
16
- "!!**/build",
17
- "!!build",
18
- "!!**/coverage",
19
- "!!coverage"
20
- ]
21
- }
22
- }
package/bunfig.toml DELETED
@@ -1,10 +0,0 @@
1
- [test]
2
- preload = ["./src/tests/testEnv.ts", "./src/tests/bunSetup.ts"]
3
- root = "./src"
4
- coverage = true
5
- coveragePathIgnorePatterns = ["dist/**", "**/*.test.ts", "**/*.isolated.ts", "**/isolated/**", "**/tests/**", "**/vendor/**", "../**"]
6
- # Enforced by scripts/check-coverage.ts; Bun parses this key but does not
7
- # fail the run when coverage is below threshold. See
8
- # https://github.com/oven-sh/bun/issues/7367 and https://github.com/oven-sh/bun/pull/27933.
9
- coverageThreshold = { line = 95, function = 95 }
10
-
package/bunfig.unit.toml DELETED
@@ -1,3 +0,0 @@
1
- [test]
2
- root = "./src"
3
- preload = []
@@ -1,13 +0,0 @@
1
- /**
2
- * One-line warning for modelRouter `realtime`. Keep in sync with the
3
- * `@terreno/rtk` helpers and `docs/implementationPlans/remove-legacy-realtime.md`.
4
- */
5
- /** @internal */
6
- export declare const REALTIME_DEPRECATION_MESSAGE = "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.";
7
- /**
8
- * Emits a one-time deprecation warning per model/routePath per process when a
9
- * consumer enables the legacy RTK cache-patching `realtime` option.
10
- */
11
- export declare const warnRealtimeDeprecated: (modelName: string, routePath?: string) => void;
12
- /** @internal Test helper — clears one-time realtime deprecation warnings. */
13
- export declare const resetRealtimeDeprecationWarningsForTests: () => void;
@@ -1,31 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resetRealtimeDeprecationWarningsForTests = exports.warnRealtimeDeprecated = exports.REALTIME_DEPRECATION_MESSAGE = void 0;
4
- const logger_1 = require("../logger");
5
- /**
6
- * One-line warning for modelRouter `realtime`. Keep in sync with the
7
- * `@terreno/rtk` helpers and `docs/implementationPlans/remove-legacy-realtime.md`.
8
- */
9
- /** @internal */
10
- exports.REALTIME_DEPRECATION_MESSAGE = "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.";
11
- const warnedKeys = new Set();
12
- const warningKey = (modelName, routePath) => `${modelName}:${routePath ?? ""}`;
13
- /**
14
- * Emits a one-time deprecation warning per model/routePath per process when a
15
- * consumer enables the legacy RTK cache-patching `realtime` option.
16
- */
17
- const warnRealtimeDeprecated = (modelName, routePath) => {
18
- const key = warningKey(modelName, routePath);
19
- if (warnedKeys.has(key)) {
20
- return;
21
- }
22
- warnedKeys.add(key);
23
- const location = routePath ? `${modelName} at ${routePath}` : modelName;
24
- logger_1.logger.warn(`[realtime] ${exports.REALTIME_DEPRECATION_MESSAGE} (${location})`);
25
- };
26
- exports.warnRealtimeDeprecated = warnRealtimeDeprecated;
27
- /** @internal Test helper — clears one-time realtime deprecation warnings. */
28
- const resetRealtimeDeprecationWarningsForTests = () => {
29
- warnedKeys.clear();
30
- };
31
- exports.resetRealtimeDeprecationWarningsForTests = resetRealtimeDeprecationWarningsForTests;
@@ -1,37 +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
- * Compute a deterministic queryId from collection and query on the server side.
10
- * This prevents clients from hijacking other subscriptions by providing a colliding queryId.
11
- */
12
- export declare const computeQueryId: (collection: string, query: Record<string, unknown>) => string;
13
- /**
14
- * Register a query subscription for a socket.
15
- * The socket joins the `query:{queryId}` room (handled by the caller).
16
- */
17
- export declare const addQuerySubscription: (socketId: string, collection: string, query: Record<string, unknown>, queryId: string) => void;
18
- /**
19
- * Remove a single query subscription for a socket.
20
- */
21
- export declare const removeQuerySubscription: (socketId: string, queryId: string) => void;
22
- /**
23
- * Remove all query subscriptions for a disconnected socket.
24
- */
25
- export declare const removeAllSocketQueries: (socketId: string) => void;
26
- /**
27
- * Get all unique query subscriptions for a given collection.
28
- * Used by the change stream watcher to evaluate which query rooms to emit to.
29
- */
30
- export declare const getQuerySubscriptionsForCollection: (collection: string) => {
31
- queryId: string;
32
- query: Record<string, unknown>;
33
- }[];
34
- /**
35
- * Clear all subscriptions (for testing).
36
- */
37
- export declare const clearQueryStore: () => void;
@@ -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;