@hyper-fetch/sockets 8.1.1 → 8.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +81 -28
  2. package/__tests__/e2e/e2e.connection.spec.ts +1 -1
  3. package/__tests__/e2e/e2e.edge-cases.spec.ts +1 -1
  4. package/__tests__/e2e/e2e.emitters.spec.ts +1 -1
  5. package/__tests__/e2e/e2e.heartbeat.spec.ts +4 -4
  6. package/__tests__/features/adapter/adapter.base.spec.ts +1 -0
  7. package/__tests__/features/adapter/adapter.bindings.spec.ts +2 -1
  8. package/__tests__/features/adapter/adapter.connection.spec.ts +2 -2
  9. package/__tests__/features/adapter/adapter.error.spec.ts +1 -1
  10. package/__tests__/features/adapter/adapter.sse.connection.spec.ts +2 -2
  11. package/__tests__/features/adapter/adapter.sse.spec.ts +6 -6
  12. package/__tests__/features/adapter/adapter.websocket.heartbeat.spec.ts +1 -1
  13. package/__tests__/features/adapter/adapter.websocket.spec.ts +5 -5
  14. package/__tests__/features/listener/listener.listen.spec.ts +1 -1
  15. package/__tests__/features/listener/listener.sse.spec.ts +2 -2
  16. package/__tests__/features/listener/listener.typescript.spec.ts +0 -1
  17. package/__tests__/features/sdk/sdk.base.spec.ts +11 -14
  18. package/__tests__/features/sdk/sdk.configuration.spec.ts +9 -11
  19. package/__tests__/features/sdk/sdk.types.spec.ts +303 -0
  20. package/__tests__/features/socket/socket.base.spec.ts +4 -4
  21. package/__tests__/features/socket/socket.callbacks.spec.ts +1 -1
  22. package/__tests__/features/socket/socket.methods.spec.ts +1 -2
  23. package/__tests__/features/socket/socket.misc.spec.ts +3 -3
  24. package/__tests__/features/socket/socket.utils.spec.ts +0 -1
  25. package/__tests__/tsconfig.json +4 -17
  26. package/__tests__/utils/client.utils.ts +1 -1
  27. package/__tests__/utils/emitter.utils.ts +1 -2
  28. package/__tests__/utils/listener.utils.ts +2 -3
  29. package/__tests__/utils/socket.utils.ts +2 -2
  30. package/dist/adapter/adapter.bindings.d.ts +3 -3
  31. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  32. package/dist/adapter/adapter.d.ts +4 -4
  33. package/dist/adapter/adapter.d.ts.map +1 -1
  34. package/dist/adapter/adapter.types.d.ts.map +1 -1
  35. package/dist/adapter-sse/sse-adapter.d.ts +2 -1
  36. package/dist/adapter-sse/sse-adapter.d.ts.map +1 -1
  37. package/dist/adapter-sse/sse-adapter.utils.d.ts.map +1 -1
  38. package/dist/adapter-websockets/websocket-adapter.d.ts +1 -0
  39. package/dist/adapter-websockets/websocket-adapter.d.ts.map +1 -1
  40. package/dist/adapter-websockets/websocket-adapter.utils.d.ts.map +1 -1
  41. package/dist/emitter/emitter.d.ts +11 -1
  42. package/dist/emitter/emitter.d.ts.map +1 -1
  43. package/dist/emitter/emitter.types.d.ts +62 -0
  44. package/dist/emitter/emitter.types.d.ts.map +1 -1
  45. package/dist/index.mjs +862 -842
  46. package/dist/index.mjs.map +1 -1
  47. package/dist/listener/listener.d.ts +9 -1
  48. package/dist/listener/listener.d.ts.map +1 -1
  49. package/dist/listener/listener.types.d.ts +67 -0
  50. package/dist/listener/listener.types.d.ts.map +1 -1
  51. package/dist/sdk/sdk.d.ts +27 -5
  52. package/dist/sdk/sdk.d.ts.map +1 -1
  53. package/dist/socket/socket.create.d.ts +1 -1
  54. package/dist/socket/socket.create.d.ts.map +1 -1
  55. package/dist/socket/socket.d.ts +5 -5
  56. package/dist/socket/socket.d.ts.map +1 -1
  57. package/dist/socket/socket.events.d.ts +2 -2
  58. package/dist/socket/socket.events.d.ts.map +1 -1
  59. package/dist/socket/socket.types.d.ts +1 -1
  60. package/dist/socket/socket.types.d.ts.map +1 -1
  61. package/dist/socket/socket.utils.d.ts.map +1 -1
  62. package/dist/types/tuple.types.d.ts +1 -1
  63. package/dist/types/tuple.types.d.ts.map +1 -1
  64. package/dist/utils/socket.errors.d.ts.map +1 -1
  65. package/package.json +8 -8
  66. package/src/adapter/adapter.bindings.ts +3 -3
  67. package/src/adapter/adapter.ts +8 -8
  68. package/src/adapter/adapter.types.ts +1 -0
  69. package/src/adapter-sse/sse-adapter.ts +9 -8
  70. package/src/adapter-sse/sse-adapter.utils.ts +4 -4
  71. package/src/adapter-websockets/websocket-adapter.ts +12 -11
  72. package/src/adapter-websockets/websocket-adapter.utils.ts +4 -4
  73. package/src/emitter/emitter.ts +15 -6
  74. package/src/emitter/emitter.types.ts +69 -1
  75. package/src/listener/listener.ts +12 -5
  76. package/src/listener/listener.types.ts +73 -1
  77. package/src/sdk/sdk.ts +64 -13
  78. package/src/socket/socket.create.ts +1 -1
  79. package/src/socket/socket.events.ts +3 -4
  80. package/src/socket/socket.ts +8 -9
  81. package/src/socket/socket.types.ts +1 -1
  82. package/src/socket/socket.utils.ts +3 -2
  83. package/src/types/tuple.types.ts +1 -1
  84. package/src/utils/socket.errors.ts +26 -13
  85. package/tsconfig.json +20 -2
  86. package/vite.config.ts +30 -21
  87. package/.eslintrc.cjs +0 -12
@@ -1,9 +1,12 @@
1
1
  import type { ExtractUrlParams, ParamsType, PayloadMapperType, EmptyTypes } from "@hyper-fetch/core";
2
-
3
- import type { SocketInstance } from "socket";
4
2
  import type { EmitMethodOptionsType, EmitterCloneOptionsType, EmitterOptionsType, EmitType } from "emitter";
3
+ import type { SocketInstance } from "socket";
5
4
  import type { ExtractAdapterEmitterOptionsType, ExtractSocketAdapterType } from "types";
6
5
 
6
+ /**
7
+ * Represents a socket message emitter bound to a specific topic. Use it to send typed payloads
8
+ * over WebSocket or Server-Sent Events connections via the socket adapter.
9
+ */
7
10
  export class Emitter<
8
11
  Payload,
9
12
  Topic extends string,
@@ -12,11 +15,11 @@ export class Emitter<
12
15
  HasParams extends boolean = false,
13
16
  > {
14
17
  readonly topic: Topic;
15
- params?: ParamsType;
18
+ params?: ParamsType = undefined;
16
19
  payload: Payload | undefined;
17
20
  options: ExtractAdapterEmitterOptionsType<ExtractSocketAdapterType<Socket>> | undefined;
18
21
  /** @internal */
19
- unstable_payloadMapper?: PayloadMapperType<any>;
22
+ unstable_payloadMapper?: PayloadMapperType<any> = undefined;
20
23
 
21
24
  constructor(
22
25
  readonly socket: Socket,
@@ -35,24 +38,28 @@ export class Emitter<
35
38
  this.params = snapshot?.params;
36
39
  }
37
40
 
41
+ /** Set adapter-specific emit options (e.g., acknowledgment, timeout). */
38
42
  setOptions(options: ExtractAdapterEmitterOptionsType<ExtractSocketAdapterType<Socket>> | undefined) {
39
43
  return this.clone({ options });
40
44
  }
41
45
 
46
+ /** Set the message payload to be emitted. */
42
47
  setPayload = <D extends Payload>(payload: D) => {
43
48
  return this.clone<D, D extends EmptyTypes ? false : true, HasParams>({
44
49
  payload,
45
50
  });
46
51
  };
47
52
 
53
+ /** Set a mapper function that transforms the payload before it is sent. */
48
54
  setPayloadMapper = <DataMapper extends (payload: Payload) => any | Promise<any>>(payloadMapper: DataMapper) => {
49
- const cloned = this.clone<Payload, HasPayload, HasParams>(undefined);
55
+ const cloned = this.clone<Payload, HasPayload, HasParams>();
50
56
 
51
57
  cloned.unstable_payloadMapper = payloadMapper;
52
58
 
53
59
  return cloned;
54
60
  };
55
61
 
62
+ /** Set the URL path parameters for the topic (e.g., `:channelId`). */
56
63
  setParams(params: NonNullable<ExtractUrlParams<Topic>>) {
57
64
  return this.clone<Payload, HasPayload, true>({ params });
58
65
  }
@@ -61,13 +68,14 @@ export class Emitter<
61
68
  let topic = this.emitterOptions.topic as string;
62
69
  if (params) {
63
70
  Object.entries(params).forEach(([key, value]) => {
64
- topic = topic.replace(new RegExp(`:${key}`, "g"), String(value));
71
+ topic = topic.replaceAll(new RegExp(`:${key}`, "g"), String(value));
65
72
  });
66
73
  }
67
74
 
68
75
  return topic as Topic;
69
76
  };
70
77
 
78
+ /** Create a new emitter instance with optional configuration overrides. */
71
79
  clone<
72
80
  NewPayload extends Payload = Payload,
73
81
  NewHasPayload extends boolean = HasPayload,
@@ -94,6 +102,7 @@ export class Emitter<
94
102
  return newInstance;
95
103
  }
96
104
 
105
+ /** Send the message through the socket adapter on the configured topic. */
97
106
  emit: EmitType<Emitter<Payload, Topic, Socket, HasPayload, HasParams>> = (options = {}) => {
98
107
  const typedOptions = options as EmitMethodOptionsType<Emitter<Payload, Topic, Socket, HasPayload, HasParams>>;
99
108
  const instance = this.clone<Payload, HasPayload, HasParams>(typedOptions);
@@ -1,6 +1,5 @@
1
1
  /* eslint-disable @typescript-eslint/no-shadow */
2
2
  import type { ExtractUrlParams, EmptyTypes, TypeWithDefaults, ParamsType } from "@hyper-fetch/core";
3
-
4
3
  import type { SocketAdapterInstance } from "adapter";
5
4
  import type { Emitter } from "emitter";
6
5
  import type { SocketInstance } from "socket";
@@ -22,6 +21,25 @@ export type EmitterInstanceProperties = {
22
21
  hasPayload?: boolean;
23
22
  };
24
23
 
24
+ /**
25
+ * The **constraint** form of an Emitter type. Mindset: "any Emitter that matches this partial shape".
26
+ *
27
+ * Use `EmitterInstance` when you are writing a **reusable abstraction** that accepts emitters
28
+ * from the outside - generic helpers (`<T extends EmitterInstance>`), reusable UI components /
29
+ * hooks, `sdk.$configure({...})` callbacks, mocking utilities, return types, etc.
30
+ *
31
+ * Unspecified generic parameters default to `any` **on purpose**: an omitted field means
32
+ * "I do not care about that field, the caller picks anything". This is exactly what you want
33
+ * for a constraint - any concrete `Emitter` satisfies it. Partial constraints work too:
34
+ * `EmitterInstance<{ payload: { text: string } }>` accepts every emitter whose payload has a
35
+ * `text` field, regardless of topic, params, etc.
36
+ *
37
+ * For describing a **single topic** inside a socket SDK schema, use {@link EmitterModel} instead.
38
+ * `EmitterModel` uses safe non-`any` defaults (`undefined`, `string`, `false`) so omitted fields
39
+ * stay strict instead of silently collapsing to `any`.
40
+ *
41
+ * @see {@link EmitterModel} - definition counterpart for SDK schema modeling.
42
+ */
25
43
  export type EmitterInstance<EmitterProperties extends EmitterInstanceProperties = {}> = Emitter<
26
44
  TypeWithDefaults<EmitterProperties, "payload", any>,
27
45
  TypeWithDefaults<EmitterProperties, "topic", any>,
@@ -30,13 +48,63 @@ export type EmitterInstance<EmitterProperties extends EmitterInstanceProperties
30
48
  TypeWithDefaults<EmitterProperties, "hasParams", any>
31
49
  >;
32
50
 
51
+ /**
52
+ * The **definition** form of an Emitter type. Mindset: "**this** specific topic".
53
+ *
54
+ * Use `EmitterModel` when you are **defining** an emitter inside a socket SDK schema. Unlike
55
+ * {@link EmitterInstance}, every unspecified field stays strict instead of falling back to
56
+ * `any` - because in a definition, an omitted field means "**this topic carries no payload**",
57
+ * not "anything goes". The type system will reject mismatches at the call site instead of
58
+ * silently erasing them.
59
+ *
60
+ * The `socket` field is also injected automatically by `createSocketSdk(socket)` at the SDK
61
+ * boundary, so you never need to repeat it inside schema declarations.
62
+ *
63
+ * ### Defaults for omitted fields
64
+ *
65
+ * | Field | Default | Why |
66
+ * | ------------ | ---------------- | ---------------------------------------------------------------- |
67
+ * | `payload` | `undefined` | "No payload declared." `.setData()` is required for typed bodies.|
68
+ * | `topic` | `string` | Allows literal narrowing without erasure. Pass a string literal. |
69
+ * | `socket` | `SocketInstance` | Injected by `createSocketSdk(socket)`; do not set this manually. |
70
+ * | `hasPayload` | `false` | "Caller must call `.setData()`." Override only when bound. |
71
+ * | `hasParams` | `false` | "Caller must call `.setParams()`." Override only when bound. |
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * // Schema describes shape only - socket is injected by createSocketSdk(socket).
76
+ * type ChatSchema = {
77
+ * chat: {
78
+ * messages: {
79
+ * $emitter: EmitterModel<{
80
+ * payload: { text: string };
81
+ * topic: "chat/messages";
82
+ * }>;
83
+ * };
84
+ * };
85
+ * };
86
+ * ```
87
+ *
88
+ * @see {@link EmitterInstance} - constraint counterpart for accepting any Emitter.
89
+ */
90
+ export type EmitterModel<EmitterProperties extends EmitterInstanceProperties = {}> = Emitter<
91
+ TypeWithDefaults<EmitterProperties, "payload", undefined>,
92
+ TypeWithDefaults<EmitterProperties, "topic", string>,
93
+ TypeWithDefaults<EmitterProperties, "socket", SocketInstance>,
94
+ TypeWithDefaults<EmitterProperties, "hasPayload", false>,
95
+ TypeWithDefaults<EmitterProperties, "hasParams", false>
96
+ >;
97
+
33
98
  export type EmitterCloneOptionsType<Payload, Params, Topic extends string, Socket extends SocketInstance> = {
34
99
  payload?: Payload;
35
100
  params?: Params | null;
36
101
  } & Partial<EmitterOptionsType<Topic, ExtractSocketAdapterType<Socket>>>;
37
102
 
103
+ /** Configuration options for creating an Emitter instance. */
38
104
  export type EmitterOptionsType<Topic extends string, AdapterType extends SocketAdapterInstance> = {
105
+ /** The topic/channel name to emit messages on */
39
106
  topic: Topic;
107
+ /** Adapter-specific emit options */
40
108
  options?: ExtractAdapterEmitterOptionsType<AdapterType>;
41
109
  };
42
110
 
@@ -1,9 +1,12 @@
1
1
  import type { ExtractUrlParams, ParamsType } from "@hyper-fetch/core";
2
-
3
- import type { SocketInstance } from "socket";
4
2
  import type { ListenType, ListenerConfigurationType, ListenerOptionsType } from "listener";
3
+ import type { SocketInstance } from "socket";
5
4
  import type { ExtractAdapterListenerOptionsType, ExtractSocketAdapterType } from "types";
6
5
 
6
+ /**
7
+ * Represents a socket message listener bound to a specific topic. Use it to subscribe to
8
+ * typed messages from WebSocket or Server-Sent Events connections via the socket adapter.
9
+ */
7
10
  export class Listener<
8
11
  Response,
9
12
  Topic extends string,
@@ -11,8 +14,8 @@ export class Listener<
11
14
  HasParams extends boolean = false,
12
15
  > {
13
16
  readonly topic: Topic;
14
- params?: ParamsType;
15
- options?: ExtractAdapterListenerOptionsType<ExtractSocketAdapterType<Socket>>;
17
+ params?: ParamsType = undefined;
18
+ options?: ExtractAdapterListenerOptionsType<ExtractSocketAdapterType<Socket>> = undefined;
16
19
 
17
20
  constructor(
18
21
  readonly socket: Socket,
@@ -23,14 +26,17 @@ export class Listener<
23
26
  this.options = options;
24
27
  }
25
28
 
29
+ /** Set adapter-specific listener options. */
26
30
  setOptions(options: ExtractAdapterListenerOptionsType<ExtractSocketAdapterType<Socket>>) {
27
31
  return this.clone({ options });
28
32
  }
29
33
 
34
+ /** Set the URL path parameters for the topic (e.g., `:channelId`). */
30
35
  setParams(params: ExtractUrlParams<Topic>) {
31
36
  return this.clone<true>({ params });
32
37
  }
33
38
 
39
+ /** Create a new listener instance with optional configuration overrides. */
34
40
  clone<NewHasParams extends true | false = HasParams>(
35
41
  options?: ListenerConfigurationType<ExtractUrlParams<Topic>, Topic, Socket>,
36
42
  ) {
@@ -43,6 +49,7 @@ export class Listener<
43
49
  return newInstance;
44
50
  }
45
51
 
52
+ /** Start listening for messages on the configured topic. Returns a function to unsubscribe. */
46
53
  listen: ListenType<Listener<Response, Topic, Socket, HasParams>, Socket> = (
47
54
  callback: Parameters<ListenType<Listener<Response, Topic, Socket, HasParams>, Socket>>[0],
48
55
  ) => {
@@ -59,7 +66,7 @@ export class Listener<
59
66
  let topic = this.listenerOptions.topic as string;
60
67
  if (params) {
61
68
  Object.entries(params).forEach(([key, value]) => {
62
- topic = topic.replace(new RegExp(`:${key}`, "g"), String(value));
69
+ topic = topic.replaceAll(new RegExp(`:${key}`, "g"), String(value));
63
70
  });
64
71
  }
65
72
 
@@ -1,6 +1,5 @@
1
1
  /* eslint-disable @typescript-eslint/no-shadow */
2
2
  import type { ExtractUrlParams, EmptyTypes, TypeWithDefaults } from "@hyper-fetch/core";
3
-
4
3
  import type { SocketAdapterInstance } from "adapter";
5
4
  import type { Listener } from "listener";
6
5
  import type { Socket, SocketInstance } from "socket";
@@ -21,6 +20,25 @@ export type ListenerInstanceProperties = {
21
20
  hasParams?: boolean;
22
21
  };
23
22
 
23
+ /**
24
+ * The **constraint** form of a Listener type. Mindset: "any Listener that matches this partial shape".
25
+ *
26
+ * Use `ListenerInstance` when you are writing a **reusable abstraction** that accepts listeners
27
+ * from the outside - generic helpers (`<T extends ListenerInstance>`), reusable UI components /
28
+ * hooks, `sdk.$configure({...})` callbacks, mocking utilities, return types, etc.
29
+ *
30
+ * Unspecified generic parameters default to `any` **on purpose**: an omitted field means
31
+ * "I do not care about that field, the caller picks anything". This is exactly what you want
32
+ * for a constraint - any concrete `Listener` satisfies it. Partial constraints work too:
33
+ * `ListenerInstance<{ response: { text: string } }>` accepts every listener whose response has a
34
+ * `text` field, regardless of topic, params, etc.
35
+ *
36
+ * For describing a **single topic** inside a socket SDK schema, use {@link ListenerModel} instead.
37
+ * `ListenerModel` uses safe non-`any` defaults (`unknown`, `string`, `false`) so omitted fields
38
+ * stay strict instead of silently collapsing to `any`.
39
+ *
40
+ * @see {@link ListenerModel} - definition counterpart for SDK schema modeling.
41
+ */
24
42
  export type ListenerInstance<ListenerProperties extends ListenerInstanceProperties = {}> = Listener<
25
43
  TypeWithDefaults<ListenerProperties, "response", any>,
26
44
  TypeWithDefaults<ListenerProperties, "topic", any>,
@@ -28,10 +46,64 @@ export type ListenerInstance<ListenerProperties extends ListenerInstanceProperti
28
46
  TypeWithDefaults<ListenerProperties, "hasParams", any>
29
47
  >;
30
48
 
49
+ /**
50
+ * The **definition** form of a Listener type. Mindset: "**this** specific topic".
51
+ *
52
+ * Use `ListenerModel` when you are **defining** a listener inside a socket SDK schema. Unlike
53
+ * {@link ListenerInstance}, every unspecified field stays strict instead of falling back to
54
+ * `any` - because in a definition, an omitted field means "**this topic carries no params**",
55
+ * not "anything goes". The type system will reject mismatches at the call site instead of
56
+ * silently erasing them.
57
+ *
58
+ * The `socket` field is also injected automatically by `createSocketSdk(socket)` at the SDK
59
+ * boundary, so you never need to repeat it inside schema declarations.
60
+ *
61
+ * ### Defaults for omitted fields
62
+ *
63
+ * | Field | Default | Why |
64
+ * | ----------- | ---------------- | ------------------------------------------------------------------ |
65
+ * | `response` | `unknown` | Forces narrowing in consumer code; never silently widened. |
66
+ * | `topic` | `string` | Allows literal narrowing without erasure. Pass a string literal. |
67
+ * | `socket` | `SocketInstance` | Injected by `createSocketSdk(socket)`; do not set this manually. |
68
+ * | `hasParams` | `false` | "Caller must call `.setParams()`." Override only when bound. |
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * // Schema describes shape only - socket is injected by createSocketSdk(socket).
73
+ * type ChatSchema = {
74
+ * chat: {
75
+ * messages: {
76
+ * $listener: ListenerModel<{
77
+ * response: { text: string; user: string };
78
+ * topic: "chat/messages";
79
+ * }>;
80
+ * };
81
+ * $roomId: {
82
+ * $listener: ListenerModel<{
83
+ * response: { text: string; user: string };
84
+ * topic: "chat/:roomId";
85
+ * }>;
86
+ * };
87
+ * };
88
+ * };
89
+ * ```
90
+ *
91
+ * @see {@link ListenerInstance} - constraint counterpart for accepting any Listener.
92
+ */
93
+ export type ListenerModel<ListenerProperties extends ListenerInstanceProperties = {}> = Listener<
94
+ TypeWithDefaults<ListenerProperties, "response", unknown>,
95
+ TypeWithDefaults<ListenerProperties, "topic", string>,
96
+ TypeWithDefaults<ListenerProperties, "socket", SocketInstance>,
97
+ TypeWithDefaults<ListenerProperties, "hasParams", false>
98
+ >;
99
+
31
100
  export type ListenerOfAdapter<A extends SocketAdapterInstance> = Listener<any, any, Socket<A>, any>;
32
101
 
102
+ /** Configuration options for creating a Listener instance. */
33
103
  export type ListenerOptionsType<Topic extends string, AdapterType extends SocketAdapterInstance> = {
104
+ /** The topic/channel name to listen on */
34
105
  topic: Topic;
106
+ /** Adapter-specific listener options */
35
107
  options?: ExtractAdapterListenerOptionsType<AdapterType>;
36
108
  };
37
109
 
package/src/sdk/sdk.ts CHANGED
@@ -1,11 +1,51 @@
1
+ import type { Emitter, EmitterInstance } from "emitter";
2
+ import type { Listener, ListenerInstance } from "listener";
1
3
  import type { SocketInstance } from "socket";
2
- import type { ListenerInstance } from "listener";
3
- import type { EmitterInstance } from "emitter";
4
+ import type {
5
+ ExtractListenerResponseType,
6
+ ExtractListenerTopicType,
7
+ ExtractListenerHasParamsType,
8
+ ExtractEmitterPayloadType,
9
+ ExtractEmitterTopicType,
10
+ ExtractEmitterHasPayloadType,
11
+ ExtractEmitterHasParamsType,
12
+ } from "types";
4
13
 
5
14
  export type RecursiveSocketSchemaType = Record<string, any>;
6
15
 
7
16
  type SocketSdkLeaf = ListenerInstance | EmitterInstance;
8
17
 
18
+ /**
19
+ * Recursively walks a socket schema and rebuilds every `Listener` / `Emitter` leaf with the
20
+ * SDK's actual socket type injected into the `Socket` generic slot. Lets users omit `socket`
21
+ * from their `ListenerModel<{...}>` / `EmitterModel<{...}>` declarations - the SDK fills it
22
+ * in from the socket passed to `createSocketSdk(socket)`.
23
+ *
24
+ * Non-leaf values (primitive types, plain values) are passed through unchanged. Nested schema
25
+ * objects are recursed into. Depth is guarded at 10 levels to keep the type checker within
26
+ * reasonable bounds.
27
+ */
28
+ export type InjectSocket<T, S extends SocketInstance, Depth extends unknown[] = []> = Depth["length"] extends 10
29
+ ? T
30
+ : T extends ListenerInstance
31
+ ? Listener<
32
+ ExtractListenerResponseType<T>,
33
+ ExtractListenerTopicType<T> extends string ? ExtractListenerTopicType<T> : string,
34
+ S,
35
+ ExtractListenerHasParamsType<T> extends boolean ? ExtractListenerHasParamsType<T> : false
36
+ >
37
+ : T extends EmitterInstance
38
+ ? Emitter<
39
+ ExtractEmitterPayloadType<T>,
40
+ ExtractEmitterTopicType<T> extends string ? ExtractEmitterTopicType<T> : string,
41
+ S,
42
+ ExtractEmitterHasPayloadType<T> extends boolean ? ExtractEmitterHasPayloadType<T> : false,
43
+ ExtractEmitterHasParamsType<T> extends boolean ? ExtractEmitterHasParamsType<T> : false
44
+ >
45
+ : T extends Record<string, any>
46
+ ? { [K in keyof T]: InjectSocket<T[K], S, [...Depth, unknown]> }
47
+ : T;
48
+
9
49
  type ExtractTopicFromLeaf<T> = T extends { topic: infer Topic extends string } ? Topic : never;
10
50
 
11
51
  /**
@@ -102,8 +142,8 @@ const isTopicGroup = (key: string): boolean => {
102
142
  };
103
143
 
104
144
  const topicMatchesPattern = (topic: string, pattern: string): boolean => {
105
- if (pattern === "*") return true;
106
- if (pattern === topic) return true;
145
+ if (pattern === "*") {return true;}
146
+ if (pattern === topic) {return true;}
107
147
  if (pattern.endsWith("/*")) {
108
148
  const prefix = pattern.slice(0, -1);
109
149
  return topic.startsWith(prefix) || topic === prefix.slice(0, -1);
@@ -113,7 +153,7 @@ const topicMatchesPattern = (topic: string, pattern: string): boolean => {
113
153
 
114
154
  const applySocketObjectDefaults = (instance: SocketSdkLeaf, config: SocketSdkDefaults): SocketSdkLeaf => {
115
155
  let result = instance;
116
- if (config.options !== undefined) result = result.setOptions(config.options);
156
+ if (config.options !== undefined) {result = result.setOptions(config.options);}
117
157
  return result;
118
158
  };
119
159
 
@@ -128,7 +168,7 @@ const applySocketDefaults = ({
128
168
  sdkPath: string;
129
169
  defaults?: Partial<Record<string, SocketSdkConfigurationValue>>;
130
170
  }): SocketSdkLeaf => {
131
- if (!defaults) return instance;
171
+ if (!defaults) {return instance;}
132
172
 
133
173
  let result = instance;
134
174
  const entries = Object.entries(defaults);
@@ -139,7 +179,7 @@ const applySocketDefaults = ({
139
179
 
140
180
  for (let i = 0; i < entries.length; i += 1) {
141
181
  const [key, value] = entries[i];
142
- if (!value) continue;
182
+ if (!value) {continue;}
143
183
  const entry: [string, SocketSdkConfigurationValue] = [key, value];
144
184
  if (entry[0] === "*") {
145
185
  globalEntries.push(entry);
@@ -189,7 +229,7 @@ const createSocketRecursiveProxy = ({
189
229
  return new Proxy(() => {}, {
190
230
  get: (_target, key: string) => {
191
231
  if (typeof key === "symbol" || key === "inspect") {
192
- return undefined;
232
+ return;
193
233
  }
194
234
 
195
235
  const currentSdkKeys = [...sdkKeys, key];
@@ -200,7 +240,7 @@ const createSocketRecursiveProxy = ({
200
240
  if (key.startsWith("$") && !LEAF_KEYS.has(key)) {
201
241
  pathSegment = `:${key.slice(1)}`;
202
242
  } else if (options?.camelCaseToKebabCase) {
203
- pathSegment = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
243
+ pathSegment = key.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
204
244
  }
205
245
 
206
246
  if (LEAF_KEYS.has(key)) {
@@ -225,14 +265,25 @@ const createSocketRecursiveProxy = ({
225
265
  });
226
266
  };
227
267
 
228
- export type SocketSdkInstance<Schema extends RecursiveSocketSchemaType> = Schema & {
229
- $configure: (defaults: SocketSdkConfigurationMap<Schema>) => SocketSdkInstance<Schema>;
268
+ /**
269
+ * The fully-resolved Socket SDK instance type returned by `createSocketSdk`.
270
+ *
271
+ * The schema is rewritten via {@link InjectSocket} so every `Listener` / `Emitter` leaf
272
+ * carries the actual socket type passed to `createSocketSdk(socket)` - users do not need
273
+ * to repeat `socket: AppSocket` in every `ListenerModel<{...}>` / `EmitterModel<{...}>`
274
+ * declaration.
275
+ */
276
+ export type SocketSdkInstance<
277
+ Schema extends RecursiveSocketSchemaType,
278
+ S extends SocketInstance = SocketInstance,
279
+ > = InjectSocket<Schema, S> & {
280
+ $configure: (defaults: SocketSdkConfigurationMap<Schema>) => SocketSdkInstance<Schema, S>;
230
281
  };
231
282
 
232
283
  export const createSocketSdk = <S extends SocketInstance, RecursiveSchema extends RecursiveSocketSchemaType>(
233
284
  socket: S,
234
285
  options?: CreateSocketSdkOptions<RecursiveSchema>,
235
- ): SocketSdkInstance<RecursiveSchema> => {
286
+ ): SocketSdkInstance<RecursiveSchema, S> => {
236
287
  const { camelCaseToKebabCase = true, ...rest } = options ?? {};
237
288
 
238
289
  const mergedOptions: CreateSocketSdkOptions<RecursiveSchema> = { camelCaseToKebabCase, ...rest };
@@ -251,7 +302,7 @@ export const createSocketSdk = <S extends SocketInstance, RecursiveSchema extend
251
302
  }
252
303
  return target[key];
253
304
  },
254
- }) as SocketSdkInstance<RecursiveSchema>;
305
+ }) as SocketSdkInstance<RecursiveSchema, S>;
255
306
  };
256
307
 
257
308
  /**
@@ -1,7 +1,7 @@
1
1
  import type { SocketAdapterInstance } from "adapter";
2
+ import type { WebsocketAdapterType } from "adapter-websockets/websocket-adapter";
2
3
  import type { SocketOptionsType } from "socket";
3
4
  import { Socket } from "socket";
4
- import type { WebsocketAdapterType } from "adapter-websockets/websocket-adapter";
5
5
 
6
6
  export function createSocketClient<Adapter extends SocketAdapterInstance = WebsocketAdapterType>(
7
7
  options: SocketOptionsType<Adapter>,
@@ -1,5 +1,7 @@
1
+ import type { SocketAdapterInstance } from "adapter";
2
+ import type { EmitterInstance } from "emitter";
1
3
  import type EventEmitter from "events";
2
-
4
+ import type { ListenerInstance } from "listener";
3
5
  import {
4
6
  getErrorKey,
5
7
  getCloseKey,
@@ -16,9 +18,6 @@ import {
16
18
  getEmitterErrorKey,
17
19
  getEmitterErrorByTopicKey,
18
20
  } from "socket";
19
- import type { EmitterInstance } from "emitter";
20
- import type { ListenerInstance } from "listener";
21
- import type { SocketAdapterInstance } from "adapter";
22
21
  import type { ExtractAdapterExtraType } from "types";
23
22
 
24
23
  export const getSocketEvents = <Adapter extends SocketAdapterInstance>(eventEmitter: EventEmitter) =>
@@ -1,7 +1,13 @@
1
- import EventEmitter from "events";
2
1
  import type { LogLevel } from "@hyper-fetch/core";
3
2
  import { LoggerManager, AppManager, Time } from "@hyper-fetch/core";
4
-
3
+ import type { SocketAdapterInstance } from "adapter";
4
+ import type { WebsocketAdapterType } from "adapter-websockets/websocket-adapter";
5
+ import { WebsocketAdapter } from "adapter-websockets/websocket-adapter";
6
+ import type { EmitterInstance, EmitterOptionsType } from "emitter";
7
+ import { Emitter } from "emitter";
8
+ import EventEmitter from "events";
9
+ import type { ListenerOptionsType } from "listener";
10
+ import { Listener } from "listener";
5
11
  import type {
6
12
  SocketOptionsType,
7
13
  ReconnectCallbackType,
@@ -13,14 +19,7 @@ import type {
13
19
  ErrorCallbackType,
14
20
  } from "socket";
15
21
  import { getSocketEvents, interceptListener, interceptEmitter } from "socket";
16
- import type { ListenerOptionsType } from "listener";
17
- import { Listener } from "listener";
18
- import type { EmitterInstance, EmitterOptionsType } from "emitter";
19
- import { Emitter } from "emitter";
20
- import type { SocketAdapterInstance } from "adapter";
21
22
  import type { ExtractAdapterExtraType, ExtractAdapterQueryParamsType } from "types";
22
- import type { WebsocketAdapterType } from "adapter-websockets/websocket-adapter";
23
- import { WebsocketAdapter } from "adapter-websockets/websocket-adapter";
24
23
 
25
24
  export class Socket<Adapter extends SocketAdapterInstance = WebsocketAdapterType> {
26
25
  public emitter = new EventEmitter();
@@ -1,6 +1,6 @@
1
- import type { Socket } from "socket";
2
1
  import type { SocketAdapterInstance } from "adapter";
3
2
  import type { EmitterInstance } from "emitter";
3
+ import type { Socket } from "socket";
4
4
  import type { ExtractAdapterOptionsType, ExtractAdapterQueryParamsType } from "types";
5
5
 
6
6
  export type SocketInstance = Socket<SocketAdapterInstance>;
@@ -1,4 +1,5 @@
1
1
  import type { EmitterInstance } from "emitter";
2
+
2
3
  import type { MessageCallbackType, SendCallbackType } from "./socket.types";
3
4
 
4
5
  export const getErrorKey = () => "socket_error";
@@ -21,7 +22,7 @@ export const interceptListener = (interceptors: MessageCallbackType<any>[], even
21
22
  // eslint-disable-next-line no-restricted-syntax
22
23
  for (const interceptor of interceptors) {
23
24
  newResponse = interceptor({ event: event.data });
24
- if (!newResponse) throw new Error("Listener modifier must return data");
25
+ if (!newResponse) {throw new Error("Listener modifier must return data");}
25
26
  }
26
27
 
27
28
  return newResponse;
@@ -35,7 +36,7 @@ export const interceptEmitter = <EmitterType extends EmitterInstance>(
35
36
  // eslint-disable-next-line no-restricted-syntax
36
37
  for (const interceptor of interceptors) {
37
38
  newEmitter = interceptor({ emitter }) as EmitterType;
38
- if (!newEmitter) throw new Error("Send modifier must return emitter");
39
+ if (!newEmitter) {throw new Error("Send modifier must return emitter");}
39
40
  }
40
41
  return newEmitter;
41
42
  };
@@ -1 +1 @@
1
- export type TupleRestType<T> = T extends [first: any, ...rest: infer Rest] ? (Rest extends Array<any> ? Rest : []) : [];
1
+ export type TupleRestType<T> = T extends [first: any, ...rest: infer Rest] ? (Rest extends any[] ? Rest : []) : [];
@@ -3,26 +3,36 @@
3
3
  export const getSocketError = (event: Event): string => {
4
4
  if ("code" in event) {
5
5
  switch (event.code) {
6
- case 1000:
6
+ case 1000: {
7
7
  return "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
8
- case 1001:
8
+ }
9
+ case 1001: {
9
10
  return 'An endpoint is "going away", such as a server going down or a browser having navigated away from a page.';
10
- case 1002:
11
+ }
12
+ case 1002: {
11
13
  return "An endpoint is terminating the connection due to a protocol error";
12
- case 1003:
14
+ }
15
+ case 1003: {
13
16
  return "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
14
- case 1004:
17
+ }
18
+ case 1004: {
15
19
  return "Reserved. The specific meaning might be defined in the future.";
16
- case 1005:
20
+ }
21
+ case 1005: {
17
22
  return "No status code was actually present.";
18
- case 1006:
23
+ }
24
+ case 1006: {
19
25
  return "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
20
- case 1007:
26
+ }
27
+ case 1007: {
21
28
  return "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [https://www.rfc-editor.org/rfc/rfc3629] data within a text message).";
22
- case 1008:
29
+ }
30
+ case 1008: {
23
31
  return 'An endpoint is terminating the connection because it has received a message that "violates its policy". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.';
24
- case 1009:
32
+ }
33
+ case 1009: {
25
34
  return "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
35
+ }
26
36
  case 1010: {
27
37
  const reason = "reason" in event ? event.reason : null;
28
38
  // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
@@ -31,12 +41,15 @@ export const getSocketError = (event: Event): string => {
31
41
  (reason || "Unknown reason")
32
42
  );
33
43
  }
34
- case 1011:
44
+ case 1011: {
35
45
  return "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
36
- case 1015:
46
+ }
47
+ case 1015: {
37
48
  return "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
38
- default:
49
+ }
50
+ default: {
39
51
  return "Unknown reason";
52
+ }
40
53
  }
41
54
  }
42
55