@hyper-fetch/sockets 8.0.1 → 8.1.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.
- package/__tests__/e2e/e2e.callbacks.spec.ts +224 -0
- package/__tests__/e2e/e2e.connection.spec.ts +162 -0
- package/__tests__/e2e/e2e.edge-cases.spec.ts +232 -0
- package/__tests__/e2e/e2e.emitters.spec.ts +160 -0
- package/__tests__/e2e/e2e.heartbeat.spec.ts +162 -0
- package/__tests__/e2e/e2e.listeners.spec.ts +215 -0
- package/__tests__/e2e/e2e.reconnection.spec.ts +240 -0
- package/__tests__/e2e/e2e.sse.spec.ts +191 -0
- package/__tests__/features/adapter/adapter.sse.connection.spec.ts +1 -1
- package/__tests__/features/sdk/sdk.base.spec.ts +125 -0
- package/__tests__/features/sdk/sdk.configuration.spec.ts +341 -0
- package/__tests__/vitest.setup.ts +19 -6
- package/dist/adapter/adapter.bindings.d.ts.map +1 -1
- package/dist/adapter-sse/sse-adapter.d.ts.map +1 -1
- package/dist/adapter-sse/sse-adapter.utils.d.ts +1 -1
- package/dist/adapter-sse/sse-adapter.utils.d.ts.map +1 -1
- package/dist/adapter-websockets/websocket-adapter.utils.d.ts +1 -1
- package/dist/adapter-websockets/websocket-adapter.utils.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +153 -32
- package/dist/index.mjs.map +1 -1
- package/dist/sdk/index.d.ts +2 -0
- package/dist/sdk/index.d.ts.map +1 -0
- package/dist/sdk/sdk.d.ts +70 -0
- package/dist/sdk/sdk.d.ts.map +1 -0
- package/dist/socket/index.d.ts +1 -0
- package/dist/socket/index.d.ts.map +1 -1
- package/dist/socket/socket.create.d.ts +5 -0
- package/dist/socket/socket.create.d.ts.map +1 -0
- package/package.json +1 -1
- package/src/adapter/adapter.bindings.ts +15 -6
- package/src/adapter-sse/sse-adapter.ts +6 -14
- package/src/adapter-sse/sse-adapter.utils.ts +8 -7
- package/src/adapter-websockets/websocket-adapter.utils.ts +5 -4
- package/src/index.ts +1 -0
- package/src/sdk/index.ts +1 -0
- package/src/sdk/sdk.ts +268 -0
- package/src/socket/index.ts +1 -0
- package/src/socket/socket.create.ts +10 -0
- package/vite.config.ts +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/socket/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/socket/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,iBAAiB,CAAC;AAChC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { SocketAdapterInstance } from '../adapter';
|
|
2
|
+
import { SocketOptionsType, Socket } from '.';
|
|
3
|
+
import { WebsocketAdapterType } from '../adapter-websockets/websocket-adapter';
|
|
4
|
+
export declare function createSocketClient<Adapter extends SocketAdapterInstance = WebsocketAdapterType>(options: SocketOptionsType<Adapter>): Socket<Adapter>;
|
|
5
|
+
//# sourceMappingURL=socket.create.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket.create.d.ts","sourceRoot":"","sources":["../../src/socket/socket.create.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,QAAQ,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAEjF,wBAAgB,kBAAkB,CAAC,OAAO,SAAS,qBAAqB,GAAG,oBAAoB,EAC7F,OAAO,EAAE,iBAAiB,CAAC,OAAO,CAAC,GAClC,MAAM,CAAC,OAAO,CAAC,CAEjB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyper-fetch/sockets",
|
|
3
|
-
"version": "8.0
|
|
3
|
+
"version": "8.1.0",
|
|
4
4
|
"description": "Sockets connection for hyper-fetch",
|
|
5
5
|
"author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
|
|
6
6
|
"homepage": "https://hyperfetch.bettertyped.com/",
|
|
@@ -50,32 +50,40 @@ export const getAdapterBindings = <T extends SocketAdapterInstance>(socket: Sock
|
|
|
50
50
|
disconnect: () => Promise<any>;
|
|
51
51
|
connect: () => Promise<any>;
|
|
52
52
|
}): Promise<boolean> => {
|
|
53
|
+
// Capture attempts before disconnect/connect reset them
|
|
54
|
+
const currentAttempts = adapter.reconnectionAttempts;
|
|
55
|
+
|
|
53
56
|
socket.unstable_onReconnectCallbacks.forEach((callback) => {
|
|
54
57
|
callback();
|
|
55
58
|
});
|
|
56
|
-
socket.events.emitReconnecting({ attempts:
|
|
59
|
+
socket.events.emitReconnecting({ attempts: currentAttempts });
|
|
57
60
|
|
|
58
61
|
await disconnect();
|
|
59
|
-
if (
|
|
60
|
-
|
|
62
|
+
if (currentAttempts < socket.reconnectAttempts) {
|
|
63
|
+
const nextAttempts = currentAttempts + 1;
|
|
64
|
+
socket.adapter.setReconnectionAttempts(nextAttempts);
|
|
61
65
|
logger.debug({
|
|
62
66
|
title: "Reconnecting",
|
|
63
67
|
type: "system",
|
|
64
|
-
extra: { reconnectionAttempts:
|
|
68
|
+
extra: { reconnectionAttempts: nextAttempts },
|
|
65
69
|
});
|
|
66
70
|
await connect();
|
|
71
|
+
// Restore only if the connection didn't succeed — onConnected resets to 0 on success
|
|
72
|
+
if (!adapter.connected) {
|
|
73
|
+
socket.adapter.setReconnectionAttempts(nextAttempts);
|
|
74
|
+
}
|
|
67
75
|
return true;
|
|
68
76
|
}
|
|
69
77
|
|
|
70
78
|
logger.error({
|
|
71
79
|
title: "Stopped reconnecting",
|
|
72
80
|
type: "system",
|
|
73
|
-
extra: { reconnectionAttempts:
|
|
81
|
+
extra: { reconnectionAttempts: currentAttempts },
|
|
74
82
|
});
|
|
75
83
|
socket.unstable_onReconnectFailedCallbacks.forEach((callback) => {
|
|
76
84
|
callback();
|
|
77
85
|
});
|
|
78
|
-
socket.events.emitReconnectingFailed({ attempts:
|
|
86
|
+
socket.events.emitReconnectingFailed({ attempts: currentAttempts });
|
|
79
87
|
return false;
|
|
80
88
|
};
|
|
81
89
|
|
|
@@ -129,6 +137,7 @@ export const getAdapterBindings = <T extends SocketAdapterInstance>(socket: Sock
|
|
|
129
137
|
logger.info({ title: "Connection open", type: "system", extra: {} });
|
|
130
138
|
adapter.setConnected(true);
|
|
131
139
|
adapter.setConnecting(false);
|
|
140
|
+
adapter.setReconnectionAttempts(0);
|
|
132
141
|
socket.events.emitConnecting({ connecting: false });
|
|
133
142
|
socket.events.emitConnected();
|
|
134
143
|
socket.unstable_onConnectedCallbacks.forEach((callback) => {
|
|
@@ -132,26 +132,18 @@ export const ServerSentEventsAdapter = (): ServerSentEventsAdapterType =>
|
|
|
132
132
|
return Promise.resolve(true);
|
|
133
133
|
}
|
|
134
134
|
const currentSse = sse;
|
|
135
|
-
const promise = new Promise<boolean>((resolve) => {
|
|
136
|
-
if (currentSse.readyState === EventSource.CLOSED) {
|
|
137
|
-
resolve(true);
|
|
138
|
-
adapter.setConnected(false);
|
|
139
|
-
adapter.setConnecting(false);
|
|
140
|
-
return;
|
|
141
|
-
}
|
|
142
135
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
});
|
|
136
|
+
if (currentSse.readyState === EventSource.CLOSED) {
|
|
137
|
+
adapter.setConnected(false);
|
|
138
|
+
adapter.setConnecting(false);
|
|
139
|
+
return Promise.resolve(true);
|
|
140
|
+
}
|
|
149
141
|
|
|
150
142
|
onDisconnect();
|
|
151
143
|
currentSse.close();
|
|
152
144
|
onDisconnected();
|
|
153
145
|
|
|
154
|
-
return
|
|
146
|
+
return Promise.resolve(true);
|
|
155
147
|
};
|
|
156
148
|
|
|
157
149
|
const reconnect = () => {
|
|
@@ -12,7 +12,8 @@ export const getServerSentEventsAdapter = (url: string, adapterOptions: SSEAdapt
|
|
|
12
12
|
}
|
|
13
13
|
|
|
14
14
|
class HyperFetchEventSource extends EventSource {
|
|
15
|
-
|
|
15
|
+
// Named to avoid shadowing EventEmitter.listeners() in Node.js environments
|
|
16
|
+
public registeredHandlers: Map<
|
|
16
17
|
(...args: any[]) => any,
|
|
17
18
|
{ type: keyof EventSourceEventMap; listener: (...args: any[]) => void; options: any }
|
|
18
19
|
> = new Map();
|
|
@@ -23,7 +24,7 @@ export const getServerSentEventsAdapter = (url: string, adapterOptions: SSEAdapt
|
|
|
23
24
|
}
|
|
24
25
|
|
|
25
26
|
onopen: EventSource["onopen"] = (...args) => {
|
|
26
|
-
this.
|
|
27
|
+
this.registeredHandlers.forEach(({ type, listener }) => {
|
|
27
28
|
if (type === "open") {
|
|
28
29
|
listener(...args);
|
|
29
30
|
}
|
|
@@ -31,7 +32,7 @@ export const getServerSentEventsAdapter = (url: string, adapterOptions: SSEAdapt
|
|
|
31
32
|
};
|
|
32
33
|
|
|
33
34
|
onerror: EventSource["onerror"] = (...args) => {
|
|
34
|
-
this.
|
|
35
|
+
this.registeredHandlers.forEach(({ type, listener }) => {
|
|
35
36
|
if (type === "error") {
|
|
36
37
|
listener(...args);
|
|
37
38
|
}
|
|
@@ -39,7 +40,7 @@ export const getServerSentEventsAdapter = (url: string, adapterOptions: SSEAdapt
|
|
|
39
40
|
};
|
|
40
41
|
|
|
41
42
|
onmessage: EventSource["onmessage"] = (...args) => {
|
|
42
|
-
this.
|
|
43
|
+
this.registeredHandlers.forEach(({ type, listener }) => {
|
|
43
44
|
if (type === "message") {
|
|
44
45
|
listener(...args);
|
|
45
46
|
}
|
|
@@ -52,7 +53,7 @@ export const getServerSentEventsAdapter = (url: string, adapterOptions: SSEAdapt
|
|
|
52
53
|
options?: boolean | (AddEventListenerOptions & { disableCleanup?: boolean }),
|
|
53
54
|
): void => {
|
|
54
55
|
super.addEventListener(type, listener, options);
|
|
55
|
-
this.
|
|
56
|
+
this.registeredHandlers.set(listener, { type, listener, options });
|
|
56
57
|
};
|
|
57
58
|
|
|
58
59
|
removeEventListener = <K extends keyof EventSourceEventMap>(
|
|
@@ -61,11 +62,11 @@ export const getServerSentEventsAdapter = (url: string, adapterOptions: SSEAdapt
|
|
|
61
62
|
options?: boolean | EventListenerOptions,
|
|
62
63
|
): void => {
|
|
63
64
|
super.removeEventListener(type, listener, options);
|
|
64
|
-
this.
|
|
65
|
+
this.registeredHandlers.delete(listener);
|
|
65
66
|
};
|
|
66
67
|
|
|
67
68
|
clearListeners = () => {
|
|
68
|
-
this.
|
|
69
|
+
this.registeredHandlers.forEach(({ type, listener, options }) => {
|
|
69
70
|
if (!options?.disableCleanup) {
|
|
70
71
|
this.removeEventListener(type, listener, options);
|
|
71
72
|
}
|
|
@@ -12,7 +12,8 @@ export const getWebsocketAdapter = (url: string, adapterOptions: WebsocketAdapte
|
|
|
12
12
|
}
|
|
13
13
|
|
|
14
14
|
class HyperFetchWebsocket extends WebSocket {
|
|
15
|
-
|
|
15
|
+
// Named to avoid shadowing EventEmitter.listeners() in Node.js environments
|
|
16
|
+
public registeredHandlers: Map<
|
|
16
17
|
(...args: any[]) => any,
|
|
17
18
|
{ type: keyof WebSocketEventMap; listener: (...args: any[]) => void; options: any }
|
|
18
19
|
> = new Map();
|
|
@@ -28,7 +29,7 @@ export const getWebsocketAdapter = (url: string, adapterOptions: WebsocketAdapte
|
|
|
28
29
|
options?: boolean | (AddEventListenerOptions & { disableCleanup?: boolean }),
|
|
29
30
|
) => {
|
|
30
31
|
super.addEventListener(type, listener, options);
|
|
31
|
-
this.
|
|
32
|
+
this.registeredHandlers.set(listener, { type, listener, options });
|
|
32
33
|
};
|
|
33
34
|
|
|
34
35
|
removeEventListener = <K extends keyof WebSocketEventMap>(
|
|
@@ -37,11 +38,11 @@ export const getWebsocketAdapter = (url: string, adapterOptions: WebsocketAdapte
|
|
|
37
38
|
options?: boolean | EventListenerOptions,
|
|
38
39
|
) => {
|
|
39
40
|
super.removeEventListener(type, listener, options);
|
|
40
|
-
this.
|
|
41
|
+
this.registeredHandlers.delete(listener);
|
|
41
42
|
};
|
|
42
43
|
|
|
43
44
|
clearListeners = () => {
|
|
44
|
-
this.
|
|
45
|
+
this.registeredHandlers.forEach(({ type, listener, options }) => {
|
|
45
46
|
if (!options?.disableCleanup) {
|
|
46
47
|
this.removeEventListener(type, listener, options);
|
|
47
48
|
}
|
package/src/index.ts
CHANGED
package/src/sdk/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./sdk";
|
package/src/sdk/sdk.ts
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import type { SocketInstance } from "socket";
|
|
2
|
+
import type { ListenerInstance } from "listener";
|
|
3
|
+
import type { EmitterInstance } from "emitter";
|
|
4
|
+
|
|
5
|
+
export type RecursiveSocketSchemaType = Record<string, any>;
|
|
6
|
+
|
|
7
|
+
type SocketSdkLeaf = ListenerInstance | EmitterInstance;
|
|
8
|
+
|
|
9
|
+
type ExtractTopicFromLeaf<T> = T extends { topic: infer Topic extends string } ? Topic : never;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Recursively extracts topic strings from leaf nodes in a socket SDK schema.
|
|
13
|
+
*/
|
|
14
|
+
type ExtractSocketTopics<T, Depth extends unknown[] = []> = Depth["length"] extends 10
|
|
15
|
+
? never
|
|
16
|
+
: {
|
|
17
|
+
[K in keyof T & string]: T[K] extends SocketSdkLeaf
|
|
18
|
+
? ExtractTopicFromLeaf<T[K]>
|
|
19
|
+
: T[K] extends Record<string, any>
|
|
20
|
+
? ExtractSocketTopics<T[K], [...Depth, unknown]>
|
|
21
|
+
: never;
|
|
22
|
+
}[keyof T & string];
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Extracts all intermediate prefixes from a slash-separated topic.
|
|
26
|
+
* "chat/messages/pinned" → "chat" | "chat/messages"
|
|
27
|
+
*/
|
|
28
|
+
type TopicPrefixes<T extends string> = T extends `${infer Head}/${infer Tail}`
|
|
29
|
+
? Head | `${Head}/${TopicPrefixes<Tail> & string}`
|
|
30
|
+
: never;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Recursively extracts dot-path accessor keys from a socket SDK schema.
|
|
34
|
+
* These mirror the SDK property chain: "chat.$listener", "chat.messages.$emitter", etc.
|
|
35
|
+
*/
|
|
36
|
+
type ExtractSocketSdkPaths<T, Prefix extends string = "", Depth extends unknown[] = []> = Depth["length"] extends 10
|
|
37
|
+
? never
|
|
38
|
+
: {
|
|
39
|
+
[K in keyof T & string]: T[K] extends SocketSdkLeaf
|
|
40
|
+
? `${Prefix}${K}`
|
|
41
|
+
: T[K] extends Record<string, any>
|
|
42
|
+
? ExtractSocketSdkPaths<T[K], `${Prefix}${K}.`, [...Depth, unknown]>
|
|
43
|
+
: never;
|
|
44
|
+
}[keyof T & string];
|
|
45
|
+
|
|
46
|
+
type AllTopicKeys<Schema extends RecursiveSocketSchemaType> = ExtractSocketTopics<Schema>;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Builds the set of valid configuration keys from a socket SDK schema:
|
|
50
|
+
* - "*" (global wildcard)
|
|
51
|
+
* - exact topic strings extracted from leaf nodes (topic group keys)
|
|
52
|
+
* - wildcard topic patterns like "chat/*" (topic group keys)
|
|
53
|
+
* - dot-path accessor keys like "chat.messages.$listener" (instance-specific keys)
|
|
54
|
+
*/
|
|
55
|
+
type SocketSdkConfigurationKeys<Schema extends RecursiveSocketSchemaType> =
|
|
56
|
+
| "*"
|
|
57
|
+
| AllTopicKeys<Schema>
|
|
58
|
+
| `${(AllTopicKeys<Schema> | TopicPrefixes<AllTopicKeys<Schema> & string>) & string}/*`
|
|
59
|
+
| ExtractSocketSdkPaths<Schema>;
|
|
60
|
+
|
|
61
|
+
export type SocketSdkDefaults = {
|
|
62
|
+
options?: Record<string, unknown>;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
export type SocketSdkConfigurationValue = SocketSdkDefaults | ((instance: SocketSdkLeaf) => SocketSdkLeaf);
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Resolves a dot-path key to its leaf type in the schema.
|
|
69
|
+
* "chat.messages.$listener" → ListenerInstance<...>
|
|
70
|
+
*/
|
|
71
|
+
type ResolveDotPath<T, Path extends string> = Path extends `${infer Head}.${infer Tail}`
|
|
72
|
+
? Head extends keyof T
|
|
73
|
+
? ResolveDotPath<T[Head], Tail>
|
|
74
|
+
: SocketSdkLeaf
|
|
75
|
+
: Path extends keyof T
|
|
76
|
+
? T[Path]
|
|
77
|
+
: SocketSdkLeaf;
|
|
78
|
+
|
|
79
|
+
type SocketSdkConfigurationValueFor<T> = SocketSdkDefaults | ((instance: T) => T);
|
|
80
|
+
|
|
81
|
+
export type SocketSdkConfigurationMap<Schema extends RecursiveSocketSchemaType = RecursiveSocketSchemaType> = {
|
|
82
|
+
[K in SocketSdkConfigurationKeys<Schema>]?: SocketSdkConfigurationValueFor<
|
|
83
|
+
K extends ExtractSocketSdkPaths<Schema> ? ResolveDotPath<Schema, K> : SocketSdkLeaf
|
|
84
|
+
>;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
export type CreateSocketSdkOptions<Schema extends RecursiveSocketSchemaType = RecursiveSocketSchemaType> = {
|
|
88
|
+
/** @default true */
|
|
89
|
+
camelCaseToKebabCase?: boolean;
|
|
90
|
+
/** Per-path defaults (plain objects or functions) */
|
|
91
|
+
defaults?: SocketSdkConfigurationMap<Schema>;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const LEAF_KEYS = new Set(["$listener", "$emitter"]);
|
|
95
|
+
|
|
96
|
+
const isDotPath = (key: string): boolean => {
|
|
97
|
+
return key.includes(".") && !key.includes("/");
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const isTopicGroup = (key: string): boolean => {
|
|
101
|
+
return key.includes("/") || (!key.includes(".") && key !== "*");
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const topicMatchesPattern = (topic: string, pattern: string): boolean => {
|
|
105
|
+
if (pattern === "*") return true;
|
|
106
|
+
if (pattern === topic) return true;
|
|
107
|
+
if (pattern.endsWith("/*")) {
|
|
108
|
+
const prefix = pattern.slice(0, -1);
|
|
109
|
+
return topic.startsWith(prefix) || topic === prefix.slice(0, -1);
|
|
110
|
+
}
|
|
111
|
+
return false;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const applySocketObjectDefaults = (instance: SocketSdkLeaf, config: SocketSdkDefaults): SocketSdkLeaf => {
|
|
115
|
+
let result = instance;
|
|
116
|
+
if (config.options !== undefined) result = result.setOptions(config.options);
|
|
117
|
+
return result;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const applySocketDefaults = ({
|
|
121
|
+
instance,
|
|
122
|
+
topic,
|
|
123
|
+
sdkPath,
|
|
124
|
+
defaults,
|
|
125
|
+
}: {
|
|
126
|
+
instance: SocketSdkLeaf;
|
|
127
|
+
topic: string;
|
|
128
|
+
sdkPath: string;
|
|
129
|
+
defaults?: Partial<Record<string, SocketSdkConfigurationValue>>;
|
|
130
|
+
}): SocketSdkLeaf => {
|
|
131
|
+
if (!defaults) return instance;
|
|
132
|
+
|
|
133
|
+
let result = instance;
|
|
134
|
+
const entries = Object.entries(defaults);
|
|
135
|
+
|
|
136
|
+
const globalEntries: [string, SocketSdkConfigurationValue][] = [];
|
|
137
|
+
const groupEntries: [string, SocketSdkConfigurationValue][] = [];
|
|
138
|
+
const pathEntries: [string, SocketSdkConfigurationValue][] = [];
|
|
139
|
+
|
|
140
|
+
for (let i = 0; i < entries.length; i += 1) {
|
|
141
|
+
const [key, value] = entries[i];
|
|
142
|
+
if (!value) continue;
|
|
143
|
+
const entry: [string, SocketSdkConfigurationValue] = [key, value];
|
|
144
|
+
if (entry[0] === "*") {
|
|
145
|
+
globalEntries.push(entry);
|
|
146
|
+
} else if (isDotPath(entry[0])) {
|
|
147
|
+
pathEntries.push(entry);
|
|
148
|
+
} else if (isTopicGroup(entry[0])) {
|
|
149
|
+
groupEntries.push(entry);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const sorted = [...globalEntries, ...groupEntries, ...pathEntries];
|
|
154
|
+
|
|
155
|
+
for (let i = 0; i < sorted.length; i += 1) {
|
|
156
|
+
const [pattern, config] = sorted[i];
|
|
157
|
+
|
|
158
|
+
let matches = false;
|
|
159
|
+
if (isDotPath(pattern)) {
|
|
160
|
+
matches = pattern === sdkPath;
|
|
161
|
+
} else {
|
|
162
|
+
matches = topicMatchesPattern(topic, pattern);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (matches) {
|
|
166
|
+
if (typeof config === "function") {
|
|
167
|
+
result = config(result) as SocketSdkLeaf;
|
|
168
|
+
} else {
|
|
169
|
+
result = applySocketObjectDefaults(result, config);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return result;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const createSocketRecursiveProxy = ({
|
|
178
|
+
socket,
|
|
179
|
+
path,
|
|
180
|
+
sdkKeys,
|
|
181
|
+
options,
|
|
182
|
+
}: {
|
|
183
|
+
socket: SocketInstance;
|
|
184
|
+
path: string[];
|
|
185
|
+
sdkKeys: string[];
|
|
186
|
+
options?: CreateSocketSdkOptions<any>;
|
|
187
|
+
}): any => {
|
|
188
|
+
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
|
189
|
+
return new Proxy(() => {}, {
|
|
190
|
+
get: (_target, key: string) => {
|
|
191
|
+
if (typeof key === "symbol" || key === "inspect") {
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const currentSdkKeys = [...sdkKeys, key];
|
|
196
|
+
const sdkPath = currentSdkKeys.join(".");
|
|
197
|
+
|
|
198
|
+
let pathSegment = key;
|
|
199
|
+
|
|
200
|
+
if (key.startsWith("$") && !LEAF_KEYS.has(key)) {
|
|
201
|
+
pathSegment = `:${key.slice(1)}`;
|
|
202
|
+
} else if (options?.camelCaseToKebabCase) {
|
|
203
|
+
pathSegment = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (LEAF_KEYS.has(key)) {
|
|
207
|
+
const topic = path.join("/");
|
|
208
|
+
|
|
209
|
+
let instance: SocketSdkLeaf;
|
|
210
|
+
if (key === "$listener") {
|
|
211
|
+
instance = socket.createListener()({ topic });
|
|
212
|
+
} else {
|
|
213
|
+
instance = socket.createEmitter()({ topic });
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
instance = applySocketDefaults({ instance, topic, sdkPath, defaults: options?.defaults });
|
|
217
|
+
return instance;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const newPath = [...path, pathSegment];
|
|
221
|
+
const deeperProxy = createSocketRecursiveProxy({ socket, path: newPath, sdkKeys: currentSdkKeys, options });
|
|
222
|
+
|
|
223
|
+
return deeperProxy;
|
|
224
|
+
},
|
|
225
|
+
});
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
export type SocketSdkInstance<Schema extends RecursiveSocketSchemaType> = Schema & {
|
|
229
|
+
$configure: (defaults: SocketSdkConfigurationMap<Schema>) => SocketSdkInstance<Schema>;
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
export const createSocketSdk = <S extends SocketInstance, RecursiveSchema extends RecursiveSocketSchemaType>(
|
|
233
|
+
socket: S,
|
|
234
|
+
options?: CreateSocketSdkOptions<RecursiveSchema>,
|
|
235
|
+
): SocketSdkInstance<RecursiveSchema> => {
|
|
236
|
+
const { camelCaseToKebabCase = true, ...rest } = options ?? {};
|
|
237
|
+
|
|
238
|
+
const mergedOptions: CreateSocketSdkOptions<RecursiveSchema> = { camelCaseToKebabCase, ...rest };
|
|
239
|
+
const proxy = createSocketRecursiveProxy({ socket, path: [], sdkKeys: [], options: mergedOptions as never });
|
|
240
|
+
|
|
241
|
+
return new Proxy(proxy, {
|
|
242
|
+
get: (target: any, key: string) => {
|
|
243
|
+
if (key === "$configure") {
|
|
244
|
+
return (defaults: SocketSdkConfigurationMap<RecursiveSchema>) => {
|
|
245
|
+
const existingDefaults = mergedOptions.defaults || {};
|
|
246
|
+
return createSocketSdk<S, RecursiveSchema>(socket, {
|
|
247
|
+
...mergedOptions,
|
|
248
|
+
defaults: { ...existingDefaults, ...defaults } as SocketSdkConfigurationMap<RecursiveSchema>,
|
|
249
|
+
});
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
return target[key];
|
|
253
|
+
},
|
|
254
|
+
}) as SocketSdkInstance<RecursiveSchema>;
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Type-safe factory for creating socket SDK configuration maps.
|
|
259
|
+
*
|
|
260
|
+
* @example
|
|
261
|
+
* const config = createSocketConfiguration<MyChatSchema>()({
|
|
262
|
+
* "*": { options: { reconnect: true } },
|
|
263
|
+
* "chat.messages.$listener": (instance) => instance.setOptions({ buffer: true }),
|
|
264
|
+
* })
|
|
265
|
+
*/
|
|
266
|
+
export const createSocketConfiguration = <Schema extends RecursiveSocketSchemaType>() => {
|
|
267
|
+
return (defaults: SocketSdkConfigurationMap<Schema>): SocketSdkConfigurationMap<Schema> => defaults;
|
|
268
|
+
};
|
package/src/socket/index.ts
CHANGED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { SocketAdapterInstance } from "adapter";
|
|
2
|
+
import type { SocketOptionsType } from "socket";
|
|
3
|
+
import { Socket } from "socket";
|
|
4
|
+
import type { WebsocketAdapterType } from "adapter-websockets/websocket-adapter";
|
|
5
|
+
|
|
6
|
+
export function createSocketClient<Adapter extends SocketAdapterInstance = WebsocketAdapterType>(
|
|
7
|
+
options: SocketOptionsType<Adapter>,
|
|
8
|
+
): Socket<Adapter> {
|
|
9
|
+
return new Socket<Adapter>(options);
|
|
10
|
+
}
|
package/vite.config.ts
CHANGED
|
@@ -30,6 +30,7 @@ export default defineConfig({
|
|
|
30
30
|
globals: true,
|
|
31
31
|
environment: "jsdom",
|
|
32
32
|
setupFiles: ["./__tests__/vitest.setup.ts"],
|
|
33
|
+
environmentMatchGlobs: [["__tests__/e2e/**", "node"]],
|
|
33
34
|
include: ["__tests__/**/*.spec.{ts,tsx}", "src/**/*.spec.{ts,tsx}"],
|
|
34
35
|
coverage: {
|
|
35
36
|
provider: "v8",
|