-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1218 lines (1096 loc) · 41.6 KB
/
server.js
File metadata and controls
1218 lines (1096 loc) · 41.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const WebSocket = require("ws")
const randomColor = require("randomcolor")
const fs = require("fs")
const https = require("https")
const path = require("path")
const os = require("os")
const DEFAULT_WS_PORT = 21665
const DEFAULT_WS_HOST = "0.0.0.0"
const WS_PORT = Number.parseInt(
process.env.WS_PORT || process.env.PORT || String(DEFAULT_WS_PORT),
10
)
const effectiveWsPort = Number.isFinite(WS_PORT) ? WS_PORT : DEFAULT_WS_PORT
// Bind on all interfaces by default so it works on remote/Ubuntu servers.
// Override with WS_HOST/HOST if you need to restrict exposure.
const WS_HOST = String(
process.env.WS_HOST || process.env.HOST || DEFAULT_WS_HOST
).trim()
const effectiveWsHost = WS_HOST || DEFAULT_WS_HOST
// Optional TLS (WSS) mode: provide absolute paths via env vars.
// This avoids the need for a reverse proxy, but requires:
// - the port to be reachable publicly (firewall/security group)
// - a valid TLS certificate for the hostname (Let's Encrypt etc.)
const TLS_KEY_PATH = String(process.env.WS_TLS_KEY || "").trim()
const TLS_CERT_PATH = String(process.env.WS_TLS_CERT || "").trim()
const useTls = Boolean(TLS_KEY_PATH && TLS_CERT_PATH)
let httpServer = null
let server = null
if (useTls) {
const key = fs.readFileSync(TLS_KEY_PATH)
const cert = fs.readFileSync(TLS_CERT_PATH)
httpServer = https.createServer({ key, cert }, (req, res) => {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" })
res.end("WebSocket server is running.\n")
})
server = new WebSocket.Server({ server: httpServer })
httpServer.listen({ port: effectiveWsPort, host: effectiveWsHost })
} else {
server = new WebSocket.Server({
port: effectiveWsPort,
host: effectiveWsHost,
})
}
// ---------------------------------------------------------------------------
// Bestehende Collaborative-Editor-Logik (nicht verändern/brechen)
let users = []
let documentContent = ""
// ---------------------------------------------------------------------------
// WCAG-Test Kollaboration (Session-basierte Zustands-Synchronisation)
// Zentraler Speicher: lokales Dateisystem auf dem Host, keine Cloud.
const wcagSessions = new Map()
// IMPORTANT:
// When serving pages via Live Server (e.g. https://127.0.0.1:5504), any file change
// inside the workspace folder can trigger a full page reload.
// Our collaboration layer saves state to disk frequently (on ops), so storing files
// under the workspace would cause constant reloads (WS close code 1001).
// Therefore we store outside the workspace by default.
const BASE_STORE_DIR = String(process.env.COLLAB_STORE_DIR || "").trim()
? path.resolve(process.env.COLLAB_STORE_DIR)
: path.join(os.homedir(), ".a11y-workshop-collab")
const WCAG_STORE_DIR = path.join(BASE_STORE_DIR, "sessions")
// ---------------------------------------------------------------------------
// Workspace Kollaboration (Treemap v4 + Whiteboard)
// Gemeinsames JSON-Schema (später kompatibel mit WCAG-Test zusammenführbar)
const workspaceSessions = new Map()
const WORKSPACE_STORE_DIR = path.join(BASE_STORE_DIR, "workspaces")
function sessionStats() {
let totalClients = 0
for (const session of wcagSessions.values()) {
totalClients += session.clients?.size || 0
}
return {
sessions: wcagSessions.size,
totalClients,
}
}
function logListening() {
console.log("✅ WebSocket Server gestartet")
console.log(
`- Mode: ${useTls ? "wss" : "ws"} (${useTls ? "TLS" : "no TLS"})`
)
console.log(`- Bind: ${effectiveWsHost}:${effectiveWsPort}`)
try {
const isPrivateIpv4 = (ip) => {
const s = String(ip || "").trim()
const m = s.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)
if (!m) return false
const a = Number(m[1])
const b = Number(m[2])
if (
![a, b, Number(m[3]), Number(m[4])].every(
(n) => n >= 0 && n <= 255
)
) {
return false
}
// RFC1918
if (a === 10) return true
if (a === 172 && b >= 16 && b <= 31) return true
if (a === 192 && b === 168) return true
return false
}
const nets = os.networkInterfaces()
const candidates = []
for (const addrs of Object.values(nets || {})) {
for (const addr of addrs || []) {
if (!addr || addr.internal) continue
if (addr.family !== "IPv4" && addr.family !== 4) continue
candidates.push(addr.address)
}
}
const unique = Array.from(new Set(candidates)).sort()
if (unique.length) {
console.log("- Erreichbar (Beispiele):")
for (const ip of unique.slice(0, 6)) {
console.log(` - ws://${ip}:${effectiveWsPort}`)
}
if (unique.length > 6) {
console.log(` - … (${unique.length - 6} weitere)`)
}
const hasNonPrivate = unique.some((ip) => !isPrivateIpv4(ip))
if (!hasNonPrivate) {
console.log(
"- Hinweis: Das sind private IPs (z.B. 172.16–31.x.x). Von außerhalb (Internet) ist der WS-Port so meist NICHT direkt erreichbar."
)
console.log(
" Typisch brauchst du entweder (a) Security-Group/UFW Port-Freigabe + Public-IP oder (b) einen Reverse-Proxy über 443 (wss://...) der auf ws://127.0.0.1:" +
effectiveWsPort +
" weiterleitet."
)
}
}
} catch {
// ignore
}
console.log(`- WCAG Session Store: ${WCAG_STORE_DIR}`)
console.log(`- Workspace Store: ${WORKSPACE_STORE_DIR}`)
}
// In TLS mode the underlying HTTP server emits the listening event.
if (httpServer) {
httpServer.on("listening", logListening)
} else {
server.on("listening", logListening)
}
function handleServerError(err) {
console.error("❌ WebSocket Server Fehler:", err?.message || err)
if (err && err.code === "EADDRINUSE") {
console.error(
`❌ Port ${effectiveWsPort} ist bereits belegt. Stoppe den anderen Prozess oder ändere den Port (z.B. \\"WS_PORT=21666 node server.js\\").`
)
}
process.exitCode = 1
}
server.on("error", handleServerError)
if (httpServer) httpServer.on("error", handleServerError)
function ensureWcagStoreDir() {
try {
fs.mkdirSync(WCAG_STORE_DIR, { recursive: true })
} catch (e) {
console.error("❌ Konnte WCAG Store Dir nicht erstellen:", e)
}
}
function ensureWorkspaceStoreDir() {
try {
fs.mkdirSync(WORKSPACE_STORE_DIR, { recursive: true })
} catch (e) {
console.error("❌ Konnte Workspace Store Dir nicht erstellen:", e)
}
}
function sanitizeSessionId(sessionId) {
return String(sessionId || "")
.trim()
.replace(/[^a-zA-Z0-9_-]/g, "_")
.slice(0, 64)
}
function getWorkspaceFilePath(sessionId) {
return path.join(
WORKSPACE_STORE_DIR,
`${sanitizeSessionId(sessionId)}.json`
)
}
function loadWorkspaceFromDisk(sessionId) {
ensureWorkspaceStoreDir()
const filePath = getWorkspaceFilePath(sessionId)
try {
if (!fs.existsSync(filePath)) return null
const raw = fs.readFileSync(filePath, "utf8")
const parsed = JSON.parse(raw)
if (!parsed || typeof parsed !== "object") return null
if (!parsed.state) return null
console.log(
`📥 Workspace geladen: ${sanitizeSessionId(sessionId)} (rev ${typeof parsed.rev === "number" ? parsed.rev : 0})`
)
return {
rev: typeof parsed.rev === "number" ? parsed.rev : 0,
state: parsed.state,
}
} catch (e) {
console.error("❌ Fehler beim Laden des Workspace:", sessionId, e)
return null
}
}
function saveWorkspaceToDisk(sessionId, session) {
ensureWorkspaceStoreDir()
const filePath = getWorkspaceFilePath(sessionId)
try {
fs.writeFileSync(
filePath,
JSON.stringify(
{
sessionId: sanitizeSessionId(sessionId),
rev: session.rev,
savedAt: new Date().toISOString(),
state: session.state,
},
null,
2
),
"utf8"
)
console.log(
`💾 Workspace gespeichert: ${sanitizeSessionId(sessionId)} (rev ${session.rev}) -> ${path.relative(
process.cwd(),
filePath
)}`
)
} catch (e) {
console.error("❌ Fehler beim Speichern des Workspace:", sessionId, e)
}
}
function scheduleWorkspaceSave(
session,
{ delayMs = 250, immediate = false } = {}
) {
if (!session) return
if (session.__workspaceSaveTimeout) {
clearTimeout(session.__workspaceSaveTimeout)
session.__workspaceSaveTimeout = 0
}
if (immediate) {
saveWorkspaceToDisk(session.id, session)
return
}
session.__workspaceSaveTimeout = setTimeout(
() => {
session.__workspaceSaveTimeout = 0
saveWorkspaceToDisk(session.id, session)
},
Math.max(0, Number(delayMs) || 0)
)
}
function getOrCreateWorkspace(sessionId) {
const id = sanitizeSessionId(sessionId)
if (!id) return null
if (!workspaceSessions.has(id)) {
const fromDisk = loadWorkspaceFromDisk(id)
workspaceSessions.set(id, {
id,
rev: fromDisk?.rev ?? 0,
state: fromDisk?.state ?? null,
clients: new Set(),
users: new Map(), // clientId -> { username, color }
})
}
const session = workspaceSessions.get(id)
ensureWorkspaceStateShape(session)
return session
}
function workspaceBroadcast(session, payload, excludeSocket = null) {
const msg = JSON.stringify(payload)
session.clients.forEach((clientSocket) => {
if (excludeSocket && clientSocket === excludeSocket) return
if (clientSocket.readyState === WebSocket.OPEN) {
clientSocket.send(msg)
}
})
}
function workspaceUserList(session) {
return Array.from(session.users.entries()).map(([clientId, user]) => ({
clientId,
username: user.username,
color: user.color,
}))
}
function ensureWorkspaceStateShape(session) {
if (!session.state || typeof session.state !== "object") {
session.state = {
version: 1,
wcagTest: null,
collections: {},
whiteboard: { items: {} },
meta: { updatedAt: new Date().toISOString() },
}
}
session.state.collections = session.state.collections || {}
session.state.whiteboard = session.state.whiteboard || {}
session.state.whiteboard.items = session.state.whiteboard.items || {}
session.state.whiteboard.hiddenThemes =
session.state.whiteboard.hiddenThemes || {}
session.state.whiteboard.textFrames =
session.state.whiteboard.textFrames || {}
session.state.whiteboard.zOrder = Array.isArray(
session.state.whiteboard.zOrder
)
? session.state.whiteboard.zOrder
: []
session.state.whiteboard.locks = session.state.whiteboard.locks || {}
session.state.meta = session.state.meta || {}
session.state.meta.updatedAt = new Date().toISOString()
}
function workspaceStateHasContent(state) {
if (!state || typeof state !== "object") return false
const collections = state.collections || {}
const hasCollections = Object.keys(collections).some((k) => {
const arr = collections[k]
return Array.isArray(arr) && arr.length > 0
})
const wb = state.whiteboard || {}
const hasItems =
wb.items &&
typeof wb.items === "object" &&
Object.keys(wb.items).length > 0
const hasText =
wb.textFrames &&
typeof wb.textFrames === "object" &&
Object.keys(wb.textFrames).length > 0
return Boolean(hasCollections || hasItems || hasText)
}
function applyWorkspaceOp(session, op, { clientId, username }) {
ensureWorkspaceStateShape(session)
if (!op || typeof op !== "object") return false
const t = String(op.type || "")
const wb = session.state.whiteboard
if (t === "collections.toggle") {
const theme = String(op.theme || "").trim()
const criteriaId = String(op.criteriaId || "").trim()
if (!theme || !criteriaId) return false
session.state.collections = session.state.collections || {}
const existing = Array.isArray(session.state.collections[theme])
? session.state.collections[theme]
: []
if (existing.includes(criteriaId)) {
session.state.collections[theme] = existing.filter(
(x) => x !== criteriaId
)
} else {
session.state.collections[theme] = [...existing, criteriaId]
}
return true
}
if (t === "collections.theme.delete") {
const theme = String(op.theme || "").trim()
if (!theme) return false
session.state.collections = session.state.collections || {}
delete session.state.collections[theme]
return true
}
if (t === "collections.theme.rename") {
const from = String(op.from || "").trim()
const to = String(op.to || "").trim()
if (!from || !to || from === to) return false
session.state.collections = session.state.collections || {}
const hadFrom = Object.hasOwn(session.state.collections, from)
if (hadFrom) {
const existing = session.state.collections[from]
const targetExisting = Object.hasOwn(session.state.collections, to)
? session.state.collections[to]
: null
if (Array.isArray(existing) && Array.isArray(targetExisting)) {
const merged = [...targetExisting]
for (const id of existing) {
if (!merged.includes(id)) merged.push(id)
}
session.state.collections[to] = merged
} else {
session.state.collections[to] = existing
}
delete session.state.collections[from]
}
// hiddenThemes key rename
if (wb.hiddenThemes && Object.hasOwn(wb.hiddenThemes, from)) {
wb.hiddenThemes[to] = wb.hiddenThemes[from]
delete wb.hiddenThemes[from]
}
const headerFrom = `themeHeader::${from}`
const headerTo = `themeHeader::${to}`
const prefixFrom = `${from}::`
const prefixTo = `${to}::`
const renameKey = (oldKey, newKey) => {
if (
wb.items &&
Object.hasOwn(wb.items, oldKey) &&
!Object.hasOwn(wb.items, newKey)
) {
wb.items[newKey] = wb.items[oldKey]
}
if (wb.items && Object.hasOwn(wb.items, oldKey))
delete wb.items[oldKey]
if (
wb.locks &&
Object.hasOwn(wb.locks, oldKey) &&
!Object.hasOwn(wb.locks, newKey)
) {
wb.locks[newKey] = wb.locks[oldKey]
}
if (wb.locks && Object.hasOwn(wb.locks, oldKey))
delete wb.locks[oldKey]
}
renameKey(headerFrom, headerTo)
for (const key of Object.keys(wb.items || {})) {
if (!key.startsWith(prefixFrom)) continue
const rest = key.slice(prefixFrom.length)
renameKey(key, `${prefixTo}${rest}`)
}
if (Array.isArray(wb.zOrder)) {
wb.zOrder = wb.zOrder
.map((k) => {
const kk = String(k || "")
if (kk === headerFrom) return headerTo
if (kk.startsWith(prefixFrom)) {
return `${prefixTo}${kk.slice(prefixFrom.length)}`
}
return kk
})
.filter(Boolean)
}
return true
}
if (t === "wb.item.move") {
const key = String(op.key || "")
const x = Number(op.x)
const y = Number(op.y)
if (!key || !Number.isFinite(x) || !Number.isFinite(y)) return false
wb.items[key] = {
x: Math.round(Math.max(0, x)),
y: Math.round(Math.max(0, y)),
}
return true
}
if (t === "wb.items.batch") {
const updates = Array.isArray(op.updates) ? op.updates : []
if (!updates.length) return false
for (const u of updates) {
const key = String(u?.key || "")
const x = Number(u?.x)
const y = Number(u?.y)
if (!key || !Number.isFinite(x) || !Number.isFinite(y)) continue
wb.items[key] = {
x: Math.round(Math.max(0, x)),
y: Math.round(Math.max(0, y)),
}
}
return true
}
if (t === "wb.item.delete") {
const key = String(op.key || op.id || "")
if (!key) return false
op = { type: "wb.items.delete", keys: [key] }
}
if (String(op.type || "") === "wb.items.delete") {
const keys = Array.isArray(op.keys)
? op.keys.map((k) => String(k || "")).filter(Boolean)
: []
if (!keys.length) return false
const removed = new Set()
const removeKeyFromWhiteboard = (key) => {
const k = String(key || "")
if (!k) return false
let changed = false
removed.add(k)
if (wb.items && Object.hasOwn(wb.items, k)) {
delete wb.items[k]
changed = true
}
if (wb.textFrames && Object.hasOwn(wb.textFrames, k)) {
delete wb.textFrames[k]
changed = true
}
if (wb.locks && Object.hasOwn(wb.locks, k)) {
delete wb.locks[k]
changed = true
}
return changed
}
let changedAny = false
for (const key of keys) {
if (key.startsWith("themeHeader::")) {
const theme = key.slice("themeHeader::".length)
const headerKey = `themeHeader::${theme}`
// Delete theme collection (removes all connected criteria cards from view).
if (
session.state.collections &&
Object.hasOwn(session.state.collections, theme)
) {
delete session.state.collections[theme]
changedAny = true
}
if (wb.hiddenThemes && Object.hasOwn(wb.hiddenThemes, theme)) {
delete wb.hiddenThemes[theme]
changedAny = true
}
// Remove header + all criteria-card positions for that theme.
const prefix = `${theme}::`
changedAny = removeKeyFromWhiteboard(headerKey) || changedAny
for (const k of Object.keys(wb.items || {})) {
if (k.startsWith(prefix)) {
changedAny = removeKeyFromWhiteboard(k) || changedAny
}
}
// Also purge any zOrder-only keys for this theme.
if (Array.isArray(wb.zOrder)) {
for (const zk of wb.zOrder) {
const zkk = String(zk || "")
if (zkk === headerKey || zkk.startsWith(prefix)) {
removed.add(zkk)
}
}
}
continue
}
if (key.startsWith("text::")) {
changedAny = removeKeyFromWhiteboard(key) || changedAny
continue
}
if (key.includes("::")) {
const parts = key.split("::")
const theme = String(parts[0] || "")
const criteriaId = parts.slice(1).join("::")
if (theme && criteriaId && session.state.collections) {
const existing = Array.isArray(
session.state.collections[theme]
)
? session.state.collections[theme]
: null
if (existing) {
const nextArr = existing.filter(
(x) => String(x) !== String(criteriaId)
)
if (nextArr.length) {
session.state.collections[theme] = nextArr
changedAny = true
} else {
delete session.state.collections[theme]
if (
wb.hiddenThemes &&
Object.hasOwn(wb.hiddenThemes, theme)
) {
delete wb.hiddenThemes[theme]
}
// Remove theme header + any leftover positions for this theme.
const headerKey = `themeHeader::${theme}`
const prefix = `${theme}::`
changedAny =
removeKeyFromWhiteboard(headerKey) || changedAny
for (const k of Object.keys(wb.items || {})) {
if (k.startsWith(prefix)) {
changedAny =
removeKeyFromWhiteboard(k) || changedAny
}
}
if (Array.isArray(wb.zOrder)) {
for (const zk of wb.zOrder) {
const zkk = String(zk || "")
if (
zkk === headerKey ||
zkk.startsWith(prefix)
) {
removed.add(zkk)
}
}
}
changedAny = true
}
}
}
changedAny = removeKeyFromWhiteboard(key) || changedAny
continue
}
changedAny = removeKeyFromWhiteboard(key) || changedAny
}
if (removed.size && Array.isArray(wb.zOrder)) {
const before = wb.zOrder.length
wb.zOrder = wb.zOrder
.map((k) => String(k || ""))
.filter((k) => k && !removed.has(k))
if (wb.zOrder.length !== before) changedAny = true
}
return changedAny
}
if (t === "wb.hidden.set") {
const theme = String(op.theme || "").trim()
if (!theme) return false
wb.hiddenThemes[theme] = Boolean(op.hidden)
return true
}
if (t === "wb.text.create") {
const id = String(op.id || "")
const x = Number(op.x)
const y = Number(op.y)
if (!id || !Number.isFinite(x) || !Number.isFinite(y)) return false
wb.textFrames[id] = wb.textFrames[id] || {}
wb.textFrames[id].text = String(op.text || "")
wb.items[id] = {
x: Math.round(Math.max(0, x)),
y: Math.round(Math.max(0, y)),
}
return true
}
if (t === "wb.text.set") {
const id = String(op.id || "")
if (!id) return false
wb.textFrames[id] = wb.textFrames[id] || {}
wb.textFrames[id].text = String(op.text || "")
return true
}
if (t === "wb.zorder.set") {
const z = Array.isArray(op.zOrder) ? op.zOrder : null
if (!z) return false
wb.zOrder = z.map((k) => String(k || "")).filter(Boolean)
return true
}
if (t === "wb.lock") {
const id = String(op.id || "")
const locked = Boolean(op.locked)
if (!id) return false
if (locked) {
wb.locks[id] = {
clientId: String(clientId || ""),
username: String(username || "").trim() || "Anonym",
at: new Date().toISOString(),
}
return true
}
// Only the lock owner may clear the lock.
const existing = wb.locks[id]
if (!existing) return true
if (String(existing.clientId || "") !== String(clientId || "")) {
return false
}
delete wb.locks[id]
return true
}
if (t === "wb.lock.releaseByClient") {
const by = String(op.clientId || "")
if (!by) return false
const locks = wb.locks || {}
let changed = false
for (const [id, lock] of Object.entries(locks)) {
if (String(lock?.clientId || "") === by) {
delete locks[id]
changed = true
}
}
wb.locks = locks
return changed
}
return false
}
function getWcagSessionFilePath(sessionId) {
return path.join(WCAG_STORE_DIR, `${sanitizeSessionId(sessionId)}.json`)
}
function loadWcagSessionFromDisk(sessionId) {
ensureWcagStoreDir()
const filePath = getWcagSessionFilePath(sessionId)
try {
if (!fs.existsSync(filePath)) return null
const raw = fs.readFileSync(filePath, "utf8")
const parsed = JSON.parse(raw)
if (!parsed || typeof parsed !== "object") return null
if (!parsed.state) return null
console.log(
`📥 WCAG Session geladen: ${sanitizeSessionId(sessionId)} (rev ${typeof parsed.rev === "number" ? parsed.rev : 0})`
)
return {
rev: typeof parsed.rev === "number" ? parsed.rev : 0,
state: parsed.state,
}
} catch (e) {
console.error("❌ Fehler beim Laden der WCAG Session:", sessionId, e)
return null
}
}
function saveWcagSessionToDisk(sessionId, session) {
ensureWcagStoreDir()
const filePath = getWcagSessionFilePath(sessionId)
try {
fs.writeFileSync(
filePath,
JSON.stringify(
{
sessionId: sanitizeSessionId(sessionId),
rev: session.rev,
savedAt: new Date().toISOString(),
state: session.state,
},
null,
2
),
"utf8"
)
console.log(
`💾 WCAG Session gespeichert: ${sanitizeSessionId(sessionId)} (rev ${session.rev}) -> ${path.relative(
process.cwd(),
filePath
)}`
)
} catch (e) {
console.error(
"❌ Fehler beim Speichern der WCAG Session:",
sessionId,
e
)
}
}
function getOrCreateWcagSession(sessionId) {
const id = sanitizeSessionId(sessionId)
if (!id) return null
if (!wcagSessions.has(id)) {
const fromDisk = loadWcagSessionFromDisk(id)
wcagSessions.set(id, {
id,
rev: fromDisk?.rev ?? 0,
state: fromDisk?.state ?? null,
clients: new Set(),
users: new Map(), // clientId -> { username, color }
})
}
return wcagSessions.get(id)
}
function wcagBroadcast(session, payload, excludeSocket = null) {
const msg = JSON.stringify(payload)
session.clients.forEach((clientSocket) => {
if (excludeSocket && clientSocket === excludeSocket) return
if (clientSocket.readyState === WebSocket.OPEN) {
clientSocket.send(msg)
}
})
}
function wcagUserList(session) {
return Array.from(session.users.entries()).map(([clientId, user]) => ({
clientId,
username: user.username,
color: user.color,
}))
}
server.on("connection", (socket, req) => {
const ua = String(req?.headers?.["user-agent"] || "").slice(0, 160)
const origin = String(req?.headers?.origin || "").slice(0, 160)
socket.__userAgent = ua
socket.__origin = origin
socket.on("message", (message) => {
let data
try {
data = JSON.parse(message)
} catch (e) {
console.error("❌ Ungültige WS-Nachricht (kein JSON)")
return
}
// ------------------------------------------------------------
// Workspace Kollaboration (Treemap v4 + Whiteboard)
if (data.type === "workspace-join") {
const sessionId = data.sessionId
const clientId = String(data.clientId || "").trim()
const username = String(data.username || "").trim() || "Anonym"
const session = getOrCreateWorkspace(sessionId)
if (!session || !clientId) {
socket.send(
JSON.stringify({
type: "workspace-error",
message: "Ungültige Session oder Client-ID",
})
)
return
}
socket.__workspaceSessionId = session.id
socket.__workspaceClientId = clientId
// Prevent multiple concurrent sockets with the same clientId in one session.
// This can happen when a link with clientId was shared, or during fast reconnects.
// We treat the new join as the latest connection and close the previous one.
for (const other of session.clients) {
if (other === socket) continue
if (other.__workspaceClientId === clientId) {
try {
other.close(4000, "Replaced by new connection")
} catch {
// ignore
}
session.clients.delete(other)
}
}
session.clients.add(socket)
if (!session.users.has(clientId)) {
session.users.set(clientId, {
username,
color: randomColor(),
})
} else {
const existing = session.users.get(clientId)
existing.username = username
session.users.set(clientId, existing)
}
socket.send(
JSON.stringify({
type: "workspace-state",
sessionId: session.id,
rev: session.rev,
state: session.state,
})
)
console.log(
`👥 Workspace join: session=${session.id} user=${username} clientId=${clientId} (clients in session: ${session.clients.size}) ua=${String(
socket.__userAgent || ""
)} origin=${String(socket.__origin || "")}`
)
workspaceBroadcast(session, {
type: "workspace-user-list",
sessionId: session.id,
users: workspaceUserList(session),
})
return
}
if (data.type === "workspace-request-state") {
const session = getOrCreateWorkspace(data.sessionId)
if (!session) return
socket.send(
JSON.stringify({
type: "workspace-state",
sessionId: session.id,
rev: session.rev,
state: session.state,
})
)
return
}
if (data.type === "workspace-update") {
const session = getOrCreateWorkspace(data.sessionId)
if (!session) return
// Full snapshots can easily overwrite newer op-based changes and feel like
// a "document reset". Therefore we only accept workspace-update as an initial
// seed when the server state is still empty.
const hadContent = workspaceStateHasContent(session.state)
const incomingHasContent = workspaceStateHasContent(data.state)
if (hadContent || !incomingHasContent) {
console.log(
`⛔️ Ignored workspace-update (snapshots disabled): session=${session.id} by=${String(
data.clientId || ""
)}`
)
return
}
session.rev = (session.rev || 0) + 1
session.state = data.state
ensureWorkspaceStateShape(session)
scheduleWorkspaceSave(session, { immediate: true })
console.log(
`📝 Workspace seed: session=${session.id} rev=${session.rev} by=${String(
data.clientId || ""
)}`
)
workspaceBroadcast(session, {
type: "workspace-state",
sessionId: session.id,
rev: session.rev,
state: session.state,
updatedBy: String(data.clientId || ""),
})
return
}
if (data.type === "workspace-op") {
const session = getOrCreateWorkspace(data.sessionId)
if (!session) return
const clientId = String(data.clientId || "").trim()
const username =
session.users.get(clientId)?.username ||
String(data.username || "")
const ok = applyWorkspaceOp(session, data.op, {
clientId,
username,
})
if (!ok) return
session.rev = (session.rev || 0) + 1
{
const t = String(data.op?.type || "")
const isMove = t === "wb.item.move" || t === "wb.items.batch"
scheduleWorkspaceSave(session, {
delayMs: isMove ? 700 : 200,
})
}
console.log(
`🧩 Workspace op: session=${session.id} rev=${session.rev} by=${clientId} op=${String(
data.op?.type || ""
)}`
)
workspaceBroadcast(session, {
type: "workspace-op",
sessionId: session.id,
rev: session.rev,
op: data.op,
updatedBy: clientId,
})
return
}