The best way to control Claude Code, Codex and more from any computer or phone
feat(mobile): iOS socket compresses traffic (#32288)
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Julius Marminge committed
Nov 8, 2026 at 16:04 UTC
f26623febe9ea7f73ad18340efa096df0f72943d
7 files changed
+535
-3
apps/mobile/modules/t3-web-socket/expo-module.config.json
new
+4
@@ -0,0 +1,4 @@
1
+{
2
+ "platforms": ["apple"],
3
+ "apple": { "modules": ["T3WebSocketModule"] }
4
+}
apps/mobile/modules/t3-web-socket/ios/T3WebSocket.podspec
new
+13
@@ -0,0 +1,13 @@
1
+Pod::Spec.new do |s|
2
+ s.name = 'T3WebSocket'
3
+ s.version = '1.0.0'
4
+ s.summary = 'WebSocket client with permessage-deflate for T3 Code mobile.'
5
+ s.description = 'React Native ships SocketRocket on iOS, which never negotiates compression. This module dials the T3 server through URLSessionWebSocketTask, which offers permessage-deflate on its own.'
6
+ s.author = 'T3 Tools'
7
+ s.homepage = 'https://t3tools.com'
8
+ s.platform = :ios, '18.0'
9
+ s.source = { :path => '.' }
10
+ s.static_framework = true
11
+ s.dependency 'ExpoModulesCore'
12
+ s.source_files = '*.swift'
13
+end
apps/mobile/modules/t3-web-socket/ios/T3WebSocketModule.swift
new
+188
@@ -0,0 +1,188 @@
1
+import ExpoModulesCore
2
+import Foundation
3
+
4
+private final class Connection {
5
+ let id: Int
6
+ var task: URLSessionWebSocketTask?
7
+ var finished = false
8
+ var requestedCloseCode: Int?
9
+ var failure: String?
10
+
11
+ init(id: Int) {
12
+ self.id = id
13
+ }
14
+}
15
+
16
+/// A WebSocket client that offers permessage-deflate. React Native's SocketRocket never does,
17
+/// so a large snapshot reached an iPhone uncompressed. URLSession offers the extension on every
18
+/// handshake with no public switch, which is what we want here.
19
+public final class T3WebSocketModule: Module {
20
+ private var connections: [Int: Connection] = [:]
21
+ private var nextId = 1
22
+ private let lock = NSLock()
23
+ private var session: URLSession?
24
+ private let delegateQueue: OperationQueue = {
25
+ let queue = OperationQueue()
26
+ queue.maxConcurrentOperationCount = 1
27
+ return queue
28
+ }()
29
+
30
+ public func definition() -> ModuleDefinition {
31
+ Name("T3WebSocket")
32
+ Events("open", "message", "close", "error")
33
+
34
+ Function("connect") { (url: URL, protocols: [String]) -> Int in
35
+ let connection = self.withLock { () -> Connection in
36
+ let connection = Connection(id: self.nextId)
37
+ self.nextId += 1
38
+ self.connections[connection.id] = connection
39
+ return connection
40
+ }
41
+ let session = self.session ?? self.makeSession()
42
+ self.session = session
43
+ let task = protocols.isEmpty
44
+ ? session.webSocketTask(with: url)
45
+ : session.webSocketTask(with: url, protocols: protocols)
46
+ // The app splits frames at 48 KiB, but older servers and the outdated-host probe send whole
47
+ // messages, so stay well above URLSession's 1 MiB default.
48
+ task.maximumMessageSize = 128 * 1024 * 1024
49
+ self.withLock { connection.task = task }
50
+ task.resume()
51
+ self.receive(on: connection, task: task)
52
+ return connection.id
53
+ }
54
+
55
+ Function("sendText") { (id: Int, text: String) in
56
+ guard let connection = self.connection(id), let task = connection.task else { return }
57
+ task.send(.string(text)) { [weak self] error in
58
+ if let error { self?.fail(connection, task: task, error: error) }
59
+ }
60
+ }
61
+
62
+ Function("sendBinary") { (id: Int, bytes: Uint8Array) in
63
+ guard let connection = self.connection(id), let task = connection.task else { return }
64
+ let data = Data(bytes: bytes.rawPointer, count: bytes.byteLength)
65
+ task.send(.data(data)) { [weak self] error in
66
+ if let error { self?.fail(connection, task: task, error: error) }
67
+ }
68
+ }
69
+
70
+ Function("close") { (id: Int, code: Int, reason: String) in
71
+ guard let connection = self.connection(id) else { return }
72
+ // URLSession can only send the codes it names; anything else goes out as a normal closure.
73
+ let closeCode = URLSessionWebSocketTask.CloseCode(rawValue: code).flatMap { $0 == .invalid ? nil : $0 } ?? .normalClosure
74
+ let task = self.withLock { () -> URLSessionWebSocketTask? in
75
+ connection.requestedCloseCode = closeCode.rawValue
76
+ return connection.task
77
+ }
78
+ task?.cancel(with: closeCode, reason: reason.isEmpty ? nil : reason.data(using: .utf8))
79
+ }
80
+
81
+ OnDestroy {
82
+ self.session?.invalidateAndCancel()
83
+ }
84
+ }
85
+
86
+ private func makeSession() -> URLSession {
87
+ let configuration = URLSessionConfiguration.default
88
+ // Dev clients register URLProtocol classes that intercept the upgrade and drop the socket.
89
+ configuration.protocolClasses = []
90
+ return URLSession(configuration: configuration, delegate: SessionDelegate(module: self), delegateQueue: delegateQueue)
91
+ }
92
+
93
+ private func connection(_ id: Int) -> Connection? {
94
+ withLock { connections[id] }
95
+ }
96
+
97
+ private func connection(for task: URLSessionTask) -> Connection? {
98
+ withLock { connections.values.first { $0.task === task } }
99
+ }
100
+
101
+ private func withLock<T>(_ body: () -> T) -> T {
102
+ lock.lock()
103
+ defer { lock.unlock() }
104
+ return body()
105
+ }
106
+
107
+ private func receive(on connection: Connection, task: URLSessionWebSocketTask) {
108
+ task.receive { [weak self] result in
109
+ guard let self else { return }
110
+ switch result {
111
+ case .success(.string(let text)):
112
+ self.sendEvent("message", ["id": connection.id, "text": text])
113
+ self.receive(on: connection, task: task)
114
+ case .success(.data(let data)):
115
+ self.sendEvent("message", ["id": connection.id, "data": data])
116
+ self.receive(on: connection, task: task)
117
+ case .success:
118
+ self.receive(on: connection, task: task)
119
+ case .failure(let error):
120
+ self.fail(connection, task: task, error: error)
121
+ }
122
+ }
123
+ }
124
+
125
+ /// Every ending is reported once, from the delegate. A receive or send failure on a task that is
126
+ /// still running (an oversized message, for one) gets no delegate callback until it is cancelled.
127
+ private func fail(_ connection: Connection, task: URLSessionWebSocketTask, error: Error) {
128
+ let live = withLock { () -> Bool in
129
+ guard !connection.finished else { return false }
130
+ if connection.failure == nil { connection.failure = error.localizedDescription }
131
+ return true
132
+ }
133
+ guard live, task.state == .running else { return }
134
+ task.cancel()
135
+ }
136
+
137
+ fileprivate func didOpen(task: URLSessionWebSocketTask) {
138
+ guard let connection = connection(for: task) else { return }
139
+ sendEvent("open", ["id": connection.id])
140
+ }
141
+
142
+ fileprivate func didClose(task: URLSessionWebSocketTask, code: URLSessionWebSocketTask.CloseCode, reason: Data?) {
143
+ guard let connection = connection(for: task) else { return }
144
+ finish(connection, code: code.rawValue, reason: reason.flatMap { String(data: $0, encoding: .utf8) } ?? "", clean: true)
145
+ }
146
+
147
+ fileprivate func didComplete(task: URLSessionTask, error: Error?) {
148
+ guard let connection = connection(for: task) else { return }
149
+ let (requested, failure) = withLock { (connection.requestedCloseCode, connection.failure) }
150
+ if requested == nil, let message = failure ?? error?.localizedDescription {
151
+ sendEvent("error", ["id": connection.id, "message": message])
152
+ }
153
+ // A task that ends without a close frame is an abnormal closure, as in browsers; one we
154
+ // cancelled ourselves reports the code we asked for.
155
+ finish(connection, code: requested ?? (error == nil && failure == nil ? 1005 : 1006), reason: "", clean: requested != nil)
156
+ }
157
+
158
+ private func finish(_ connection: Connection, code: Int, reason: String, clean: Bool) {
159
+ let first = withLock { () -> Bool in
160
+ if connection.finished { return false }
161
+ connection.finished = true
162
+ connections.removeValue(forKey: connection.id)
163
+ return true
164
+ }
165
+ guard first else { return }
166
+ sendEvent("close", ["id": connection.id, "code": code, "reason": reason, "wasClean": clean])
167
+ }
168
+}
169
+
170
+private final class SessionDelegate: NSObject, URLSessionWebSocketDelegate {
171
+ weak var module: T3WebSocketModule?
172
+
173
+ init(module: T3WebSocketModule) {
174
+ self.module = module
175
+ }
176
+
177
+ func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {
178
+ module?.didOpen(task: webSocketTask)
179
+ }
180
+
181
+ func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
182
+ module?.didClose(task: webSocketTask, code: closeCode, reason: reason)
183
+ }
184
+
185
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
186
+ module?.didComplete(task: task, error: error)
187
+ }
188
+}
apps/mobile/src/lib/runtime.ts
+3
-3
@@ -1,7 +1,6 @@
1
import * as Effect from "effect/Effect";
2
import * as Layer from "effect/Layer";
3
import * as ManagedRuntime from "effect/ManagedRuntime";
4
-import * as Socket from "effect/socket/Socket";
4
5
import { layerRemoteHttpClient } from "@t3tools/client-runtime/rpc";
6
@@ -9,6 +8,7 @@ import * as Dpop from "../features/cloud/dpop";
8
import * as ManagedRelayLayer from "../features/cloud/managedRelayLayer";
9
import { resolveCloudPublicConfig } from "../features/cloud/publicConfig";
10
import * as Tracing from "../features/observability/tracing";
11
+import * as NativeWebSocket from "../native/nativeWebSocket";
12
import * as Persistence from "../persistence/layer";
13
import { disposeOnFoundationReplace, type FoundationHotModule } from "./foundation-fast-refresh";
14
import { whenProtectedDataAvailable } from "./protectedData";
@@ -23,7 +23,7 @@ const layerHttpClient = layerRemoteHttpClient(fetch);
23
24
type RuntimeLayerSource =
25
| ReturnType<typeof ManagedRelayLayer.layer>
26
- | typeof Socket.layerWebSocketConstructorGlobal
26
+ | typeof NativeWebSocket.layer
27
| typeof Dpop.layer
28
| typeof layerHttpClient
29
| typeof Persistence.layer
@@ -31,7 +31,7 @@ type RuntimeLayerSource =
31
32
const layerRuntime = Layer.merge(
33
ManagedRelayLayer.layer(configuredRelayUrl()),
34
- Socket.layerWebSocketConstructorGlobal,
34
+ NativeWebSocket.layer,
35
).pipe(
36
Layer.provideMerge(Dpop.layer),
37
Layer.provideMerge(layerHttpClient),
apps/mobile/src/native/nativeWebSocket.ios.test.ts
new
+131
@@ -0,0 +1,131 @@
1
+import { describe, expect, it } from "@effect/vitest";
2
+import * as Effect from "effect/Effect";
3
+import * as Socket from "effect/socket/Socket";
4
+import { vi } from "vite-plus/test";
5
+
6
+vi.mock("expo", () => ({ requireOptionalNativeModule: () => null }));
7
+
8
+import * as NativeWebSocket from "./nativeWebSocket.ios";
9
+
10
+function setup() {
11
+ const listeners = new Map<string, (event: never) => void>();
12
+ let nextId = 7;
13
+ const native = {
14
+ connect: vi.fn(() => nextId++),
15
+ sendText: vi.fn(),
16
+ sendBinary: vi.fn(),
17
+ close: vi.fn(),
18
+ addListener: vi.fn((event: string, listener: (event: never) => void) => {
19
+ listeners.set(event, listener);
20
+ return { remove: () => listeners.delete(event) };
21
+ }),
22
+ } satisfies NativeWebSocket.NativeModule;
23
+ const emit = (event: "open" | "message" | "error" | "close", payload: Record<string, unknown>) =>
24
+ listeners.get(event)?.(payload as never);
25
+ const sockets = new NativeWebSocket.Sockets(native);
26
+ const events: Array<Record<string, unknown>> = [];
27
+ const socket = new NativeWebSocket.Connection(sockets, "ws://host/ws", ["t3"]);
28
+ for (const type of ["open", "message", "error", "close"] as const) {
29
+ socket.addEventListener(type, (event) => events.push({ ...event }));
30
+ }
31
+ return { native, emit, socket, events, sockets, id: 7 };
32
+}
33
+
34
+describe("NativeWebSocket", () => {
35
+ it("opens, then delivers text and binary frames as string and ArrayBuffer", () => {
36
+ const { native, emit, socket, events, id } = setup();
37
+ expect(native.connect).toHaveBeenCalledWith("ws://host/ws", ["t3"]);
38
+ expect(socket.readyState).toBe(NativeWebSocket.Connection.CONNECTING);
39
+ expect(() => socket.send("early")).toThrow(/connecting/);
40
+
41
+ emit("open", { id });
42
+ expect(socket.readyState).toBe(NativeWebSocket.Connection.OPEN);
43
+
44
+ const bytes = new Uint8Array([1, 2, 3]);
45
+ emit("message", { id, text: "hello" });
46
+ emit("message", { id, data: bytes.subarray(1) });
47
+ emit("message", { id: id + 1, text: "other socket" });
48
+ expect(events).toEqual([
49
+ { type: "open" },
50
+ { type: "message", data: "hello" },
51
+ { type: "message", data: new Uint8Array([2, 3]) },
52
+ ]);
53
+
54
+ socket.send("out");
55
+ socket.send(bytes);
56
+ expect(native.sendText).toHaveBeenCalledWith(id, "out");
57
+ expect(native.sendBinary).toHaveBeenCalledWith(id, bytes);
58
+ });
59
+
60
+ it("reports the server's close frame once and ignores later events", () => {
61
+ const { emit, socket, events, id } = setup();
62
+ emit("open", { id });
63
+ emit("close", { id, code: 1001, reason: "going away", wasClean: true });
64
+ emit("close", { id, code: 1006, reason: "", wasClean: false });
65
+ emit("message", { id, text: "late" });
66
+ expect(socket.readyState).toBe(NativeWebSocket.Connection.CLOSED);
67
+ expect(events.slice(1)).toEqual([
68
+ { type: "close", code: 1001, reason: "going away", wasClean: true },
69
+ ]);
70
+ });
71
+
72
+ it("fires error before close when the handshake fails", () => {
73
+ const { emit, events, id } = setup();
74
+ emit("error", { id, message: "connection refused" });
75
+ emit("close", { id, code: 1006, reason: "", wasClean: false });
76
+ expect(events).toEqual([
77
+ { type: "error", message: "connection refused" },
78
+ { type: "close", code: 1006, reason: "", wasClean: false },
79
+ ]);
80
+ });
81
+
82
+ it("closes through the native module once and honours once listeners", () => {
83
+ const { native, emit, socket, id } = setup();
84
+ const once = vi.fn();
85
+ const always = vi.fn();
86
+ socket.addEventListener("close", once, { once: true });
87
+ socket.addEventListener("close", always);
88
+ socket.addEventListener("close", always);
89
+ emit("open", { id });
90
+ socket.close(1000, "done");
91
+ socket.close(1000, "again");
92
+ expect(socket.readyState).toBe(NativeWebSocket.Connection.CLOSING);
93
+ expect(native.close).toHaveBeenCalledTimes(1);
94
+ expect(native.close).toHaveBeenCalledWith(id, 1000, "done");
95
+ expect(() => socket.send("after close")).not.toThrow();
96
+ expect(native.sendText).not.toHaveBeenCalled();
97
+
98
+ socket.removeEventListener("close", always);
99
+ emit("close", { id, code: 1000, reason: "", wasClean: true });
100
+ expect(once).toHaveBeenCalledTimes(1);
101
+ expect(always).not.toHaveBeenCalled();
102
+ });
103
+
104
+ it("closes open sockets and stops listening when disposed", () => {
105
+ const { native, emit, socket, sockets, events, id } = setup();
106
+ emit("open", { id });
107
+ sockets.dispose();
108
+ expect(native.close).toHaveBeenCalledWith(id, 1001, "");
109
+ expect(socket.readyState).toBe(NativeWebSocket.Connection.CLOSED);
110
+ expect(events.at(-1)).toEqual({ type: "close", code: 1001, reason: "", wasClean: false });
111
+ expect(emit("message", { id, text: "late" })).toBeUndefined();
112
+ });
113
+
114
+ it.effect("surfaces a server close through Effect's socket as SocketCloseError", () =>
115
+ Effect.gen(function* () {
116
+ const { emit, socket, id } = setup();
117
+ emit("open", { id });
118
+ const effectSocket = yield* Socket.fromWebSocket(Effect.succeed(socket));
119
+ const reader = yield* effectSocket.reader;
120
+ emit("message", { id, text: "hi" });
121
+ emit("close", { id, code: 1011, reason: "boom", wasClean: true });
122
+ expect(yield* reader.pull).toEqual(["hi"]);
123
+ const error = yield* Effect.flip(reader.pull);
124
+ expect(error.reason).toMatchObject({
125
+ _tag: "SocketCloseError",
126
+ code: 1011,
127
+ closeReason: "boom",
128
+ });
129
+ }).pipe(Effect.scoped),
130
+ );
131
+});
apps/mobile/src/native/nativeWebSocket.ios.ts
new
+193
@@ -0,0 +1,193 @@
1
+import * as Effect from "effect/Effect";
2
+import * as Layer from "effect/Layer";
3
+import * as Socket from "effect/socket/Socket";
4
+import { requireOptionalNativeModule } from "expo";
5
+
6
+type EventType = "open" | "message" | "error" | "close";
7
+
8
+interface NativeEvents {
9
+ readonly open: { readonly id: number };
10
+ readonly message: { readonly id: number; readonly text?: string; readonly data?: Uint8Array };
11
+ readonly error: { readonly id: number; readonly message: string };
12
+ readonly close: {
13
+ readonly id: number;
14
+ readonly code: number;
15
+ readonly reason: string;
16
+ readonly wasClean: boolean;
17
+ };
18
+}
19
+
20
+export interface NativeModule {
21
+ connect(url: string, protocols: ReadonlyArray<string>): number;
22
+ sendText(id: number, text: string): void;
23
+ sendBinary(id: number, bytes: Uint8Array): void;
24
+ close(id: number, code: number, reason: string): void;
25
+ addListener<K extends keyof NativeEvents>(
26
+ event: K,
27
+ listener: (event: NativeEvents[K]) => void,
28
+ ): { remove(): void };
29
+}
30
+
31
+interface Listener {
32
+ readonly listener: (event: Socket.WebSocketEvent) => void;
33
+ readonly once: boolean;
34
+}
35
+
36
+/** Subset of the WHATWG WebSocket API that Effect's socket layer touches, over the native module. */
37
+export class Connection implements Socket.WebSocketLike {
38
+ static readonly CONNECTING = 0;
39
+ static readonly OPEN = 1;
40
+ static readonly CLOSING = 2;
41
+ static readonly CLOSED = 3;
42
+
43
+ readonly url: string;
44
+ readyState: number = Connection.CONNECTING;
45
+
46
+ readonly #id: number;
47
+ readonly #sockets: Sockets;
48
+ readonly #listeners = new Map<EventType, Array<Listener>>();
49
+
50
+ constructor(sockets: Sockets, url: string, protocols?: string | ReadonlyArray<string>) {
51
+ this.url = url;
52
+ this.#sockets = sockets;
53
+ this.#id = sockets.native.connect(
54
+ url,
55
+ protocols === undefined ? [] : typeof protocols === "string" ? [protocols] : protocols,
56
+ );
57
+ sockets.register(this.#id, this);
58
+ }
59
+
60
+ addEventListener(
61
+ type: EventType,
62
+ listener: (event: Socket.WebSocketEvent) => void,
63
+ options?: { readonly once?: boolean },
64
+ ): void {
65
+ const entries = this.#listeners.get(type) ?? [];
66
+ if (entries.some((entry) => entry.listener === listener)) return;
67
+ entries.push({ listener, once: options?.once === true });
68
+ this.#listeners.set(type, entries);
69
+ }
70
+
71
+ removeEventListener(type: EventType, listener: (event: Socket.WebSocketEvent) => void): void {
72
+ const entries = this.#listeners.get(type);
73
+ if (entries === undefined) return;
74
+ this.#listeners.set(
75
+ type,
76
+ entries.filter((entry) => entry.listener !== listener),
77
+ );
78
+ }
79
+
80
+ send(data: string | Uint8Array<ArrayBuffer>): void {
81
+ if (this.readyState === Connection.CONNECTING) {
82
+ throw new Error("InvalidStateError: WebSocket is still connecting");
83
+ }
84
+ // Browsers drop writes after close instead of throwing.
85
+ if (this.readyState !== Connection.OPEN) return;
86
+ if (typeof data === "string") {
87
+ this.#sockets.native.sendText(this.#id, data);
88
+ } else {
89
+ this.#sockets.native.sendBinary(this.#id, data);
90
+ }
91
+ }
92
+
93
+ close(code = 1000, reason = ""): void {
94
+ if (this.readyState >= Connection.CLOSING) return;
95
+ this.readyState = Connection.CLOSING;
96
+ this.#sockets.native.close(this.#id, code, reason);
97
+ }
98
+
99
+ handleOpen(_event: NativeEvents["open"]): void {
100
+ if (this.readyState !== Connection.CONNECTING) return;
101
+ this.readyState = Connection.OPEN;
102
+ this.#dispatch("open", { type: "open" });
103
+ }
104
+
105
+ handleMessage(event: NativeEvents["message"]): void {
106
+ if (this.readyState !== Connection.OPEN) return;
107
+ this.#dispatch("message", { type: "message", data: event.text ?? event.data });
108
+ }
109
+
110
+ handleError(event: NativeEvents["error"]): void {
111
+ if (this.readyState === Connection.CLOSED) return;
112
+ this.#dispatch("error", { type: "error", message: event.message });
113
+ }
114
+
115
+ handleClose(event: NativeEvents["close"]): void {
116
+ if (this.readyState === Connection.CLOSED) return;
117
+ this.readyState = Connection.CLOSED;
118
+ this.#sockets.unregister(this.#id);
119
+ this.#dispatch("close", {
120
+ type: "close",
121
+ code: event.code,
122
+ reason: event.reason,
123
+ wasClean: event.wasClean,
124
+ });
125
+ }
126
+
127
+ #dispatch(type: EventType, event: Socket.WebSocketEvent & Record<string, unknown>): void {
128
+ const entries = this.#listeners.get(type);
129
+ if (entries === undefined || entries.length === 0) return;
130
+ this.#listeners.set(
131
+ type,
132
+ entries.filter((entry) => !entry.once),
133
+ );
134
+ for (const entry of entries) entry.listener(event);
135
+ }
136
+}
137
+
138
+/** Routes the module's per-id events to the sockets that own them. Native assigns the ids, so a reload cannot reuse one. */
139
+export class Sockets {
140
+ readonly native: NativeModule;
141
+ readonly #open = new Map<number, Connection>();
142
+ readonly #subscriptions: ReadonlyArray<{ remove(): void }>;
143
+
144
+ constructor(native: NativeModule) {
145
+ this.native = native;
146
+ this.#subscriptions = [
147
+ native.addListener("open", (event) => this.#open.get(event.id)?.handleOpen(event)),
148
+ native.addListener("message", (event) => this.#open.get(event.id)?.handleMessage(event)),
149
+ native.addListener("error", (event) => this.#open.get(event.id)?.handleError(event)),
150
+ native.addListener("close", (event) => this.#open.get(event.id)?.handleClose(event)),
151
+ ];
152
+ }
153
+
154
+ register(id: number, socket: Connection): void {
155
+ this.#open.set(id, socket);
156
+ }
157
+
158
+ unregister(id: number): void {
159
+ this.#open.delete(id);
160
+ }
161
+
162
+ dispose(): void {
163
+ for (const subscription of this.#subscriptions) subscription.remove();
164
+ for (const socket of this.#open.values()) {
165
+ socket.close(1001);
166
+ socket.handleClose({ id: 0, code: 1001, reason: "", wasClean: false });
167
+ }
168
+ }
169
+}
170
+
171
+function layerFromModule(native: NativeModule): Layer.Layer<Socket.WebSocketConstructor> {
172
+ return Layer.effect(
173
+ Socket.WebSocketConstructor,
174
+ Effect.map(
175
+ Effect.acquireRelease(
176
+ Effect.sync(() => new Sockets(native)),
177
+ (sockets) => Effect.sync(() => sockets.dispose()),
178
+ ),
179
+ (sockets) => (url, options) => {
180
+ if (options !== undefined && typeof options !== "string" && !Array.isArray(options)) {
181
+ throw new TypeError("WebSocket client options are not supported by the native WebSocket");
182
+ }
183
+ return new Connection(sockets, url, options);
184
+ },
185
+ ),
186
+ );
187
+}
188
+
189
+const native = requireOptionalNativeModule<NativeModule>("T3WebSocket");
190
+
191
+// A dev client built before this module shipped still has SocketRocket.
192
+export const layer: Layer.Layer<Socket.WebSocketConstructor> =
193
+ native === null ? Socket.layerWebSocketConstructorGlobal : layerFromModule(native);
apps/mobile/src/native/nativeWebSocket.ts
new
+3
@@ -0,0 +1,3 @@
1
+import * as Socket from "effect/socket/Socket";
2
+
3
+export const layer = Socket.layerWebSocketConstructorGlobal;