@thomas57/rennari-client-js 0.0.0-stage → 0.2.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 ADDED
@@ -0,0 +1,78 @@
1
+ # rennari-client-js
2
+
3
+ A JavaScript client for Rennari servers: events, namespaces, acknowledgements, automatic reconnection with session recovery, MessagePack or JSON. Runs in Node.js and browsers.
4
+
5
+ ## Quick start
6
+
7
+ npx rennari-client new my-client # single-file client
8
+ npx rennari-client new my-client --app # one file per event handler
9
+
10
+ cd my-client
11
+ npm install
12
+ # edit config.js: set url and token
13
+ npm start
14
+
15
+ ## Install
16
+
17
+ npm install @thomas57/rennari-client-js ws
18
+
19
+ `ws` is only needed in Node.js.
20
+
21
+ ## Connect (Node.js)
22
+
23
+ import { WebSocket } from 'ws';
24
+ import { Rennari, setWebSocket } from '@thomas57/rennari-client-js';
25
+
26
+ setWebSocket(WebSocket);
27
+
28
+ const client = new Rennari('ws://localhost:3000/ws', {
29
+ serializer: 'msgpack',
30
+ headers: { 'X-Rennari-App-Token': token },
31
+ });
32
+
33
+ client.on('connect', () => client.emit('ping', { n: 1 }));
34
+ client.on('pong', (payload) => console.log(payload.got.n));
35
+
36
+ await client.connect();
37
+
38
+ Load `token` from a private config file. Never put it in the URL, an environment variable or a command-line argument.
39
+
40
+ ## Authentication
41
+
42
+ - **Node.js:** the `headers` option sends `X-Rennari-App-Token: <raw token>` during the handshake. It is not a Bearer token.
43
+ - **Browsers and Node.js:** the `auth` option sends a first-message frame instead. Browsers cannot set custom headers.
44
+
45
+ See [docs/authentication.md](docs/authentication.md).
46
+
47
+ ## Features
48
+
49
+ - Namespaces: `client.of('/chat')`
50
+ - Acknowledgements: `await client.emitWithAck(event, payload)`
51
+ - Reconnection with exponential backoff and jitter
52
+ - Session recovery after a dropped connection
53
+ - Offline outbox while reconnecting
54
+
55
+ ## Documentation
56
+
57
+ - [Getting started](docs/getting-started.md)
58
+ - [Concepts](docs/concepts.md)
59
+ - [API reference](docs/api.md)
60
+ - [Authentication](docs/authentication.md)
61
+ - [Troubleshooting](docs/troubleshooting.md)
62
+ - [Testing and compatibility](docs/testing.md)
63
+
64
+ ## Project generator
65
+
66
+ rennari-client new <name> [--lite | --app] [--client-path <dir>]
67
+
68
+ The generator refuses a non-empty folder and never accepts a token on the command line.
69
+
70
+ ## Testing
71
+
72
+ npm test
73
+
74
+ Integration tests need the Perl implementation: `RENNARI_PERL_DIR=/path/to/perl npm test`. See [docs/testing.md](docs/testing.md).
75
+
76
+ ## License
77
+
78
+ TODO: add your license.
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ mkdirSync, readdirSync, readFileSync, writeFileSync, existsSync,
4
+ } from 'node:fs';
5
+ import { join, resolve, dirname, basename, relative, sep } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const NAME_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
9
+ const TEMPLATES = fileURLToPath(new URL('../templates/', import.meta.url));
10
+ const RENAMES = { _gitignore: '.gitignore' }; // npm strips real .gitignore files
11
+
12
+ function usage() {
13
+ return [
14
+ 'Usage: rennari-client new <name> [--lite | --app] [--client-path <dir>]',
15
+ '',
16
+ ' --lite single-file client (default)',
17
+ ' --app larger app with one file per event handler',
18
+ ' --client-path use a local copy of the client package (file: dependency)',
19
+ ' --help show this help',
20
+ '',
21
+ 'Tokens are never accepted here. Put the token in config.js after generating.',
22
+ ].join('\n');
23
+ }
24
+
25
+ function fail(message) {
26
+ console.error(`rennari-client: ${message}\n\n${usage()}`);
27
+ process.exit(2);
28
+ }
29
+
30
+ function parseArgs(argv) {
31
+ const opts = { kind: 'lite', clientPath: null, name: null, help: false };
32
+ for (let i = 0; i < argv.length; i++) {
33
+ const a = argv[i];
34
+ if (a === '--help' || a === '-h') opts.help = true;
35
+ else if (a === '--lite') opts.kind = 'lite';
36
+ else if (a === '--app') opts.kind = 'app';
37
+ else if (a === '--client-path') {
38
+ opts.clientPath = argv[++i];
39
+ if (!opts.clientPath) fail('--client-path needs a value');
40
+ } else if (a.startsWith('-')) fail(`unknown option ${a}`);
41
+ else if (opts.name === null) opts.name = a;
42
+ else fail('too many arguments');
43
+ }
44
+ return opts;
45
+ }
46
+
47
+ function* walk(dir, rel = '') {
48
+ for (const entry of readdirSync(join(dir, rel), { withFileTypes: true })) {
49
+ const r = join(rel, entry.name);
50
+ if (entry.isDirectory()) yield* walk(dir, r);
51
+ else yield r;
52
+ }
53
+ }
54
+
55
+ function main() {
56
+ const argv = process.argv.slice(2);
57
+ if (argv.length === 0 || argv[0] === '--help' || argv[0] === '-h') {
58
+ console.log(usage());
59
+ return;
60
+ }
61
+ if (argv[0] !== 'new') fail(`unknown command '${argv[0]}'`);
62
+
63
+ const opts = parseArgs(argv.slice(1));
64
+ if (opts.help) { console.log(usage()); return; }
65
+ if (!opts.name) fail('project name is required');
66
+ if (!NAME_RE.test(opts.name)) {
67
+ fail('name must be lowercase letters, numbers, dot, dash or underscore (max 64)');
68
+ }
69
+
70
+ const source = join(TEMPLATES, opts.kind);
71
+ if (!existsSync(source)) fail(`the '${opts.kind}' template is not available yet`);
72
+
73
+ const target = resolve(opts.name);
74
+ if (existsSync(target) && readdirSync(target).length > 0) {
75
+ fail(`'${opts.name}' already exists and is not empty`);
76
+ }
77
+
78
+ let clientDep = '^0.1.0';
79
+ if (opts.clientPath) {
80
+ const clientDir = resolve(opts.clientPath);
81
+ if (!existsSync(join(clientDir, 'package.json'))) {
82
+ fail(`no package.json in ${clientDir}`);
83
+ }
84
+ const rel = relative(target, clientDir).split(sep).join('/');
85
+ clientDep = `file:${rel}`;
86
+ }
87
+
88
+ mkdirSync(target, { recursive: true });
89
+
90
+ for (const rel of walk(source)) {
91
+ const text = readFileSync(join(source, rel), 'utf8')
92
+ .replace(/\{\{name\}\}/g, opts.name)
93
+ .replace(/\{\{clientDep\}\}/g, clientDep);
94
+ const base = basename(rel);
95
+ const destRel = join(dirname(rel), RENAMES[base] ?? base);
96
+ const dest = join(target, destRel);
97
+ mkdirSync(dirname(dest), { recursive: true });
98
+ writeFileSync(dest, text, { flag: 'wx' });
99
+ }
100
+
101
+ // Private config with a placeholder token that fails validation until edited.
102
+ const example = readFileSync(join(target, 'config.example.js'), 'utf8');
103
+ writeFileSync(join(target, 'config.js'), example, { flag: 'wx', mode: 0o600 });
104
+
105
+ console.log([
106
+ `Created ${opts.kind} client in ${target}`,
107
+ '',
108
+ 'Next steps:',
109
+ ` cd ${opts.name}`,
110
+ ' npm install',
111
+ ' edit config.js (url and token)',
112
+ ' npm start',
113
+ ].join('\n'));
114
+ }
115
+
116
+ main();
package/package.json CHANGED
@@ -1,6 +1,22 @@
1
1
  {
2
2
  "name": "@thomas57/rennari-client-js",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "main": "src/index.js",
6
+ "bin": {
7
+ "rennari-client": "./bin/rennari-client.mjs"
8
+ },
9
+ "files": [
10
+ "src",
11
+ "bin",
12
+ "templates",
13
+ "README.md"
14
+ ],
15
+ "scripts": {
16
+ "test": "node --test \"tests/*.test.js\""
17
+ },
18
+ "dependencies": {
19
+ "@msgpack/msgpack": "^3.0.0",
20
+ "ws": "^8.23.0"
21
+ }
22
+ }
package/src/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export const VERSION = '0.1.0';
2
+ export { Rennari, Rennari as default, setWebSocket } from './rennari.js';
@@ -0,0 +1,104 @@
1
+ import { encode, decode } from '@msgpack/msgpack';
2
+
3
+ export const DEFAULT_MAX_BYTES = 64 * 1024;
4
+
5
+ const EVENT_RE = /^[A-Za-z0-9_.:-]{1,64}$/;
6
+ const NSP_RE = /^\/[A-Za-z0-9_.:/-]{0,63}$/;
7
+ const ID_RE = /^[0-9]{1,20}$/;
8
+ const OFFSET_RE = /^[0-9]+$/;
9
+
10
+ export function validEventName(name) {
11
+ return typeof name === 'string' && EVENT_RE.test(name);
12
+ }
13
+
14
+ export function validId(id) {
15
+ if (id === undefined || id === null) return false;
16
+ return ID_RE.test(String(id));
17
+ }
18
+
19
+ export function validOffset(o) {
20
+ if (o === undefined || o === null) return false;
21
+ return OFFSET_RE.test(String(o));
22
+ }
23
+
24
+ export function validNamespaceName(name) {
25
+ return typeof name === 'string' && NSP_RE.test(name);
26
+ }
27
+
28
+ function checkSerializer(s) {
29
+ const v = s ?? 'msgpack';
30
+ if (v !== 'msgpack' && v !== 'json') {
31
+ throw new Error(`unsupported serializer '${v}'`);
32
+ }
33
+ return v;
34
+ }
35
+
36
+ export function encodeFrame(event, payload, opts = {}) {
37
+ if (!validEventName(event)) {
38
+ throw new Error('encodeFrame: invalid event name');
39
+ }
40
+ const serializer = checkSerializer(opts.serializer);
41
+ const frame = { e: event, d: payload };
42
+
43
+ if (opts.id !== undefined && opts.id !== null) {
44
+ if (!validId(opts.id)) throw new Error('encodeFrame: invalid id');
45
+ frame.id = Number(opts.id);
46
+ }
47
+ if (opts.offset !== undefined && opts.offset !== null) {
48
+ if (!validOffset(opts.offset)) throw new Error('encodeFrame: invalid offset');
49
+ frame.o = Number(opts.offset);
50
+ }
51
+ if (opts.namespace !== undefined && opts.namespace !== null && opts.namespace !== '/') {
52
+ if (!validNamespaceName(opts.namespace)) {
53
+ throw new Error('encodeFrame: invalid namespace');
54
+ }
55
+ frame.n = opts.namespace;
56
+ }
57
+
58
+ if (serializer === 'json') {
59
+ return new TextEncoder().encode(JSON.stringify(frame));
60
+ }
61
+ return encode(frame);
62
+ }
63
+
64
+ export function decodeFrame(bytes, opts = {}) {
65
+ if (bytes === undefined || bytes === null) return null;
66
+ let buf;
67
+ if (bytes instanceof Uint8Array) buf = bytes;
68
+ else if (bytes instanceof ArrayBuffer) buf = new Uint8Array(bytes);
69
+ else return null;
70
+
71
+ const max = opts.max_bytes ?? DEFAULT_MAX_BYTES;
72
+ if (buf.length > max) return null;
73
+
74
+ const serializer = checkSerializer(opts.serializer);
75
+
76
+ let frame;
77
+ try {
78
+ if (serializer === 'json') {
79
+ frame = JSON.parse(new TextDecoder().decode(buf));
80
+ } else {
81
+ frame = decode(buf);
82
+ }
83
+ } catch (_e) {
84
+ return null;
85
+ }
86
+
87
+ if (!frame || typeof frame !== 'object' || Array.isArray(frame)) return null;
88
+ if (!validEventName(frame.e)) return null;
89
+ if (!Object.prototype.hasOwnProperty.call(frame, 'd')) return null;
90
+
91
+ if (Object.prototype.hasOwnProperty.call(frame, 'o')) {
92
+ if (!validOffset(frame.o)) return null;
93
+ frame.o = Number(frame.o);
94
+ }
95
+ if (Object.prototype.hasOwnProperty.call(frame, 'id')) {
96
+ if (!validId(frame.id)) return null;
97
+ frame.id = Number(frame.id);
98
+ }
99
+ if (Object.prototype.hasOwnProperty.call(frame, 'n')) {
100
+ if (!validNamespaceName(frame.n)) return null;
101
+ }
102
+
103
+ return frame;
104
+ }
package/src/rennari.js ADDED
@@ -0,0 +1,423 @@
1
+ import { Transport, setWebSocket } from './transport.js';
2
+ import { resolveSerializer } from './serializer.js';
3
+ import {
4
+ encodeFrame,
5
+ decodeFrame,
6
+ validEventName,
7
+ } from './protocol.js';
8
+
9
+ export { setWebSocket };
10
+
11
+ const LOCAL_EVENTS = new Set([
12
+ 'connect',
13
+ 'disconnect',
14
+ 'error',
15
+ 'ack_timeout',
16
+ 'reconnect_attempt',
17
+ 'reconnect_failed',
18
+ 'recovered',
19
+ ]);
20
+
21
+ // Close code the server uses for "unauthorized". The client does not retry on it.
22
+ const CLOSE_UNAUTHORIZED = 4001;
23
+
24
+ export class Rennari {
25
+ constructor(url, opts = {}) {
26
+ this.url = url;
27
+ this.serializer = resolveSerializer(opts.serializer);
28
+ this.maxBytes = opts.maxBytes ?? 64 * 1024;
29
+ this.defaultAckTimeout = opts.ackTimeout ?? 5000;
30
+ this.defaultRetries = opts.retries ?? 3;
31
+ this.defaultNamespace = '/';
32
+
33
+ // Auth. `headers` works in Node (ws) only. `auth` works everywhere.
34
+ this.headers = opts.headers ?? null;
35
+ this.auth = opts.auth ?? null;
36
+ this.authEvent = opts.authEvent ?? 'auth';
37
+
38
+ this.maxOutbox = opts.maxOutbox ?? 1000;
39
+
40
+ this.reconnection = opts.reconnection ?? true;
41
+ this.reconnectionDelay = opts.reconnectionDelay ?? 1000;
42
+ this.reconnectionDelayMax = opts.reconnectionDelayMax ?? 5000;
43
+ this.reconnectionAttempts = opts.reconnectionAttempts ?? Infinity;
44
+ this.reconnectionJitter = opts.reconnectionJitter ?? 0.5;
45
+
46
+ this.recovery = opts.recovery ?? true;
47
+ this.recoveryWindow = opts.recoveryWindow ?? 120000;
48
+
49
+ this._transport = null;
50
+ this._handlers = new Map();
51
+ this._namespaces = new Map();
52
+ this._namespaces.set('/', this._makeNamespace('/'));
53
+
54
+ this._nextId = 0;
55
+ this._pending = new Map();
56
+
57
+ this._lastOffset = -1;
58
+ this._sessionId = null;
59
+ this._sessionExpiresAt = 0;
60
+
61
+ this._connectQueue = [];
62
+ this._outbox = [];
63
+ this._intentionalDisconnect = false;
64
+ this._reconnectAttempts = 0;
65
+ this._reconnectTimer = null;
66
+ this._connected = false;
67
+ }
68
+
69
+ on(event, cb) { this._onEvent('/', event, cb); return this; }
70
+ off(event, cb) { this._offEvent('/', event, cb); return this; }
71
+ emit(event, payload) { return this._emit('/', event, payload, null); }
72
+ emitWithAck(event, payload, opts = {}) {
73
+ return this._emitWithAck('/', event, payload, opts);
74
+ }
75
+
76
+ of(name) {
77
+ let ns = this._namespaces.get(name);
78
+ if (!ns) {
79
+ ns = this._makeNamespace(name);
80
+ this._namespaces.set(name, ns);
81
+ }
82
+ return ns;
83
+ }
84
+
85
+ get sessionId() { return this._sessionId; }
86
+ get lastOffset() { return this._lastOffset; }
87
+ get connected() { return this._connected; }
88
+
89
+ connect() {
90
+ this._intentionalDisconnect = false;
91
+ return this._open();
92
+ }
93
+
94
+ disconnect(code = 1000, reason = 'client_disconnect') {
95
+ this._intentionalDisconnect = true;
96
+ if (this._reconnectTimer) {
97
+ clearTimeout(this._reconnectTimer);
98
+ this._reconnectTimer = null;
99
+ }
100
+ for (const [id, entry] of this._pending) {
101
+ clearTimeout(entry.timer);
102
+ this._pending.delete(id);
103
+ entry.reject(new Error('rennari: disconnected'));
104
+ }
105
+ this._outbox = [];
106
+ if (this._transport) this._transport.close(code, reason);
107
+ this._connected = false;
108
+ }
109
+
110
+ _newTransport() {
111
+ return new Transport(this.url, { headers: this.headers });
112
+ }
113
+
114
+ _open() {
115
+ return new Promise((resolve, reject) => {
116
+ const transport = this._newTransport();
117
+ this._transport = transport;
118
+ let opened = false;
119
+ const stale = () => this._transport !== transport;
120
+
121
+ transport.on('open', () => {
122
+ if (stale()) return;
123
+ opened = true;
124
+ this._connected = true;
125
+ this._reconnectAttempts = 0;
126
+
127
+ // First-message auth must be the very first frame on the socket.
128
+ if (this.auth) {
129
+ try {
130
+ const payload = typeof this.auth === 'function'
131
+ ? this.auth()
132
+ : this.auth;
133
+ transport.send(encodeFrame(this.authEvent, payload, {
134
+ serializer: this.serializer.name,
135
+ }));
136
+ } catch (e) {
137
+ this._fireLocal('/', 'error', e);
138
+ transport.close(CLOSE_UNAUTHORIZED, 'auth_failed');
139
+ reject(e);
140
+ return;
141
+ }
142
+ }
143
+
144
+ const useResume = this.recovery
145
+ && this._sessionId
146
+ && Date.now() <= this._sessionExpiresAt;
147
+ if (useResume) {
148
+ transport.send(encodeFrame('rennari_resume', {
149
+ session_id: this._sessionId,
150
+ offset: this._lastOffset,
151
+ }, { serializer: this.serializer.name }));
152
+ }
153
+
154
+ for (const [name] of this._namespaces) {
155
+ if (name === '/') continue;
156
+ transport.send(encodeFrame('rennari_nsp', { name }, {
157
+ serializer: this.serializer.name,
158
+ }));
159
+ }
160
+
161
+ const queued = this._outbox;
162
+ this._outbox = [];
163
+ for (const op of queued) {
164
+ try { op(transport); } catch (e) {
165
+ this._fireLocal('/', 'error', e);
166
+ }
167
+ }
168
+
169
+ for (const fn of this._connectQueue) fn();
170
+ this._connectQueue = [];
171
+
172
+ this._fireLocal('/', 'connect');
173
+ resolve();
174
+ });
175
+
176
+ transport.on('message', (bytes) => {
177
+ if (stale()) return;
178
+ this._onMessage(bytes);
179
+ });
180
+
181
+ transport.on('close', (code, reason) => {
182
+ if (stale()) return;
183
+ this._connected = false;
184
+ if (this._sessionId) {
185
+ this._sessionExpiresAt = Date.now() + this.recoveryWindow;
186
+ }
187
+ this._fireLocal('/', 'disconnect', { code, reason });
188
+
189
+ if (!opened) {
190
+ reject(new Error(`rennari: connection closed before open (${code})`));
191
+ }
192
+
193
+ if (
194
+ !this._intentionalDisconnect
195
+ && this.reconnection
196
+ && code !== CLOSE_UNAUTHORIZED
197
+ ) {
198
+ this._scheduleReconnect();
199
+ }
200
+ });
201
+
202
+ transport.on('error', (err) => {
203
+ if (stale()) return;
204
+ this._fireLocal('/', 'error', err);
205
+ if (!opened) reject(err);
206
+ });
207
+
208
+ transport.connect();
209
+ });
210
+ }
211
+
212
+ _scheduleReconnect() {
213
+ if (this._reconnectTimer) return;
214
+ if (this._reconnectAttempts >= this.reconnectionAttempts) {
215
+ this._fireLocal('/', 'reconnect_failed');
216
+ return;
217
+ }
218
+ this._reconnectAttempts++;
219
+ const base = Math.min(
220
+ this.reconnectionDelay * Math.pow(2, this._reconnectAttempts - 1),
221
+ this.reconnectionDelayMax
222
+ );
223
+ const jitter = base * this.reconnectionJitter * (Math.random() * 2 - 1);
224
+ const delay = Math.max(
225
+ 0,
226
+ Math.min(Math.floor(base + jitter), this.reconnectionDelayMax)
227
+ );
228
+
229
+ this._fireLocal('/', 'reconnect_attempt', {
230
+ attempt: this._reconnectAttempts,
231
+ delay,
232
+ });
233
+
234
+ this._reconnectTimer = setTimeout(() => {
235
+ this._reconnectTimer = null;
236
+ this._open().catch(() => { /* errors already reported via 'error' */ });
237
+ }, delay);
238
+ }
239
+
240
+ _makeNamespace(name) {
241
+ const self = this;
242
+ return {
243
+ name,
244
+ on(event, cb) { self._onEvent(name, event, cb); return this; },
245
+ off(event, cb) { self._offEvent(name, event, cb); return this; },
246
+ emit(event, payload) { return self._emit(name, event, payload, null); },
247
+ emitWithAck(event, payload, opts) {
248
+ return self._emitWithAck(name, event, payload, opts);
249
+ },
250
+ };
251
+ }
252
+
253
+ _onEvent(nsp, event, cb) {
254
+ if (!LOCAL_EVENTS.has(event) && !validEventName(event)) {
255
+ throw new Error(`invalid event name '${event}'`);
256
+ }
257
+ if (typeof cb !== 'function') throw new Error('handler must be a function');
258
+ const key = `${nsp}\u0000${event}`;
259
+ let list = this._handlers.get(key);
260
+ if (!list) {
261
+ list = [];
262
+ this._handlers.set(key, list);
263
+ }
264
+ list.push(cb);
265
+ }
266
+
267
+ _offEvent(nsp, event, cb) {
268
+ const key = `${nsp}\u0000${event}`;
269
+ const list = this._handlers.get(key);
270
+ if (!list) return;
271
+ if (!cb) { this._handlers.delete(key); return; }
272
+ const i = list.indexOf(cb);
273
+ if (i >= 0) list.splice(i, 1);
274
+ }
275
+
276
+ _fireLocal(nsp, event, ...args) {
277
+ const list = this._handlers.get(`${nsp}\u0000${event}`) || [];
278
+ for (const cb of list.slice()) {
279
+ try { cb(...args); } catch (e) { console.error('rennari handler error', e); }
280
+ }
281
+ }
282
+
283
+ _makeWriter(nsp, event, payload, id) {
284
+ return (transport) => {
285
+ const bytes = encodeFrame(event, payload, {
286
+ serializer: this.serializer.name,
287
+ id,
288
+ namespace: nsp,
289
+ });
290
+ transport.send(bytes);
291
+ };
292
+ }
293
+
294
+ // Sends now if open, otherwise queues. `entry` (optional) limits an ack
295
+ // retry to one queued copy.
296
+ _dispatch(writer, entry = null) {
297
+ if (this._transport && this._transport.isOpen()) {
298
+ writer(this._transport);
299
+ return;
300
+ }
301
+ if (!this.reconnection) {
302
+ throw new Error('rennari: not connected');
303
+ }
304
+ if (entry) {
305
+ if (entry.queued) return;
306
+ entry.queued = true;
307
+ const inner = writer;
308
+ writer = (t) => { entry.queued = false; inner(t); };
309
+ }
310
+ if (this._outbox.length >= this.maxOutbox) {
311
+ if (entry) entry.queued = false;
312
+ throw new Error('rennari: outbox full');
313
+ }
314
+ this._outbox.push(writer);
315
+ }
316
+
317
+ _emit(nsp, event, payload, id) {
318
+ if (!validEventName(event)) {
319
+ throw new Error(`invalid event name '${event}'`);
320
+ }
321
+ this._dispatch(this._makeWriter(nsp, event, payload, id));
322
+ }
323
+
324
+ _emitWithAck(nsp, event, payload, opts = {}) {
325
+ if (!validEventName(event)) {
326
+ return Promise.reject(new Error(`invalid event name '${event}'`));
327
+ }
328
+ return new Promise((resolve, reject) => {
329
+ const timeout = opts.timeout ?? this.defaultAckTimeout;
330
+ const retries = opts.retries ?? this.defaultRetries;
331
+ const id = ++this._nextId;
332
+ const entry = {
333
+ nsp, event, payload, id, timeout, retries,
334
+ attempt: 0, queued: false, resolve, reject, timer: null,
335
+ };
336
+ this._pending.set(id, entry);
337
+ this._sendPending(id);
338
+ });
339
+ }
340
+
341
+ _sendPending(id) {
342
+ const entry = this._pending.get(id);
343
+ if (!entry) return;
344
+ if (entry.attempt > entry.retries) {
345
+ this._pending.delete(id);
346
+ this._fireLocal('/', 'ack_timeout', {
347
+ event: entry.event,
348
+ payload: entry.payload,
349
+ });
350
+ entry.reject(new Error(`ack timeout for '${entry.event}'`));
351
+ return;
352
+ }
353
+ entry.attempt++;
354
+ try {
355
+ this._dispatch(
356
+ this._makeWriter(entry.nsp, entry.event, entry.payload, entry.id),
357
+ entry
358
+ );
359
+ } catch (e) {
360
+ this._pending.delete(id);
361
+ entry.reject(e);
362
+ return;
363
+ }
364
+ if (entry.timer) clearTimeout(entry.timer);
365
+ entry.timer = setTimeout(() => this._sendPending(id), entry.timeout);
366
+ }
367
+
368
+ _onMessage(bytes) {
369
+ const frame = decodeFrame(bytes, {
370
+ serializer: this.serializer.name,
371
+ max_bytes: this.maxBytes,
372
+ });
373
+ if (!frame) {
374
+ this._fireLocal('/', 'error', new Error('bad frame'));
375
+ return;
376
+ }
377
+
378
+ if (frame.o !== undefined && frame.o > this._lastOffset) {
379
+ this._lastOffset = frame.o;
380
+ }
381
+
382
+ const d = frame.d && typeof frame.d === 'object' ? frame.d : {};
383
+
384
+ if (frame.e === 'rennari_session') {
385
+ if (d.id !== undefined) {
386
+ this._sessionId = d.id;
387
+ this._sessionExpiresAt = Date.now() + this.recoveryWindow;
388
+ }
389
+ return;
390
+ }
391
+ if (frame.e === 'rennari_resumed') {
392
+ if (d.session_id) {
393
+ this._sessionId = d.session_id;
394
+ this._sessionExpiresAt = Date.now() + this.recoveryWindow;
395
+ }
396
+ this._fireLocal('/', 'recovered', { offset: d.offset });
397
+ return;
398
+ }
399
+ if (frame.e === 'rennari_resume_failed') {
400
+ this._sessionId = null;
401
+ this._sessionExpiresAt = 0;
402
+ this._lastOffset = -1;
403
+ return;
404
+ }
405
+ if (frame.e === 'rennari_nsp_ok') {
406
+ return;
407
+ }
408
+ if (frame.e === 'rennari_ack') {
409
+ const entry = this._pending.get(d.id);
410
+ if (entry) {
411
+ clearTimeout(entry.timer);
412
+ this._pending.delete(d.id);
413
+ entry.resolve(frame.d);
414
+ }
415
+ return;
416
+ }
417
+
418
+ const nsp = frame.n ?? '/';
419
+ this._fireLocal(nsp, frame.e, frame.d, frame);
420
+ }
421
+ }
422
+
423
+ export default Rennari;
@@ -0,0 +1,28 @@
1
+ import { encode as mpEncode, decode as mpDecode } from '@msgpack/msgpack';
2
+
3
+ export function resolveSerializer(name) {
4
+ const s = name ?? 'msgpack';
5
+ if (s === 'msgpack') return msgpackSerializer;
6
+ if (s === 'json') return jsonSerializer;
7
+ throw new Error(`unsupported serializer '${s}'`);
8
+ }
9
+
10
+ export const msgpackSerializer = {
11
+ name: 'msgpack',
12
+ encode(frame) {
13
+ return mpEncode(frame);
14
+ },
15
+ decode(bytes) {
16
+ return mpDecode(bytes);
17
+ },
18
+ };
19
+
20
+ export const jsonSerializer = {
21
+ name: 'json',
22
+ encode(frame) {
23
+ return new TextEncoder().encode(JSON.stringify(frame));
24
+ },
25
+ decode(bytes) {
26
+ return JSON.parse(new TextDecoder().decode(bytes));
27
+ },
28
+ };
@@ -0,0 +1,88 @@
1
+ export class Transport {
2
+ constructor(url, opts = {}) {
3
+ this.url = url;
4
+ this.headers = opts.headers ?? null;
5
+ this.socket = null;
6
+ this.listeners = { open: [], message: [], close: [], error: [] };
7
+ }
8
+
9
+ on(event, cb) {
10
+ if (!this.listeners[event]) throw new Error(`unknown transport event '${event}'`);
11
+ this.listeners[event].push(cb);
12
+ return this;
13
+ }
14
+
15
+ emit(event, ...args) {
16
+ for (const cb of this.listeners[event] || []) {
17
+ try { cb(...args); } catch (_e) { /* listener errors do not break transport */ }
18
+ }
19
+ }
20
+
21
+ connect() {
22
+ const Ctor = pickWebSocketCtor();
23
+ if (this.headers && typeof document !== 'undefined') {
24
+ throw new Error('rennari: headers are not supported in browsers; use the auth option');
25
+ }
26
+ const socket = this.headers
27
+ ? new Ctor(this.url, { headers: this.headers })
28
+ : new Ctor(this.url);
29
+ if ('binaryType' in socket) socket.binaryType = 'arraybuffer';
30
+
31
+ socket.addEventListener('open', () => this.emit('open'));
32
+ socket.addEventListener('message', (e) => {
33
+ try {
34
+ const bytes = toBytes(e.data);
35
+ if (bytes instanceof Promise) {
36
+ bytes.then((b) => this.emit('message', b), (err) => this.emit('error', err));
37
+ } else {
38
+ this.emit('message', bytes);
39
+ }
40
+ } catch (err) { this.emit('error', err); }
41
+ });
42
+ socket.addEventListener('close', (e) => this.emit('close', e.code, e.reason));
43
+ socket.addEventListener('error', (e) => this.emit('error', e));
44
+
45
+ this.socket = socket;
46
+ return this;
47
+ }
48
+
49
+ send(bytes) {
50
+ if (!this.socket) throw new Error('transport not connected');
51
+ this.socket.send(bytes);
52
+ }
53
+
54
+ close(code, reason) {
55
+ const s = this.socket;
56
+ if (!s) return;
57
+ this.socket = null;
58
+ try { s.close(safeCloseCode(code), reason); } catch (_e) { /* already closed */ }
59
+ }
60
+
61
+ isOpen() {
62
+ return !!(this.socket && this.socket.readyState === 1);
63
+ }
64
+ }
65
+
66
+ function safeCloseCode(code) {
67
+ if (code === undefined) return 1000;
68
+ return code === 1000 || (code >= 3000 && code <= 4999) ? code : 1000;
69
+ }
70
+
71
+ function toBytes(data) {
72
+ if (data instanceof Uint8Array) return data;
73
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
74
+ if (typeof data === 'string') return new TextEncoder().encode(data);
75
+ if (data && typeof data.arrayBuffer === 'function') {
76
+ return data.arrayBuffer().then((ab) => new Uint8Array(ab));
77
+ }
78
+ throw new Error('unsupported message data type');
79
+ }
80
+
81
+ function pickWebSocketCtor() {
82
+ if (typeof globalThis.WebSocket === 'function') return globalThis.WebSocket;
83
+ throw new Error('no WebSocket implementation available; install the ws package and call setWebSocket');
84
+ }
85
+
86
+ export function setWebSocket(ctor) {
87
+ globalThis.WebSocket = ctor;
88
+ }
@@ -0,0 +1,33 @@
1
+ # {{name}}
2
+
3
+ A Rennari client with one file per event handler.
4
+
5
+ 1. npm install
6
+ 2. Edit config.js: set url and token. The token must match the server.
7
+ 3. npm start
8
+
9
+ ## Adding an event handler
10
+
11
+ 1. Create handlers/my_event.mjs:
12
+
13
+ export default {
14
+ event: 'my_event',
15
+ handle(payload, client) {
16
+ console.log('got', payload);
17
+ },
18
+ };
19
+
20
+ 2. Add it to the list in handlers/index.mjs.
21
+
22
+ Handlers receive (payload, client, frame). To send something, call
23
+ client.emit('event_name', { ... }).
24
+
25
+ ## Layout
26
+
27
+ - client.mjs starts the client and handles shutdown
28
+ - lib/config.mjs checks config.js
29
+ - lib/connect.mjs creates the client and sends the token header
30
+ - handlers/ one file per event
31
+
32
+ Never put the token in the URL, in an environment variable, or on the command line.
33
+ The token header only works in Node. Browsers cannot set it.
@@ -0,0 +1,2 @@
1
+ node_modules/
2
+ config.js
@@ -0,0 +1,42 @@
1
+ import config from './config.js';
2
+ import { validateConfig } from './lib/config.mjs';
3
+ import { createClient } from './lib/connect.mjs';
4
+ import handlers from './handlers/index.mjs';
5
+
6
+ let settings;
7
+ try {
8
+ settings = validateConfig(config);
9
+ } catch (e) {
10
+ console.error(e.message);
11
+ process.exit(2);
12
+ }
13
+
14
+ const client = createClient(settings);
15
+
16
+ for (const h of handlers) {
17
+ client.on(h.event, (payload, frame) => h.handle(payload, client, frame));
18
+ }
19
+
20
+ let stopped = false;
21
+ let status = 0;
22
+
23
+ function stop(error) {
24
+ if (stopped) return;
25
+ stopped = true;
26
+ if (error) { console.error(error); status = 1; }
27
+ client.disconnect();
28
+ process.exitCode = status;
29
+ setTimeout(() => process.exit(status), 500);
30
+ }
31
+
32
+ client.on('error', (error) => stop(error?.message ?? error?.error?.message ?? 'connection failed'));
33
+ client.on('disconnect', () => { console.log('Disconnected'); stop(); });
34
+
35
+ process.once('SIGINT', () => stop());
36
+ process.once('SIGTERM', () => stop());
37
+
38
+ try {
39
+ await client.connect();
40
+ } catch {
41
+ stop();
42
+ }
@@ -0,0 +1,6 @@
1
+ export default {
2
+ url: 'ws://127.0.0.1:3000/ws',
3
+ token: 'CHANGE_ME', // private token, 32-256 chars of A-Za-z0-9._~-; must match the server
4
+ serializer: 'msgpack', // must match the server: 'msgpack' or 'json'
5
+ // headers: { Authorization: `Bearer ${userToken}` }, // optional user auth
6
+ };
@@ -0,0 +1,9 @@
1
+ export default {
2
+ event: 'connect',
3
+ handle(_payload, client) {
4
+ console.log('Connected');
5
+ client.emit('ping', { n: 1 });
6
+ client.emit('whoami', {});
7
+ // client.emit('join_room', { room: 'lobby' });
8
+ },
9
+ };
@@ -0,0 +1,6 @@
1
+ import connect from './connect.mjs';
2
+ import pong from './pong.mjs';
3
+ import reply from './reply.mjs';
4
+
5
+ // Add your handlers to this list.
6
+ export default [connect, pong, reply];
@@ -0,0 +1,8 @@
1
+ export default {
2
+ event: 'pong',
3
+ handle(payload) {
4
+ if (!payload || typeof payload !== 'object') return;
5
+ if (!payload.got || typeof payload.got !== 'object') return;
6
+ console.log(`pong: ${payload.got.n ?? '?'}`);
7
+ },
8
+ };
@@ -0,0 +1,10 @@
1
+ export default {
2
+ event: 'reply',
3
+ handle(payload) {
4
+ if (!payload || typeof payload !== 'object') return;
5
+ if ('error' in payload) { console.log(`server error: ${payload.error ?? 'unknown'}`); return; }
6
+ if ('name' in payload) { console.log(`reply: user_id=${payload.user_id ?? '-'} name=${payload.name ?? '-'}`); return; }
7
+ if ('joined' in payload) { console.log(`joined room: ${payload.joined}`); return; }
8
+ console.log('Reply received');
9
+ },
10
+ };
@@ -0,0 +1,16 @@
1
+ const TOKEN_RE = /^[A-Za-z0-9._~-]{32,256}$/;
2
+
3
+ export function validateConfig(c) {
4
+ const token = c?.token ?? c?.TOKEN_APP;
5
+ if (typeof token !== 'string' || !TOKEN_RE.test(token) || token === 'CHANGE_ME') {
6
+ throw new Error('config.js: set token to a private token (32-256 letters/numbers/._~-)');
7
+ }
8
+ if (typeof c.url !== 'string' || !/^wss?:\/\//.test(c.url)) {
9
+ throw new Error('config.js: url must start with ws:// or wss://');
10
+ }
11
+ const serializer = c.serializer ?? 'msgpack';
12
+ if (serializer !== 'msgpack' && serializer !== 'json') {
13
+ throw new Error('config.js: serializer must be msgpack or json');
14
+ }
15
+ return { url: c.url, token, serializer, headers: c.headers ?? {} };
16
+ }
@@ -0,0 +1,12 @@
1
+ import { WebSocket } from 'ws';
2
+ import { Rennari, setWebSocket } from '@thomas57/rennari-client-js';
3
+
4
+ export function createClient(settings) {
5
+ setWebSocket(WebSocket);
6
+ return new Rennari(settings.url, {
7
+ serializer: settings.serializer,
8
+ headers: { ...settings.headers, 'X-Rennari-App-Token': settings.token },
9
+ reconnection: false,
10
+ recovery: false,
11
+ });
12
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "{{name}}",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": { "start": "node client.mjs" },
7
+ "dependencies": {
8
+ "@thomas57/rennari-client-js": "{{clientDep}}",
9
+ "ws": "^8.0.0"
10
+ }
11
+ }
@@ -0,0 +1,13 @@
1
+ # {{name}}
2
+
3
+ A small Rennari client.
4
+
5
+ 1. npm install
6
+ 2. Edit config.js: set url and token. The token must match the server.
7
+ 3. npm start
8
+
9
+ Edit client.mjs to change what happens on connect and to add event handlers.
10
+
11
+ Never put the token in the URL, in an environment variable, or on the command line.
12
+ This client sends it in the X-Rennari-App-Token header, which only works in Node.
13
+ Browsers cannot set that header.
@@ -0,0 +1,2 @@
1
+ node_modules/
2
+ config.js
@@ -0,0 +1,94 @@
1
+ import { WebSocket } from 'ws';
2
+ import { Rennari, setWebSocket } from '@thomas57/rennari-client-js';
3
+ import config from './config.js';
4
+
5
+ const TOKEN_RE = /^[A-Za-z0-9._~-]{32,256}$/;
6
+
7
+ function validateConfig(c) {
8
+ const token = c?.token ?? c?.TOKEN_APP;
9
+ if (typeof token !== 'string' || !TOKEN_RE.test(token) || token === 'CHANGE_ME') {
10
+ throw new Error('config.js: set token to a private token (32-256 letters/numbers/._~-)');
11
+ }
12
+ if (typeof c.url !== 'string' || !/^wss?:\/\//.test(c.url)) {
13
+ throw new Error('config.js: url must start with ws:// or wss://');
14
+ }
15
+ const serializer = c.serializer ?? 'msgpack';
16
+ if (serializer !== 'msgpack' && serializer !== 'json') {
17
+ throw new Error('config.js: serializer must be msgpack or json');
18
+ }
19
+ return { url: c.url, token, serializer, headers: c.headers ?? {} };
20
+ }
21
+
22
+ let settings;
23
+ try {
24
+ settings = validateConfig(config);
25
+ } catch (e) {
26
+ console.error(e.message);
27
+ process.exit(2);
28
+ }
29
+
30
+ class RennariWebSocket extends WebSocket {
31
+ constructor(url) {
32
+ super(url, {
33
+ headers: {
34
+ ...settings.headers,
35
+ 'X-Rennari-App-Token': settings.token,
36
+ },
37
+ handshakeTimeout: 5000,
38
+ });
39
+ }
40
+ }
41
+
42
+ setWebSocket(RennariWebSocket);
43
+
44
+ const client = new Rennari(settings.url, {
45
+ serializer: settings.serializer,
46
+ reconnection: false,
47
+ recovery: false,
48
+ });
49
+
50
+ let stopped = false;
51
+ let status = 0;
52
+
53
+ function stop(error) {
54
+ if (stopped) return;
55
+ stopped = true;
56
+ if (error) { console.error(error); status = 1; }
57
+ client.disconnect();
58
+ process.exitCode = status;
59
+ setTimeout(() => process.exit(status), 500);
60
+ }
61
+
62
+ // ---- What happens when connected: edit this ----
63
+ client.on('connect', () => {
64
+ console.log('Connected');
65
+ client.emit('ping', { n: 1 });
66
+ client.emit('whoami', {});
67
+ });
68
+
69
+ // ---- Incoming events: add your own here ----
70
+ client.on('pong', (payload) => {
71
+ if (!payload || typeof payload !== 'object') return;
72
+ if (!payload.got || typeof payload.got !== 'object') return;
73
+ console.log(`pong: ${payload.got.n ?? '?'}`);
74
+ });
75
+
76
+ client.on('reply', (payload) => {
77
+ if (!payload || typeof payload !== 'object') return;
78
+ if ('error' in payload) { console.log(`server error: ${payload.error ?? 'unknown'}`); return; }
79
+ if ('name' in payload) { console.log(`reply: user_id=${payload.user_id ?? '-'} name=${payload.name ?? '-'}`); return; }
80
+ if ('joined' in payload) { console.log(`joined room: ${payload.joined}`); return; }
81
+ console.log('Reply received');
82
+ });
83
+
84
+ client.on('error', (error) => stop(error?.message ?? error?.error?.message ?? 'connection failed'));
85
+ client.on('disconnect', () => { console.log('Disconnected'); stop(); });
86
+
87
+ process.once('SIGINT', () => stop());
88
+ process.once('SIGTERM', () => stop());
89
+
90
+ try {
91
+ await client.connect();
92
+ } catch {
93
+ stop();
94
+ }
@@ -0,0 +1,6 @@
1
+ export default {
2
+ url: 'ws://127.0.0.1:3000/ws',
3
+ token: 'CHANGE_ME', // private token, 32-256 chars of A-Za-z0-9._~-; must match the server
4
+ serializer: 'msgpack', // must match the server: 'msgpack' or 'json'
5
+ // headers: { Authorization: `Bearer ${userToken}` }, // optional user auth
6
+ };
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "{{name}}",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": { "start": "node client.mjs" },
7
+ "dependencies": {
8
+ "@thomas57/rennari-client-js": "{{clientDep}}",
9
+ "ws": "^8.0.0"
10
+ }
11
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.