@liveink/server 0.0.0-stage → 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.
@@ -0,0 +1,466 @@
1
+ // src/storage.ts
2
+ import { mkdir, readFile, rename, writeFile, unlink } from "node:fs/promises";
3
+ import { createHash } from "node:crypto";
4
+ import path from "node:path";
5
+ var MemoryStorage = class {
6
+ rooms = /* @__PURE__ */ new Map();
7
+ async loadRoom(room) {
8
+ const s = this.rooms.get(room);
9
+ return s ? s.slice() : null;
10
+ }
11
+ async saveRoom(room, state) {
12
+ this.rooms.set(room, state.slice());
13
+ }
14
+ async deleteRoom(room) {
15
+ this.rooms.delete(room);
16
+ }
17
+ };
18
+ var FileStorage = class {
19
+ dir;
20
+ ready;
21
+ writing = /* @__PURE__ */ new Map();
22
+ constructor(dir = path.resolve("data")) {
23
+ this.dir = dir;
24
+ this.ready = mkdir(dir, { recursive: true }).then(() => void 0);
25
+ }
26
+ fileFor(room) {
27
+ const slug = room.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 40);
28
+ const hash = createHash("sha256").update(room).digest("hex").slice(0, 16);
29
+ return path.join(this.dir, `${slug}-${hash}.ydoc`);
30
+ }
31
+ async loadRoom(room) {
32
+ await this.ready;
33
+ try {
34
+ return new Uint8Array(await readFile(this.fileFor(room)));
35
+ } catch (e) {
36
+ if (e.code === "ENOENT") return null;
37
+ throw e;
38
+ }
39
+ }
40
+ async saveRoom(room, state) {
41
+ await this.ready;
42
+ const prev = this.writing.get(room) ?? Promise.resolve();
43
+ const next = prev.catch(() => void 0).then(async () => {
44
+ const file = this.fileFor(room);
45
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
46
+ await writeFile(tmp, state);
47
+ await rename(tmp, file);
48
+ });
49
+ this.writing.set(room, next);
50
+ try {
51
+ await next;
52
+ } finally {
53
+ if (this.writing.get(room) === next) this.writing.delete(room);
54
+ }
55
+ }
56
+ async deleteRoom(room) {
57
+ try {
58
+ await unlink(this.fileFor(room));
59
+ } catch {
60
+ }
61
+ }
62
+ };
63
+
64
+ // src/server.ts
65
+ import http from "node:http";
66
+ import https from "node:https";
67
+ import { readFile as readFile2, stat } from "node:fs/promises";
68
+ import path2 from "node:path";
69
+ import os from "node:os";
70
+ import * as Y from "yjs";
71
+ import * as awarenessProtocol from "y-protocols/awareness";
72
+ import { WebSocketServer } from "ws";
73
+ import { LIMITS, MsgType, PROTOCOL_VERSION, frame, isValidRoom, jsonFrame, parseFrame, parseJson } from "@liveink/canvas/protocol";
74
+ var Conn = class {
75
+ constructor(ws, remote) {
76
+ this.ws = ws;
77
+ this.remote = remote;
78
+ }
79
+ ws;
80
+ remote;
81
+ room = null;
82
+ joining = false;
83
+ queue = [];
84
+ controlled = /* @__PURE__ */ new Set();
85
+ user = {};
86
+ windowStart = Date.now();
87
+ windowCount = 0;
88
+ send(data) {
89
+ if (this.ws.readyState === this.ws.OPEN) this.ws.send(data, { binary: true });
90
+ }
91
+ error(code, message, fatal = false) {
92
+ this.send(jsonFrame(MsgType.ERROR, { code, message, fatal }));
93
+ if (fatal) this.ws.close(1008, code);
94
+ }
95
+ };
96
+ var Room = class {
97
+ constructor(name, storage, opts, log) {
98
+ this.name = name;
99
+ this.storage = storage;
100
+ this.opts = opts;
101
+ this.log = log;
102
+ this.awareness = new awarenessProtocol.Awareness(this.doc);
103
+ this.awareness.setLocalState(null);
104
+ this.doc.on("update", (update, origin) => {
105
+ const msg = frame(MsgType.UPDATE, update);
106
+ for (const c of this.conns) if (c !== origin) c.send(msg);
107
+ this.markDirty();
108
+ });
109
+ this.awareness.on("update", ({ added, updated, removed }, origin) => {
110
+ if (origin instanceof Conn) {
111
+ for (const id of [...added, ...updated]) origin.controlled.add(id);
112
+ for (const id of removed) origin.controlled.delete(id);
113
+ }
114
+ const changed = [...added, ...updated, ...removed];
115
+ if (!changed.length) return;
116
+ const msg = frame(MsgType.AWARENESS, awarenessProtocol.encodeAwarenessUpdate(this.awareness, changed));
117
+ for (const c of this.conns) if (c !== origin) c.send(msg);
118
+ });
119
+ }
120
+ name;
121
+ storage;
122
+ opts;
123
+ log;
124
+ doc = new Y.Doc();
125
+ awareness;
126
+ conns = /* @__PURE__ */ new Set();
127
+ get clients() {
128
+ return this.conns.size;
129
+ }
130
+ saveTimer = null;
131
+ firstDirtyAt = 0;
132
+ dirty = false;
133
+ unloadTimer = null;
134
+ markDirty() {
135
+ this.dirty = true;
136
+ const now = Date.now();
137
+ if (!this.firstDirtyAt) this.firstDirtyAt = now;
138
+ if (this.saveTimer) clearTimeout(this.saveTimer);
139
+ const wait = Math.max(0, Math.min(this.opts.saveDebounceMs, this.firstDirtyAt + this.opts.saveMaxWaitMs - now));
140
+ this.saveTimer = setTimeout(() => void this.save(), wait);
141
+ }
142
+ async save() {
143
+ if (this.saveTimer) clearTimeout(this.saveTimer);
144
+ this.saveTimer = null;
145
+ if (!this.dirty) return;
146
+ this.dirty = false;
147
+ this.firstDirtyAt = 0;
148
+ try {
149
+ await this.storage.saveRoom(this.name, Y.encodeStateAsUpdate(this.doc));
150
+ } catch (e) {
151
+ this.log(`[room ${this.name}] save failed:`, e);
152
+ this.dirty = true;
153
+ this.markDirty();
154
+ }
155
+ }
156
+ destroy() {
157
+ if (this.saveTimer) clearTimeout(this.saveTimer);
158
+ if (this.unloadTimer) clearTimeout(this.unloadTimer);
159
+ this.awareness.destroy();
160
+ this.doc.destroy();
161
+ }
162
+ };
163
+ var MIME = {
164
+ ".html": "text/html; charset=utf-8",
165
+ ".js": "text/javascript; charset=utf-8",
166
+ ".mjs": "text/javascript; charset=utf-8",
167
+ ".css": "text/css; charset=utf-8",
168
+ ".json": "application/json; charset=utf-8",
169
+ ".svg": "image/svg+xml",
170
+ ".png": "image/png",
171
+ ".ico": "image/x-icon",
172
+ ".map": "application/json; charset=utf-8",
173
+ ".md": "text/markdown; charset=utf-8"
174
+ };
175
+ function toBytes(data) {
176
+ if (Array.isArray(data)) return new Uint8Array(Buffer.concat(data));
177
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
178
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
179
+ }
180
+ async function createInkServer(options = {}) {
181
+ const opts = {
182
+ port: options.port ?? 8080,
183
+ host: options.host ?? "0.0.0.0",
184
+ storage: options.storage ?? new MemoryStorage(),
185
+ staticDir: options.staticDir ?? null,
186
+ path: options.path ?? "/ws",
187
+ info: options.info ?? false,
188
+ saveDebounceMs: options.saveDebounceMs ?? 500,
189
+ saveMaxWaitMs: options.saveMaxWaitMs ?? 5e3,
190
+ roomIdleMs: options.roomIdleMs ?? 3e4,
191
+ log: options.log ?? ((...a) => console.log(...a))
192
+ };
193
+ const rooms = /* @__PURE__ */ new Map();
194
+ const loading = /* @__PURE__ */ new Map();
195
+ async function getRoom(name) {
196
+ const existing = rooms.get(name);
197
+ if (existing) return existing;
198
+ const pending = loading.get(name);
199
+ if (pending) return pending;
200
+ const p = (async () => {
201
+ const room = new Room(name, opts.storage, opts, opts.log);
202
+ try {
203
+ const state = await opts.storage.loadRoom(name);
204
+ if (state && state.length) Y.applyUpdate(room.doc, state, "storage");
205
+ } catch (e) {
206
+ opts.log(`[room ${name}] load failed, starting empty:`, e);
207
+ }
208
+ rooms.set(name, room);
209
+ loading.delete(name);
210
+ return room;
211
+ })();
212
+ loading.set(name, p);
213
+ return p;
214
+ }
215
+ const onRequest = async (req, res) => {
216
+ try {
217
+ const url = new URL(req.url ?? "/", "http://x");
218
+ if (url.pathname === "/healthz") {
219
+ res.writeHead(200, { "content-type": "application/json" });
220
+ res.end(JSON.stringify({ ok: true, rooms: rooms.size, protocol: PROTOCOL_VERSION }));
221
+ return;
222
+ }
223
+ if (opts.info && url.pathname === "/api/info") {
224
+ const addresses = [];
225
+ for (const list of Object.values(os.networkInterfaces())) for (const a of list ?? []) if (a.family === "IPv4" && !a.internal) addresses.push(a.address);
226
+ res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
227
+ res.end(JSON.stringify({ addresses, port: server.address()?.port ?? opts.port, protocol: PROTOCOL_VERSION }));
228
+ return;
229
+ }
230
+ if (!opts.staticDir || req.method !== "GET" && req.method !== "HEAD") {
231
+ res.writeHead(404).end("not found");
232
+ return;
233
+ }
234
+ let rel = decodeURIComponent(url.pathname);
235
+ if (rel.endsWith("/")) rel += "index.html";
236
+ const root = path2.resolve(opts.staticDir);
237
+ const file = path2.resolve(root, "." + rel);
238
+ if (!file.startsWith(root + path2.sep)) {
239
+ res.writeHead(403).end("forbidden");
240
+ return;
241
+ }
242
+ const st = await stat(file).catch(() => null);
243
+ if (!st || !st.isFile()) {
244
+ res.writeHead(404, { "content-type": "text/plain" }).end("not found");
245
+ return;
246
+ }
247
+ const body = await readFile2(file);
248
+ res.writeHead(200, {
249
+ "content-type": MIME[path2.extname(file)] ?? "application/octet-stream",
250
+ "cache-control": "no-cache",
251
+ "content-length": body.length
252
+ });
253
+ res.end(req.method === "HEAD" ? void 0 : body);
254
+ } catch {
255
+ if (!res.headersSent) res.writeHead(400);
256
+ res.end();
257
+ }
258
+ };
259
+ const attached = options.server ?? null;
260
+ const server = attached ?? http.createServer(onRequest);
261
+ const secure = !attached && options.https ? https.createServer({ key: options.https.key, cert: options.https.cert }, onRequest) : null;
262
+ const wss = new WebSocketServer({ noServer: true, maxPayload: LIMITS.maxFrameBytes, perMessageDeflate: false });
263
+ const onUpgrade = (req, socket, head) => {
264
+ const url = new URL(req.url ?? "/", "http://x");
265
+ if (url.pathname !== opts.path) {
266
+ if (!attached) socket.destroy();
267
+ return;
268
+ }
269
+ wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req));
270
+ };
271
+ server.on("upgrade", onUpgrade);
272
+ secure?.on("upgrade", onUpgrade);
273
+ wss.on("connection", (ws, req) => {
274
+ const conn = new Conn(ws, req.socket.remoteAddress ?? "?");
275
+ ws.isAlive = true;
276
+ ws.on("pong", () => ws.isAlive = true);
277
+ ws.on("message", (data, isBinary) => {
278
+ try {
279
+ if (!isBinary) {
280
+ conn.error("text-frame", "Only binary frames are supported");
281
+ return;
282
+ }
283
+ const now = Date.now();
284
+ if (now - conn.windowStart > 1e3) {
285
+ conn.windowStart = now;
286
+ conn.windowCount = 0;
287
+ }
288
+ if (++conn.windowCount > LIMITS.maxFramesPerSecond) {
289
+ if (conn.windowCount === LIMITS.maxFramesPerSecond + 1) conn.error("rate-limit", "Too many frames; dropping");
290
+ if (conn.windowCount > LIMITS.maxFramesPerSecond * 3) conn.error("rate-limit", "Too many frames", true);
291
+ return;
292
+ }
293
+ handle(conn, toBytes(data));
294
+ } catch (e) {
295
+ opts.log("[ws] handler error:", e);
296
+ conn.error("internal", "Failed to process frame");
297
+ }
298
+ });
299
+ ws.on("close", () => onClose(conn));
300
+ ws.on("error", () => {
301
+ });
302
+ });
303
+ function handle(conn, bytes) {
304
+ const f = parseFrame(bytes);
305
+ if (!f) {
306
+ conn.error("bad-frame", "Empty frame");
307
+ return;
308
+ }
309
+ if (f.type === MsgType.PING) {
310
+ conn.send(frame(MsgType.PONG, f.payload.subarray(0, 64)));
311
+ return;
312
+ }
313
+ if (!conn.room) {
314
+ if (conn.joining) {
315
+ if (conn.queue.length > 1e3) conn.error("queue-overflow", "Too many frames before join completed", true);
316
+ else conn.queue.push(bytes.slice());
317
+ return;
318
+ }
319
+ if (f.type !== MsgType.HELLO) {
320
+ conn.error("not-joined", "First frame must be HELLO", true);
321
+ return;
322
+ }
323
+ const hello = parseJson(f.payload);
324
+ if (!hello) return conn.error("bad-hello", "HELLO payload must be a JSON object", true);
325
+ if (hello.v !== PROTOCOL_VERSION) return conn.error("version", `Unsupported protocol version (server speaks ${PROTOCOL_VERSION})`, true);
326
+ if (!isValidRoom(hello.room)) return conn.error("bad-room", "Invalid room id", true);
327
+ const u = hello.user && typeof hello.user === "object" ? hello.user : {};
328
+ const str = (v) => typeof v === "string" ? v.slice(0, LIMITS.maxNameLength) : void 0;
329
+ conn.user = { id: str(u.id), name: str(u.name), color: str(u.color) };
330
+ conn.joining = true;
331
+ const roomName = hello.room;
332
+ getRoom(roomName).then(
333
+ (room2) => {
334
+ if (conn.ws.readyState !== conn.ws.OPEN) return;
335
+ if (room2.unloadTimer) clearTimeout(room2.unloadTimer);
336
+ room2.unloadTimer = null;
337
+ conn.room = room2;
338
+ conn.joining = false;
339
+ room2.conns.add(conn);
340
+ conn.send(jsonFrame(MsgType.WELCOME, { v: PROTOCOL_VERSION, room: roomName, serverTime: Date.now() }));
341
+ conn.send(frame(MsgType.SYNC_STEP1, Y.encodeStateVector(room2.doc)));
342
+ const states = [...room2.awareness.getStates().keys()];
343
+ if (states.length) conn.send(frame(MsgType.AWARENESS, awarenessProtocol.encodeAwarenessUpdate(room2.awareness, states)));
344
+ const q = conn.queue;
345
+ conn.queue = [];
346
+ for (const b of q) {
347
+ try {
348
+ handle(conn, b);
349
+ } catch (e) {
350
+ opts.log("[ws] queued frame error:", e);
351
+ }
352
+ }
353
+ },
354
+ (e) => {
355
+ opts.log("[ws] join failed", e);
356
+ conn.error("join-failed", "Could not open room", true);
357
+ }
358
+ );
359
+ return;
360
+ }
361
+ const room = conn.room;
362
+ switch (f.type) {
363
+ case MsgType.HELLO:
364
+ conn.error("already-joined", "HELLO already received; open a new connection to switch rooms");
365
+ return;
366
+ case MsgType.SYNC_STEP1:
367
+ conn.send(frame(MsgType.SYNC_STEP2, Y.encodeStateAsUpdate(room.doc, f.payload)));
368
+ return;
369
+ case MsgType.SYNC_STEP2:
370
+ case MsgType.UPDATE:
371
+ try {
372
+ Y.applyUpdate(room.doc, f.payload, conn);
373
+ } catch {
374
+ conn.error("bad-update", "Could not apply Yjs update");
375
+ }
376
+ return;
377
+ case MsgType.AWARENESS:
378
+ try {
379
+ awarenessProtocol.applyAwarenessUpdate(room.awareness, f.payload, conn);
380
+ } catch {
381
+ conn.error("bad-awareness", "Could not apply awareness update");
382
+ }
383
+ return;
384
+ case MsgType.EPHEMERAL: {
385
+ if (!parseJson(f.payload)) {
386
+ conn.error("bad-ephemeral", "EPHEMERAL payload must be a JSON object \u2264 64 KiB");
387
+ return;
388
+ }
389
+ for (const c of room.conns) if (c !== conn) c.send(bytes);
390
+ return;
391
+ }
392
+ default:
393
+ conn.error("unknown-type", `Unknown frame type 0x${f.type.toString(16)}`);
394
+ }
395
+ }
396
+ let closing = false;
397
+ function onClose(conn) {
398
+ const room = conn.room;
399
+ conn.room = null;
400
+ if (!room || closing) return;
401
+ room.conns.delete(conn);
402
+ if (conn.controlled.size) awarenessProtocol.removeAwarenessStates(room.awareness, [...conn.controlled], null);
403
+ if (room.conns.size === 0) {
404
+ void room.save();
405
+ if (room.unloadTimer) clearTimeout(room.unloadTimer);
406
+ room.unloadTimer = setTimeout(async () => {
407
+ if (room.conns.size) return;
408
+ await room.save();
409
+ if (room.conns.size) return;
410
+ rooms.delete(room.name);
411
+ room.destroy();
412
+ }, opts.roomIdleMs);
413
+ }
414
+ }
415
+ const liveness = setInterval(() => {
416
+ for (const ws of wss.clients) {
417
+ const w = ws;
418
+ if (!w.isAlive) {
419
+ ws.terminate();
420
+ continue;
421
+ }
422
+ w.isAlive = false;
423
+ ws.ping();
424
+ }
425
+ }, 3e4);
426
+ const listen = (srv, port2) => new Promise((resolve, reject) => {
427
+ srv.once("error", reject);
428
+ srv.listen(port2, opts.host, () => {
429
+ srv.off("error", reject);
430
+ const addr = srv.address();
431
+ resolve(typeof addr === "object" && addr ? addr.port : port2);
432
+ });
433
+ });
434
+ const port = attached ? attached.address()?.port ?? 0 : await listen(server, opts.port);
435
+ const httpsPort = secure && options.https ? await listen(secure, options.https.port) : null;
436
+ async function flush() {
437
+ await Promise.all([...rooms.values()].map((r) => r.save()));
438
+ }
439
+ return {
440
+ port,
441
+ http: server,
442
+ https: secure,
443
+ httpsPort,
444
+ rooms,
445
+ flush,
446
+ async close() {
447
+ closing = true;
448
+ clearInterval(liveness);
449
+ for (const ws of wss.clients) ws.terminate();
450
+ await flush();
451
+ for (const r of rooms.values()) r.destroy();
452
+ rooms.clear();
453
+ await new Promise((res) => wss.close(() => res()));
454
+ if (attached) attached.off("upgrade", onUpgrade);
455
+ else await new Promise((res) => server.close(() => res()));
456
+ if (secure) await new Promise((res) => secure.close(() => res()));
457
+ }
458
+ };
459
+ }
460
+
461
+ export {
462
+ MemoryStorage,
463
+ FileStorage,
464
+ createInkServer
465
+ };
466
+ //# sourceMappingURL=chunk-5WGYVCZI.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/storage.ts", "../../src/server.ts"],
4
+ "sourcesContent": ["/**\n * Pluggable room storage. The server keeps one Y.Doc per active room and persists\n * the full encoded Yjs state (Y.encodeStateAsUpdate) \u2014 a compact snapshot that already\n * contains tombstones needed to merge late offline edits.\n */\nimport { mkdir, readFile, rename, writeFile, unlink } from 'node:fs/promises';\nimport { createHash } from 'node:crypto';\nimport path from 'node:path';\n\nexport interface RoomStorage {\n /** Return the stored Yjs state for a room, or null if the room is new. */\n loadRoom(room: string): Promise<Uint8Array | null>;\n /** Persist the full Yjs state of a room (replaces previous snapshot). */\n saveRoom(room: string, state: Uint8Array): Promise<void>;\n /** Optional: remove a room. */\n deleteRoom?(room: string): Promise<void>;\n}\n\nexport class MemoryStorage implements RoomStorage {\n private rooms = new Map<string, Uint8Array>();\n async loadRoom(room: string) {\n const s = this.rooms.get(room);\n return s ? s.slice() : null;\n }\n async saveRoom(room: string, state: Uint8Array) {\n this.rooms.set(room, state.slice());\n }\n async deleteRoom(room: string) {\n this.rooms.delete(room);\n }\n}\n\n/**\n * One file per room in `dir` (default ./data). File name = readable slug + hash of the\n * exact room id, so arbitrary room strings can't escape the directory or collide.\n * Writes are atomic (temp file + rename).\n */\nexport class FileStorage implements RoomStorage {\n readonly dir: string;\n private ready: Promise<void>;\n private writing = new Map<string, Promise<void>>();\n\n constructor(dir = path.resolve('data')) {\n this.dir = dir;\n this.ready = mkdir(dir, { recursive: true }).then(() => undefined);\n }\n\n fileFor(room: string): string {\n const slug = room.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 40);\n const hash = createHash('sha256').update(room).digest('hex').slice(0, 16);\n return path.join(this.dir, `${slug}-${hash}.ydoc`);\n }\n\n async loadRoom(room: string): Promise<Uint8Array | null> {\n await this.ready;\n try {\n return new Uint8Array(await readFile(this.fileFor(room)));\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw e;\n }\n }\n\n async saveRoom(room: string, state: Uint8Array): Promise<void> {\n await this.ready;\n // Serialise writes per room so renames never race.\n const prev = this.writing.get(room) ?? Promise.resolve();\n const next = prev\n .catch(() => undefined)\n .then(async () => {\n const file = this.fileFor(room);\n const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;\n await writeFile(tmp, state);\n await rename(tmp, file);\n });\n this.writing.set(room, next);\n try {\n await next;\n } finally {\n if (this.writing.get(room) === next) this.writing.delete(room);\n }\n }\n\n async deleteRoom(room: string): Promise<void> {\n try {\n await unlink(this.fileFor(room));\n } catch {\n /* ignore */\n }\n }\n}\n", "/**\n * @liveink/server: WebSocket sync for <ink-canvas> rooms, standalone (HTTP + WebSocket on one\n * port, optionally serving a static site) or attached to an existing Node HTTP(S) server.\n * Holds one authoritative Y.Doc + Awareness per active room, relays updates,\n * persists via a pluggable RoomStorage.\n */\nimport http from 'node:http';\nimport https from 'node:https';\nimport { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport os from 'node:os';\nimport * as Y from 'yjs';\nimport * as awarenessProtocol from 'y-protocols/awareness';\nimport { WebSocketServer, type WebSocket, type RawData } from 'ws';\nimport { LIMITS, MsgType, PROTOCOL_VERSION, frame, isValidRoom, jsonFrame, parseFrame, parseJson } from '@liveink/canvas/protocol';\nimport { MemoryStorage, type RoomStorage } from './storage.js';\n\nexport interface InkServerOptions {\n /**\n * Attach to an existing HTTP(S) server instead of starting one: only WebSocket upgrades on\n * `path` are handled; all other requests stay with your app, and `port`, `host`, `staticDir`,\n * `https` and `info` are ignored. close() does not close your server.\n */\n server?: http.Server | https.Server;\n /** WebSocket path (default '/ws'). */\n path?: string;\n /** Serve GET /api/info (LAN addresses + port, used by the demo's share link). Default false. */\n info?: boolean;\n port?: number;\n host?: string;\n storage?: RoomStorage;\n /** Directory with the built demo (index.html etc). null = no static serving. */\n staticDir?: string | null;\n /** Debounce before persisting a changed room. */\n saveDebounceMs?: number;\n /** Max time a dirty room may stay unsaved while edits keep coming. */\n saveMaxWaitMs?: number;\n /** Keep an empty room in memory this long before unloading it. */\n roomIdleMs?: number;\n log?: (...args: unknown[]) => void;\n /** Optionally ALSO serve HTTPS/WSS (same rooms) on another port, e.g. to unlock secure-context-only input APIs. */\n https?: { key: string | Buffer; cert: string | Buffer; port: number };\n}\n\nexport interface InkServer {\n /** Listening port (when attached: the host server's port, or 0 if it isn't listening yet). */\n port: number;\n http: http.Server | https.Server;\n https: https.Server | null;\n httpsPort: number | null;\n /** Rooms currently loaded in memory. */\n rooms: ReadonlyMap<string, InkRoom>;\n /** Persist all dirty rooms now. */\n flush(): Promise<void>;\n close(): Promise<void>;\n}\n\nclass Conn {\n room: Room | null = null;\n joining = false;\n queue: Uint8Array[] = [];\n controlled = new Set<number>();\n user: { id?: string; name?: string; color?: string } = {};\n windowStart = Date.now();\n windowCount = 0;\n constructor(readonly ws: WebSocket, readonly remote: string) {}\n send(data: Uint8Array) {\n if (this.ws.readyState === this.ws.OPEN) this.ws.send(data, { binary: true });\n }\n error(code: string, message: string, fatal = false) {\n this.send(jsonFrame(MsgType.ERROR, { code, message, fatal }));\n if (fatal) this.ws.close(1008, code);\n }\n}\n\n/** Public view of an active room. */\nexport interface InkRoom {\n readonly name: string;\n /** The room's authoritative Yjs document (read it; edits made here sync to every client). */\n readonly doc: Y.Doc;\n /** Connected clients. */\n readonly clients: number;\n}\n\nclass Room implements InkRoom {\n readonly doc = new Y.Doc();\n readonly awareness: awarenessProtocol.Awareness;\n readonly conns = new Set<Conn>();\n get clients() {\n return this.conns.size;\n }\n private saveTimer: ReturnType<typeof setTimeout> | null = null;\n private firstDirtyAt = 0;\n private dirty = false;\n unloadTimer: ReturnType<typeof setTimeout> | null = null;\n constructor(\n readonly name: string,\n private storage: RoomStorage,\n private opts: { saveDebounceMs: number; saveMaxWaitMs: number },\n private log: (...a: unknown[]) => void,\n ) {\n this.awareness = new awarenessProtocol.Awareness(this.doc);\n this.awareness.setLocalState(null); // the server is not a peer\n this.doc.on('update', (update: Uint8Array, origin: unknown) => {\n const msg = frame(MsgType.UPDATE, update);\n for (const c of this.conns) if (c !== origin) c.send(msg);\n this.markDirty();\n });\n this.awareness.on('update', ({ added, updated, removed }: { added: number[]; updated: number[]; removed: number[] }, origin: unknown) => {\n if (origin instanceof Conn) {\n for (const id of [...added, ...updated]) origin.controlled.add(id);\n for (const id of removed) origin.controlled.delete(id);\n }\n const changed = [...added, ...updated, ...removed];\n if (!changed.length) return;\n const msg = frame(MsgType.AWARENESS, awarenessProtocol.encodeAwarenessUpdate(this.awareness, changed));\n for (const c of this.conns) if (c !== origin) c.send(msg);\n });\n }\n\n markDirty() {\n this.dirty = true;\n const now = Date.now();\n if (!this.firstDirtyAt) this.firstDirtyAt = now;\n if (this.saveTimer) clearTimeout(this.saveTimer);\n const wait = Math.max(0, Math.min(this.opts.saveDebounceMs, this.firstDirtyAt + this.opts.saveMaxWaitMs - now));\n this.saveTimer = setTimeout(() => void this.save(), wait);\n }\n\n async save(): Promise<void> {\n if (this.saveTimer) clearTimeout(this.saveTimer);\n this.saveTimer = null;\n if (!this.dirty) return;\n this.dirty = false;\n this.firstDirtyAt = 0;\n try {\n await this.storage.saveRoom(this.name, Y.encodeStateAsUpdate(this.doc));\n } catch (e) {\n this.log(`[room ${this.name}] save failed:`, e);\n this.dirty = true;\n this.markDirty();\n }\n }\n\n destroy() {\n if (this.saveTimer) clearTimeout(this.saveTimer);\n if (this.unloadTimer) clearTimeout(this.unloadTimer);\n this.awareness.destroy();\n this.doc.destroy();\n }\n}\n\nconst MIME: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.ico': 'image/x-icon',\n '.map': 'application/json; charset=utf-8',\n '.md': 'text/markdown; charset=utf-8',\n};\n\nfunction toBytes(data: RawData): Uint8Array {\n if (Array.isArray(data)) return new Uint8Array(Buffer.concat(data));\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n}\n\nexport async function createInkServer(options: InkServerOptions = {}): Promise<InkServer> {\n const opts = {\n port: options.port ?? 8080,\n host: options.host ?? '0.0.0.0',\n storage: options.storage ?? new MemoryStorage(),\n staticDir: options.staticDir ?? null,\n path: options.path ?? '/ws',\n info: options.info ?? false,\n saveDebounceMs: options.saveDebounceMs ?? 500,\n saveMaxWaitMs: options.saveMaxWaitMs ?? 5000,\n roomIdleMs: options.roomIdleMs ?? 30_000,\n log: options.log ?? ((...a: unknown[]) => console.log(...a)),\n };\n const rooms = new Map<string, Room>();\n const loading = new Map<string, Promise<Room>>();\n\n async function getRoom(name: string): Promise<Room> {\n const existing = rooms.get(name);\n if (existing) return existing;\n const pending = loading.get(name);\n if (pending) return pending;\n const p = (async () => {\n const room = new Room(name, opts.storage, opts, opts.log);\n try {\n const state = await opts.storage.loadRoom(name);\n if (state && state.length) Y.applyUpdate(room.doc, state, 'storage');\n } catch (e) {\n opts.log(`[room ${name}] load failed, starting empty:`, e);\n }\n rooms.set(name, room);\n loading.delete(name);\n return room;\n })();\n loading.set(name, p);\n return p;\n }\n\n // ------------------------------------------------------------ HTTP\n\n const onRequest = async (req: http.IncomingMessage, res: http.ServerResponse) => {\n try {\n const url = new URL(req.url ?? '/', 'http://x');\n if (url.pathname === '/healthz') {\n res.writeHead(200, { 'content-type': 'application/json' });\n res.end(JSON.stringify({ ok: true, rooms: rooms.size, protocol: PROTOCOL_VERSION }));\n return;\n }\n if (opts.info && url.pathname === '/api/info') {\n const addresses: string[] = [];\n for (const list of Object.values(os.networkInterfaces())) for (const a of list ?? []) if (a.family === 'IPv4' && !a.internal) addresses.push(a.address);\n res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });\n res.end(JSON.stringify({ addresses, port: (server.address() as { port?: number } | null)?.port ?? opts.port, protocol: PROTOCOL_VERSION }));\n return;\n }\n if (!opts.staticDir || (req.method !== 'GET' && req.method !== 'HEAD')) {\n res.writeHead(404).end('not found');\n return;\n }\n let rel = decodeURIComponent(url.pathname);\n if (rel.endsWith('/')) rel += 'index.html';\n const root = path.resolve(opts.staticDir);\n const file = path.resolve(root, '.' + rel);\n if (!file.startsWith(root + path.sep)) {\n res.writeHead(403).end('forbidden');\n return;\n }\n const st = await stat(file).catch(() => null);\n if (!st || !st.isFile()) {\n res.writeHead(404, { 'content-type': 'text/plain' }).end('not found');\n return;\n }\n const body = await readFile(file);\n res.writeHead(200, {\n 'content-type': MIME[path.extname(file)] ?? 'application/octet-stream',\n 'cache-control': 'no-cache',\n 'content-length': body.length,\n });\n res.end(req.method === 'HEAD' ? undefined : body);\n } catch {\n if (!res.headersSent) res.writeHead(400);\n res.end();\n }\n };\n const attached = options.server ?? null;\n const server: http.Server | https.Server = attached ?? http.createServer(onRequest);\n const secure = !attached && options.https ? https.createServer({ key: options.https.key, cert: options.https.cert }, onRequest) : null;\n\n // ------------------------------------------------------------ WebSocket\n\n const wss = new WebSocketServer({ noServer: true, maxPayload: LIMITS.maxFrameBytes, perMessageDeflate: false });\n const onUpgrade = (req: http.IncomingMessage, socket: import('node:stream').Duplex, head: Buffer) => {\n const url = new URL(req.url ?? '/', 'http://x');\n if (url.pathname !== opts.path) {\n // Attached to someone else's server: other upgrade handlers may want this request.\n if (!attached) socket.destroy();\n return;\n }\n wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));\n };\n server.on('upgrade', onUpgrade);\n secure?.on('upgrade', onUpgrade);\n\n wss.on('connection', (ws: WebSocket, req: http.IncomingMessage) => {\n const conn = new Conn(ws, req.socket.remoteAddress ?? '?');\n (ws as unknown as { isAlive: boolean }).isAlive = true;\n ws.on('pong', () => ((ws as unknown as { isAlive: boolean }).isAlive = true));\n ws.on('message', (data: RawData, isBinary: boolean) => {\n try {\n if (!isBinary) {\n conn.error('text-frame', 'Only binary frames are supported');\n return;\n }\n // Rate limiting\n const now = Date.now();\n if (now - conn.windowStart > 1000) {\n conn.windowStart = now;\n conn.windowCount = 0;\n }\n if (++conn.windowCount > LIMITS.maxFramesPerSecond) {\n if (conn.windowCount === LIMITS.maxFramesPerSecond + 1) conn.error('rate-limit', 'Too many frames; dropping');\n if (conn.windowCount > LIMITS.maxFramesPerSecond * 3) conn.error('rate-limit', 'Too many frames', true);\n return;\n }\n handle(conn, toBytes(data));\n } catch (e) {\n opts.log('[ws] handler error:', e);\n conn.error('internal', 'Failed to process frame');\n }\n });\n ws.on('close', () => onClose(conn));\n ws.on('error', () => {\n /* close follows */\n });\n });\n\n function handle(conn: Conn, bytes: Uint8Array) {\n const f = parseFrame(bytes);\n if (!f) {\n conn.error('bad-frame', 'Empty frame');\n return;\n }\n if (f.type === MsgType.PING) {\n conn.send(frame(MsgType.PONG, f.payload.subarray(0, 64)));\n return;\n }\n if (!conn.room) {\n if (conn.joining) {\n if (conn.queue.length > 1000) conn.error('queue-overflow', 'Too many frames before join completed', true);\n else conn.queue.push(bytes.slice());\n return;\n }\n if (f.type !== MsgType.HELLO) {\n conn.error('not-joined', 'First frame must be HELLO', true);\n return;\n }\n const hello = parseJson(f.payload);\n if (!hello) return conn.error('bad-hello', 'HELLO payload must be a JSON object', true);\n if (hello.v !== PROTOCOL_VERSION) return conn.error('version', `Unsupported protocol version (server speaks ${PROTOCOL_VERSION})`, true);\n if (!isValidRoom(hello.room)) return conn.error('bad-room', 'Invalid room id', true);\n const u = (hello.user && typeof hello.user === 'object' ? hello.user : {}) as Record<string, unknown>;\n const str = (v: unknown) => (typeof v === 'string' ? v.slice(0, LIMITS.maxNameLength) : undefined);\n conn.user = { id: str(u.id), name: str(u.name), color: str(u.color) };\n conn.joining = true;\n const roomName = hello.room;\n getRoom(roomName).then(\n (room) => {\n if (conn.ws.readyState !== conn.ws.OPEN) return;\n if (room.unloadTimer) clearTimeout(room.unloadTimer);\n room.unloadTimer = null;\n conn.room = room;\n conn.joining = false;\n room.conns.add(conn);\n conn.send(jsonFrame(MsgType.WELCOME, { v: PROTOCOL_VERSION, room: roomName, serverTime: Date.now() }));\n conn.send(frame(MsgType.SYNC_STEP1, Y.encodeStateVector(room.doc)));\n const states = [...room.awareness.getStates().keys()];\n if (states.length) conn.send(frame(MsgType.AWARENESS, awarenessProtocol.encodeAwarenessUpdate(room.awareness, states)));\n const q = conn.queue;\n conn.queue = [];\n for (const b of q) {\n try {\n handle(conn, b);\n } catch (e) {\n opts.log('[ws] queued frame error:', e);\n }\n }\n },\n (e) => {\n opts.log('[ws] join failed', e);\n conn.error('join-failed', 'Could not open room', true);\n },\n );\n return;\n }\n const room = conn.room;\n switch (f.type) {\n case MsgType.HELLO:\n conn.error('already-joined', 'HELLO already received; open a new connection to switch rooms');\n return;\n case MsgType.SYNC_STEP1:\n conn.send(frame(MsgType.SYNC_STEP2, Y.encodeStateAsUpdate(room.doc, f.payload)));\n return;\n case MsgType.SYNC_STEP2:\n case MsgType.UPDATE:\n try {\n Y.applyUpdate(room.doc, f.payload, conn);\n } catch {\n conn.error('bad-update', 'Could not apply Yjs update');\n }\n return;\n case MsgType.AWARENESS:\n try {\n awarenessProtocol.applyAwarenessUpdate(room.awareness, f.payload, conn);\n } catch {\n conn.error('bad-awareness', 'Could not apply awareness update');\n }\n return;\n case MsgType.EPHEMERAL: {\n if (!parseJson(f.payload)) {\n conn.error('bad-ephemeral', 'EPHEMERAL payload must be a JSON object \u2264 64 KiB');\n return;\n }\n for (const c of room.conns) if (c !== conn) c.send(bytes);\n return;\n }\n default:\n conn.error('unknown-type', `Unknown frame type 0x${f.type.toString(16)}`);\n }\n }\n\n let closing = false;\n function onClose(conn: Conn) {\n const room = conn.room;\n conn.room = null;\n if (!room || closing) return;\n room.conns.delete(conn);\n if (conn.controlled.size) awarenessProtocol.removeAwarenessStates(room.awareness, [...conn.controlled], null);\n if (room.conns.size === 0) {\n void room.save();\n if (room.unloadTimer) clearTimeout(room.unloadTimer);\n room.unloadTimer = setTimeout(async () => {\n if (room.conns.size) return;\n await room.save();\n if (room.conns.size) return;\n rooms.delete(room.name);\n room.destroy();\n }, opts.roomIdleMs);\n }\n }\n\n // Protocol-level ping to cull dead TCP connections.\n const liveness = setInterval(() => {\n for (const ws of wss.clients) {\n const w = ws as unknown as { isAlive: boolean };\n if (!w.isAlive) {\n ws.terminate();\n continue;\n }\n w.isAlive = false;\n ws.ping();\n }\n }, 30_000);\n\n const listen = (srv: http.Server | https.Server, port: number) =>\n new Promise<number>((resolve, reject) => {\n srv.once('error', reject);\n srv.listen(port, opts.host, () => {\n srv.off('error', reject);\n const addr = srv.address();\n resolve(typeof addr === 'object' && addr ? addr.port : port);\n });\n });\n const port = attached ? ((attached.address() as { port?: number } | null)?.port ?? 0) : await listen(server, opts.port);\n const httpsPort = secure && options.https ? await listen(secure, options.https.port) : null;\n\n async function flush() {\n await Promise.all([...rooms.values()].map((r) => r.save()));\n }\n\n return {\n port,\n http: server,\n https: secure,\n httpsPort,\n rooms,\n flush,\n async close() {\n closing = true;\n clearInterval(liveness);\n for (const ws of wss.clients) ws.terminate();\n await flush();\n for (const r of rooms.values()) r.destroy();\n rooms.clear();\n await new Promise<void>((res) => wss.close(() => res()));\n if (attached) attached.off('upgrade', onUpgrade);\n else await new Promise<void>((res) => server.close(() => res()));\n if (secure) await new Promise<void>((res) => secure.close(() => res()));\n },\n };\n}\n"],
5
+ "mappings": ";AAKA,SAAS,OAAO,UAAU,QAAQ,WAAW,cAAc;AAC3D,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AAWV,IAAM,gBAAN,MAA2C;AAAA,EACxC,QAAQ,oBAAI,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,EAAE,KAAK,CAAC,CAAC;AAAA,EAC5D;AAEA,SAAO;AAAA,IACL;AAAA,IACA,MAAM;AAAA,IACN,OAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA,MAAM,QAAQ;AACZ,gBAAU;AACV,oBAAc,QAAQ;AACtB,iBAAW,MAAM,IAAI,QAAS,IAAG,UAAU;AAC3C,YAAM,MAAM;AACZ,iBAAW,KAAK,MAAM,OAAO,EAAG,GAAE,QAAQ;AAC1C,YAAM,MAAM;AACZ,YAAM,IAAI,QAAc,CAAC,QAAQ,IAAI,MAAM,MAAM,IAAI,CAAC,CAAC;AACvD,UAAI,SAAU,UAAS,IAAI,WAAW,SAAS;AAAA,UAC1C,OAAM,IAAI,QAAc,CAAC,QAAQ,OAAO,MAAM,MAAM,IAAI,CAAC,CAAC;AAC/D,UAAI,OAAQ,OAAM,IAAI,QAAc,CAAC,QAAQ,OAAO,MAAM,MAAM,IAAI,CAAC,CAAC;AAAA,IACxE;AAAA,EACF;AACF;",
6
+ "names": ["readFile", "path", "path", "readFile", "room", "port"]
7
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ FileStorage,
4
+ MemoryStorage,
5
+ createInkServer
6
+ } from "./chunks/chunk-5WGYVCZI.js";
7
+
8
+ // src/cli.ts
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ import { parseArgs } from "node:util";
12
+ import { execFileSync } from "node:child_process";
13
+ import { existsSync, mkdirSync, readFileSync } from "node:fs";
14
+ var { values: a } = parseArgs({
15
+ options: {
16
+ port: { type: "string" },
17
+ host: { type: "string" },
18
+ "data-dir": { type: "string" },
19
+ memory: { type: "boolean" },
20
+ static: { type: "string" },
21
+ https: { type: "boolean" },
22
+ "https-port": { type: "string" },
23
+ cert: { type: "string" },
24
+ key: { type: "string" },
25
+ help: { type: "boolean", short: "h" }
26
+ }
27
+ });
28
+ if (a.help) {
29
+ console.log(`liveink-server: sync server for <ink-canvas> (@liveink/canvas)
30
+
31
+ --port <n> HTTP + WebSocket port (default 8080, env PORT)
32
+ --host <addr> bind address (default 0.0.0.0, env HOST)
33
+ --data-dir <dir> where rooms are saved (default ./liveink-data, env DATA_DIR)
34
+ --memory keep rooms in memory only (env STORAGE=memory)
35
+ --static <dir> also serve this folder over HTTP, e.g. your page (env STATIC_DIR)
36
+ --https also serve HTTPS/WSS (env HTTPS=1); self-signed cert unless --cert/--key
37
+ --https-port <n> (default 8443, env HTTPS_PORT)
38
+ --cert, --key PEM files for HTTPS (env HTTPS_CERT, HTTPS_KEY)
39
+
40
+ WebSocket endpoint: ws://<host>:<port>/ws health: GET /healthz`);
41
+ process.exit(0);
42
+ }
43
+ var env = process.env;
44
+ var port = Number(a.port ?? env.PORT ?? 8080);
45
+ var host = a.host ?? env.HOST ?? "0.0.0.0";
46
+ var dataDir = path.resolve(a["data-dir"] ?? env.DATA_DIR ?? "liveink-data");
47
+ var memory = a.memory ?? env.STORAGE === "memory";
48
+ var staticDir = a.static ?? env.STATIC_DIR ?? null;
49
+ var storage = memory ? new MemoryStorage() : new FileStorage(dataDir);
50
+ var lanIps = [];
51
+ for (const [name, addrs] of Object.entries(os.networkInterfaces())) {
52
+ for (const x of addrs ?? []) if (x.family === "IPv4" && !x.internal) lanIps.push([x.address, name]);
53
+ }
54
+ function loadHttps() {
55
+ const on = a.https ?? (!!env.HTTPS && env.HTTPS !== "0");
56
+ if (!on) return void 0;
57
+ const httpsPort = Number(a["https-port"] ?? env.HTTPS_PORT ?? 8443);
58
+ let keyFile = a.key ?? env.HTTPS_KEY, certFile = a.cert ?? env.HTTPS_CERT;
59
+ if (!keyFile || !certFile) {
60
+ const dir = path.join(dataDir, "tls");
61
+ keyFile = path.join(dir, "key.pem");
62
+ certFile = path.join(dir, "cert.pem");
63
+ if (!existsSync(keyFile) || !existsSync(certFile)) {
64
+ mkdirSync(dir, { recursive: true });
65
+ const san = ["DNS:localhost", "IP:127.0.0.1", ...lanIps.map(([ip]) => `IP:${ip}`)].join(",");
66
+ try {
67
+ execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "825", "-subj", "/CN=liveink-server", "-addext", `subjectAltName=${san}`, "-keyout", keyFile, "-out", certFile], { stdio: "ignore" });
68
+ } catch (e) {
69
+ console.error("HTTPS requested but no certificate could be generated (is openssl installed?). Pass --cert and --key.", e);
70
+ return void 0;
71
+ }
72
+ }
73
+ }
74
+ return { key: readFileSync(keyFile), cert: readFileSync(certFile), port: httpsPort };
75
+ }
76
+ var srv = await createInkServer({ port, host, storage, staticDir, info: !!staticDir, https: loadHttps() });
77
+ console.log(`
78
+ liveink-server listening on ${host}:${srv.port} (WebSocket path /ws)`);
79
+ console.log(` storage: ${memory ? "memory" : dataDir}${staticDir ? ` static: ${path.resolve(staticDir)}` : ""}
80
+ `);
81
+ var hosts = host === "0.0.0.0" ? ["localhost", ...lanIps.map(([ip]) => ip)] : [host];
82
+ for (const h of hosts) console.log(` ws://${h}:${srv.port}/ws${staticDir ? ` http://${h}:${srv.port}/` : ""}`);
83
+ if (srv.httpsPort) for (const h of hosts) console.log(` wss://${h}:${srv.httpsPort}/ws`);
84
+ console.log("");
85
+ var closing = false;
86
+ async function shutdown() {
87
+ if (closing) return;
88
+ closing = true;
89
+ console.log("\nshutting down, saving rooms\u2026");
90
+ const t = setTimeout(() => process.exit(1), 5e3);
91
+ await srv.close();
92
+ clearTimeout(t);
93
+ process.exit(0);
94
+ }
95
+ process.on("SIGINT", shutdown);
96
+ process.on("SIGTERM", shutdown);
97
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/cli.ts"],
4
+ "sourcesContent": ["#!/usr/bin/env node\n/**\n * liveink-server: run a sync server for <ink-canvas> rooms.\n *\n * liveink-server [--port 8080] [--host 0.0.0.0] [--data-dir ./liveink-data | --memory]\n * [--static ./site] [--https [--https-port 8443] [--cert c.pem --key k.pem]]\n *\n * Every flag can also be given as an environment variable: PORT, HOST, DATA_DIR, STORAGE=memory,\n * STATIC_DIR, HTTPS=1, HTTPS_PORT, HTTPS_CERT, HTTPS_KEY.\n */\nimport os from 'node:os';\nimport path from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync } from 'node:fs';\nimport { createInkServer } from './server.js';\nimport { FileStorage, MemoryStorage } from './storage.js';\n\nconst { values: a } = parseArgs({\n options: {\n port: { type: 'string' },\n host: { type: 'string' },\n 'data-dir': { type: 'string' },\n memory: { type: 'boolean' },\n static: { type: 'string' },\n https: { type: 'boolean' },\n 'https-port': { type: 'string' },\n cert: { type: 'string' },\n key: { type: 'string' },\n help: { type: 'boolean', short: 'h' },\n },\n});\nif (a.help) {\n console.log(`liveink-server: sync server for <ink-canvas> (@liveink/canvas)\n\n --port <n> HTTP + WebSocket port (default 8080, env PORT)\n --host <addr> bind address (default 0.0.0.0, env HOST)\n --data-dir <dir> where rooms are saved (default ./liveink-data, env DATA_DIR)\n --memory keep rooms in memory only (env STORAGE=memory)\n --static <dir> also serve this folder over HTTP, e.g. your page (env STATIC_DIR)\n --https also serve HTTPS/WSS (env HTTPS=1); self-signed cert unless --cert/--key\n --https-port <n> (default 8443, env HTTPS_PORT)\n --cert, --key PEM files for HTTPS (env HTTPS_CERT, HTTPS_KEY)\n\n WebSocket endpoint: ws://<host>:<port>/ws health: GET /healthz`);\n process.exit(0);\n}\n\nconst env = process.env;\nconst port = Number(a.port ?? env.PORT ?? 8080);\nconst host = a.host ?? env.HOST ?? '0.0.0.0';\nconst dataDir = path.resolve(a['data-dir'] ?? env.DATA_DIR ?? 'liveink-data');\nconst memory = a.memory ?? env.STORAGE === 'memory';\nconst staticDir = a.static ?? env.STATIC_DIR ?? null;\nconst storage = memory ? new MemoryStorage() : new FileStorage(dataDir);\n\nconst lanIps: Array<[string, string]> = [];\nfor (const [name, addrs] of Object.entries(os.networkInterfaces())) {\n for (const x of addrs ?? []) if (x.family === 'IPv4' && !x.internal) lanIps.push([x.address, name]);\n}\n\n/**\n * Optional HTTPS. Browsers expose some low-latency pen APIs (getCoalescedEvents,\n * pointerrawupdate) only in secure contexts, so over plain http://<LAN-IP> a tablet gets fewer\n * pen samples. Uses the given cert/key, else generates a self-signed one with openssl.\n */\nfunction loadHttps(): { key: Buffer; cert: Buffer; port: number } | undefined {\n const on = a.https ?? (!!env.HTTPS && env.HTTPS !== '0');\n if (!on) return undefined;\n const httpsPort = Number(a['https-port'] ?? env.HTTPS_PORT ?? 8443);\n let keyFile = a.key ?? env.HTTPS_KEY, certFile = a.cert ?? env.HTTPS_CERT;\n if (!keyFile || !certFile) {\n const dir = path.join(dataDir, 'tls');\n keyFile = path.join(dir, 'key.pem');\n certFile = path.join(dir, 'cert.pem');\n if (!existsSync(keyFile) || !existsSync(certFile)) {\n mkdirSync(dir, { recursive: true });\n const san = ['DNS:localhost', 'IP:127.0.0.1', ...lanIps.map(([ip]) => `IP:${ip}`)].join(',');\n try {\n execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '825', '-subj', '/CN=liveink-server', '-addext', `subjectAltName=${san}`, '-keyout', keyFile, '-out', certFile], { stdio: 'ignore' });\n } catch (e) {\n console.error('HTTPS requested but no certificate could be generated (is openssl installed?). Pass --cert and --key.', e);\n return undefined;\n }\n }\n }\n return { key: readFileSync(keyFile), cert: readFileSync(certFile), port: httpsPort };\n}\n\nconst srv = await createInkServer({ port, host, storage, staticDir, info: !!staticDir, https: loadHttps() });\n\nconsole.log(`\\n liveink-server listening on ${host}:${srv.port} (WebSocket path /ws)`);\nconsole.log(` storage: ${memory ? 'memory' : dataDir}${staticDir ? ` static: ${path.resolve(staticDir)}` : ''}\\n`);\nconst hosts = host === '0.0.0.0' ? ['localhost', ...lanIps.map(([ip]) => ip)] : [host];\nfor (const h of hosts) console.log(` ws://${h}:${srv.port}/ws${staticDir ? ` http://${h}:${srv.port}/` : ''}`);\nif (srv.httpsPort) for (const h of hosts) console.log(` wss://${h}:${srv.httpsPort}/ws`);\nconsole.log('');\n\nlet closing = false;\nasync function shutdown() {\n if (closing) return;\n closing = true;\n console.log('\\nshutting down, saving rooms\u2026');\n const t = setTimeout(() => process.exit(1), 5000);\n await srv.close();\n clearTimeout(t);\n process.exit(0);\n}\nprocess.on('SIGINT', shutdown);\nprocess.on('SIGTERM', shutdown);\n"],
5
+ "mappings": ";;;;;;;;AAUA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,iBAAiB;AAC1B,SAAS,oBAAoB;AAC7B,SAAS,YAAY,WAAW,oBAAoB;AAIpD,IAAM,EAAE,QAAQ,EAAE,IAAI,UAAU;AAAA,EAC9B,SAAS;AAAA,IACP,MAAM,EAAE,MAAM,SAAS;AAAA,IACvB,MAAM,EAAE,MAAM,SAAS;AAAA,IACvB,YAAY,EAAE,MAAM,SAAS;AAAA,IAC7B,QAAQ,EAAE,MAAM,UAAU;AAAA,IAC1B,QAAQ,EAAE,MAAM,SAAS;AAAA,IACzB,OAAO,EAAE,MAAM,UAAU;AAAA,IACzB,cAAc,EAAE,MAAM,SAAS;AAAA,IAC/B,MAAM,EAAE,MAAM,SAAS;AAAA,IACvB,KAAK,EAAE,MAAM,SAAS;AAAA,IACtB,MAAM,EAAE,MAAM,WAAW,OAAO,IAAI;AAAA,EACtC;AACF,CAAC;AACD,IAAI,EAAE,MAAM;AACV,UAAQ,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oEAWsD;AAClE,UAAQ,KAAK,CAAC;AAChB;AAEA,IAAM,MAAM,QAAQ;AACpB,IAAM,OAAO,OAAO,EAAE,QAAQ,IAAI,QAAQ,IAAI;AAC9C,IAAM,OAAO,EAAE,QAAQ,IAAI,QAAQ;AACnC,IAAM,UAAU,KAAK,QAAQ,EAAE,UAAU,KAAK,IAAI,YAAY,cAAc;AAC5E,IAAM,SAAS,EAAE,UAAU,IAAI,Y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