@simplysm/service-server 14.0.4 → 14.0.6

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/docs/main.md DELETED
@@ -1,81 +0,0 @@
1
- # Main
2
-
3
- ## ServiceServer\<TAuthInfo\>
4
-
5
- Main server class. Extends `EventEmitter` with `ready` and `close` events. Manages Fastify, WebSocket connections, service routing, and event broadcasting.
6
-
7
- ```ts
8
- class ServiceServer<TAuthInfo = unknown> extends EventEmitter<{
9
- ready: void;
10
- close: void;
11
- }> {
12
- constructor(options: ServiceServerOptions);
13
- }
14
- ```
15
-
16
- ### Events
17
-
18
- | Event | Data Type | Description |
19
- |-------|-----------|-------------|
20
- | `ready` | `void` | Emitted when the server is listening and ready |
21
- | `close` | `void` | Emitted when the server has shut down |
22
-
23
- ### Properties
24
-
25
- | Property | Type | Description |
26
- |----------|------|-------------|
27
- | `isOpen` | `boolean` | Whether the server is currently listening |
28
- | `fastify` | `FastifyInstance` | Underlying Fastify instance for advanced configuration |
29
- | `options` | `ServiceServerOptions` | Server configuration options |
30
-
31
- ### Methods
32
-
33
- | Method | Parameters | Return | Description |
34
- |--------|-----------|--------|-------------|
35
- | `listen` | -- | `Promise<void>` | Start the server and begin accepting connections |
36
- | `close` | -- | `Promise<void>` | Gracefully shut down the server |
37
- | `emitEvent` | `eventDef: ServiceEventDef<TInfo, TData>`, `infoSelector: (item: TInfo) => boolean`, `data: TData` | `Promise<void>` | Broadcast an event to matching listeners across all connected sockets |
38
- | `signAuthToken` | `payload: AuthTokenPayload<TAuthInfo>` | `Promise<string>` | Sign a JWT token using the server's configured secret |
39
- | `verifyAuthToken` | `token: string` | `Promise<AuthTokenPayload<TAuthInfo>>` | Verify and decode a JWT token |
40
-
41
- ### Usage
42
-
43
- ```ts
44
- import { createServiceServer, defineService } from "@simplysm/service-server";
45
-
46
- const server = createServiceServer({
47
- rootPath: process.cwd(),
48
- port: 3000,
49
- auth: { jwtSecret: "secret" },
50
- services: [
51
- defineService("Hello", () => ({
52
- greet(name: string) { return `Hello, ${name}!`; },
53
- })),
54
- ],
55
- });
56
-
57
- server.on("ready", () => {
58
- // server is listening
59
- });
60
-
61
- await server.listen();
62
-
63
- // Later: shut down
64
- await server.close();
65
- ```
66
-
67
- ## createServiceServer
68
-
69
- Factory function to create a `ServiceServer` instance.
70
-
71
- ```ts
72
- function createServiceServer<TAuthInfo = unknown>(
73
- options: ServiceServerOptions,
74
- ): ServiceServer<TAuthInfo>;
75
- ```
76
-
77
- | Parameter | Type | Description |
78
- |-----------|------|-------------|
79
- | `options` | `ServiceServerOptions` | Server configuration |
80
-
81
- Returns a new `ServiceServer` instance. Call `listen()` to start accepting connections.
package/docs/protocol.md DELETED
@@ -1,31 +0,0 @@
1
- # Protocol
2
-
3
- Server-side protocol wrapper that automatically delegates heavy message encoding/decoding to worker threads.
4
-
5
- ## ServerProtocolWrapper
6
-
7
- Protocol wrapper interface. Heavy messages are encoded/decoded in a worker thread; lightweight messages are processed on the main thread.
8
-
9
- ```ts
10
- interface ServerProtocolWrapper {
11
- encode(uuid: string, message: ServiceMessage): Promise<{ chunks: Bytes[]; totalSize: number }>;
12
- decode(bytes: Bytes): Promise<ServiceMessageDecodeResult<ServiceMessage>>;
13
- dispose(): void;
14
- }
15
- ```
16
-
17
- | Method | Parameters | Return | Description |
18
- |--------|-----------|--------|-------------|
19
- | `encode` | `uuid: string`, `message: ServiceMessage` | `Promise<{ chunks: Bytes[]; totalSize: number }>` | Encode a message into binary chunks |
20
- | `decode` | `bytes: Bytes` | `Promise<ServiceMessageDecodeResult<ServiceMessage>>` | Decode received binary data |
21
- | `dispose` | -- | `void` | Dispose the wrapper and terminate worker threads |
22
-
23
- ## createServerProtocolWrapper
24
-
25
- Create a `ServerProtocolWrapper` instance.
26
-
27
- ```ts
28
- function createServerProtocolWrapper(): ServerProtocolWrapper;
29
- ```
30
-
31
- Returns a new protocol wrapper with automatic worker thread delegation for heavy payloads.
package/docs/services.md DELETED
@@ -1,63 +0,0 @@
1
- # Services
2
-
3
- Built-in service definitions that can be included in `ServiceServerOptions.services`.
4
-
5
- ## OrmService
6
-
7
- Built-in ORM service definition. Provides database connection management, transaction control, and query execution over the RPC layer. Supports MySQL, MSSQL, and PostgreSQL.
8
-
9
- ```ts
10
- const OrmService: ServiceDefinition<{
11
- getInfo(opt: DbConnOptions & { configName: string }): Promise<{ dialect: Dialect; database?: string; schema?: string }>;
12
- connect(opt: DbConnOptions & { configName: string }): Promise<number>;
13
- close(connId: number): Promise<void>;
14
- beginTransaction(connId: number, isolationLevel?: IsolationLevel): Promise<void>;
15
- commitTransaction(connId: number): Promise<void>;
16
- rollbackTransaction(connId: number): Promise<void>;
17
- executeParametrized(connId: number, query: string, params?: unknown[]): Promise<unknown[][]>;
18
- executeDefs(connId: number, defs: QueryDef[], options?: (ResultMeta | undefined)[]): Promise<unknown[][]>;
19
- bulkInsert(connId: number, tableName: string, columnDefs: Record<string, ColumnMeta>, records: Record<string, unknown>[]): Promise<void>;
20
- }>;
21
- ```
22
-
23
- | Method | Parameters | Return | Description |
24
- |--------|-----------|--------|-------------|
25
- | `getInfo` | `opt` | `Promise<{ dialect; database?; schema? }>` | Get database dialect and schema info |
26
- | `connect` | `opt` | `Promise<number>` | Open a connection; returns connection ID |
27
- | `close` | `connId` | `Promise<void>` | Close a connection |
28
- | `beginTransaction` | `connId`, `isolationLevel?` | `Promise<void>` | Begin a transaction |
29
- | `commitTransaction` | `connId` | `Promise<void>` | Commit the current transaction |
30
- | `rollbackTransaction` | `connId` | `Promise<void>` | Rollback the current transaction |
31
- | `executeParametrized` | `connId`, `query`, `params?` | `Promise<unknown[][]>` | Execute a parameterized SQL query |
32
- | `executeDefs` | `connId`, `defs`, `options?` | `Promise<unknown[][]>` | Execute query definitions |
33
- | `bulkInsert` | `connId`, `tableName`, `columnDefs`, `records` | `Promise<void>` | Bulk insert records into a table |
34
-
35
- ### OrmServiceType
36
-
37
- Utility type for extracting ORM service method signatures.
38
-
39
- ```ts
40
- type OrmServiceType = ServiceMethods<typeof OrmService>;
41
- ```
42
-
43
- ## AutoUpdateService
44
-
45
- Built-in auto-update service definition. Retrieves the latest version information for client applications by platform.
46
-
47
- ```ts
48
- const AutoUpdateService: ServiceDefinition<{
49
- getLastVersion(platform: string): Promise<{ version: string; downloadPath: string } | undefined>;
50
- }>;
51
- ```
52
-
53
- | Method | Parameters | Return | Description |
54
- |--------|-----------|--------|-------------|
55
- | `getLastVersion` | `platform: string` | `Promise<{ version; downloadPath } \| undefined>` | Get latest version info for a platform |
56
-
57
- ### AutoUpdateServiceType
58
-
59
- Utility type for extracting auto-update service method signatures.
60
-
61
- ```ts
62
- type AutoUpdateServiceType = ServiceMethods<typeof AutoUpdateService>;
63
- ```
package/docs/transport.md DELETED
@@ -1,169 +0,0 @@
1
- # Transport
2
-
3
- WebSocket and HTTP transport handlers for routing client messages to services.
4
-
5
- ## WebSocket Transport
6
-
7
- ### WebSocketHandler
8
-
9
- Manages multiple WebSocket connections, routes messages to services, and handles event broadcasting.
10
-
11
- ```ts
12
- interface WebSocketHandler {
13
- addSocket(socket: WebSocket, clientId: string, clientName: string, connReq: FastifyRequest): void;
14
- closeAll(): void;
15
- emit<TInfo, TData>(eventDef: ServiceEventDef<TInfo, TData>, infoSelector: (item: TInfo) => boolean, data: TData): Promise<void>;
16
- }
17
- ```
18
-
19
- | Method | Parameters | Return | Description |
20
- |--------|-----------|--------|-------------|
21
- | `addSocket` | `socket: WebSocket`, `clientId: string`, `clientName: string`, `connReq: FastifyRequest` | `void` | Register a new WebSocket connection |
22
- | `closeAll` | -- | `void` | Close all managed connections |
23
- | `emit` | `eventDef`, `infoSelector`, `data` | `Promise<void>` | Broadcast an event to matching listeners across all sockets |
24
-
25
- ### createWebSocketHandler
26
-
27
- Create a `WebSocketHandler` instance.
28
-
29
- ```ts
30
- function createWebSocketHandler(
31
- runMethod: (def: {
32
- serviceName: string;
33
- methodName: string;
34
- params: unknown[];
35
- socket?: ServiceSocket;
36
- }) => Promise<unknown>,
37
- jwtSecret: string | undefined,
38
- ): WebSocketHandler;
39
- ```
40
-
41
- | Parameter | Type | Description |
42
- |-----------|------|-------------|
43
- | `runMethod` | `(def) => Promise<unknown>` | Callback to execute a service method |
44
- | `jwtSecret` | `string \| undefined` | JWT secret for authenticating socket connections. `undefined` disables auth. |
45
-
46
- ### ServiceSocket
47
-
48
- Represents a single WebSocket connection with protocol encoding/decoding, ping/pong keep-alive, and event listener tracking.
49
-
50
- ```ts
51
- interface ServiceSocket {
52
- readonly connectedAtDateTime: DateTime;
53
- readonly clientName: string;
54
- readonly connReq: FastifyRequest;
55
- authTokenPayload?: AuthTokenPayload;
56
- close(): void;
57
- send(uuid: string, msg: ServiceServerMessage): Promise<number>;
58
- addListener(key: string, eventName: string, info: unknown): void;
59
- removeListener(key: string): void;
60
- getEventListeners(eventName: string): Array<{ key: string; info: unknown }>;
61
- filterEventTargetKeys(targetKeys: string[]): string[];
62
- on(event: "error", handler: (err: Error) => void): void;
63
- on(event: "close", handler: (code: number) => void): void;
64
- on(event: "message", handler: (data: { uuid: string; msg: ServiceClientMessage }) => void): void;
65
- }
66
- ```
67
-
68
- | Member | Kind | Type | Description |
69
- |--------|------|------|-------------|
70
- | `connectedAtDateTime` | property | `DateTime` | Connection timestamp |
71
- | `clientName` | property | `string` | Client identifier |
72
- | `connReq` | property | `FastifyRequest` | Original Fastify request |
73
- | `authTokenPayload` | property | `AuthTokenPayload?` | Authenticated token payload (set after auth message) |
74
- | `close` | method | `() => void` | Close the socket |
75
- | `send` | method | `(uuid, msg) => Promise<number>` | Send a server message; returns number of bytes sent |
76
- | `addListener` | method | `(key, eventName, info) => void` | Register an event listener on this socket |
77
- | `removeListener` | method | `(key) => void` | Remove an event listener by key |
78
- | `getEventListeners` | method | `(eventName) => Array<{ key; info }>` | Get all listeners for an event name |
79
- | `filterEventTargetKeys` | method | `(targetKeys) => string[]` | Filter target keys to only those on this socket |
80
- | `on("error")` | method | `(handler) => void` | Subscribe to error events |
81
- | `on("close")` | method | `(handler) => void` | Subscribe to close events (with close code) |
82
- | `on("message")` | method | `(handler) => void` | Subscribe to decoded message events |
83
-
84
- ### createServiceSocket
85
-
86
- Create a `ServiceSocket` instance wrapping a raw WebSocket.
87
-
88
- ```ts
89
- function createServiceSocket(
90
- socket: WebSocket,
91
- clientId: string,
92
- clientName: string,
93
- connReq: FastifyRequest,
94
- ): ServiceSocket;
95
- ```
96
-
97
- | Parameter | Type | Description |
98
- |-----------|------|-------------|
99
- | `socket` | `WebSocket` | Raw WebSocket instance |
100
- | `clientId` | `string` | Unique connection identifier |
101
- | `clientName` | `string` | Client name |
102
- | `connReq` | `FastifyRequest` | Fastify request that initiated the upgrade |
103
-
104
- ## HTTP Transport
105
-
106
- ### handleHttpRequest
107
-
108
- Handle an HTTP RPC request. Parses the request body, verifies authentication, executes the service method, and sends the response.
109
-
110
- ```ts
111
- async function handleHttpRequest<TAuthInfo = unknown>(
112
- req: FastifyRequest,
113
- reply: FastifyReply,
114
- jwtSecret: string | undefined,
115
- runMethod: (def: {
116
- serviceName: string;
117
- methodName: string;
118
- params: unknown[];
119
- http: { clientName: string; authTokenPayload?: AuthTokenPayload<TAuthInfo> };
120
- }) => Promise<unknown>,
121
- ): Promise<void>;
122
- ```
123
-
124
- | Parameter | Type | Description |
125
- |-----------|------|-------------|
126
- | `req` | `FastifyRequest` | Fastify request |
127
- | `reply` | `FastifyReply` | Fastify reply |
128
- | `jwtSecret` | `string \| undefined` | JWT secret. `undefined` disables auth verification. |
129
- | `runMethod` | `(def) => Promise<unknown>` | Callback to execute the service method |
130
-
131
- ### handleUpload
132
-
133
- Handle a file upload request. Saves uploaded files to the server's root path and returns upload results.
134
-
135
- ```ts
136
- async function handleUpload(
137
- req: FastifyRequest,
138
- reply: FastifyReply,
139
- rootPath: string,
140
- jwtSecret: string | undefined,
141
- ): Promise<void>;
142
- ```
143
-
144
- | Parameter | Type | Description |
145
- |-----------|------|-------------|
146
- | `req` | `FastifyRequest` | Fastify request (multipart) |
147
- | `reply` | `FastifyReply` | Fastify reply |
148
- | `rootPath` | `string` | Server root path for file storage |
149
- | `jwtSecret` | `string \| undefined` | JWT secret for auth verification |
150
-
151
- ### handleStaticFile
152
-
153
- Serve a static file from the server's root path.
154
-
155
- ```ts
156
- async function handleStaticFile(
157
- req: FastifyRequest,
158
- reply: FastifyReply,
159
- rootPath: string,
160
- urlPath: string,
161
- ): Promise<void>;
162
- ```
163
-
164
- | Parameter | Type | Description |
165
- |-----------|------|-------------|
166
- | `req` | `FastifyRequest` | Fastify request |
167
- | `reply` | `FastifyReply` | Fastify reply |
168
- | `rootPath` | `string` | Server root directory |
169
- | `urlPath` | `string` | URL path portion to resolve |
package/docs/types.md DELETED
@@ -1,31 +0,0 @@
1
- # Types
2
-
3
- ## ServiceServerOptions
4
-
5
- Server configuration options passed to `createServiceServer`.
6
-
7
- ```ts
8
- interface ServiceServerOptions {
9
- rootPath: string;
10
- port: number;
11
- ssl?: {
12
- pfxBytes: Uint8Array;
13
- passphrase: string;
14
- };
15
- auth?: {
16
- jwtSecret: string;
17
- } | false;
18
- services: ServiceDefinition[];
19
- }
20
- ```
21
-
22
- | Field | Type | Description |
23
- |-------|------|-------------|
24
- | `rootPath` | `string` | Root directory path for static files and uploads |
25
- | `port` | `number` | Server listening port |
26
- | `ssl` | `{ pfxBytes: Uint8Array; passphrase: string }?` | SSL/TLS configuration using a PFX certificate |
27
- | `ssl.pfxBytes` | `Uint8Array` | PFX certificate bytes |
28
- | `ssl.passphrase` | `string` | PFX passphrase |
29
- | `auth` | `{ jwtSecret: string } \| false` | JWT authentication configuration. Set to `false` to disable authentication. |
30
- | `auth.jwtSecret` | `string` | Secret key for JWT signing and verification |
31
- | `services` | `ServiceDefinition[]` | Array of service definitions to register |
package/docs/utilities.md DELETED
@@ -1,27 +0,0 @@
1
- # Utilities
2
-
3
- ## getConfig
4
-
5
- Read a configuration section from a JSON file.
6
-
7
- ```ts
8
- async function getConfig<TConfig>(filePath: string): Promise<TConfig | undefined>;
9
- ```
10
-
11
- | Parameter | Type | Description |
12
- |-----------|------|-------------|
13
- | `filePath` | `string` | Path to the configuration JSON file |
14
-
15
- Returns the parsed configuration object typed as `TConfig`, or `undefined` if the file does not exist.
16
-
17
- ```ts
18
- import { getConfig } from "@simplysm/service-server";
19
-
20
- interface DbConfig {
21
- host: string;
22
- port: number;
23
- database: string;
24
- }
25
-
26
- const dbConfig = await getConfig<DbConfig>("config/db.json");
27
- ```