spacetimedb 2.5.0 → 2.6.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 (180) hide show
  1. package/LICENSE.txt +759 -759
  2. package/README.md +211 -211
  3. package/dist/angular/index.cjs.map +1 -1
  4. package/dist/angular/index.mjs.map +1 -1
  5. package/dist/browser/angular/index.mjs.map +1 -1
  6. package/dist/browser/react/index.mjs +129 -57
  7. package/dist/browser/react/index.mjs.map +1 -1
  8. package/dist/browser/solid/index.mjs +120 -50
  9. package/dist/browser/solid/index.mjs.map +1 -1
  10. package/dist/browser/svelte/index.mjs.map +1 -1
  11. package/dist/browser/vue/index.mjs.map +1 -1
  12. package/dist/index.browser.mjs +10 -2
  13. package/dist/index.browser.mjs.map +1 -1
  14. package/dist/index.cjs +10 -2
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.mjs +10 -2
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/min/index.browser.mjs +1 -1
  19. package/dist/min/index.browser.mjs.map +1 -1
  20. package/dist/min/react/index.mjs +1 -1
  21. package/dist/min/react/index.mjs.map +1 -1
  22. package/dist/min/sdk/index.browser.mjs +1 -1
  23. package/dist/min/sdk/index.browser.mjs.map +1 -1
  24. package/dist/react/index.cjs +129 -57
  25. package/dist/react/index.cjs.map +1 -1
  26. package/dist/react/index.mjs +129 -57
  27. package/dist/react/index.mjs.map +1 -1
  28. package/dist/react/useTable.d.ts.map +1 -1
  29. package/dist/sdk/connection_manager.d.ts +8 -0
  30. package/dist/sdk/connection_manager.d.ts.map +1 -1
  31. package/dist/sdk/db_connection_impl.d.ts +7 -0
  32. package/dist/sdk/db_connection_impl.d.ts.map +1 -1
  33. package/dist/sdk/index.browser.mjs +10 -2
  34. package/dist/sdk/index.browser.mjs.map +1 -1
  35. package/dist/sdk/index.cjs +10 -2
  36. package/dist/sdk/index.cjs.map +1 -1
  37. package/dist/sdk/index.mjs +10 -2
  38. package/dist/sdk/index.mjs.map +1 -1
  39. package/dist/sdk/websocket_test_adapter.d.ts +2 -1
  40. package/dist/sdk/websocket_test_adapter.d.ts.map +1 -1
  41. package/dist/server/index.mjs.map +1 -1
  42. package/dist/server/runtime.d.ts.map +1 -1
  43. package/dist/solid/index.cjs +120 -50
  44. package/dist/solid/index.cjs.map +1 -1
  45. package/dist/solid/index.mjs +120 -50
  46. package/dist/solid/index.mjs.map +1 -1
  47. package/dist/svelte/index.cjs.map +1 -1
  48. package/dist/svelte/index.mjs.map +1 -1
  49. package/dist/tanstack/index.cjs +120 -50
  50. package/dist/tanstack/index.cjs.map +1 -1
  51. package/dist/tanstack/index.mjs +120 -50
  52. package/dist/tanstack/index.mjs.map +1 -1
  53. package/dist/vue/index.cjs.map +1 -1
  54. package/dist/vue/index.mjs.map +1 -1
  55. package/package.json +1 -1
  56. package/src/angular/connection_state.ts +19 -19
  57. package/src/angular/index.ts +3 -3
  58. package/src/angular/injectors/index.ts +4 -4
  59. package/src/angular/injectors/inject-reducer.ts +62 -62
  60. package/src/angular/injectors/inject-spacetimedb-connected.ts +13 -13
  61. package/src/angular/injectors/inject-spacetimedb.ts +10 -10
  62. package/src/angular/injectors/inject-table.ts +234 -234
  63. package/src/angular/providers/index.ts +1 -1
  64. package/src/angular/providers/provide-spacetimedb.ts +96 -96
  65. package/src/index.ts +16 -16
  66. package/src/lib/algebraic_type.ts +819 -819
  67. package/src/lib/algebraic_type_variants.ts +26 -26
  68. package/src/lib/algebraic_value.ts +10 -10
  69. package/src/lib/autogen/types.ts +746 -746
  70. package/src/lib/binary_reader.ts +188 -188
  71. package/src/lib/binary_writer.ts +213 -213
  72. package/src/lib/connection_id.ts +102 -102
  73. package/src/lib/constraints.ts +48 -48
  74. package/src/lib/errors.ts +26 -26
  75. package/src/lib/filter.ts +195 -195
  76. package/src/lib/identity.ts +83 -83
  77. package/src/lib/indexes.ts +251 -251
  78. package/src/lib/option.ts +34 -34
  79. package/src/lib/query.ts +1019 -1019
  80. package/src/lib/reducer_schema.ts +38 -38
  81. package/src/lib/reducers.ts +116 -116
  82. package/src/lib/result.ts +36 -36
  83. package/src/lib/schedule_at.ts +86 -86
  84. package/src/lib/schema.ts +420 -420
  85. package/src/lib/table.ts +548 -548
  86. package/src/lib/table_schema.ts +64 -64
  87. package/src/lib/time_duration.ts +77 -77
  88. package/src/lib/timestamp.ts +148 -148
  89. package/src/lib/type_builders.test-d.ts +128 -128
  90. package/src/lib/type_builders.ts +4014 -4014
  91. package/src/lib/type_util.ts +124 -124
  92. package/src/lib/util.ts +196 -196
  93. package/src/lib/uuid.ts +337 -337
  94. package/src/react/SpacetimeDBProvider.ts +84 -84
  95. package/src/react/connection_state.ts +6 -6
  96. package/src/react/index.ts +5 -5
  97. package/src/react/useProcedure.ts +60 -60
  98. package/src/react/useReducer.ts +53 -53
  99. package/src/react/useSpacetimeDB.ts +18 -18
  100. package/src/react/useTable.ts +256 -251
  101. package/src/sdk/client_api/index.ts +114 -114
  102. package/src/sdk/client_api/types/procedures.ts +8 -8
  103. package/src/sdk/client_api/types/reducers.ts +8 -8
  104. package/src/sdk/client_api/types.ts +288 -288
  105. package/src/sdk/client_cache.ts +129 -129
  106. package/src/sdk/client_table.ts +179 -179
  107. package/src/sdk/connection_manager.ts +352 -237
  108. package/src/sdk/db_connection_builder.ts +290 -290
  109. package/src/sdk/db_connection_impl.ts +1356 -1347
  110. package/src/sdk/db_context.ts +28 -28
  111. package/src/sdk/db_view.ts +12 -12
  112. package/src/sdk/decompress.ts +51 -51
  113. package/src/sdk/event.ts +18 -18
  114. package/src/sdk/event_context.ts +51 -51
  115. package/src/sdk/event_emitter.ts +32 -32
  116. package/src/sdk/index.ts +14 -14
  117. package/src/sdk/internal.ts +2 -2
  118. package/src/sdk/json_api.ts +46 -46
  119. package/src/sdk/logger.ts +134 -134
  120. package/src/sdk/message_types.ts +46 -46
  121. package/src/sdk/procedures.ts +83 -83
  122. package/src/sdk/reducer_event.ts +20 -20
  123. package/src/sdk/reducer_handle.ts +12 -12
  124. package/src/sdk/reducers.ts +159 -159
  125. package/src/sdk/schema.ts +45 -45
  126. package/src/sdk/spacetime_module.ts +28 -28
  127. package/src/sdk/subscription_builder_impl.ts +275 -275
  128. package/src/sdk/table_cache.ts +581 -581
  129. package/src/sdk/type_utils.ts +19 -19
  130. package/src/sdk/version.ts +133 -133
  131. package/src/sdk/websocket_decompress_adapter.ts +63 -63
  132. package/src/sdk/websocket_protocols.ts +25 -25
  133. package/src/sdk/websocket_test_adapter.ts +107 -100
  134. package/src/sdk/websocket_v3_frames.ts +126 -126
  135. package/src/sdk/ws.ts +105 -105
  136. package/src/server/console.ts +81 -81
  137. package/src/server/db_view.ts +21 -21
  138. package/src/server/errors.ts +138 -138
  139. package/src/server/http.test-d.ts +80 -80
  140. package/src/server/http.ts +14 -14
  141. package/src/server/http_handlers.ts +413 -413
  142. package/src/server/http_internal.ts +79 -79
  143. package/src/server/http_shared.ts +186 -186
  144. package/src/server/index.ts +37 -37
  145. package/src/server/polyfills.ts +4 -4
  146. package/src/server/procedures.ts +239 -239
  147. package/src/server/query.ts +1 -1
  148. package/src/server/range.ts +53 -53
  149. package/src/server/reducers.ts +113 -113
  150. package/src/server/rng.ts +113 -113
  151. package/src/server/runtime.ts +1102 -1102
  152. package/src/server/schema.test-d.ts +99 -99
  153. package/src/server/schema.ts +663 -663
  154. package/src/server/sys.d.ts +125 -125
  155. package/src/server/view.test-d.ts +194 -194
  156. package/src/server/views.ts +340 -340
  157. package/src/solid/SpacetimeDBProvider.ts +97 -97
  158. package/src/solid/connection_state.ts +6 -6
  159. package/src/solid/index.ts +5 -5
  160. package/src/solid/useProcedure.ts +57 -57
  161. package/src/solid/useReducer.ts +50 -50
  162. package/src/solid/useSpacetimeDB.ts +18 -18
  163. package/src/solid/useTable.ts +203 -203
  164. package/src/svelte/SpacetimeDBProvider.ts +101 -101
  165. package/src/svelte/connection_state.ts +16 -16
  166. package/src/svelte/index.ts +4 -4
  167. package/src/svelte/useReducer.ts +61 -61
  168. package/src/svelte/useSpacetimeDB.ts +22 -22
  169. package/src/svelte/useTable.ts +218 -218
  170. package/src/tanstack/SpacetimeDBQueryClient.ts +330 -330
  171. package/src/tanstack/hooks.ts +83 -83
  172. package/src/tanstack/index.ts +16 -16
  173. package/src/util-stub.ts +1 -1
  174. package/src/vue/SpacetimeDBProvider.ts +157 -157
  175. package/src/vue/connection_state.ts +19 -19
  176. package/src/vue/index.ts +5 -5
  177. package/src/vue/useProcedure.ts +62 -62
  178. package/src/vue/useReducer.ts +55 -55
  179. package/src/vue/useSpacetimeDB.ts +18 -18
  180. package/src/vue/useTable.ts +229 -229
@@ -1,237 +1,352 @@
1
- /**
2
- * ConnectionManager - A reference-counted connection manager for SpacetimeDB.
3
- *
4
- * This module implements a TanStack Query-style pattern for managing WebSocket
5
- * connections in React applications. It solves the React StrictMode double-mount
6
- * problem by using reference counting and deferred cleanup.
7
- *
8
- * ## How it works:
9
- *
10
- * 1. **Reference Counting**: Each `retain()` increments a counter, `release()` decrements it.
11
- * The connection is only closed when the count reaches zero.
12
- *
13
- * 2. **Deferred Cleanup**: When refCount hits zero, cleanup is scheduled via `setTimeout(0)`.
14
- * This allows React StrictMode's rapid unmount→remount cycle to cancel the cleanup.
15
- *
16
- * 3. **useSyncExternalStore Integration**: The `subscribe()` and `getSnapshot()` methods
17
- * are designed to work with React's `useSyncExternalStore` hook for tear-free reads.
18
- *
19
- * ## StrictMode Lifecycle:
20
- *
21
- * ```
22
- * Mount → retain() → refCount: 0→1, connection created
23
- * Unmount → release() → refCount: 1→0, cleanup SCHEDULED (not executed)
24
- * Remount → retain() → refCount: 0→1, cleanup CANCELLED
25
- * Result: Single WebSocket survives ✓
26
- * ```
27
- *
28
- * @module connection_manager
29
- */
30
- import type {
31
- DbConnectionBuilder,
32
- DbConnectionImpl,
33
- ErrorContextInterface,
34
- } from './db_connection_impl';
35
- import type { Identity } from '../lib/identity';
36
- import { ConnectionId } from '../lib/connection_id';
37
-
38
- /** Represents the current state of a managed connection. */
39
- export type ConnectionState = {
40
- isActive: boolean;
41
- identity?: Identity;
42
- token?: string;
43
- connectionId: ConnectionId;
44
- connectionError?: Error;
45
- };
46
-
47
- type Listener = () => void;
48
-
49
- type ManagedConnection = {
50
- connection?: DbConnectionImpl<any>;
51
- refCount: number;
52
- state: ConnectionState;
53
- listeners: Set<Listener>;
54
- pendingRelease: ReturnType<typeof setTimeout> | null;
55
- onConnect?: (conn: DbConnectionImpl<any>) => void;
56
- onDisconnect?: (ctx: ErrorContextInterface<any>, error?: Error) => void;
57
- onConnectError?: (ctx: ErrorContextInterface<any>, error: Error) => void;
58
- };
59
-
60
- function defaultState(): ConnectionState {
61
- return {
62
- isActive: false,
63
- identity: undefined,
64
- token: undefined,
65
- connectionId: ConnectionId.random(),
66
- connectionError: undefined,
67
- };
68
- }
69
-
70
- /**
71
- * Singleton manager for SpacetimeDB connections.
72
- * Use the exported `ConnectionManager` instance rather than instantiating directly.
73
- */
74
- class ConnectionManagerImpl {
75
- #connections = new Map<string, ManagedConnection>();
76
-
77
- /** Generates a unique key for a connection based on URI and module name. */
78
- static getKey(uri: string, moduleName: string): string {
79
- return `${uri}::${moduleName}`;
80
- }
81
-
82
- /** Instance method wrapper for getKey. */
83
- getKey(uri: string, moduleName: string): string {
84
- return ConnectionManagerImpl.getKey(uri, moduleName);
85
- }
86
-
87
- #ensureEntry(key: string): ManagedConnection {
88
- const existing = this.#connections.get(key);
89
- if (existing) {
90
- return existing;
91
- }
92
- const managed: ManagedConnection = {
93
- connection: undefined,
94
- refCount: 0,
95
- state: defaultState(),
96
- listeners: new Set(),
97
- pendingRelease: null,
98
- };
99
- this.#connections.set(key, managed);
100
- return managed;
101
- }
102
-
103
- #notify(managed: ManagedConnection): void {
104
- for (const listener of managed.listeners) {
105
- listener();
106
- }
107
- }
108
-
109
- /**
110
- * Retains a connection, incrementing its reference count.
111
- * Creates the connection on first call; returns existing connection on subsequent calls.
112
- * Cancels any pending release if the connection was about to be cleaned up.
113
- *
114
- * @param key - Unique identifier for the connection (use getKey to generate)
115
- * @param builder - Connection builder to create the connection if needed
116
- * @returns The managed connection instance
117
- */
118
- retain<T extends DbConnectionImpl<any>>(
119
- key: string,
120
- builder: DbConnectionBuilder<T>
121
- ): T {
122
- const managed = this.#ensureEntry(key);
123
- if (managed.pendingRelease) {
124
- clearTimeout(managed.pendingRelease);
125
- managed.pendingRelease = null;
126
- }
127
- managed.refCount += 1;
128
- if (managed.connection) {
129
- return managed.connection as T;
130
- }
131
-
132
- const connection = builder.build();
133
- managed.connection = connection;
134
-
135
- const updateState = (updates: Partial<ConnectionState>) => {
136
- managed.state = { ...managed.state, ...updates };
137
- this.#notify(managed);
138
- };
139
-
140
- updateState({
141
- isActive: connection.isActive,
142
- identity: connection.identity,
143
- token: connection.token,
144
- connectionId: connection.connectionId,
145
- connectionError: undefined,
146
- });
147
-
148
- managed.onConnect = conn => {
149
- updateState({
150
- isActive: conn.isActive,
151
- identity: conn.identity,
152
- token: conn.token,
153
- connectionId: conn.connectionId,
154
- connectionError: undefined,
155
- });
156
- };
157
-
158
- managed.onDisconnect = (ctx, error) => {
159
- updateState({
160
- isActive: ctx.isActive,
161
- connectionError: error ?? undefined,
162
- });
163
- };
164
-
165
- managed.onConnectError = (ctx, error) => {
166
- updateState({
167
- isActive: ctx.isActive,
168
- connectionError: error,
169
- });
170
- };
171
-
172
- builder.onConnect(managed.onConnect);
173
- builder.onDisconnect(managed.onDisconnect);
174
- builder.onConnectError(managed.onConnectError);
175
-
176
- return connection as T;
177
- }
178
-
179
- release(key: string): void {
180
- const managed = this.#connections.get(key);
181
- if (!managed) {
182
- return;
183
- }
184
-
185
- managed.refCount -= 1;
186
- if (managed.refCount > 0 || managed.pendingRelease) {
187
- return;
188
- }
189
-
190
- managed.pendingRelease = setTimeout(() => {
191
- managed.pendingRelease = null;
192
- if (managed.refCount > 0) {
193
- return;
194
- }
195
- if (managed.connection) {
196
- if (managed.onConnect) {
197
- managed.connection.removeOnConnect(managed.onConnect as any);
198
- }
199
- if (managed.onDisconnect) {
200
- managed.connection.removeOnDisconnect(managed.onDisconnect as any);
201
- }
202
- if (managed.onConnectError) {
203
- managed.connection.removeOnConnectError(
204
- managed.onConnectError as any
205
- );
206
- }
207
- managed.connection.disconnect();
208
- }
209
- this.#connections.delete(key);
210
- }, 0);
211
- }
212
-
213
- subscribe(key: string, listener: Listener): () => void {
214
- const managed = this.#ensureEntry(key);
215
- managed.listeners.add(listener);
216
- return () => {
217
- managed.listeners.delete(listener);
218
- if (
219
- managed.refCount <= 0 &&
220
- managed.listeners.size === 0 &&
221
- !managed.connection
222
- ) {
223
- this.#connections.delete(key);
224
- }
225
- };
226
- }
227
-
228
- getSnapshot(key: string): ConnectionState | undefined {
229
- return this.#connections.get(key)?.state;
230
- }
231
-
232
- getConnection<T extends DbConnectionImpl<any>>(key: string): T | null {
233
- return (this.#connections.get(key)?.connection as T | undefined) ?? null;
234
- }
235
- }
236
-
237
- export const ConnectionManager = new ConnectionManagerImpl();
1
+ /**
2
+ * ConnectionManager - A reference-counted connection manager for SpacetimeDB.
3
+ *
4
+ * This module implements a TanStack Query-style pattern for managing WebSocket
5
+ * connections in React applications. It solves the React StrictMode double-mount
6
+ * problem by using reference counting and deferred cleanup.
7
+ *
8
+ * ## How it works:
9
+ *
10
+ * 1. **Reference Counting**: Each `retain()` increments a counter, `release()` decrements it.
11
+ * The connection is only closed when the count reaches zero.
12
+ *
13
+ * 2. **Deferred Cleanup**: When refCount hits zero, cleanup is scheduled via `setTimeout(0)`.
14
+ * This allows React StrictMode's rapid unmount→remount cycle to cancel the cleanup.
15
+ *
16
+ * 3. **useSyncExternalStore Integration**: The `subscribe()` and `getSnapshot()` methods
17
+ * are designed to work with React's `useSyncExternalStore` hook for tear-free reads.
18
+ *
19
+ * ## StrictMode Lifecycle:
20
+ *
21
+ * ```
22
+ * Mount → retain() → refCount: 0→1, connection created
23
+ * Unmount → release() → refCount: 1→0, cleanup SCHEDULED (not executed)
24
+ * Remount → retain() → refCount: 0→1, cleanup CANCELLED
25
+ * Result: Single WebSocket survives ✓
26
+ * ```
27
+ *
28
+ * @module connection_manager
29
+ */
30
+ import type {
31
+ DbConnectionBuilder,
32
+ DbConnectionImpl,
33
+ ErrorContextInterface,
34
+ } from './db_connection_impl';
35
+ import type { Identity } from '../lib/identity';
36
+ import { ConnectionId } from '../lib/connection_id';
37
+
38
+ /** Represents the current state of a managed connection. */
39
+ export type ConnectionState = {
40
+ isActive: boolean;
41
+ identity?: Identity;
42
+ token?: string;
43
+ connectionId: ConnectionId;
44
+ connectionError?: Error;
45
+ };
46
+
47
+ type Listener = () => void;
48
+
49
+ export const CONNECTION_MANAGER_RECONNECT_BASE_DELAY_MS = 1000;
50
+ export const CONNECTION_MANAGER_RECONNECT_MAX_DELAY_MS = 30_000;
51
+
52
+ /**
53
+ * Computes the reconnect delay for the given attempt (0-based) using
54
+ * exponential backoff: the base delay doubles with each consecutive failed
55
+ * attempt, capped at the maximum delay.
56
+ */
57
+ export function connectionManagerReconnectDelayMs(attempt: number): number {
58
+ return Math.min(
59
+ CONNECTION_MANAGER_RECONNECT_BASE_DELAY_MS * 2 ** attempt,
60
+ CONNECTION_MANAGER_RECONNECT_MAX_DELAY_MS
61
+ );
62
+ }
63
+
64
+ type ManagedConnection = {
65
+ connection?: DbConnectionImpl<any>;
66
+ builder?: DbConnectionBuilder<any>;
67
+ refCount: number;
68
+ state: ConnectionState;
69
+ listeners: Set<Listener>;
70
+ pendingRelease: ReturnType<typeof setTimeout> | null;
71
+ reconnectTimer: ReturnType<typeof setTimeout> | null;
72
+ reconnectAttempt: number;
73
+ onConnect?: (conn: DbConnectionImpl<any>) => void;
74
+ onDisconnect?: (ctx: ErrorContextInterface<any>, error?: Error) => void;
75
+ onConnectError?: (ctx: ErrorContextInterface<any>, error: Error) => void;
76
+ };
77
+
78
+ function defaultState(): ConnectionState {
79
+ return {
80
+ isActive: false,
81
+ identity: undefined,
82
+ token: undefined,
83
+ connectionId: ConnectionId.random(),
84
+ connectionError: undefined,
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Singleton manager for SpacetimeDB connections.
90
+ * Use the exported `ConnectionManager` instance rather than instantiating directly.
91
+ */
92
+ class ConnectionManagerImpl {
93
+ #connections = new Map<string, ManagedConnection>();
94
+
95
+ /** Generates a unique key for a connection based on URI and module name. */
96
+ static getKey(uri: string, moduleName: string): string {
97
+ return `${uri}::${moduleName}`;
98
+ }
99
+
100
+ /** Instance method wrapper for getKey. */
101
+ getKey(uri: string, moduleName: string): string {
102
+ return ConnectionManagerImpl.getKey(uri, moduleName);
103
+ }
104
+
105
+ #ensureEntry(key: string): ManagedConnection {
106
+ const existing = this.#connections.get(key);
107
+ if (existing) {
108
+ return existing;
109
+ }
110
+ const managed: ManagedConnection = {
111
+ connection: undefined,
112
+ builder: undefined,
113
+ refCount: 0,
114
+ state: defaultState(),
115
+ listeners: new Set(),
116
+ pendingRelease: null,
117
+ reconnectTimer: null,
118
+ reconnectAttempt: 0,
119
+ };
120
+ this.#connections.set(key, managed);
121
+ return managed;
122
+ }
123
+
124
+ #notify(managed: ManagedConnection): void {
125
+ for (const listener of managed.listeners) {
126
+ listener();
127
+ }
128
+ }
129
+
130
+ #updateState(
131
+ managed: ManagedConnection,
132
+ updates: Partial<ConnectionState>
133
+ ): void {
134
+ managed.state = { ...managed.state, ...updates };
135
+ this.#notify(managed);
136
+ }
137
+
138
+ #ensureCallbacks(managed: ManagedConnection): void {
139
+ if (managed.onConnect) {
140
+ return;
141
+ }
142
+
143
+ managed.onConnect = conn => {
144
+ if (conn !== managed.connection) {
145
+ return;
146
+ }
147
+ managed.reconnectAttempt = 0;
148
+ this.#updateState(managed, {
149
+ isActive: conn.isActive,
150
+ identity: conn.identity,
151
+ token: conn.token,
152
+ connectionId: conn.connectionId,
153
+ connectionError: undefined,
154
+ });
155
+ };
156
+
157
+ managed.onDisconnect = (ctx, error) => {
158
+ if (ctx !== managed.connection) {
159
+ return;
160
+ }
161
+ this.#updateState(managed, {
162
+ isActive: false,
163
+ connectionError: error ?? undefined,
164
+ });
165
+ this.#scheduleReconnect(managed);
166
+ };
167
+
168
+ managed.onConnectError = (ctx, error) => {
169
+ if (ctx !== managed.connection) {
170
+ return;
171
+ }
172
+ this.#updateState(managed, {
173
+ isActive: false,
174
+ connectionError: error,
175
+ });
176
+ this.#scheduleReconnect(managed);
177
+ };
178
+ }
179
+
180
+ #attachCallbacks<T extends DbConnectionImpl<any>>(
181
+ managed: ManagedConnection,
182
+ builder: DbConnectionBuilder<T>
183
+ ): void {
184
+ this.#ensureCallbacks(managed);
185
+ builder.onConnect(managed.onConnect!);
186
+ builder.onDisconnect(managed.onDisconnect!);
187
+ builder.onConnectError(managed.onConnectError!);
188
+ }
189
+
190
+ #detachCallbacks(
191
+ managed: ManagedConnection,
192
+ connection: DbConnectionImpl<any>
193
+ ): void {
194
+ if (managed.onConnect) {
195
+ connection.removeOnConnect(managed.onConnect as any);
196
+ }
197
+ if (managed.onDisconnect) {
198
+ connection.removeOnDisconnect(managed.onDisconnect as any);
199
+ }
200
+ if (managed.onConnectError) {
201
+ connection.removeOnConnectError(managed.onConnectError as any);
202
+ }
203
+ }
204
+
205
+ #buildManagedConnection<T extends DbConnectionImpl<any>>(
206
+ managed: ManagedConnection,
207
+ builder: DbConnectionBuilder<T>
208
+ ): T {
209
+ managed.builder = builder;
210
+ const connection = builder.build();
211
+ managed.connection = connection;
212
+ this.#attachCallbacks(managed, builder);
213
+
214
+ this.#updateState(managed, {
215
+ isActive: connection.isActive,
216
+ identity: connection.identity,
217
+ token: connection.token,
218
+ connectionId: connection.connectionId,
219
+ connectionError: undefined,
220
+ });
221
+
222
+ return connection as T;
223
+ }
224
+
225
+ #scheduleReconnect(managed: ManagedConnection): void {
226
+ if (
227
+ managed.refCount <= 0 ||
228
+ managed.pendingRelease ||
229
+ managed.reconnectTimer ||
230
+ !managed.builder
231
+ ) {
232
+ return;
233
+ }
234
+
235
+ const connection = managed.connection;
236
+ if (connection) {
237
+ this.#detachCallbacks(managed, connection);
238
+ }
239
+ managed.connection = undefined;
240
+
241
+ // The application asked this connection to close; don't fight it. A
242
+ // subsequent retain() will still build a fresh connection.
243
+ if (connection?.isDisconnectRequested) {
244
+ return;
245
+ }
246
+
247
+ const delay = connectionManagerReconnectDelayMs(managed.reconnectAttempt);
248
+ managed.reconnectAttempt += 1;
249
+ managed.reconnectTimer = setTimeout(() => {
250
+ managed.reconnectTimer = null;
251
+ if (
252
+ managed.refCount <= 0 ||
253
+ managed.pendingRelease ||
254
+ managed.connection ||
255
+ !managed.builder
256
+ ) {
257
+ return;
258
+ }
259
+
260
+ this.#buildManagedConnection(managed, managed.builder);
261
+ }, delay);
262
+ }
263
+
264
+ /**
265
+ * Retains a connection, incrementing its reference count.
266
+ * Creates the connection on first call; returns existing connection on subsequent calls.
267
+ * Cancels any pending release if the connection was about to be cleaned up.
268
+ *
269
+ * @param key - Unique identifier for the connection (use getKey to generate)
270
+ * @param builder - Connection builder to create the connection if needed
271
+ * @returns The managed connection instance
272
+ */
273
+ retain<T extends DbConnectionImpl<any>>(
274
+ key: string,
275
+ builder: DbConnectionBuilder<T>
276
+ ): T {
277
+ const managed = this.#ensureEntry(key);
278
+ if (managed.pendingRelease) {
279
+ clearTimeout(managed.pendingRelease);
280
+ managed.pendingRelease = null;
281
+ }
282
+ if (managed.reconnectTimer) {
283
+ clearTimeout(managed.reconnectTimer);
284
+ managed.reconnectTimer = null;
285
+ }
286
+
287
+ managed.refCount += 1;
288
+ managed.builder = builder;
289
+
290
+ if (managed.connection) {
291
+ return managed.connection as T;
292
+ }
293
+
294
+ return this.#buildManagedConnection(managed, builder);
295
+ }
296
+
297
+ release(key: string): void {
298
+ const managed = this.#connections.get(key);
299
+ if (!managed) {
300
+ return;
301
+ }
302
+
303
+ managed.refCount -= 1;
304
+ if (managed.refCount > 0 || managed.pendingRelease) {
305
+ return;
306
+ }
307
+
308
+ if (managed.reconnectTimer) {
309
+ clearTimeout(managed.reconnectTimer);
310
+ managed.reconnectTimer = null;
311
+ }
312
+
313
+ managed.pendingRelease = setTimeout(() => {
314
+ managed.pendingRelease = null;
315
+ if (managed.refCount > 0) {
316
+ return;
317
+ }
318
+ const connection = managed.connection;
319
+ managed.connection = undefined;
320
+ if (connection) {
321
+ this.#detachCallbacks(managed, connection);
322
+ connection.disconnect();
323
+ }
324
+ this.#connections.delete(key);
325
+ }, 0);
326
+ }
327
+
328
+ subscribe(key: string, listener: Listener): () => void {
329
+ const managed = this.#ensureEntry(key);
330
+ managed.listeners.add(listener);
331
+ return () => {
332
+ managed.listeners.delete(listener);
333
+ if (
334
+ managed.refCount <= 0 &&
335
+ managed.listeners.size === 0 &&
336
+ !managed.connection
337
+ ) {
338
+ this.#connections.delete(key);
339
+ }
340
+ };
341
+ }
342
+
343
+ getSnapshot(key: string): ConnectionState | undefined {
344
+ return this.#connections.get(key)?.state;
345
+ }
346
+
347
+ getConnection<T extends DbConnectionImpl<any>>(key: string): T | null {
348
+ return (this.#connections.get(key)?.connection as T | undefined) ?? null;
349
+ }
350
+ }
351
+
352
+ export const ConnectionManager = new ConnectionManagerImpl();