@evolu/common 7.4.0 → 8.0.0-next.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 (251) hide show
  1. package/README.md +4 -61
  2. package/dist/src/Array.d.ts +343 -102
  3. package/dist/src/Array.d.ts.map +1 -1
  4. package/dist/src/Array.js +181 -85
  5. package/dist/src/Assert.d.ts +57 -11
  6. package/dist/src/Assert.d.ts.map +1 -1
  7. package/dist/src/Assert.js +47 -11
  8. package/dist/src/BigInt.d.ts +6 -1
  9. package/dist/src/BigInt.d.ts.map +1 -1
  10. package/dist/src/BigInt.js +5 -0
  11. package/dist/src/Brand.d.ts +40 -12
  12. package/dist/src/Brand.d.ts.map +1 -1
  13. package/dist/src/Brand.js +5 -0
  14. package/dist/src/Buffer.d.ts +6 -1
  15. package/dist/src/Buffer.d.ts.map +1 -1
  16. package/dist/src/Buffer.js +7 -2
  17. package/dist/src/Cache.d.ts +10 -2
  18. package/dist/src/Cache.d.ts.map +1 -1
  19. package/dist/src/Cache.js +6 -0
  20. package/dist/src/Callbacks.d.ts +10 -7
  21. package/dist/src/Callbacks.d.ts.map +1 -1
  22. package/dist/src/Callbacks.js +23 -13
  23. package/dist/src/Console.d.ts +361 -69
  24. package/dist/src/Console.d.ts.map +1 -1
  25. package/dist/src/Console.js +217 -117
  26. package/dist/src/Crypto.d.ts +70 -21
  27. package/dist/src/Crypto.d.ts.map +1 -1
  28. package/dist/src/Crypto.js +72 -27
  29. package/dist/src/Eq.d.ts +22 -2
  30. package/dist/src/Eq.d.ts.map +1 -1
  31. package/dist/src/Eq.js +21 -1
  32. package/dist/src/Error.d.ts +23 -12
  33. package/dist/src/Error.d.ts.map +1 -1
  34. package/dist/src/Error.js +27 -11
  35. package/dist/src/Function.d.ts +128 -56
  36. package/dist/src/Function.d.ts.map +1 -1
  37. package/dist/src/Function.js +118 -14
  38. package/dist/src/Identicon.d.ts +5 -0
  39. package/dist/src/Identicon.d.ts.map +1 -1
  40. package/dist/src/Identicon.js +6 -1
  41. package/dist/src/Lookup.d.ts +160 -0
  42. package/dist/src/Lookup.d.ts.map +1 -0
  43. package/dist/src/Lookup.js +192 -0
  44. package/dist/src/Microtask.d.ts +21 -0
  45. package/dist/src/Microtask.d.ts.map +1 -0
  46. package/dist/src/Microtask.js +37 -0
  47. package/dist/src/Number.d.ts +18 -4
  48. package/dist/src/Number.d.ts.map +1 -1
  49. package/dist/src/Number.js +23 -1
  50. package/dist/src/Object.d.ts +110 -5
  51. package/dist/src/Object.d.ts.map +1 -1
  52. package/dist/src/Object.js +108 -5
  53. package/dist/src/Option.d.ts +58 -0
  54. package/dist/src/Option.d.ts.map +1 -0
  55. package/dist/src/Option.js +43 -0
  56. package/dist/src/Order.d.ts +5 -0
  57. package/dist/src/Order.d.ts.map +1 -1
  58. package/dist/src/Order.js +8 -3
  59. package/dist/src/Platform.d.ts +36 -2
  60. package/dist/src/Platform.d.ts.map +1 -1
  61. package/dist/src/Platform.js +10 -6
  62. package/dist/src/Polyfills.d.ts +27 -0
  63. package/dist/src/Polyfills.d.ts.map +1 -0
  64. package/dist/src/Polyfills.js +299 -0
  65. package/dist/src/Random.d.ts +18 -7
  66. package/dist/src/Random.d.ts.map +1 -1
  67. package/dist/src/Random.js +9 -7
  68. package/dist/src/Redacted.d.ts +7 -4
  69. package/dist/src/Redacted.d.ts.map +1 -1
  70. package/dist/src/Redacted.js +5 -0
  71. package/dist/src/Ref.d.ts +31 -16
  72. package/dist/src/Ref.d.ts.map +1 -1
  73. package/dist/src/Ref.js +35 -7
  74. package/dist/src/RefCount.d.ts +62 -0
  75. package/dist/src/RefCount.d.ts.map +1 -0
  76. package/dist/src/RefCount.js +83 -0
  77. package/dist/src/Relation.d.ts +84 -29
  78. package/dist/src/Relation.d.ts.map +1 -1
  79. package/dist/src/Relation.js +83 -105
  80. package/dist/src/Resource.d.ts +263 -0
  81. package/dist/src/Resource.d.ts.map +1 -0
  82. package/dist/src/Resource.js +389 -0
  83. package/dist/src/Result.d.ts +390 -374
  84. package/dist/src/Result.d.ts.map +1 -1
  85. package/dist/src/Result.js +142 -70
  86. package/dist/src/Schedule.d.ts +953 -0
  87. package/dist/src/Schedule.d.ts.map +1 -0
  88. package/dist/src/Schedule.js +1199 -0
  89. package/dist/src/Set.d.ts +181 -0
  90. package/dist/src/Set.d.ts.map +1 -0
  91. package/dist/src/Set.js +137 -0
  92. package/dist/src/Skiplist.d.ts +6 -1
  93. package/dist/src/Skiplist.d.ts.map +1 -1
  94. package/dist/src/Skiplist.js +5 -0
  95. package/dist/src/Sqlite.d.ts +160 -60
  96. package/dist/src/Sqlite.d.ts.map +1 -1
  97. package/dist/src/Sqlite.js +290 -190
  98. package/dist/src/Store.d.ts +36 -28
  99. package/dist/src/Store.d.ts.map +1 -1
  100. package/dist/src/Store.js +55 -15
  101. package/dist/src/String.d.ts +5 -0
  102. package/dist/src/String.d.ts.map +1 -1
  103. package/dist/src/String.js +5 -0
  104. package/dist/src/Task.d.ts +2263 -423
  105. package/dist/src/Task.d.ts.map +1 -1
  106. package/dist/src/Task.js +1488 -348
  107. package/dist/src/Test.d.ts +122 -0
  108. package/dist/src/Test.d.ts.map +1 -0
  109. package/dist/src/Test.js +66 -0
  110. package/dist/src/Time.d.ts +201 -48
  111. package/dist/src/Time.d.ts.map +1 -1
  112. package/dist/src/Time.js +190 -86
  113. package/dist/src/Tracer.d.ts +48 -0
  114. package/dist/src/Tracer.d.ts.map +1 -0
  115. package/dist/src/Tracer.js +6 -0
  116. package/dist/src/Type.d.ts +582 -209
  117. package/dist/src/Type.d.ts.map +1 -1
  118. package/dist/src/Type.js +362 -240
  119. package/dist/src/Types.d.ts +160 -6
  120. package/dist/src/Types.d.ts.map +1 -1
  121. package/dist/src/Types.js +22 -2
  122. package/dist/src/WebSocket.d.ts +113 -58
  123. package/dist/src/WebSocket.d.ts.map +1 -1
  124. package/dist/src/WebSocket.js +210 -118
  125. package/dist/src/Worker.d.ts +245 -60
  126. package/dist/src/Worker.d.ts.map +1 -1
  127. package/dist/src/Worker.js +220 -64
  128. package/dist/src/index.d.ts +25 -3
  129. package/dist/src/index.d.ts.map +1 -1
  130. package/dist/src/index.js +19 -3
  131. package/dist/src/local-first/Db.d.ts +24 -213
  132. package/dist/src/local-first/Db.d.ts.map +1 -1
  133. package/dist/src/local-first/Db.js +622 -293
  134. package/dist/src/local-first/Error.d.ts +12 -0
  135. package/dist/src/local-first/Error.d.ts.map +1 -0
  136. package/dist/src/local-first/Error.js +6 -0
  137. package/dist/src/local-first/Evolu.d.ts +330 -285
  138. package/dist/src/local-first/Evolu.d.ts.map +1 -1
  139. package/dist/src/local-first/Evolu.js +472 -402
  140. package/dist/src/local-first/LocalAuth.d.ts +10 -10
  141. package/dist/src/local-first/LocalAuth.d.ts.map +1 -1
  142. package/dist/src/local-first/LocalAuth.js +6 -1
  143. package/dist/src/local-first/Owner.d.ts +70 -27
  144. package/dist/src/local-first/Owner.d.ts.map +1 -1
  145. package/dist/src/local-first/Owner.js +27 -14
  146. package/dist/src/local-first/Protocol.d.ts +58 -50
  147. package/dist/src/local-first/Protocol.d.ts.map +1 -1
  148. package/dist/src/local-first/Protocol.js +253 -155
  149. package/dist/src/local-first/Query.d.ts +133 -43
  150. package/dist/src/local-first/Query.d.ts.map +1 -1
  151. package/dist/src/local-first/Query.js +139 -90
  152. package/dist/src/local-first/Relay.d.ts +18 -38
  153. package/dist/src/local-first/Relay.d.ts.map +1 -1
  154. package/dist/src/local-first/Relay.js +59 -171
  155. package/dist/src/local-first/Schema.d.ts +139 -144
  156. package/dist/src/local-first/Schema.d.ts.map +1 -1
  157. package/dist/src/local-first/Schema.js +78 -163
  158. package/dist/src/local-first/Shared.d.ts +125 -0
  159. package/dist/src/local-first/Shared.d.ts.map +1 -0
  160. package/dist/src/local-first/Shared.js +569 -0
  161. package/dist/src/local-first/Storage.d.ts +50 -53
  162. package/dist/src/local-first/Storage.d.ts.map +1 -1
  163. package/dist/src/local-first/Storage.js +121 -173
  164. package/dist/src/local-first/Timestamp.d.ts +28 -35
  165. package/dist/src/local-first/Timestamp.d.ts.map +1 -1
  166. package/dist/src/local-first/Timestamp.js +24 -25
  167. package/dist/src/local-first/index.d.ts +2 -15
  168. package/dist/src/local-first/index.d.ts.map +1 -1
  169. package/dist/src/local-first/index.js +2 -15
  170. package/package.json +36 -26
  171. package/src/Array.ts +467 -106
  172. package/src/Assert.ts +87 -12
  173. package/src/BigInt.ts +7 -1
  174. package/src/Brand.ts +41 -12
  175. package/src/Buffer.ts +10 -4
  176. package/src/Cache.ts +11 -2
  177. package/src/Callbacks.ts +33 -23
  178. package/src/Console.ts +567 -178
  179. package/src/Crypto.ts +111 -62
  180. package/src/Eq.ts +30 -3
  181. package/src/Error.ts +50 -34
  182. package/src/Function.ts +140 -68
  183. package/src/Identicon.ts +7 -1
  184. package/src/Lookup.ts +415 -0
  185. package/src/Microtask.ts +58 -0
  186. package/src/Number.ts +40 -7
  187. package/src/Object.ts +155 -16
  188. package/src/Option.ts +74 -0
  189. package/src/Order.ts +11 -3
  190. package/src/Platform.ts +43 -7
  191. package/src/Polyfills.ts +465 -0
  192. package/src/Random.ts +25 -11
  193. package/src/Redacted.ts +8 -4
  194. package/src/Ref.ts +72 -21
  195. package/src/RefCount.ts +170 -0
  196. package/src/Relation.ts +188 -136
  197. package/src/Resource.ts +864 -0
  198. package/src/Result.ts +548 -381
  199. package/src/Schedule.ts +1471 -0
  200. package/src/Set.ts +247 -0
  201. package/src/Skiplist.ts +7 -1
  202. package/src/Sqlite.ts +409 -304
  203. package/src/Store.ts +94 -48
  204. package/src/String.ts +6 -0
  205. package/src/Task.ts +3685 -740
  206. package/src/Test.ts +162 -0
  207. package/src/Time.ts +348 -145
  208. package/src/Tracer.ts +54 -0
  209. package/src/Type.ts +1064 -630
  210. package/src/Types.ts +202 -7
  211. package/src/WebSocket.ts +311 -178
  212. package/src/Worker.ts +527 -147
  213. package/src/index.ts +74 -3
  214. package/src/local-first/Db.ts +871 -597
  215. package/src/local-first/Error.ts +17 -0
  216. package/src/local-first/Evolu.ts +884 -823
  217. package/src/local-first/LocalAuth.ts +10 -10
  218. package/src/local-first/Owner.ts +94 -42
  219. package/src/local-first/Protocol.ts +440 -303
  220. package/src/local-first/Query.ts +243 -194
  221. package/src/local-first/Relay.ts +91 -252
  222. package/src/local-first/Schema.ts +284 -394
  223. package/src/local-first/Shared.ts +932 -0
  224. package/src/local-first/Storage.ts +209 -282
  225. package/src/local-first/Timestamp.ts +38 -45
  226. package/src/local-first/index.ts +2 -16
  227. package/LICENSE +0 -21
  228. package/dist/src/Instances.d.ts +0 -34
  229. package/dist/src/Instances.d.ts.map +0 -1
  230. package/dist/src/Instances.js +0 -44
  231. package/dist/src/Resources.d.ts +0 -118
  232. package/dist/src/Resources.d.ts.map +0 -1
  233. package/dist/src/Resources.js +0 -197
  234. package/dist/src/local-first/Platform.d.ts +0 -25
  235. package/dist/src/local-first/Platform.d.ts.map +0 -1
  236. package/dist/src/local-first/Platform.js +0 -1
  237. package/dist/src/local-first/Public.d.ts +0 -22
  238. package/dist/src/local-first/Public.d.ts.map +0 -1
  239. package/dist/src/local-first/Public.js +0 -15
  240. package/dist/src/local-first/PublicKysely.d.ts +0 -148
  241. package/dist/src/local-first/PublicKysely.d.ts.map +0 -1
  242. package/dist/src/local-first/PublicKysely.js +0 -184
  243. package/dist/src/local-first/Sync.d.ts +0 -112
  244. package/dist/src/local-first/Sync.d.ts.map +0 -1
  245. package/dist/src/local-first/Sync.js +0 -529
  246. package/src/Instances.ts +0 -90
  247. package/src/Resources.ts +0 -367
  248. package/src/local-first/Platform.ts +0 -27
  249. package/src/local-first/Public.ts +0 -42
  250. package/src/local-first/PublicKysely.ts +0 -239
  251. package/src/local-first/Sync.ts +0 -960
package/src/Worker.ts CHANGED
@@ -1,172 +1,552 @@
1
+ /**
2
+ * Platform-agnostic Worker abstractions.
3
+ *
4
+ * @module
5
+ */
6
+
1
7
  import { assert } from "./Assert.js";
2
- import { createTransferableError, TransferableError } from "./Error.js";
8
+ import type { Brand } from "./Brand.js";
9
+ import type { ConsoleDep, ConsoleStoreOutputEntryDep } from "./Console.js";
10
+ import { testWaitForMacrotask } from "./Test.js";
11
+
12
+ /**
13
+ * Platform-agnostic Worker.
14
+ *
15
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Worker
16
+ */
17
+ export interface Worker<Input, Output = never> extends MessagePort<
18
+ Input,
19
+ Output
20
+ > {}
21
+
22
+ /**
23
+ * Platform-agnostic SharedWorker.
24
+ *
25
+ * A shared worker is shared across multiple clients (tabs, windows, iframes)
26
+ * and provides a port for bidirectional communication with each client.
27
+ *
28
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker
29
+ */
30
+ export interface SharedWorker<Input, Output = never> extends Disposable {
31
+ /** Port for communicating with the shared worker. */
32
+ readonly port: MessagePort<Input, Output>;
33
+ }
34
+
35
+ /**
36
+ * Platform-agnostic MessagePort.
37
+ *
38
+ * Note: There is no reliable way to detect when a port is closed or
39
+ * disconnected. Calling `postMessage` on a disposed port does not throw — it
40
+ * silently fails. To detect dead ports, use a heartbeat pattern where the other
41
+ * end periodically sends "alive" messages and stale ports are pruned after a
42
+ * timeout.
43
+ *
44
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/MessagePort
45
+ */
46
+ export interface MessagePort<Input, Output = never> extends Disposable {
47
+ readonly postMessage: (
48
+ message: Input,
49
+ transfer?: ReadonlyArray<Transferable>,
50
+ ) => void;
51
+
52
+ /**
53
+ * Handler for incoming messages. Messages are queued until this is assigned,
54
+ * matching native `MessagePort` behavior where setting `onmessage` implicitly
55
+ * calls `start()`. This enables safe async initialization — the sender can
56
+ * post messages immediately while the receiver sets up.
57
+ */
58
+ onMessage: ((message: Output) => void) | null;
59
+
60
+ /**
61
+ * The native underlying port for transferring via `postMessage`.
62
+ *
63
+ * ### Example
64
+ *
65
+ * ```ts
66
+ * sharedWorker.port.postMessage(
67
+ * { type: "InitConsole", port: consoleChannel.port1.native },
68
+ * [consoleChannel.port1.native],
69
+ * );
70
+ * ```
71
+ */
72
+ readonly native: NativeMessagePort<Input, Output>;
73
+ }
74
+
75
+ /**
76
+ * Objects whose ownership can be transferred between threads via `postMessage`.
77
+ *
78
+ * Intentionally scoped to types Evolu uses. The web platform defines additional
79
+ * transferable types (`ImageBitmap`, `OffscreenCanvas`, `ReadableStream`, etc.)
80
+ * that can be added here if needed.
81
+ */
82
+ export type Transferable = NativeMessagePort<any, any> | ArrayBuffer;
83
+
84
+ /**
85
+ * Opaque type for platform-specific native MessagePort.
86
+ *
87
+ * Exists because `postMessage` transfer requires the native object itself, not
88
+ * a wrapper. Ensures type-safe wiring between {@link MessagePort.native} and
89
+ * {@link CreateMessagePort} without exposing platform details.
90
+ */
91
+ export type NativeMessagePort<
92
+ Input = unknown,
93
+ Output = never,
94
+ > = Brand<"NativeMessagePort"> & {
95
+ readonly [nativeMessagePortInput]?: Input;
96
+ readonly [nativeMessagePortOutput]?: Output;
97
+ };
98
+
99
+ declare const nativeMessagePortInput: unique symbol;
100
+ declare const nativeMessagePortOutput: unique symbol;
101
+
102
+ /** Factory function to create a {@link MessagePort} from a native port. */
103
+ export type CreateMessagePort = <Input, Output = never>(
104
+ nativePort: NativeMessagePort<Input, Output>,
105
+ ) => MessagePort<Input, Output>;
106
+
107
+ export interface CreateMessagePortDep {
108
+ readonly createMessagePort: CreateMessagePort;
109
+ }
110
+
111
+ /** Common dependencies for worker entry points. */
112
+ export type WorkerDeps = ConsoleDep &
113
+ ConsoleStoreOutputEntryDep &
114
+ CreateMessagePortDep;
115
+
116
+ /**
117
+ * Platform-agnostic MessageChannel.
118
+ *
119
+ * Creates two entangled ports: keep one and transfer the other (e.g., to a
120
+ * SharedWorker via `postMessage` with `transfer`). Messages sent to one port
121
+ * are received by the other.
122
+ *
123
+ * Messages are queued until `onMessage` is assigned, enabling safe async
124
+ * initialization. The sender can post messages immediately while the receiver
125
+ * performs async setup — no manual buffering required.
126
+ *
127
+ * For one-way communication, omit `Output` (defaults to `never`).
128
+ *
129
+ * ### Example
130
+ *
131
+ * Transfer a channel port to a SharedWorker for async initialization:
132
+ *
133
+ * ```ts
134
+ * // Main thread: create channel, transfer port1, use port2 immediately.
135
+ * const channel = createMessageChannel<EvoluRequest, EvoluResponse>();
136
+ *
137
+ * sharedWorker.port.postMessage(
138
+ * { type: "CreateEvolu", port: channel.port1.native },
139
+ * [channel.port1.native],
140
+ * );
141
+ *
142
+ * // Safe to send immediately — messages queue until worker is ready.
143
+ * channel.port2.postMessage({ type: "Query", query });
144
+ * channel.port2.onMessage = (response) => {
145
+ * handleResponse(response);
146
+ * };
147
+ * ```
148
+ *
149
+ * ```ts
150
+ * // Worker: receive the port, do async init, then start listening.
151
+ * const evoluPort = createMessagePort<EvoluResponse, EvoluRequest>(
152
+ * message.port,
153
+ * );
154
+ * await openDatabase(name);
155
+ * evoluPort.onMessage = (request) => {
156
+ * handleRequest(request);
157
+ * };
158
+ * // Queued messages are now delivered in order.
159
+ * ```
160
+ *
161
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel
162
+ */
163
+ export interface MessageChannel<Input, Output = never> extends Disposable {
164
+ /** The first port of the channel. */
165
+ readonly port1: MessagePort<Input, Output>;
3
166
 
4
- /** Cross-platform worker abstraction. */
5
- export interface Worker<Input, Output> {
6
- /** Sends a message to the worker. */
7
- readonly postMessage: (message: Input) => void;
167
+ /** The second port of the channel. */
168
+ readonly port2: MessagePort<Output, Input>;
169
+ }
170
+
171
+ /** Factory function to create a {@link MessageChannel}. */
172
+ export type CreateMessageChannel = <Input, Output = never>() => MessageChannel<
173
+ Input,
174
+ Output
175
+ >;
8
176
 
9
- /** Sets a callback for messages from the worker. */
10
- readonly onMessage: (callback: (message: Output) => void) => void;
177
+ export interface CreateMessageChannelDep {
178
+ readonly createMessageChannel: CreateMessageChannel;
11
179
  }
12
180
 
13
- export interface WorkerPostMessageDep<Output> {
14
- readonly postMessage: (message: Output) => void;
181
+ /**
182
+ * Typed `self` for code running inside a dedicated worker.
183
+ *
184
+ * This is the worker-side counterpart to {@link Worker} — a typed
185
+ * {@link MessagePort} that wraps `self` inside the worker.
186
+ */
187
+ export interface WorkerSelf<Input, Output = never> extends MessagePort<
188
+ Output,
189
+ Input
190
+ > {}
191
+
192
+ /**
193
+ * Typed `self` for code running inside a shared worker.
194
+ *
195
+ * This is the worker-side counterpart to {@link SharedWorker}. It wraps `self`
196
+ * inside the shared worker, providing typed `onConnect` callbacks.
197
+ */
198
+ export interface SharedWorkerSelf<Input, Output = never> extends Disposable {
199
+ onConnect: ((port: MessagePort<Output, Input>) => void) | null;
15
200
  }
16
201
 
17
202
  /**
18
- * Error reporting wrapper that catches synchronous errors in handlers and
19
- * converts them to transferable error messages sent to the main thread.
20
- */
21
- export type WithErrorReporting = <A extends Array<any>>(
22
- handler: (...args: A) => void,
23
- ) => (...args: A) => void;
24
-
25
- type HasInit<Input> =
26
- Extract<Input, { type: "init" }> extends never
27
- ? ["Input must contain a variant with { type: 'init' }"]
28
- : unknown;
29
-
30
- type HasWorkerErrorOutput<T> =
31
- Extract<T, { type: "onError" }> extends infer E
32
- ? [E] extends [never]
33
- ? [
34
- "Output must contain { type: 'onError'; error: TransferableError | ... }",
35
- ]
36
- : E extends { error: infer Err }
37
- ? TransferableError extends Err
38
- ? unknown
39
- : ["Output.onError.error must include TransferableError"]
40
- : ["Output.onError must have an error property"]
41
- : never;
42
-
43
- /**
44
- * Creates a {@link Worker} that supports initialization with dependencies and
45
- * safe error handling.
46
- */
47
- export const createInitializedWorker = <
48
- Input extends { readonly type: string } & HasInit<Input>,
49
- Output extends { readonly type: string } & HasWorkerErrorOutput<Output>,
50
- Deps,
51
- >({
52
- init,
53
- onMessage,
54
- }: {
55
- readonly init: (
56
- initMessage: Extract<Input, { type: "init" }>,
57
- postMessage: (msg: Output) => void,
58
- withErrorReporting: WithErrorReporting,
59
- ) => Promise<Deps | null>;
60
- readonly onMessage: (
61
- deps: Deps,
62
- ) => (message: Exclude<Input, { type: "init" }>) => void;
63
- }): Worker<Input, Output> => {
64
- type NonInitMessage = Exclude<Input, { type: "init" }>;
65
-
66
- let onMessageCallback: ((msg: Output) => void) | null = null;
67
- let deps: Deps | null = null;
68
- const pendingMessages: Array<Input> = [];
69
- let initializing = false;
70
-
71
- const postMessage = (msg: Output) => {
72
- assert(onMessageCallback != null, "The onMessage wasn't set");
73
- onMessageCallback(msg);
203
+ * Creates an in-memory {@link Worker}.
204
+ *
205
+ * This is a memory-only fallback for platforms without native worker support.
206
+ * Message delivery is asynchronous in-process.
207
+ */
208
+ export const createWorker = <Input, Output = never>(
209
+ initWorker: (self: WorkerSelf<Input, Output>) => void,
210
+ ): Worker<Input, Output> => {
211
+ const { worker, self } = createMemoryWorkerPair<Input, Output>();
212
+ initWorker(self);
213
+ return worker;
214
+ };
215
+
216
+ /**
217
+ * Creates an in-memory {@link SharedWorker}.
218
+ *
219
+ * This is a memory-only fallback for platforms without native SharedWorker
220
+ * support. Connection is synchronous while message delivery is asynchronous
221
+ * in-process.
222
+ *
223
+ * Intended usage is one shared worker instance per process/app runtime.
224
+ */
225
+ export const createSharedWorker = <Input, Output = never>(
226
+ initWorker: (self: SharedWorkerSelf<Input, Output>) => void,
227
+ ): SharedWorker<Input, Output> => {
228
+ const { worker, self, connect } = createMemorySharedWorkerPair<
229
+ Input,
230
+ Output
231
+ >();
232
+
233
+ initWorker(self);
234
+ connect();
235
+
236
+ return worker;
237
+ };
238
+
239
+ /**
240
+ * Creates an in-memory {@link MessageChannel}.
241
+ *
242
+ * This is a memory-only fallback for platforms without native MessageChannel
243
+ * support. Message delivery is asynchronous in-process.
244
+ */
245
+ export const createMessageChannel: CreateMessageChannel = <
246
+ Input,
247
+ Output = never,
248
+ >(): MessageChannel<Input, Output> => {
249
+ const state1: PortState<Output> = {
250
+ handler: null,
251
+ queue: [],
252
+ flushScheduled: false,
253
+ };
254
+ const state2: PortState<Input> = {
255
+ handler: null,
256
+ queue: [],
257
+ flushScheduled: false,
74
258
  };
75
259
 
76
- const postMessageTransferableError = (error: unknown) => {
77
- postMessage({
78
- type: "onError",
79
- error: createTransferableError(error),
80
- } as unknown as Output);
260
+ const native1 = createNativeMessagePortToken<Input, Output>();
261
+ const native2 = createNativeMessagePortToken<Output, Input>();
262
+
263
+ const port1 = createTestPort<Input, Output>(state1, state2, native1);
264
+ const port2 = createTestPort<Output, Input>(state2, state1, native2);
265
+
266
+ nativePortRegistry.set(native1, port1);
267
+ nativePortRegistry.set(native2, port2);
268
+
269
+ return {
270
+ port1,
271
+ port2,
272
+ [Symbol.dispose]: () => {
273
+ port1[Symbol.dispose]();
274
+ port2[Symbol.dispose]();
275
+ },
81
276
  };
277
+ };
82
278
 
83
- /**
84
- * Wraps function to catch errors and send them to the main thread instead of
85
- * crashing the worker.
86
- */
87
- const withErrorReporting =
88
- <A extends Array<any>>(handler: (...args: A) => void) =>
89
- (...args: A) => {
90
- try {
91
- handler(...args);
92
- } catch (error) {
93
- postMessageTransferableError(error);
94
- }
95
- };
279
+ /**
280
+ * Creates an in-memory {@link MessagePort} from a native token.
281
+ *
282
+ * This is a memory-only fallback for platforms without native MessagePort
283
+ * support. Message delivery through returned ports is asynchronous in-process.
284
+ */
285
+ export const createMessagePort: CreateMessagePort = <Input, Output = never>(
286
+ nativePort: NativeMessagePort<Input, Output>,
287
+ ): MessagePort<Input, Output> => {
288
+ const pair = nativePortRegistry.get(nativePort);
289
+ assert(pair, "Unknown native port — did you transfer it?");
290
+ return pair as MessagePort<Input, Output>;
291
+ };
292
+
293
+ /**
294
+ * Test {@link Worker} with access to its paired worker-side `self`.
295
+ *
296
+ * Use `self` to simulate messages and behavior from inside the worker.
297
+ */
298
+ export interface TestWorker<Input, Output = never> extends Worker<
299
+ Input,
300
+ Output
301
+ > {
302
+ /** Typed `self` counterpart for worker-side testing assertions. */
303
+ readonly self: WorkerSelf<Input, Output>;
304
+ }
305
+
306
+ /**
307
+ * Test {@link SharedWorker} with direct access to `self` and `connect`.
308
+ *
309
+ * Call `connect()` to simulate a client connection and trigger
310
+ * `self.onConnect`.
311
+ */
312
+ export interface TestSharedWorker<Input, Output = never> extends SharedWorker<
313
+ Input,
314
+ Output
315
+ > {
316
+ readonly self: SharedWorkerSelf<Input, Output>;
317
+ readonly connect: () => void;
318
+ }
319
+
320
+ /** {@link MessageChannel} with disposal tracking for testing. */
321
+ export interface TestMessageChannel<
322
+ Input,
323
+ Output = never,
324
+ > extends MessageChannel<Input, Output> {
325
+ readonly isDisposed: () => boolean;
326
+ }
327
+
328
+ /**
329
+ * Creates a connected {@link TestWorker} for testing.
330
+ *
331
+ * The returned worker includes its typed {@link TestWorker.self} counterpart, so
332
+ * tests can exercise dedicated worker communication without a real thread.
333
+ */
334
+ export const testCreateWorker = <Input, Output = never>(): TestWorker<
335
+ Input,
336
+ Output
337
+ > => {
338
+ let self!: WorkerSelf<Input, Output>;
339
+
340
+ const worker = createWorker<Input, Output>((nextSelf) => {
341
+ self = nextSelf;
342
+ });
343
+
344
+ return Object.assign(worker, { self }) as TestWorker<Input, Output>;
345
+ };
346
+
347
+ /**
348
+ * Creates a connected {@link TestSharedWorker} for testing.
349
+ *
350
+ * The returned worker includes `self` and `connect` so tests can exercise the
351
+ * full worker ↔ client pipeline without a real worker thread.
352
+ */
353
+ export const testCreateSharedWorker = <
354
+ Input,
355
+ Output = never,
356
+ >(): TestSharedWorker<Input, Output> => {
357
+ const { worker, self, connect } = createMemorySharedWorkerPair<
358
+ Input,
359
+ Output
360
+ >();
361
+ return Object.assign(worker, {
362
+ self,
363
+ connect,
364
+ }) as TestSharedWorker<Input, Output>;
365
+ };
366
+
367
+ /**
368
+ * Creates an in-memory {@link MessageChannel} for testing.
369
+ *
370
+ * Messages are queued until `onMessage` is assigned, matching the browser
371
+ * MessagePort behavior where the port message queue starts disabled.
372
+ *
373
+ * Both ports are registered in the native port registry so
374
+ * {@link testCreateMessagePort} can look them up by their native token.
375
+ */
376
+ export const testCreateMessageChannel = <
377
+ Input,
378
+ Output = never,
379
+ >(): TestMessageChannel<Input, Output> => {
380
+ const channel = createMessageChannel<Input, Output>();
381
+
382
+ let disposed = false;
383
+
384
+ return {
385
+ port1: channel.port1,
386
+ port2: channel.port2,
387
+ isDisposed: () => disposed,
388
+ [Symbol.dispose]: () => {
389
+ disposed = true;
390
+ channel[Symbol.dispose]();
391
+ },
392
+ };
393
+ };
394
+
395
+ /** Creates an in-memory {@link CreateMessagePort} for testing. */
396
+ export const testCreateMessagePort: CreateMessagePort = <Input, Output = never>(
397
+ nativePort: NativeMessagePort<Input, Output>,
398
+ ): MessagePort<Input, Output> => createMessagePort(nativePort);
399
+
400
+ /**
401
+ * Waits long enough for multi-hop in-memory worker message delivery in tests.
402
+ *
403
+ * Some flows require several queued macrotasks across worker/message-port
404
+ * boundaries; this helper advances that pipeline deterministically.
405
+ */
406
+ export const testWaitForWorkerMessage = async (): Promise<void> => {
407
+ await testWaitForMacrotask();
408
+ await testWaitForMacrotask();
409
+ };
410
+
411
+ const createMemoryWorkerPair = <Input, Output = never>(): {
412
+ readonly worker: Worker<Input, Output>;
413
+ readonly self: WorkerSelf<Input, Output>;
414
+ } => {
415
+ const channel = createMessageChannel<Input, Output>();
416
+
417
+ const self: WorkerSelf<Input, Output> = {
418
+ postMessage: channel.port2.postMessage,
419
+ get onMessage() {
420
+ return channel.port2.onMessage;
421
+ },
422
+ set onMessage(value) {
423
+ channel.port2.onMessage = value;
424
+ },
425
+ native: channel.port2.native,
426
+ [Symbol.dispose]: () => {
427
+ channel.port2[Symbol.dispose]();
428
+ },
429
+ };
96
430
 
97
431
  const worker: Worker<Input, Output> = {
98
- postMessage: (message) => {
99
- if (message.type !== "init") {
100
- if (!deps) {
101
- pendingMessages.push(message);
102
- } else {
103
- withErrorReporting(onMessage(deps))(message as NonInitMessage);
104
- }
105
- return;
106
- }
432
+ postMessage: channel.port1.postMessage,
433
+ get onMessage() {
434
+ return channel.port1.onMessage;
435
+ },
436
+ set onMessage(value) {
437
+ channel.port1.onMessage = value;
438
+ },
439
+ native: channel.port1.native,
440
+ [Symbol.dispose]: () => {
441
+ channel[Symbol.dispose]();
442
+ },
443
+ };
107
444
 
108
- if (initializing) return;
109
- initializing = true;
110
-
111
- init(
112
- message as Extract<Input, { type: "init" }>,
113
- postMessage,
114
- withErrorReporting,
115
- )
116
- .then((_deps) => {
117
- if (_deps == null) return;
118
- deps = _deps;
119
- for (const message of pendingMessages) {
120
- withErrorReporting(onMessage(deps))(message as NonInitMessage);
121
- }
122
- pendingMessages.length = 0;
123
- })
124
- .catch(postMessageTransferableError);
445
+ return { worker, self };
446
+ };
447
+
448
+ const createMemorySharedWorkerPair = <Input, Output = never>(): {
449
+ readonly worker: SharedWorker<Input, Output>;
450
+ readonly self: SharedWorkerSelf<Input, Output>;
451
+ readonly connect: () => void;
452
+ } => {
453
+ const channel = createMessageChannel<Input, Output>();
454
+
455
+ const self: SharedWorkerSelf<Input, Output> = {
456
+ onConnect: null,
457
+ [Symbol.dispose]: () => {
458
+ self.onConnect = null;
125
459
  },
460
+ };
126
461
 
127
- onMessage: (callback) => {
128
- onMessageCallback = callback;
462
+ const worker: SharedWorker<Input, Output> = {
463
+ port: channel.port1,
464
+ [Symbol.dispose]: () => {
465
+ channel[Symbol.dispose]();
129
466
  },
130
467
  };
131
468
 
132
- return worker;
469
+ const connect = (): void => {
470
+ assert(
471
+ self.onConnect,
472
+ "onConnect must be set before receiving connections",
473
+ );
474
+ self.onConnect(channel.port2);
475
+ };
476
+
477
+ return { worker, self, connect };
133
478
  };
134
479
 
135
- /** Type helper to extract message types from a union type */
136
- export type MessageHandlers<Input extends { readonly type: string }, Deps> = {
137
- readonly [K in Input["type"]]: (
138
- deps: Deps,
139
- ) => (message: Extract<Input, { type: K }>) => void;
480
+ interface PortState<T> {
481
+ handler: ((message: T) => void) | null;
482
+ readonly queue: Array<T>;
483
+ flushScheduled: boolean;
484
+ }
485
+
486
+ const createPort = <Input, Output>(
487
+ receive: PortState<Output>,
488
+ peerReceive: PortState<Input>,
489
+ native: NativeMessagePort<Input, Output>,
490
+ ): MessagePort<Input, Output> => {
491
+ const scheduleFlush = (state: PortState<any>): void => {
492
+ if (state.flushScheduled) return;
493
+ state.flushScheduled = true;
494
+
495
+ // Native worker messages are task-queued; use macrotask timing.
496
+ setTimeout(() => {
497
+ state.flushScheduled = false;
498
+
499
+ const handler = state.handler;
500
+ if (!handler) return;
501
+
502
+ for (const message of state.queue.splice(0)) {
503
+ handler(message);
504
+ }
505
+ }, 0);
506
+ };
507
+
508
+ return {
509
+ postMessage: (message) => {
510
+ peerReceive.queue.push(message);
511
+ scheduleFlush(peerReceive);
512
+ },
513
+ get onMessage() {
514
+ return receive.handler;
515
+ },
516
+ set onMessage(fn) {
517
+ receive.handler = fn;
518
+ if (fn) scheduleFlush(receive);
519
+ },
520
+ native,
521
+ [Symbol.dispose]: () => {
522
+ receive.handler = null;
523
+ receive.flushScheduled = false;
524
+ },
525
+ };
140
526
  };
141
527
 
528
+ const createTestPort = <Input, Output>(
529
+ receive: PortState<Output>,
530
+ peerReceive: PortState<Input>,
531
+ native: NativeMessagePort<Input, Output>,
532
+ ): MessagePort<Input, Output> => createPort(receive, peerReceive, native);
533
+
534
+ const createNativeMessagePortToken = <Input, Output>(): NativeMessagePort<
535
+ Input,
536
+ Output
537
+ > => ({}) as NativeMessagePort<Input, Output>;
538
+
142
539
  /**
143
- * Creates a {@link Worker} with type-safe message handlers for each message
144
- * type. This provides better type safety and organization compared to a single
145
- * onMessage handler.
146
- */
147
- export const createInitializedWorkerWithHandlers = <
148
- Input extends { readonly type: string } & HasInit<Input>,
149
- Output extends { readonly type: string } & HasWorkerErrorOutput<Output>,
150
- Deps,
151
- >({
152
- init,
153
- handlers,
154
- }: {
155
- readonly init: (
156
- initMessage: Extract<Input, { type: "init" }>,
157
- postMessage: (msg: Output) => void,
158
- withErrorReporting: WithErrorReporting,
159
- ) => Promise<Deps | null>;
160
- readonly handlers: Omit<MessageHandlers<Input, Deps>, "init">;
161
- }): Worker<Input, Output> =>
162
- createInitializedWorker({
163
- init,
164
- onMessage: (deps) => (message) => {
165
- type NonInitMessageType = Exclude<Input["type"], "init">;
166
- const messageType = message.type as NonInitMessageType;
167
- const handler = handlers[messageType];
168
-
169
- // TypeScript knows handler exists because handlers covers all non-init message types
170
- handler(deps)(message as Extract<Input, { type: typeof messageType }>);
171
- },
172
- });
540
+ * Registry mapping native port tokens to their in-memory port counterparts.
541
+ *
542
+ * When {@link testCreateMessageChannel} creates a pair, both ports are
543
+ * registered here. When {@link testCreateMessagePort} wraps a native token
544
+ * (received via `postMessage` transfer), it looks up the actual port.
545
+ *
546
+ * Uses `WeakMap` so entries are garbage collected when the native token is no
547
+ * longer referenced.
548
+ */
549
+ const nativePortRegistry = new WeakMap<
550
+ NativeMessagePort<any, any>,
551
+ MessagePort<any, any>
552
+ >();