shardwire 0.0.3 → 0.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/README.md CHANGED
@@ -24,6 +24,7 @@
24
24
  - [API Overview](#api-overview)
25
25
  - [Configuration](#configuration)
26
26
  - [Error Model](#error-model)
27
+ - [Recipes and Troubleshooting](#recipes-and-troubleshooting)
27
28
  - [Compatibility](#compatibility)
28
29
  - [Security Notes](#security-notes)
29
30
  - [Roadmap Constraints (v1)](#roadmap-constraints-v1)
@@ -44,6 +45,7 @@ Running bot logic inside your Discord host process while orchestrating it from e
44
45
  - **Single factory API** (`createShardwire`) with host and consumer overloads.
45
46
  - **Built-in reliability controls** with reconnect backoff, jitter, and timeouts.
46
47
  - **Runtime input validation** for config, names, and JSON-serializable payloads.
48
+ - **Optional schema validation** for command and event payloads.
47
49
  - **Optional token-only Discord mode** where shardwire can own client lifecycle.
48
50
  - **Dual package output** for ESM and CJS consumers.
49
51
 
@@ -59,7 +61,10 @@ Define shared message contracts:
59
61
 
60
62
  ```ts
61
63
  type Commands = {
62
- "ban-user": { userId: string };
64
+ "ban-user": {
65
+ request: { userId: string };
66
+ response: { banned: true; userId: string };
67
+ };
63
68
  };
64
69
 
65
70
  type Events = {
@@ -73,7 +78,10 @@ type Events = {
73
78
  import { createShardwire } from "shardwire";
74
79
 
75
80
  type Commands = {
76
- "ban-user": { userId: string };
81
+ "ban-user": {
82
+ request: { userId: string };
83
+ response: { banned: true; userId: string };
84
+ };
77
85
  };
78
86
 
79
87
  type Events = {
@@ -104,7 +112,10 @@ wire.emitEvent("member-joined", { userId: "123", guildId: "456" });
104
112
  import { createShardwire } from "shardwire";
105
113
 
106
114
  type Commands = {
107
- "ban-user": { userId: string };
115
+ "ban-user": {
116
+ request: { userId: string };
117
+ response: { banned: true; userId: string };
118
+ };
108
119
  };
109
120
 
110
121
  type Events = {
@@ -115,6 +126,7 @@ const wire = createShardwire<Commands, Events>({
115
126
  url: "ws://localhost:3001/shardwire",
116
127
  secret: process.env.SHARDWIRE_SECRET!,
117
128
  secretId: "s0",
129
+ clientName: "dashboard-api",
118
130
  });
119
131
 
120
132
  const result = await wire.send("ban-user", { userId: "123" });
@@ -128,6 +140,12 @@ if (result.ok) {
128
140
  wire.on("member-joined", (payload, meta) => {
129
141
  console.log("event", payload, meta.ts);
130
142
  });
143
+
144
+ wire.onReconnecting(({ attempt, delayMs }) => {
145
+ console.warn(`reconnecting attempt ${attempt} in ${delayMs}ms`);
146
+ });
147
+
148
+ await wire.ready();
131
149
  ```
132
150
 
133
151
  ## Token-Only Host (No Existing discord.js Client)
@@ -167,6 +185,38 @@ const wire = createShardwire({
167
185
  });
168
186
  ```
169
187
 
188
+ ## Schema Validation (Zod)
189
+
190
+ Use runtime schemas to validate command request/response payloads and emitted event payloads.
191
+
192
+ ```ts
193
+ import { z } from "zod";
194
+ import { createShardwire, fromZodSchema } from "shardwire";
195
+
196
+ type Commands = {
197
+ "ban-user": {
198
+ request: { userId: string };
199
+ response: { banned: true; userId: string };
200
+ };
201
+ };
202
+
203
+ const wire = createShardwire<Commands, {}>({
204
+ server: {
205
+ port: 3001,
206
+ secrets: [process.env.SHARDWIRE_SECRET!],
207
+ primarySecretId: "s0",
208
+ },
209
+ validation: {
210
+ commands: {
211
+ "ban-user": {
212
+ request: fromZodSchema(z.object({ userId: z.string().min(3) })),
213
+ response: fromZodSchema(z.object({ banned: z.literal(true), userId: z.string() })),
214
+ },
215
+ },
216
+ },
217
+ });
218
+ ```
219
+
170
220
  ## API Overview
171
221
 
172
222
  ### Host API
@@ -181,7 +231,12 @@ const wire = createShardwire({
181
231
  - `wire.send(name, payload, options?)` send command and await typed result.
182
232
  - `wire.on(name, handler)` subscribe to events.
183
233
  - `wire.off(name, handler)` unsubscribe a specific handler.
234
+ - `wire.ready()` wait for authenticated connection.
235
+ - `wire.onConnected(handler)` subscribe to authenticated connection events.
236
+ - `wire.onDisconnected(handler)` subscribe to disconnect events.
237
+ - `wire.onReconnecting(handler)` subscribe to reconnect scheduling events.
184
238
  - `wire.connected()` check authenticated connection state.
239
+ - `wire.connectionId()` get current authenticated connection id (or `null`).
185
240
  - `wire.close()` close socket and stop reconnect attempts.
186
241
 
187
242
  ## Configuration
@@ -205,6 +260,7 @@ const wire = createShardwire({
205
260
  - `url` host endpoint (for example `ws://localhost:3001/shardwire`).
206
261
  - `secret` shared secret matching host.
207
262
  - `secretId` optional secret id (for example `"s0"`) used during handshake.
263
+ - `clientName` optional identity sent during auth handshake for host-side telemetry.
208
264
  - `requestTimeoutMs` default timeout for `send`.
209
265
  - `reconnect` reconnect policy (`enabled`, delays, jitter).
210
266
  - `webSocketFactory` optional custom client implementation.
@@ -219,14 +275,46 @@ const wire = createShardwire({
219
275
  - success: `{ ok: true, requestId, ts, data }`
220
276
  - failure: `{ ok: false, requestId, ts, error }`
221
277
 
278
+ When `error.code === "VALIDATION_ERROR"`, `error.details` includes:
279
+
280
+ - `name`: command/event name
281
+ - `stage`: `"command.request" | "command.response" | "event.emit"`
282
+ - `issues`: optional normalized issue list (`path`, `message`)
283
+
222
284
  Failure codes:
223
285
 
224
286
  - `UNAUTHORIZED`
225
287
  - `TIMEOUT`
288
+ - `DISCONNECTED`
226
289
  - `COMMAND_NOT_FOUND`
227
290
  - `VALIDATION_ERROR`
228
291
  - `INTERNAL_ERROR`
229
292
 
293
+ ## Recipes and Troubleshooting
294
+
295
+ Run local examples:
296
+
297
+ ```bash
298
+ pnpm run example:host
299
+ pnpm run example:consumer
300
+ pnpm run example:host:schema
301
+ pnpm run example:consumer:schema
302
+ ```
303
+
304
+ Practical guides:
305
+
306
+ - [Integration reference](./.agents/skills/shardwire/references.md)
307
+ - [Add command + event flow](./.agents/skills/shardwire/examples/command-event-change.md)
308
+ - [Reconnect hardening](./.agents/skills/shardwire/examples/reconnect-hardening.md)
309
+ - [Token-only host setup](./.agents/skills/shardwire/examples/token-only-host.md)
310
+ - [Troubleshooting flow](./.agents/skills/shardwire/examples/troubleshooting-flow.md)
311
+
312
+ Common symptoms:
313
+
314
+ - `UNAUTHORIZED`: verify `secret`, `secretId`, and host `server.secrets` ordering.
315
+ - `DISCONNECTED`: host unavailable or connection dropped before response completed.
316
+ - Frequent `TIMEOUT`: increase `requestTimeoutMs` and inspect host command handler duration.
317
+
230
318
  ## Compatibility
231
319
 
232
320
  - Node.js `>=18.18`
package/dist/index.d.mts CHANGED
@@ -1,5 +1,20 @@
1
- type CommandMap = Record<string, unknown>;
1
+ import { ZodType } from 'zod';
2
+
3
+ interface CommandSchema<Request = unknown, Response = unknown> {
4
+ request: Request;
5
+ response: Response;
6
+ }
7
+ type CommandMap = Record<string, unknown | CommandSchema>;
2
8
  type EventMap = Record<string, unknown>;
9
+ interface SchemaValidationIssue {
10
+ path: string;
11
+ message: string;
12
+ }
13
+ interface RuntimeSchema<T = unknown> {
14
+ parse: (value: unknown) => T;
15
+ }
16
+ type CommandRequestOf<T> = T extends CommandSchema<infer Request, any> ? Request : T;
17
+ type CommandResponseOf<T> = T extends CommandSchema<any, infer Response> ? Response : unknown;
3
18
  type Unsubscribe = () => void;
4
19
  interface ShardwireLogger {
5
20
  debug?: (message: string, meta?: Record<string, unknown>) => void;
@@ -35,7 +50,7 @@ interface CommandFailure {
35
50
  requestId: string;
36
51
  ts: number;
37
52
  error: {
38
- code: "UNAUTHORIZED" | "TIMEOUT" | "COMMAND_NOT_FOUND" | "VALIDATION_ERROR" | "INTERNAL_ERROR";
53
+ code: "UNAUTHORIZED" | "TIMEOUT" | "DISCONNECTED" | "COMMAND_NOT_FOUND" | "VALIDATION_ERROR" | "INTERNAL_ERROR";
39
54
  message: string;
40
55
  details?: unknown;
41
56
  };
@@ -55,6 +70,17 @@ interface HostOptions<C extends CommandMap, E extends EventMap> {
55
70
  maxPayloadBytes?: number;
56
71
  corsOrigins?: string[];
57
72
  };
73
+ validation?: {
74
+ commands?: Partial<{
75
+ [K in keyof C & string]: {
76
+ request?: RuntimeSchema<CommandRequestOf<C[K]>>;
77
+ response?: RuntimeSchema<CommandResponseOf<C[K]>>;
78
+ };
79
+ }>;
80
+ events?: Partial<{
81
+ [K in keyof E & string]: RuntimeSchema<E[K]>;
82
+ }>;
83
+ };
58
84
  name?: string;
59
85
  logger?: ShardwireLogger;
60
86
  }
@@ -62,6 +88,7 @@ interface ConsumerOptions<C extends CommandMap, E extends EventMap> {
62
88
  url: string;
63
89
  secret: string;
64
90
  secretId?: string;
91
+ clientName?: string;
65
92
  webSocketFactory?: (url: string) => {
66
93
  readyState: number;
67
94
  send(data: string): void;
@@ -80,24 +107,63 @@ interface ConsumerOptions<C extends CommandMap, E extends EventMap> {
80
107
  }
81
108
  interface HostShardwire<C extends CommandMap, E extends EventMap> {
82
109
  mode: "host";
83
- onCommand<K extends keyof C & string>(name: K, handler: (payload: C[K], ctx: CommandContext) => Promise<unknown> | unknown): Unsubscribe;
110
+ onCommand<K extends keyof C & string>(name: K, handler: (payload: CommandRequestOf<C[K]>, ctx: CommandContext) => Promise<CommandResponseOf<C[K]>> | CommandResponseOf<C[K]>): Unsubscribe;
84
111
  emitEvent<K extends keyof E & string>(name: K, payload: E[K]): void;
85
112
  broadcast<K extends keyof E & string>(name: K, payload: E[K]): void;
86
113
  close(): Promise<void>;
87
114
  }
88
115
  interface ConsumerShardwire<C extends CommandMap, E extends EventMap> {
89
116
  mode: "consumer";
90
- send<K extends keyof C & string>(name: K, payload: C[K], options?: {
117
+ send<K extends keyof C & string>(name: K, payload: CommandRequestOf<C[K]>, options?: {
91
118
  timeoutMs?: number;
92
119
  requestId?: string;
93
- }): Promise<CommandResult>;
120
+ }): Promise<CommandResult<CommandResponseOf<C[K]>>>;
94
121
  on<K extends keyof E & string>(name: K, handler: (payload: E[K], meta: EventMeta) => void): Unsubscribe;
95
122
  off<K extends keyof E & string>(name: K, handler: (payload: E[K], meta: EventMeta) => void): void;
123
+ onConnected(handler: (info: {
124
+ connectionId: string;
125
+ connectedAt: number;
126
+ }) => void): Unsubscribe;
127
+ onDisconnected(handler: (info: {
128
+ reason: string;
129
+ at: number;
130
+ willReconnect: boolean;
131
+ }) => void): Unsubscribe;
132
+ onReconnecting(handler: (info: {
133
+ attempt: number;
134
+ delayMs: number;
135
+ at: number;
136
+ }) => void): Unsubscribe;
137
+ ready(): Promise<void>;
96
138
  connected(): boolean;
139
+ connectionId(): string | null;
97
140
  close(): Promise<void>;
98
141
  }
142
+ interface CreateShardwire {
143
+ <C extends CommandMap = {}, E extends EventMap = {}>(options: HostOptions<C, E>): HostShardwire<C, E>;
144
+ <C extends CommandMap = {}, E extends EventMap = {}>(options: ConsumerOptions<C, E>): ConsumerShardwire<C, E>;
145
+ }
146
+
147
+ interface SafeParseResultSuccess<T> {
148
+ success: true;
149
+ data: T;
150
+ }
151
+ interface SafeParseResultFailure {
152
+ success: false;
153
+ error: {
154
+ message: string;
155
+ issues?: SchemaValidationIssue[];
156
+ };
157
+ }
158
+ type SafeParseResult<T> = SafeParseResultSuccess<T> | SafeParseResultFailure;
159
+ interface SafeParseSchema<T> {
160
+ safeParse: (value: unknown) => SafeParseResult<T>;
161
+ }
162
+ declare function fromSafeParseSchema<T>(schema: SafeParseSchema<T>): RuntimeSchema<T>;
163
+
164
+ declare function fromZodSchema<T>(schema: ZodType<T>): RuntimeSchema<T>;
99
165
 
100
166
  declare function createShardwire<C extends CommandMap = {}, E extends EventMap = {}>(options: HostOptions<C, E>): HostShardwire<C, E>;
101
167
  declare function createShardwire<C extends CommandMap = {}, E extends EventMap = {}>(options: ConsumerOptions<C, E>): ConsumerShardwire<C, E>;
102
168
 
103
- export { type CommandContext, type CommandFailure, type CommandMap, type CommandResult, type CommandSuccess, type ConsumerOptions, type ConsumerShardwire, type DiscordClientLike, type EventMap, type EventMeta, type HostOptions, type HostShardwire, type ShardwireLogger, type Unsubscribe, createShardwire };
169
+ export { type CommandContext, type CommandFailure, type CommandMap, type CommandRequestOf, type CommandResponseOf, type CommandResult, type CommandSchema, type CommandSuccess, type ConsumerOptions, type ConsumerShardwire, type CreateShardwire, type DiscordClientLike, type EventMap, type EventMeta, type HostOptions, type HostShardwire, type RuntimeSchema, type SchemaValidationIssue, type ShardwireLogger, type Unsubscribe, createShardwire, fromSafeParseSchema, fromZodSchema };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,20 @@
1
- type CommandMap = Record<string, unknown>;
1
+ import { ZodType } from 'zod';
2
+
3
+ interface CommandSchema<Request = unknown, Response = unknown> {
4
+ request: Request;
5
+ response: Response;
6
+ }
7
+ type CommandMap = Record<string, unknown | CommandSchema>;
2
8
  type EventMap = Record<string, unknown>;
9
+ interface SchemaValidationIssue {
10
+ path: string;
11
+ message: string;
12
+ }
13
+ interface RuntimeSchema<T = unknown> {
14
+ parse: (value: unknown) => T;
15
+ }
16
+ type CommandRequestOf<T> = T extends CommandSchema<infer Request, any> ? Request : T;
17
+ type CommandResponseOf<T> = T extends CommandSchema<any, infer Response> ? Response : unknown;
3
18
  type Unsubscribe = () => void;
4
19
  interface ShardwireLogger {
5
20
  debug?: (message: string, meta?: Record<string, unknown>) => void;
@@ -35,7 +50,7 @@ interface CommandFailure {
35
50
  requestId: string;
36
51
  ts: number;
37
52
  error: {
38
- code: "UNAUTHORIZED" | "TIMEOUT" | "COMMAND_NOT_FOUND" | "VALIDATION_ERROR" | "INTERNAL_ERROR";
53
+ code: "UNAUTHORIZED" | "TIMEOUT" | "DISCONNECTED" | "COMMAND_NOT_FOUND" | "VALIDATION_ERROR" | "INTERNAL_ERROR";
39
54
  message: string;
40
55
  details?: unknown;
41
56
  };
@@ -55,6 +70,17 @@ interface HostOptions<C extends CommandMap, E extends EventMap> {
55
70
  maxPayloadBytes?: number;
56
71
  corsOrigins?: string[];
57
72
  };
73
+ validation?: {
74
+ commands?: Partial<{
75
+ [K in keyof C & string]: {
76
+ request?: RuntimeSchema<CommandRequestOf<C[K]>>;
77
+ response?: RuntimeSchema<CommandResponseOf<C[K]>>;
78
+ };
79
+ }>;
80
+ events?: Partial<{
81
+ [K in keyof E & string]: RuntimeSchema<E[K]>;
82
+ }>;
83
+ };
58
84
  name?: string;
59
85
  logger?: ShardwireLogger;
60
86
  }
@@ -62,6 +88,7 @@ interface ConsumerOptions<C extends CommandMap, E extends EventMap> {
62
88
  url: string;
63
89
  secret: string;
64
90
  secretId?: string;
91
+ clientName?: string;
65
92
  webSocketFactory?: (url: string) => {
66
93
  readyState: number;
67
94
  send(data: string): void;
@@ -80,24 +107,63 @@ interface ConsumerOptions<C extends CommandMap, E extends EventMap> {
80
107
  }
81
108
  interface HostShardwire<C extends CommandMap, E extends EventMap> {
82
109
  mode: "host";
83
- onCommand<K extends keyof C & string>(name: K, handler: (payload: C[K], ctx: CommandContext) => Promise<unknown> | unknown): Unsubscribe;
110
+ onCommand<K extends keyof C & string>(name: K, handler: (payload: CommandRequestOf<C[K]>, ctx: CommandContext) => Promise<CommandResponseOf<C[K]>> | CommandResponseOf<C[K]>): Unsubscribe;
84
111
  emitEvent<K extends keyof E & string>(name: K, payload: E[K]): void;
85
112
  broadcast<K extends keyof E & string>(name: K, payload: E[K]): void;
86
113
  close(): Promise<void>;
87
114
  }
88
115
  interface ConsumerShardwire<C extends CommandMap, E extends EventMap> {
89
116
  mode: "consumer";
90
- send<K extends keyof C & string>(name: K, payload: C[K], options?: {
117
+ send<K extends keyof C & string>(name: K, payload: CommandRequestOf<C[K]>, options?: {
91
118
  timeoutMs?: number;
92
119
  requestId?: string;
93
- }): Promise<CommandResult>;
120
+ }): Promise<CommandResult<CommandResponseOf<C[K]>>>;
94
121
  on<K extends keyof E & string>(name: K, handler: (payload: E[K], meta: EventMeta) => void): Unsubscribe;
95
122
  off<K extends keyof E & string>(name: K, handler: (payload: E[K], meta: EventMeta) => void): void;
123
+ onConnected(handler: (info: {
124
+ connectionId: string;
125
+ connectedAt: number;
126
+ }) => void): Unsubscribe;
127
+ onDisconnected(handler: (info: {
128
+ reason: string;
129
+ at: number;
130
+ willReconnect: boolean;
131
+ }) => void): Unsubscribe;
132
+ onReconnecting(handler: (info: {
133
+ attempt: number;
134
+ delayMs: number;
135
+ at: number;
136
+ }) => void): Unsubscribe;
137
+ ready(): Promise<void>;
96
138
  connected(): boolean;
139
+ connectionId(): string | null;
97
140
  close(): Promise<void>;
98
141
  }
142
+ interface CreateShardwire {
143
+ <C extends CommandMap = {}, E extends EventMap = {}>(options: HostOptions<C, E>): HostShardwire<C, E>;
144
+ <C extends CommandMap = {}, E extends EventMap = {}>(options: ConsumerOptions<C, E>): ConsumerShardwire<C, E>;
145
+ }
146
+
147
+ interface SafeParseResultSuccess<T> {
148
+ success: true;
149
+ data: T;
150
+ }
151
+ interface SafeParseResultFailure {
152
+ success: false;
153
+ error: {
154
+ message: string;
155
+ issues?: SchemaValidationIssue[];
156
+ };
157
+ }
158
+ type SafeParseResult<T> = SafeParseResultSuccess<T> | SafeParseResultFailure;
159
+ interface SafeParseSchema<T> {
160
+ safeParse: (value: unknown) => SafeParseResult<T>;
161
+ }
162
+ declare function fromSafeParseSchema<T>(schema: SafeParseSchema<T>): RuntimeSchema<T>;
163
+
164
+ declare function fromZodSchema<T>(schema: ZodType<T>): RuntimeSchema<T>;
99
165
 
100
166
  declare function createShardwire<C extends CommandMap = {}, E extends EventMap = {}>(options: HostOptions<C, E>): HostShardwire<C, E>;
101
167
  declare function createShardwire<C extends CommandMap = {}, E extends EventMap = {}>(options: ConsumerOptions<C, E>): ConsumerShardwire<C, E>;
102
168
 
103
- export { type CommandContext, type CommandFailure, type CommandMap, type CommandResult, type CommandSuccess, type ConsumerOptions, type ConsumerShardwire, type DiscordClientLike, type EventMap, type EventMeta, type HostOptions, type HostShardwire, type ShardwireLogger, type Unsubscribe, createShardwire };
169
+ export { type CommandContext, type CommandFailure, type CommandMap, type CommandRequestOf, type CommandResponseOf, type CommandResult, type CommandSchema, type CommandSuccess, type ConsumerOptions, type ConsumerShardwire, type CreateShardwire, type DiscordClientLike, type EventMap, type EventMeta, type HostOptions, type HostShardwire, type RuntimeSchema, type SchemaValidationIssue, type ShardwireLogger, type Unsubscribe, createShardwire, fromSafeParseSchema, fromZodSchema };